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 case CallingConv::AMDGPU_Gfx: 2833 return true; 2834 default: 2835 return canGuaranteeTCO(CC); 2836 } 2837 } 2838 2839 bool SITargetLowering::isEligibleForTailCallOptimization( 2840 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2841 const SmallVectorImpl<ISD::OutputArg> &Outs, 2842 const SmallVectorImpl<SDValue> &OutVals, 2843 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2844 if (!mayTailCallThisCC(CalleeCC)) 2845 return false; 2846 2847 MachineFunction &MF = DAG.getMachineFunction(); 2848 const Function &CallerF = MF.getFunction(); 2849 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2850 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2851 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2852 2853 // Kernels aren't callable, and don't have a live in return address so it 2854 // doesn't make sense to do a tail call with entry functions. 2855 if (!CallerPreserved) 2856 return false; 2857 2858 bool CCMatch = CallerCC == CalleeCC; 2859 2860 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2861 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2862 return true; 2863 return false; 2864 } 2865 2866 // TODO: Can we handle var args? 2867 if (IsVarArg) 2868 return false; 2869 2870 for (const Argument &Arg : CallerF.args()) { 2871 if (Arg.hasByValAttr()) 2872 return false; 2873 } 2874 2875 LLVMContext &Ctx = *DAG.getContext(); 2876 2877 // Check that the call results are passed in the same way. 2878 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2879 CCAssignFnForCall(CalleeCC, IsVarArg), 2880 CCAssignFnForCall(CallerCC, IsVarArg))) 2881 return false; 2882 2883 // The callee has to preserve all registers the caller needs to preserve. 2884 if (!CCMatch) { 2885 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2886 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2887 return false; 2888 } 2889 2890 // Nothing more to check if the callee is taking no arguments. 2891 if (Outs.empty()) 2892 return true; 2893 2894 SmallVector<CCValAssign, 16> ArgLocs; 2895 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2896 2897 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2898 2899 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2900 // If the stack arguments for this call do not fit into our own save area then 2901 // the call cannot be made tail. 2902 // TODO: Is this really necessary? 2903 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2904 return false; 2905 2906 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2907 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2908 } 2909 2910 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2911 if (!CI->isTailCall()) 2912 return false; 2913 2914 const Function *ParentFn = CI->getParent()->getParent(); 2915 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2916 return false; 2917 return true; 2918 } 2919 2920 // The wave scratch offset register is used as the global base pointer. 2921 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2922 SmallVectorImpl<SDValue> &InVals) const { 2923 SelectionDAG &DAG = CLI.DAG; 2924 const SDLoc &DL = CLI.DL; 2925 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2926 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2927 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2928 SDValue Chain = CLI.Chain; 2929 SDValue Callee = CLI.Callee; 2930 bool &IsTailCall = CLI.IsTailCall; 2931 CallingConv::ID CallConv = CLI.CallConv; 2932 bool IsVarArg = CLI.IsVarArg; 2933 bool IsSibCall = false; 2934 bool IsThisReturn = false; 2935 MachineFunction &MF = DAG.getMachineFunction(); 2936 2937 if (Callee.isUndef() || isNullConstant(Callee)) { 2938 if (!CLI.IsTailCall) { 2939 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2940 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2941 } 2942 2943 return Chain; 2944 } 2945 2946 if (IsVarArg) { 2947 return lowerUnhandledCall(CLI, InVals, 2948 "unsupported call to variadic function "); 2949 } 2950 2951 if (!CLI.CB) 2952 report_fatal_error("unsupported libcall legalization"); 2953 2954 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2955 !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) { 2956 return lowerUnhandledCall(CLI, InVals, 2957 "unsupported indirect call to function "); 2958 } 2959 2960 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2961 return lowerUnhandledCall(CLI, InVals, 2962 "unsupported required tail call to function "); 2963 } 2964 2965 if (AMDGPU::isShader(CallConv)) { 2966 // Note the issue is with the CC of the called function, not of the call 2967 // itself. 2968 return lowerUnhandledCall(CLI, InVals, 2969 "unsupported call to a shader function "); 2970 } 2971 2972 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2973 CallConv != CallingConv::AMDGPU_Gfx) { 2974 // Only allow calls with specific calling conventions. 2975 return lowerUnhandledCall(CLI, InVals, 2976 "unsupported calling convention for call from " 2977 "graphics shader of function "); 2978 } 2979 2980 if (IsTailCall) { 2981 IsTailCall = isEligibleForTailCallOptimization( 2982 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2983 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2984 report_fatal_error("failed to perform tail call elimination on a call " 2985 "site marked musttail"); 2986 } 2987 2988 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2989 2990 // A sibling call is one where we're under the usual C ABI and not planning 2991 // to change that but can still do a tail call: 2992 if (!TailCallOpt && IsTailCall) 2993 IsSibCall = true; 2994 2995 if (IsTailCall) 2996 ++NumTailCalls; 2997 } 2998 2999 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3000 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3001 SmallVector<SDValue, 8> MemOpChains; 3002 3003 // Analyze operands of the call, assigning locations to each operand. 3004 SmallVector<CCValAssign, 16> ArgLocs; 3005 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3006 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3007 3008 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3009 CallConv != CallingConv::AMDGPU_Gfx) { 3010 // With a fixed ABI, allocate fixed registers before user arguments. 3011 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3012 } 3013 3014 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3015 3016 // Get a count of how many bytes are to be pushed on the stack. 3017 unsigned NumBytes = CCInfo.getNextStackOffset(); 3018 3019 if (IsSibCall) { 3020 // Since we're not changing the ABI to make this a tail call, the memory 3021 // operands are already available in the caller's incoming argument space. 3022 NumBytes = 0; 3023 } 3024 3025 // FPDiff is the byte offset of the call's argument area from the callee's. 3026 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3027 // by this amount for a tail call. In a sibling call it must be 0 because the 3028 // caller will deallocate the entire stack and the callee still expects its 3029 // arguments to begin at SP+0. Completely unused for non-tail calls. 3030 int32_t FPDiff = 0; 3031 MachineFrameInfo &MFI = MF.getFrameInfo(); 3032 3033 // Adjust the stack pointer for the new arguments... 3034 // These operations are automatically eliminated by the prolog/epilog pass 3035 if (!IsSibCall) { 3036 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3037 3038 if (!Subtarget->enableFlatScratch()) { 3039 SmallVector<SDValue, 4> CopyFromChains; 3040 3041 // In the HSA case, this should be an identity copy. 3042 SDValue ScratchRSrcReg 3043 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3044 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3045 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3046 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3047 } 3048 } 3049 3050 MVT PtrVT = MVT::i32; 3051 3052 // Walk the register/memloc assignments, inserting copies/loads. 3053 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3054 CCValAssign &VA = ArgLocs[i]; 3055 SDValue Arg = OutVals[i]; 3056 3057 // Promote the value if needed. 3058 switch (VA.getLocInfo()) { 3059 case CCValAssign::Full: 3060 break; 3061 case CCValAssign::BCvt: 3062 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3063 break; 3064 case CCValAssign::ZExt: 3065 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3066 break; 3067 case CCValAssign::SExt: 3068 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3069 break; 3070 case CCValAssign::AExt: 3071 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3072 break; 3073 case CCValAssign::FPExt: 3074 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3075 break; 3076 default: 3077 llvm_unreachable("Unknown loc info!"); 3078 } 3079 3080 if (VA.isRegLoc()) { 3081 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3082 } else { 3083 assert(VA.isMemLoc()); 3084 3085 SDValue DstAddr; 3086 MachinePointerInfo DstInfo; 3087 3088 unsigned LocMemOffset = VA.getLocMemOffset(); 3089 int32_t Offset = LocMemOffset; 3090 3091 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3092 MaybeAlign Alignment; 3093 3094 if (IsTailCall) { 3095 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3096 unsigned OpSize = Flags.isByVal() ? 3097 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3098 3099 // FIXME: We can have better than the minimum byval required alignment. 3100 Alignment = 3101 Flags.isByVal() 3102 ? Flags.getNonZeroByValAlign() 3103 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3104 3105 Offset = Offset + FPDiff; 3106 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3107 3108 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3109 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3110 3111 // Make sure any stack arguments overlapping with where we're storing 3112 // are loaded before this eventual operation. Otherwise they'll be 3113 // clobbered. 3114 3115 // FIXME: Why is this really necessary? This seems to just result in a 3116 // lot of code to copy the stack and write them back to the same 3117 // locations, which are supposed to be immutable? 3118 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3119 } else { 3120 DstAddr = PtrOff; 3121 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3122 Alignment = 3123 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3124 } 3125 3126 if (Outs[i].Flags.isByVal()) { 3127 SDValue SizeNode = 3128 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3129 SDValue Cpy = 3130 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3131 Outs[i].Flags.getNonZeroByValAlign(), 3132 /*isVol = */ false, /*AlwaysInline = */ true, 3133 /*isTailCall = */ false, DstInfo, 3134 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3135 3136 MemOpChains.push_back(Cpy); 3137 } else { 3138 SDValue Store = 3139 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3140 MemOpChains.push_back(Store); 3141 } 3142 } 3143 } 3144 3145 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3146 CallConv != CallingConv::AMDGPU_Gfx) { 3147 // Copy special input registers after user input arguments. 3148 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3149 } 3150 3151 if (!MemOpChains.empty()) 3152 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3153 3154 // Build a sequence of copy-to-reg nodes chained together with token chain 3155 // and flag operands which copy the outgoing args into the appropriate regs. 3156 SDValue InFlag; 3157 for (auto &RegToPass : RegsToPass) { 3158 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3159 RegToPass.second, InFlag); 3160 InFlag = Chain.getValue(1); 3161 } 3162 3163 3164 SDValue PhysReturnAddrReg; 3165 if (IsTailCall) { 3166 // Since the return is being combined with the call, we need to pass on the 3167 // return address. 3168 3169 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3170 SDValue ReturnAddrReg = CreateLiveInRegister( 3171 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3172 3173 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3174 MVT::i64); 3175 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3176 InFlag = Chain.getValue(1); 3177 } 3178 3179 // We don't usually want to end the call-sequence here because we would tidy 3180 // the frame up *after* the call, however in the ABI-changing tail-call case 3181 // we've carefully laid out the parameters so that when sp is reset they'll be 3182 // in the correct location. 3183 if (IsTailCall && !IsSibCall) { 3184 Chain = DAG.getCALLSEQ_END(Chain, 3185 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3186 DAG.getTargetConstant(0, DL, MVT::i32), 3187 InFlag, DL); 3188 InFlag = Chain.getValue(1); 3189 } 3190 3191 std::vector<SDValue> Ops; 3192 Ops.push_back(Chain); 3193 Ops.push_back(Callee); 3194 // Add a redundant copy of the callee global which will not be legalized, as 3195 // we need direct access to the callee later. 3196 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3197 const GlobalValue *GV = GSD->getGlobal(); 3198 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3199 } else { 3200 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3201 } 3202 3203 if (IsTailCall) { 3204 // Each tail call may have to adjust the stack by a different amount, so 3205 // this information must travel along with the operation for eventual 3206 // consumption by emitEpilogue. 3207 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3208 3209 Ops.push_back(PhysReturnAddrReg); 3210 } 3211 3212 // Add argument registers to the end of the list so that they are known live 3213 // into the call. 3214 for (auto &RegToPass : RegsToPass) { 3215 Ops.push_back(DAG.getRegister(RegToPass.first, 3216 RegToPass.second.getValueType())); 3217 } 3218 3219 // Add a register mask operand representing the call-preserved registers. 3220 3221 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3222 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3223 assert(Mask && "Missing call preserved mask for calling convention"); 3224 Ops.push_back(DAG.getRegisterMask(Mask)); 3225 3226 if (InFlag.getNode()) 3227 Ops.push_back(InFlag); 3228 3229 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3230 3231 // If we're doing a tall call, use a TC_RETURN here rather than an 3232 // actual call instruction. 3233 if (IsTailCall) { 3234 MFI.setHasTailCall(); 3235 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3236 } 3237 3238 // Returns a chain and a flag for retval copy to use. 3239 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3240 Chain = Call.getValue(0); 3241 InFlag = Call.getValue(1); 3242 3243 uint64_t CalleePopBytes = NumBytes; 3244 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3245 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3246 InFlag, DL); 3247 if (!Ins.empty()) 3248 InFlag = Chain.getValue(1); 3249 3250 // Handle result values, copying them out of physregs into vregs that we 3251 // return. 3252 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3253 InVals, IsThisReturn, 3254 IsThisReturn ? OutVals[0] : SDValue()); 3255 } 3256 3257 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3258 // except for applying the wave size scale to the increment amount. 3259 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3260 SDValue Op, SelectionDAG &DAG) const { 3261 const MachineFunction &MF = DAG.getMachineFunction(); 3262 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3263 3264 SDLoc dl(Op); 3265 EVT VT = Op.getValueType(); 3266 SDValue Tmp1 = Op; 3267 SDValue Tmp2 = Op.getValue(1); 3268 SDValue Tmp3 = Op.getOperand(2); 3269 SDValue Chain = Tmp1.getOperand(0); 3270 3271 Register SPReg = Info->getStackPtrOffsetReg(); 3272 3273 // Chain the dynamic stack allocation so that it doesn't modify the stack 3274 // pointer when other instructions are using the stack. 3275 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3276 3277 SDValue Size = Tmp2.getOperand(1); 3278 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3279 Chain = SP.getValue(1); 3280 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3281 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3282 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3283 unsigned Opc = 3284 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3285 ISD::ADD : ISD::SUB; 3286 3287 SDValue ScaledSize = DAG.getNode( 3288 ISD::SHL, dl, VT, Size, 3289 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3290 3291 Align StackAlign = TFL->getStackAlign(); 3292 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3293 if (Alignment && *Alignment > StackAlign) { 3294 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3295 DAG.getConstant(-(uint64_t)Alignment->value() 3296 << ST.getWavefrontSizeLog2(), 3297 dl, VT)); 3298 } 3299 3300 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3301 Tmp2 = DAG.getCALLSEQ_END( 3302 Chain, DAG.getIntPtrConstant(0, dl, true), 3303 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3304 3305 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3306 } 3307 3308 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3309 SelectionDAG &DAG) const { 3310 // We only handle constant sizes here to allow non-entry block, static sized 3311 // allocas. A truly dynamic value is more difficult to support because we 3312 // don't know if the size value is uniform or not. If the size isn't uniform, 3313 // we would need to do a wave reduction to get the maximum size to know how 3314 // much to increment the uniform stack pointer. 3315 SDValue Size = Op.getOperand(1); 3316 if (isa<ConstantSDNode>(Size)) 3317 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3318 3319 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3320 } 3321 3322 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3323 const MachineFunction &MF) const { 3324 Register Reg = StringSwitch<Register>(RegName) 3325 .Case("m0", AMDGPU::M0) 3326 .Case("exec", AMDGPU::EXEC) 3327 .Case("exec_lo", AMDGPU::EXEC_LO) 3328 .Case("exec_hi", AMDGPU::EXEC_HI) 3329 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3330 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3331 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3332 .Default(Register()); 3333 3334 if (Reg == AMDGPU::NoRegister) { 3335 report_fatal_error(Twine("invalid register name \"" 3336 + StringRef(RegName) + "\".")); 3337 3338 } 3339 3340 if (!Subtarget->hasFlatScrRegister() && 3341 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3342 report_fatal_error(Twine("invalid register \"" 3343 + StringRef(RegName) + "\" for subtarget.")); 3344 } 3345 3346 switch (Reg) { 3347 case AMDGPU::M0: 3348 case AMDGPU::EXEC_LO: 3349 case AMDGPU::EXEC_HI: 3350 case AMDGPU::FLAT_SCR_LO: 3351 case AMDGPU::FLAT_SCR_HI: 3352 if (VT.getSizeInBits() == 32) 3353 return Reg; 3354 break; 3355 case AMDGPU::EXEC: 3356 case AMDGPU::FLAT_SCR: 3357 if (VT.getSizeInBits() == 64) 3358 return Reg; 3359 break; 3360 default: 3361 llvm_unreachable("missing register type checking"); 3362 } 3363 3364 report_fatal_error(Twine("invalid type for register \"" 3365 + StringRef(RegName) + "\".")); 3366 } 3367 3368 // If kill is not the last instruction, split the block so kill is always a 3369 // proper terminator. 3370 MachineBasicBlock * 3371 SITargetLowering::splitKillBlock(MachineInstr &MI, 3372 MachineBasicBlock *BB) const { 3373 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3374 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3375 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3376 return SplitBB; 3377 } 3378 3379 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3380 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3381 // be the first instruction in the remainder block. 3382 // 3383 /// \returns { LoopBody, Remainder } 3384 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3385 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3386 MachineFunction *MF = MBB.getParent(); 3387 MachineBasicBlock::iterator I(&MI); 3388 3389 // To insert the loop we need to split the block. Move everything after this 3390 // point to a new block, and insert a new empty block between the two. 3391 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3392 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3393 MachineFunction::iterator MBBI(MBB); 3394 ++MBBI; 3395 3396 MF->insert(MBBI, LoopBB); 3397 MF->insert(MBBI, RemainderBB); 3398 3399 LoopBB->addSuccessor(LoopBB); 3400 LoopBB->addSuccessor(RemainderBB); 3401 3402 // Move the rest of the block into a new block. 3403 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3404 3405 if (InstInLoop) { 3406 auto Next = std::next(I); 3407 3408 // Move instruction to loop body. 3409 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3410 3411 // Move the rest of the block. 3412 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3413 } else { 3414 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3415 } 3416 3417 MBB.addSuccessor(LoopBB); 3418 3419 return std::make_pair(LoopBB, RemainderBB); 3420 } 3421 3422 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3423 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3424 MachineBasicBlock *MBB = MI.getParent(); 3425 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3426 auto I = MI.getIterator(); 3427 auto E = std::next(I); 3428 3429 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3430 .addImm(0); 3431 3432 MIBundleBuilder Bundler(*MBB, I, E); 3433 finalizeBundle(*MBB, Bundler.begin()); 3434 } 3435 3436 MachineBasicBlock * 3437 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3438 MachineBasicBlock *BB) const { 3439 const DebugLoc &DL = MI.getDebugLoc(); 3440 3441 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3442 3443 MachineBasicBlock *LoopBB; 3444 MachineBasicBlock *RemainderBB; 3445 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3446 3447 // Apparently kill flags are only valid if the def is in the same block? 3448 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3449 Src->setIsKill(false); 3450 3451 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3452 3453 MachineBasicBlock::iterator I = LoopBB->end(); 3454 3455 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3456 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3457 3458 // Clear TRAP_STS.MEM_VIOL 3459 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3460 .addImm(0) 3461 .addImm(EncodedReg); 3462 3463 bundleInstWithWaitcnt(MI); 3464 3465 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3466 3467 // Load and check TRAP_STS.MEM_VIOL 3468 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3469 .addImm(EncodedReg); 3470 3471 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3472 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3473 .addReg(Reg, RegState::Kill) 3474 .addImm(0); 3475 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3476 .addMBB(LoopBB); 3477 3478 return RemainderBB; 3479 } 3480 3481 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3482 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3483 // will only do one iteration. In the worst case, this will loop 64 times. 3484 // 3485 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3486 static MachineBasicBlock::iterator 3487 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3488 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3489 const DebugLoc &DL, const MachineOperand &Idx, 3490 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3491 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3492 Register &SGPRIdxReg) { 3493 3494 MachineFunction *MF = OrigBB.getParent(); 3495 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3496 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3497 MachineBasicBlock::iterator I = LoopBB.begin(); 3498 3499 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3500 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3501 Register NewExec = MRI.createVirtualRegister(BoolRC); 3502 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3503 Register CondReg = MRI.createVirtualRegister(BoolRC); 3504 3505 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3506 .addReg(InitReg) 3507 .addMBB(&OrigBB) 3508 .addReg(ResultReg) 3509 .addMBB(&LoopBB); 3510 3511 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3512 .addReg(InitSaveExecReg) 3513 .addMBB(&OrigBB) 3514 .addReg(NewExec) 3515 .addMBB(&LoopBB); 3516 3517 // Read the next variant <- also loop target. 3518 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3519 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3520 3521 // Compare the just read M0 value to all possible Idx values. 3522 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3523 .addReg(CurrentIdxReg) 3524 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3525 3526 // Update EXEC, save the original EXEC value to VCC. 3527 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3528 : AMDGPU::S_AND_SAVEEXEC_B64), 3529 NewExec) 3530 .addReg(CondReg, RegState::Kill); 3531 3532 MRI.setSimpleHint(NewExec, CondReg); 3533 3534 if (UseGPRIdxMode) { 3535 if (Offset == 0) { 3536 SGPRIdxReg = CurrentIdxReg; 3537 } else { 3538 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3539 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3540 .addReg(CurrentIdxReg, RegState::Kill) 3541 .addImm(Offset); 3542 } 3543 } else { 3544 // Move index from VCC into M0 3545 if (Offset == 0) { 3546 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3547 .addReg(CurrentIdxReg, RegState::Kill); 3548 } else { 3549 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3550 .addReg(CurrentIdxReg, RegState::Kill) 3551 .addImm(Offset); 3552 } 3553 } 3554 3555 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3556 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3557 MachineInstr *InsertPt = 3558 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3559 : AMDGPU::S_XOR_B64_term), Exec) 3560 .addReg(Exec) 3561 .addReg(NewExec); 3562 3563 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3564 // s_cbranch_scc0? 3565 3566 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3567 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3568 .addMBB(&LoopBB); 3569 3570 return InsertPt->getIterator(); 3571 } 3572 3573 // This has slightly sub-optimal regalloc when the source vector is killed by 3574 // the read. The register allocator does not understand that the kill is 3575 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3576 // subregister from it, using 1 more VGPR than necessary. This was saved when 3577 // this was expanded after register allocation. 3578 static MachineBasicBlock::iterator 3579 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3580 unsigned InitResultReg, unsigned PhiReg, int Offset, 3581 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3582 MachineFunction *MF = MBB.getParent(); 3583 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3584 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3585 MachineRegisterInfo &MRI = MF->getRegInfo(); 3586 const DebugLoc &DL = MI.getDebugLoc(); 3587 MachineBasicBlock::iterator I(&MI); 3588 3589 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3590 Register DstReg = MI.getOperand(0).getReg(); 3591 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3592 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3593 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3594 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3595 3596 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3597 3598 // Save the EXEC mask 3599 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3600 .addReg(Exec); 3601 3602 MachineBasicBlock *LoopBB; 3603 MachineBasicBlock *RemainderBB; 3604 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3605 3606 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3607 3608 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3609 InitResultReg, DstReg, PhiReg, TmpExec, 3610 Offset, UseGPRIdxMode, SGPRIdxReg); 3611 3612 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3613 MachineFunction::iterator MBBI(LoopBB); 3614 ++MBBI; 3615 MF->insert(MBBI, LandingPad); 3616 LoopBB->removeSuccessor(RemainderBB); 3617 LandingPad->addSuccessor(RemainderBB); 3618 LoopBB->addSuccessor(LandingPad); 3619 MachineBasicBlock::iterator First = LandingPad->begin(); 3620 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3621 .addReg(SaveExec); 3622 3623 return InsPt; 3624 } 3625 3626 // Returns subreg index, offset 3627 static std::pair<unsigned, int> 3628 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3629 const TargetRegisterClass *SuperRC, 3630 unsigned VecReg, 3631 int Offset) { 3632 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3633 3634 // Skip out of bounds offsets, or else we would end up using an undefined 3635 // register. 3636 if (Offset >= NumElts || Offset < 0) 3637 return std::make_pair(AMDGPU::sub0, Offset); 3638 3639 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3640 } 3641 3642 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3643 MachineRegisterInfo &MRI, MachineInstr &MI, 3644 int Offset) { 3645 MachineBasicBlock *MBB = MI.getParent(); 3646 const DebugLoc &DL = MI.getDebugLoc(); 3647 MachineBasicBlock::iterator I(&MI); 3648 3649 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3650 3651 assert(Idx->getReg() != AMDGPU::NoRegister); 3652 3653 if (Offset == 0) { 3654 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3655 } else { 3656 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3657 .add(*Idx) 3658 .addImm(Offset); 3659 } 3660 } 3661 3662 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3663 MachineRegisterInfo &MRI, MachineInstr &MI, 3664 int Offset) { 3665 MachineBasicBlock *MBB = MI.getParent(); 3666 const DebugLoc &DL = MI.getDebugLoc(); 3667 MachineBasicBlock::iterator I(&MI); 3668 3669 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3670 3671 if (Offset == 0) 3672 return Idx->getReg(); 3673 3674 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3675 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3676 .add(*Idx) 3677 .addImm(Offset); 3678 return Tmp; 3679 } 3680 3681 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3682 MachineBasicBlock &MBB, 3683 const GCNSubtarget &ST) { 3684 const SIInstrInfo *TII = ST.getInstrInfo(); 3685 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3686 MachineFunction *MF = MBB.getParent(); 3687 MachineRegisterInfo &MRI = MF->getRegInfo(); 3688 3689 Register Dst = MI.getOperand(0).getReg(); 3690 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3691 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3692 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3693 3694 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3695 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3696 3697 unsigned SubReg; 3698 std::tie(SubReg, Offset) 3699 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3700 3701 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3702 3703 // Check for a SGPR index. 3704 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3705 MachineBasicBlock::iterator I(&MI); 3706 const DebugLoc &DL = MI.getDebugLoc(); 3707 3708 if (UseGPRIdxMode) { 3709 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3710 // to avoid interfering with other uses, so probably requires a new 3711 // optimization pass. 3712 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3713 3714 const MCInstrDesc &GPRIDXDesc = 3715 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3716 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3717 .addReg(SrcReg) 3718 .addReg(Idx) 3719 .addImm(SubReg); 3720 } else { 3721 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3722 3723 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3724 .addReg(SrcReg, 0, SubReg) 3725 .addReg(SrcReg, RegState::Implicit); 3726 } 3727 3728 MI.eraseFromParent(); 3729 3730 return &MBB; 3731 } 3732 3733 // Control flow needs to be inserted if indexing with a VGPR. 3734 const DebugLoc &DL = MI.getDebugLoc(); 3735 MachineBasicBlock::iterator I(&MI); 3736 3737 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3738 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3739 3740 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3741 3742 Register SGPRIdxReg; 3743 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3744 UseGPRIdxMode, SGPRIdxReg); 3745 3746 MachineBasicBlock *LoopBB = InsPt->getParent(); 3747 3748 if (UseGPRIdxMode) { 3749 const MCInstrDesc &GPRIDXDesc = 3750 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3751 3752 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3753 .addReg(SrcReg) 3754 .addReg(SGPRIdxReg) 3755 .addImm(SubReg); 3756 } else { 3757 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3758 .addReg(SrcReg, 0, SubReg) 3759 .addReg(SrcReg, RegState::Implicit); 3760 } 3761 3762 MI.eraseFromParent(); 3763 3764 return LoopBB; 3765 } 3766 3767 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3768 MachineBasicBlock &MBB, 3769 const GCNSubtarget &ST) { 3770 const SIInstrInfo *TII = ST.getInstrInfo(); 3771 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3772 MachineFunction *MF = MBB.getParent(); 3773 MachineRegisterInfo &MRI = MF->getRegInfo(); 3774 3775 Register Dst = MI.getOperand(0).getReg(); 3776 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3777 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3778 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3779 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3780 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3781 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3782 3783 // This can be an immediate, but will be folded later. 3784 assert(Val->getReg()); 3785 3786 unsigned SubReg; 3787 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3788 SrcVec->getReg(), 3789 Offset); 3790 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3791 3792 if (Idx->getReg() == AMDGPU::NoRegister) { 3793 MachineBasicBlock::iterator I(&MI); 3794 const DebugLoc &DL = MI.getDebugLoc(); 3795 3796 assert(Offset == 0); 3797 3798 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3799 .add(*SrcVec) 3800 .add(*Val) 3801 .addImm(SubReg); 3802 3803 MI.eraseFromParent(); 3804 return &MBB; 3805 } 3806 3807 // Check for a SGPR index. 3808 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3809 MachineBasicBlock::iterator I(&MI); 3810 const DebugLoc &DL = MI.getDebugLoc(); 3811 3812 if (UseGPRIdxMode) { 3813 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3814 3815 const MCInstrDesc &GPRIDXDesc = 3816 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3817 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3818 .addReg(SrcVec->getReg()) 3819 .add(*Val) 3820 .addReg(Idx) 3821 .addImm(SubReg); 3822 } else { 3823 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3824 3825 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3826 TRI.getRegSizeInBits(*VecRC), 32, false); 3827 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3828 .addReg(SrcVec->getReg()) 3829 .add(*Val) 3830 .addImm(SubReg); 3831 } 3832 MI.eraseFromParent(); 3833 return &MBB; 3834 } 3835 3836 // Control flow needs to be inserted if indexing with a VGPR. 3837 if (Val->isReg()) 3838 MRI.clearKillFlags(Val->getReg()); 3839 3840 const DebugLoc &DL = MI.getDebugLoc(); 3841 3842 Register PhiReg = MRI.createVirtualRegister(VecRC); 3843 3844 Register SGPRIdxReg; 3845 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3846 UseGPRIdxMode, SGPRIdxReg); 3847 MachineBasicBlock *LoopBB = InsPt->getParent(); 3848 3849 if (UseGPRIdxMode) { 3850 const MCInstrDesc &GPRIDXDesc = 3851 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3852 3853 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3854 .addReg(PhiReg) 3855 .add(*Val) 3856 .addReg(SGPRIdxReg) 3857 .addImm(AMDGPU::sub0); 3858 } else { 3859 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3860 TRI.getRegSizeInBits(*VecRC), 32, false); 3861 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3862 .addReg(PhiReg) 3863 .add(*Val) 3864 .addImm(AMDGPU::sub0); 3865 } 3866 3867 MI.eraseFromParent(); 3868 return LoopBB; 3869 } 3870 3871 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3872 MachineInstr &MI, MachineBasicBlock *BB) const { 3873 3874 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3875 MachineFunction *MF = BB->getParent(); 3876 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3877 3878 switch (MI.getOpcode()) { 3879 case AMDGPU::S_UADDO_PSEUDO: 3880 case AMDGPU::S_USUBO_PSEUDO: { 3881 const DebugLoc &DL = MI.getDebugLoc(); 3882 MachineOperand &Dest0 = MI.getOperand(0); 3883 MachineOperand &Dest1 = MI.getOperand(1); 3884 MachineOperand &Src0 = MI.getOperand(2); 3885 MachineOperand &Src1 = MI.getOperand(3); 3886 3887 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3888 ? AMDGPU::S_ADD_I32 3889 : AMDGPU::S_SUB_I32; 3890 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3891 3892 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3893 .addImm(1) 3894 .addImm(0); 3895 3896 MI.eraseFromParent(); 3897 return BB; 3898 } 3899 case AMDGPU::S_ADD_U64_PSEUDO: 3900 case AMDGPU::S_SUB_U64_PSEUDO: { 3901 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3902 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3903 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3904 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3905 const DebugLoc &DL = MI.getDebugLoc(); 3906 3907 MachineOperand &Dest = MI.getOperand(0); 3908 MachineOperand &Src0 = MI.getOperand(1); 3909 MachineOperand &Src1 = MI.getOperand(2); 3910 3911 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3912 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3913 3914 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3915 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3916 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3917 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3918 3919 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3920 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3921 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3922 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3923 3924 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3925 3926 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3927 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3928 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3929 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3930 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3931 .addReg(DestSub0) 3932 .addImm(AMDGPU::sub0) 3933 .addReg(DestSub1) 3934 .addImm(AMDGPU::sub1); 3935 MI.eraseFromParent(); 3936 return BB; 3937 } 3938 case AMDGPU::V_ADD_U64_PSEUDO: 3939 case AMDGPU::V_SUB_U64_PSEUDO: { 3940 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3941 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3942 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3943 const DebugLoc &DL = MI.getDebugLoc(); 3944 3945 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3946 3947 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3948 3949 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3950 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3951 3952 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3953 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3954 3955 MachineOperand &Dest = MI.getOperand(0); 3956 MachineOperand &Src0 = MI.getOperand(1); 3957 MachineOperand &Src1 = MI.getOperand(2); 3958 3959 const TargetRegisterClass *Src0RC = Src0.isReg() 3960 ? MRI.getRegClass(Src0.getReg()) 3961 : &AMDGPU::VReg_64RegClass; 3962 const TargetRegisterClass *Src1RC = Src1.isReg() 3963 ? MRI.getRegClass(Src1.getReg()) 3964 : &AMDGPU::VReg_64RegClass; 3965 3966 const TargetRegisterClass *Src0SubRC = 3967 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3968 const TargetRegisterClass *Src1SubRC = 3969 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3970 3971 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3972 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3973 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3974 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3975 3976 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3977 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3978 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3979 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3980 3981 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3982 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3983 .addReg(CarryReg, RegState::Define) 3984 .add(SrcReg0Sub0) 3985 .add(SrcReg1Sub0) 3986 .addImm(0); // clamp bit 3987 3988 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3989 MachineInstr *HiHalf = 3990 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3991 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3992 .add(SrcReg0Sub1) 3993 .add(SrcReg1Sub1) 3994 .addReg(CarryReg, RegState::Kill) 3995 .addImm(0); // clamp bit 3996 3997 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3998 .addReg(DestSub0) 3999 .addImm(AMDGPU::sub0) 4000 .addReg(DestSub1) 4001 .addImm(AMDGPU::sub1); 4002 TII->legalizeOperands(*LoHalf); 4003 TII->legalizeOperands(*HiHalf); 4004 MI.eraseFromParent(); 4005 return BB; 4006 } 4007 case AMDGPU::S_ADD_CO_PSEUDO: 4008 case AMDGPU::S_SUB_CO_PSEUDO: { 4009 // This pseudo has a chance to be selected 4010 // only from uniform add/subcarry node. All the VGPR operands 4011 // therefore assumed to be splat vectors. 4012 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4013 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4014 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4015 MachineBasicBlock::iterator MII = MI; 4016 const DebugLoc &DL = MI.getDebugLoc(); 4017 MachineOperand &Dest = MI.getOperand(0); 4018 MachineOperand &CarryDest = MI.getOperand(1); 4019 MachineOperand &Src0 = MI.getOperand(2); 4020 MachineOperand &Src1 = MI.getOperand(3); 4021 MachineOperand &Src2 = MI.getOperand(4); 4022 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4023 ? AMDGPU::S_ADDC_U32 4024 : AMDGPU::S_SUBB_U32; 4025 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4026 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4027 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4028 .addReg(Src0.getReg()); 4029 Src0.setReg(RegOp0); 4030 } 4031 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4032 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4033 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4034 .addReg(Src1.getReg()); 4035 Src1.setReg(RegOp1); 4036 } 4037 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4038 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4039 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4040 .addReg(Src2.getReg()); 4041 Src2.setReg(RegOp2); 4042 } 4043 4044 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4045 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4046 if (ST.hasScalarCompareEq64()) { 4047 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4048 .addReg(Src2.getReg()) 4049 .addImm(0); 4050 } else { 4051 const TargetRegisterClass *SubRC = 4052 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4053 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4054 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4055 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4056 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4057 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4058 4059 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4060 .add(Src2Sub0) 4061 .add(Src2Sub1); 4062 4063 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4064 .addReg(Src2_32, RegState::Kill) 4065 .addImm(0); 4066 } 4067 } else { 4068 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4069 .addReg(Src2.getReg()) 4070 .addImm(0); 4071 } 4072 4073 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4074 4075 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4076 .addReg(AMDGPU::SCC); 4077 MI.eraseFromParent(); 4078 return BB; 4079 } 4080 case AMDGPU::SI_INIT_M0: { 4081 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4082 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4083 .add(MI.getOperand(0)); 4084 MI.eraseFromParent(); 4085 return BB; 4086 } 4087 case AMDGPU::GET_GROUPSTATICSIZE: { 4088 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4089 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4090 DebugLoc DL = MI.getDebugLoc(); 4091 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4092 .add(MI.getOperand(0)) 4093 .addImm(MFI->getLDSSize()); 4094 MI.eraseFromParent(); 4095 return BB; 4096 } 4097 case AMDGPU::SI_INDIRECT_SRC_V1: 4098 case AMDGPU::SI_INDIRECT_SRC_V2: 4099 case AMDGPU::SI_INDIRECT_SRC_V4: 4100 case AMDGPU::SI_INDIRECT_SRC_V8: 4101 case AMDGPU::SI_INDIRECT_SRC_V16: 4102 case AMDGPU::SI_INDIRECT_SRC_V32: 4103 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4104 case AMDGPU::SI_INDIRECT_DST_V1: 4105 case AMDGPU::SI_INDIRECT_DST_V2: 4106 case AMDGPU::SI_INDIRECT_DST_V4: 4107 case AMDGPU::SI_INDIRECT_DST_V8: 4108 case AMDGPU::SI_INDIRECT_DST_V16: 4109 case AMDGPU::SI_INDIRECT_DST_V32: 4110 return emitIndirectDst(MI, *BB, *getSubtarget()); 4111 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4112 case AMDGPU::SI_KILL_I1_PSEUDO: 4113 return splitKillBlock(MI, BB); 4114 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4115 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4116 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4117 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4118 4119 Register Dst = MI.getOperand(0).getReg(); 4120 Register Src0 = MI.getOperand(1).getReg(); 4121 Register Src1 = MI.getOperand(2).getReg(); 4122 const DebugLoc &DL = MI.getDebugLoc(); 4123 Register SrcCond = MI.getOperand(3).getReg(); 4124 4125 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4126 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4127 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4128 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4129 4130 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4131 .addReg(SrcCond); 4132 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4133 .addImm(0) 4134 .addReg(Src0, 0, AMDGPU::sub0) 4135 .addImm(0) 4136 .addReg(Src1, 0, AMDGPU::sub0) 4137 .addReg(SrcCondCopy); 4138 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4139 .addImm(0) 4140 .addReg(Src0, 0, AMDGPU::sub1) 4141 .addImm(0) 4142 .addReg(Src1, 0, AMDGPU::sub1) 4143 .addReg(SrcCondCopy); 4144 4145 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4146 .addReg(DstLo) 4147 .addImm(AMDGPU::sub0) 4148 .addReg(DstHi) 4149 .addImm(AMDGPU::sub1); 4150 MI.eraseFromParent(); 4151 return BB; 4152 } 4153 case AMDGPU::SI_BR_UNDEF: { 4154 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4155 const DebugLoc &DL = MI.getDebugLoc(); 4156 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4157 .add(MI.getOperand(0)); 4158 Br->getOperand(1).setIsUndef(true); // read undef SCC 4159 MI.eraseFromParent(); 4160 return BB; 4161 } 4162 case AMDGPU::ADJCALLSTACKUP: 4163 case AMDGPU::ADJCALLSTACKDOWN: { 4164 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4165 MachineInstrBuilder MIB(*MF, &MI); 4166 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4167 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4168 return BB; 4169 } 4170 case AMDGPU::SI_CALL_ISEL: { 4171 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4172 const DebugLoc &DL = MI.getDebugLoc(); 4173 4174 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4175 4176 MachineInstrBuilder MIB; 4177 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4178 4179 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4180 MIB.add(MI.getOperand(I)); 4181 4182 MIB.cloneMemRefs(MI); 4183 MI.eraseFromParent(); 4184 return BB; 4185 } 4186 case AMDGPU::V_ADD_CO_U32_e32: 4187 case AMDGPU::V_SUB_CO_U32_e32: 4188 case AMDGPU::V_SUBREV_CO_U32_e32: { 4189 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4190 const DebugLoc &DL = MI.getDebugLoc(); 4191 unsigned Opc = MI.getOpcode(); 4192 4193 bool NeedClampOperand = false; 4194 if (TII->pseudoToMCOpcode(Opc) == -1) { 4195 Opc = AMDGPU::getVOPe64(Opc); 4196 NeedClampOperand = true; 4197 } 4198 4199 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4200 if (TII->isVOP3(*I)) { 4201 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4202 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4203 I.addReg(TRI->getVCC(), RegState::Define); 4204 } 4205 I.add(MI.getOperand(1)) 4206 .add(MI.getOperand(2)); 4207 if (NeedClampOperand) 4208 I.addImm(0); // clamp bit for e64 encoding 4209 4210 TII->legalizeOperands(*I); 4211 4212 MI.eraseFromParent(); 4213 return BB; 4214 } 4215 case AMDGPU::DS_GWS_INIT: 4216 case AMDGPU::DS_GWS_SEMA_V: 4217 case AMDGPU::DS_GWS_SEMA_BR: 4218 case AMDGPU::DS_GWS_SEMA_P: 4219 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4220 case AMDGPU::DS_GWS_BARRIER: 4221 // A s_waitcnt 0 is required to be the instruction immediately following. 4222 if (getSubtarget()->hasGWSAutoReplay()) { 4223 bundleInstWithWaitcnt(MI); 4224 return BB; 4225 } 4226 4227 return emitGWSMemViolTestLoop(MI, BB); 4228 case AMDGPU::S_SETREG_B32: { 4229 // Try to optimize cases that only set the denormal mode or rounding mode. 4230 // 4231 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4232 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4233 // instead. 4234 // 4235 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4236 // allow you to have a no side effect instruction in the output of a 4237 // sideeffecting pattern. 4238 unsigned ID, Offset, Width; 4239 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4240 if (ID != AMDGPU::Hwreg::ID_MODE) 4241 return BB; 4242 4243 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4244 const unsigned SetMask = WidthMask << Offset; 4245 4246 if (getSubtarget()->hasDenormModeInst()) { 4247 unsigned SetDenormOp = 0; 4248 unsigned SetRoundOp = 0; 4249 4250 // The dedicated instructions can only set the whole denorm or round mode 4251 // at once, not a subset of bits in either. 4252 if (SetMask == 4253 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4254 // If this fully sets both the round and denorm mode, emit the two 4255 // dedicated instructions for these. 4256 SetRoundOp = AMDGPU::S_ROUND_MODE; 4257 SetDenormOp = AMDGPU::S_DENORM_MODE; 4258 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4259 SetRoundOp = AMDGPU::S_ROUND_MODE; 4260 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4261 SetDenormOp = AMDGPU::S_DENORM_MODE; 4262 } 4263 4264 if (SetRoundOp || SetDenormOp) { 4265 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4266 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4267 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4268 unsigned ImmVal = Def->getOperand(1).getImm(); 4269 if (SetRoundOp) { 4270 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4271 .addImm(ImmVal & 0xf); 4272 4273 // If we also have the denorm mode, get just the denorm mode bits. 4274 ImmVal >>= 4; 4275 } 4276 4277 if (SetDenormOp) { 4278 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4279 .addImm(ImmVal & 0xf); 4280 } 4281 4282 MI.eraseFromParent(); 4283 return BB; 4284 } 4285 } 4286 } 4287 4288 // If only FP bits are touched, used the no side effects pseudo. 4289 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4290 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4291 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4292 4293 return BB; 4294 } 4295 default: 4296 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4297 } 4298 } 4299 4300 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4301 return isTypeLegal(VT.getScalarType()); 4302 } 4303 4304 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4305 // This currently forces unfolding various combinations of fsub into fma with 4306 // free fneg'd operands. As long as we have fast FMA (controlled by 4307 // isFMAFasterThanFMulAndFAdd), we should perform these. 4308 4309 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4310 // most of these combines appear to be cycle neutral but save on instruction 4311 // count / code size. 4312 return true; 4313 } 4314 4315 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4316 EVT VT) const { 4317 if (!VT.isVector()) { 4318 return MVT::i1; 4319 } 4320 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4321 } 4322 4323 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4324 // TODO: Should i16 be used always if legal? For now it would force VALU 4325 // shifts. 4326 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4327 } 4328 4329 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4330 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4331 ? Ty.changeElementSize(16) 4332 : Ty.changeElementSize(32); 4333 } 4334 4335 // Answering this is somewhat tricky and depends on the specific device which 4336 // have different rates for fma or all f64 operations. 4337 // 4338 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4339 // regardless of which device (although the number of cycles differs between 4340 // devices), so it is always profitable for f64. 4341 // 4342 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4343 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4344 // which we can always do even without fused FP ops since it returns the same 4345 // result as the separate operations and since it is always full 4346 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4347 // however does not support denormals, so we do report fma as faster if we have 4348 // a fast fma device and require denormals. 4349 // 4350 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4351 EVT VT) const { 4352 VT = VT.getScalarType(); 4353 4354 switch (VT.getSimpleVT().SimpleTy) { 4355 case MVT::f32: { 4356 // If mad is not available this depends only on if f32 fma is full rate. 4357 if (!Subtarget->hasMadMacF32Insts()) 4358 return Subtarget->hasFastFMAF32(); 4359 4360 // Otherwise f32 mad is always full rate and returns the same result as 4361 // the separate operations so should be preferred over fma. 4362 // However does not support denomals. 4363 if (hasFP32Denormals(MF)) 4364 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4365 4366 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4367 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4368 } 4369 case MVT::f64: 4370 return true; 4371 case MVT::f16: 4372 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4373 default: 4374 break; 4375 } 4376 4377 return false; 4378 } 4379 4380 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4381 const SDNode *N) const { 4382 // TODO: Check future ftz flag 4383 // v_mad_f32/v_mac_f32 do not support denormals. 4384 EVT VT = N->getValueType(0); 4385 if (VT == MVT::f32) 4386 return Subtarget->hasMadMacF32Insts() && 4387 !hasFP32Denormals(DAG.getMachineFunction()); 4388 if (VT == MVT::f16) { 4389 return Subtarget->hasMadF16() && 4390 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4391 } 4392 4393 return false; 4394 } 4395 4396 //===----------------------------------------------------------------------===// 4397 // Custom DAG Lowering Operations 4398 //===----------------------------------------------------------------------===// 4399 4400 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4401 // wider vector type is legal. 4402 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4403 SelectionDAG &DAG) const { 4404 unsigned Opc = Op.getOpcode(); 4405 EVT VT = Op.getValueType(); 4406 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4407 4408 SDValue Lo, Hi; 4409 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4410 4411 SDLoc SL(Op); 4412 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4413 Op->getFlags()); 4414 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4415 Op->getFlags()); 4416 4417 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4418 } 4419 4420 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4421 // wider vector type is legal. 4422 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4423 SelectionDAG &DAG) const { 4424 unsigned Opc = Op.getOpcode(); 4425 EVT VT = Op.getValueType(); 4426 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4427 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4428 4429 SDValue Lo0, Hi0; 4430 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4431 SDValue Lo1, Hi1; 4432 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4433 4434 SDLoc SL(Op); 4435 4436 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4437 Op->getFlags()); 4438 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4439 Op->getFlags()); 4440 4441 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4442 } 4443 4444 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4445 SelectionDAG &DAG) const { 4446 unsigned Opc = Op.getOpcode(); 4447 EVT VT = Op.getValueType(); 4448 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4449 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4450 4451 SDValue Lo0, Hi0; 4452 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4453 SDValue Lo1, Hi1; 4454 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4455 SDValue Lo2, Hi2; 4456 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4457 4458 SDLoc SL(Op); 4459 4460 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4461 Op->getFlags()); 4462 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4463 Op->getFlags()); 4464 4465 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4466 } 4467 4468 4469 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4470 switch (Op.getOpcode()) { 4471 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4472 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4473 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4474 case ISD::LOAD: { 4475 SDValue Result = LowerLOAD(Op, DAG); 4476 assert((!Result.getNode() || 4477 Result.getNode()->getNumValues() == 2) && 4478 "Load should return a value and a chain"); 4479 return Result; 4480 } 4481 4482 case ISD::FSIN: 4483 case ISD::FCOS: 4484 return LowerTrig(Op, DAG); 4485 case ISD::SELECT: return LowerSELECT(Op, DAG); 4486 case ISD::FDIV: return LowerFDIV(Op, DAG); 4487 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4488 case ISD::STORE: return LowerSTORE(Op, DAG); 4489 case ISD::GlobalAddress: { 4490 MachineFunction &MF = DAG.getMachineFunction(); 4491 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4492 return LowerGlobalAddress(MFI, Op, DAG); 4493 } 4494 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4495 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4496 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4497 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4498 case ISD::INSERT_SUBVECTOR: 4499 return lowerINSERT_SUBVECTOR(Op, DAG); 4500 case ISD::INSERT_VECTOR_ELT: 4501 return lowerINSERT_VECTOR_ELT(Op, DAG); 4502 case ISD::EXTRACT_VECTOR_ELT: 4503 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4504 case ISD::VECTOR_SHUFFLE: 4505 return lowerVECTOR_SHUFFLE(Op, DAG); 4506 case ISD::BUILD_VECTOR: 4507 return lowerBUILD_VECTOR(Op, DAG); 4508 case ISD::FP_ROUND: 4509 return lowerFP_ROUND(Op, DAG); 4510 case ISD::TRAP: 4511 return lowerTRAP(Op, DAG); 4512 case ISD::DEBUGTRAP: 4513 return lowerDEBUGTRAP(Op, DAG); 4514 case ISD::FABS: 4515 case ISD::FNEG: 4516 case ISD::FCANONICALIZE: 4517 case ISD::BSWAP: 4518 return splitUnaryVectorOp(Op, DAG); 4519 case ISD::FMINNUM: 4520 case ISD::FMAXNUM: 4521 return lowerFMINNUM_FMAXNUM(Op, DAG); 4522 case ISD::FMA: 4523 return splitTernaryVectorOp(Op, DAG); 4524 case ISD::SHL: 4525 case ISD::SRA: 4526 case ISD::SRL: 4527 case ISD::ADD: 4528 case ISD::SUB: 4529 case ISD::MUL: 4530 case ISD::SMIN: 4531 case ISD::SMAX: 4532 case ISD::UMIN: 4533 case ISD::UMAX: 4534 case ISD::FADD: 4535 case ISD::FMUL: 4536 case ISD::FMINNUM_IEEE: 4537 case ISD::FMAXNUM_IEEE: 4538 case ISD::UADDSAT: 4539 case ISD::USUBSAT: 4540 case ISD::SADDSAT: 4541 case ISD::SSUBSAT: 4542 return splitBinaryVectorOp(Op, DAG); 4543 case ISD::SMULO: 4544 case ISD::UMULO: 4545 return lowerXMULO(Op, DAG); 4546 case ISD::DYNAMIC_STACKALLOC: 4547 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4548 } 4549 return SDValue(); 4550 } 4551 4552 // Used for D16: Casts the result of an instruction into the right vector, 4553 // packs values if loads return unpacked values. 4554 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4555 const SDLoc &DL, 4556 SelectionDAG &DAG, bool Unpacked) { 4557 if (!LoadVT.isVector()) 4558 return Result; 4559 4560 // Cast back to the original packed type or to a larger type that is a 4561 // multiple of 32 bit for D16. Widening the return type is a required for 4562 // legalization. 4563 EVT FittingLoadVT = LoadVT; 4564 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4565 FittingLoadVT = 4566 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4567 LoadVT.getVectorNumElements() + 1); 4568 } 4569 4570 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4571 // Truncate to v2i16/v4i16. 4572 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4573 4574 // Workaround legalizer not scalarizing truncate after vector op 4575 // legalization but not creating intermediate vector trunc. 4576 SmallVector<SDValue, 4> Elts; 4577 DAG.ExtractVectorElements(Result, Elts); 4578 for (SDValue &Elt : Elts) 4579 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4580 4581 // Pad illegal v1i16/v3fi6 to v4i16 4582 if ((LoadVT.getVectorNumElements() % 2) == 1) 4583 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4584 4585 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4586 4587 // Bitcast to original type (v2f16/v4f16). 4588 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4589 } 4590 4591 // Cast back to the original packed type. 4592 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4593 } 4594 4595 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4596 MemSDNode *M, 4597 SelectionDAG &DAG, 4598 ArrayRef<SDValue> Ops, 4599 bool IsIntrinsic) const { 4600 SDLoc DL(M); 4601 4602 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4603 EVT LoadVT = M->getValueType(0); 4604 4605 EVT EquivLoadVT = LoadVT; 4606 if (LoadVT.isVector()) { 4607 if (Unpacked) { 4608 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4609 LoadVT.getVectorNumElements()); 4610 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4611 // Widen v3f16 to legal type 4612 EquivLoadVT = 4613 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4614 LoadVT.getVectorNumElements() + 1); 4615 } 4616 } 4617 4618 // Change from v4f16/v2f16 to EquivLoadVT. 4619 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4620 4621 SDValue Load 4622 = DAG.getMemIntrinsicNode( 4623 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4624 VTList, Ops, M->getMemoryVT(), 4625 M->getMemOperand()); 4626 4627 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4628 4629 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4630 } 4631 4632 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4633 SelectionDAG &DAG, 4634 ArrayRef<SDValue> Ops) const { 4635 SDLoc DL(M); 4636 EVT LoadVT = M->getValueType(0); 4637 EVT EltType = LoadVT.getScalarType(); 4638 EVT IntVT = LoadVT.changeTypeToInteger(); 4639 4640 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4641 4642 unsigned Opc = 4643 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4644 4645 if (IsD16) { 4646 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4647 } 4648 4649 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4650 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4651 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4652 4653 if (isTypeLegal(LoadVT)) { 4654 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4655 M->getMemOperand(), DAG); 4656 } 4657 4658 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4659 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4660 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4661 M->getMemOperand(), DAG); 4662 return DAG.getMergeValues( 4663 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4664 DL); 4665 } 4666 4667 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4668 SDNode *N, SelectionDAG &DAG) { 4669 EVT VT = N->getValueType(0); 4670 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4671 unsigned CondCode = CD->getZExtValue(); 4672 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4673 return DAG.getUNDEF(VT); 4674 4675 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4676 4677 SDValue LHS = N->getOperand(1); 4678 SDValue RHS = N->getOperand(2); 4679 4680 SDLoc DL(N); 4681 4682 EVT CmpVT = LHS.getValueType(); 4683 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4684 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4685 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4686 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4687 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4688 } 4689 4690 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4691 4692 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4693 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4694 4695 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4696 DAG.getCondCode(CCOpcode)); 4697 if (VT.bitsEq(CCVT)) 4698 return SetCC; 4699 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4700 } 4701 4702 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4703 SDNode *N, SelectionDAG &DAG) { 4704 EVT VT = N->getValueType(0); 4705 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4706 4707 unsigned CondCode = CD->getZExtValue(); 4708 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4709 return DAG.getUNDEF(VT); 4710 4711 SDValue Src0 = N->getOperand(1); 4712 SDValue Src1 = N->getOperand(2); 4713 EVT CmpVT = Src0.getValueType(); 4714 SDLoc SL(N); 4715 4716 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4717 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4718 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4719 } 4720 4721 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4722 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4723 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4724 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4725 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4726 Src1, DAG.getCondCode(CCOpcode)); 4727 if (VT.bitsEq(CCVT)) 4728 return SetCC; 4729 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4730 } 4731 4732 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4733 SelectionDAG &DAG) { 4734 EVT VT = N->getValueType(0); 4735 SDValue Src = N->getOperand(1); 4736 SDLoc SL(N); 4737 4738 if (Src.getOpcode() == ISD::SETCC) { 4739 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4740 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4741 Src.getOperand(1), Src.getOperand(2)); 4742 } 4743 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4744 // (ballot 0) -> 0 4745 if (Arg->isNullValue()) 4746 return DAG.getConstant(0, SL, VT); 4747 4748 // (ballot 1) -> EXEC/EXEC_LO 4749 if (Arg->isOne()) { 4750 Register Exec; 4751 if (VT.getScalarSizeInBits() == 32) 4752 Exec = AMDGPU::EXEC_LO; 4753 else if (VT.getScalarSizeInBits() == 64) 4754 Exec = AMDGPU::EXEC; 4755 else 4756 return SDValue(); 4757 4758 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4759 } 4760 } 4761 4762 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4763 // ISD::SETNE) 4764 return DAG.getNode( 4765 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4766 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4767 } 4768 4769 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4770 SmallVectorImpl<SDValue> &Results, 4771 SelectionDAG &DAG) const { 4772 switch (N->getOpcode()) { 4773 case ISD::INSERT_VECTOR_ELT: { 4774 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4775 Results.push_back(Res); 4776 return; 4777 } 4778 case ISD::EXTRACT_VECTOR_ELT: { 4779 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4780 Results.push_back(Res); 4781 return; 4782 } 4783 case ISD::INTRINSIC_WO_CHAIN: { 4784 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4785 switch (IID) { 4786 case Intrinsic::amdgcn_cvt_pkrtz: { 4787 SDValue Src0 = N->getOperand(1); 4788 SDValue Src1 = N->getOperand(2); 4789 SDLoc SL(N); 4790 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4791 Src0, Src1); 4792 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4793 return; 4794 } 4795 case Intrinsic::amdgcn_cvt_pknorm_i16: 4796 case Intrinsic::amdgcn_cvt_pknorm_u16: 4797 case Intrinsic::amdgcn_cvt_pk_i16: 4798 case Intrinsic::amdgcn_cvt_pk_u16: { 4799 SDValue Src0 = N->getOperand(1); 4800 SDValue Src1 = N->getOperand(2); 4801 SDLoc SL(N); 4802 unsigned Opcode; 4803 4804 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4805 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4806 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4807 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4808 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4809 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4810 else 4811 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4812 4813 EVT VT = N->getValueType(0); 4814 if (isTypeLegal(VT)) 4815 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4816 else { 4817 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4818 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4819 } 4820 return; 4821 } 4822 } 4823 break; 4824 } 4825 case ISD::INTRINSIC_W_CHAIN: { 4826 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4827 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4828 // FIXME: Hacky 4829 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4830 Results.push_back(Res.getOperand(I)); 4831 } 4832 } else { 4833 Results.push_back(Res); 4834 Results.push_back(Res.getValue(1)); 4835 } 4836 return; 4837 } 4838 4839 break; 4840 } 4841 case ISD::SELECT: { 4842 SDLoc SL(N); 4843 EVT VT = N->getValueType(0); 4844 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4845 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4846 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4847 4848 EVT SelectVT = NewVT; 4849 if (NewVT.bitsLT(MVT::i32)) { 4850 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4851 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4852 SelectVT = MVT::i32; 4853 } 4854 4855 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4856 N->getOperand(0), LHS, RHS); 4857 4858 if (NewVT != SelectVT) 4859 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4860 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4861 return; 4862 } 4863 case ISD::FNEG: { 4864 if (N->getValueType(0) != MVT::v2f16) 4865 break; 4866 4867 SDLoc SL(N); 4868 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4869 4870 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4871 BC, 4872 DAG.getConstant(0x80008000, SL, MVT::i32)); 4873 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4874 return; 4875 } 4876 case ISD::FABS: { 4877 if (N->getValueType(0) != MVT::v2f16) 4878 break; 4879 4880 SDLoc SL(N); 4881 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4882 4883 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4884 BC, 4885 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4886 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4887 return; 4888 } 4889 default: 4890 break; 4891 } 4892 } 4893 4894 /// Helper function for LowerBRCOND 4895 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4896 4897 SDNode *Parent = Value.getNode(); 4898 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4899 I != E; ++I) { 4900 4901 if (I.getUse().get() != Value) 4902 continue; 4903 4904 if (I->getOpcode() == Opcode) 4905 return *I; 4906 } 4907 return nullptr; 4908 } 4909 4910 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4911 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4912 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4913 case Intrinsic::amdgcn_if: 4914 return AMDGPUISD::IF; 4915 case Intrinsic::amdgcn_else: 4916 return AMDGPUISD::ELSE; 4917 case Intrinsic::amdgcn_loop: 4918 return AMDGPUISD::LOOP; 4919 case Intrinsic::amdgcn_end_cf: 4920 llvm_unreachable("should not occur"); 4921 default: 4922 return 0; 4923 } 4924 } 4925 4926 // break, if_break, else_break are all only used as inputs to loop, not 4927 // directly as branch conditions. 4928 return 0; 4929 } 4930 4931 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4932 const Triple &TT = getTargetMachine().getTargetTriple(); 4933 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4934 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4935 AMDGPU::shouldEmitConstantsToTextSection(TT); 4936 } 4937 4938 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4939 // FIXME: Either avoid relying on address space here or change the default 4940 // address space for functions to avoid the explicit check. 4941 return (GV->getValueType()->isFunctionTy() || 4942 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4943 !shouldEmitFixup(GV) && 4944 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4945 } 4946 4947 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4948 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4949 } 4950 4951 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4952 if (!GV->hasExternalLinkage()) 4953 return true; 4954 4955 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4956 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4957 } 4958 4959 /// This transforms the control flow intrinsics to get the branch destination as 4960 /// last parameter, also switches branch target with BR if the need arise 4961 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4962 SelectionDAG &DAG) const { 4963 SDLoc DL(BRCOND); 4964 4965 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4966 SDValue Target = BRCOND.getOperand(2); 4967 SDNode *BR = nullptr; 4968 SDNode *SetCC = nullptr; 4969 4970 if (Intr->getOpcode() == ISD::SETCC) { 4971 // As long as we negate the condition everything is fine 4972 SetCC = Intr; 4973 Intr = SetCC->getOperand(0).getNode(); 4974 4975 } else { 4976 // Get the target from BR if we don't negate the condition 4977 BR = findUser(BRCOND, ISD::BR); 4978 assert(BR && "brcond missing unconditional branch user"); 4979 Target = BR->getOperand(1); 4980 } 4981 4982 unsigned CFNode = isCFIntrinsic(Intr); 4983 if (CFNode == 0) { 4984 // This is a uniform branch so we don't need to legalize. 4985 return BRCOND; 4986 } 4987 4988 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4989 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4990 4991 assert(!SetCC || 4992 (SetCC->getConstantOperandVal(1) == 1 && 4993 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4994 ISD::SETNE)); 4995 4996 // operands of the new intrinsic call 4997 SmallVector<SDValue, 4> Ops; 4998 if (HaveChain) 4999 Ops.push_back(BRCOND.getOperand(0)); 5000 5001 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5002 Ops.push_back(Target); 5003 5004 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5005 5006 // build the new intrinsic call 5007 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5008 5009 if (!HaveChain) { 5010 SDValue Ops[] = { 5011 SDValue(Result, 0), 5012 BRCOND.getOperand(0) 5013 }; 5014 5015 Result = DAG.getMergeValues(Ops, DL).getNode(); 5016 } 5017 5018 if (BR) { 5019 // Give the branch instruction our target 5020 SDValue Ops[] = { 5021 BR->getOperand(0), 5022 BRCOND.getOperand(2) 5023 }; 5024 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5025 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5026 } 5027 5028 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5029 5030 // Copy the intrinsic results to registers 5031 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5032 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5033 if (!CopyToReg) 5034 continue; 5035 5036 Chain = DAG.getCopyToReg( 5037 Chain, DL, 5038 CopyToReg->getOperand(1), 5039 SDValue(Result, i - 1), 5040 SDValue()); 5041 5042 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5043 } 5044 5045 // Remove the old intrinsic from the chain 5046 DAG.ReplaceAllUsesOfValueWith( 5047 SDValue(Intr, Intr->getNumValues() - 1), 5048 Intr->getOperand(0)); 5049 5050 return Chain; 5051 } 5052 5053 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5054 SelectionDAG &DAG) const { 5055 MVT VT = Op.getSimpleValueType(); 5056 SDLoc DL(Op); 5057 // Checking the depth 5058 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5059 return DAG.getConstant(0, DL, VT); 5060 5061 MachineFunction &MF = DAG.getMachineFunction(); 5062 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5063 // Check for kernel and shader functions 5064 if (Info->isEntryFunction()) 5065 return DAG.getConstant(0, DL, VT); 5066 5067 MachineFrameInfo &MFI = MF.getFrameInfo(); 5068 // There is a call to @llvm.returnaddress in this function 5069 MFI.setReturnAddressIsTaken(true); 5070 5071 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5072 // Get the return address reg and mark it as an implicit live-in 5073 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5074 5075 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5076 } 5077 5078 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5079 SDValue Op, 5080 const SDLoc &DL, 5081 EVT VT) const { 5082 return Op.getValueType().bitsLE(VT) ? 5083 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5084 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5085 DAG.getTargetConstant(0, DL, MVT::i32)); 5086 } 5087 5088 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5089 assert(Op.getValueType() == MVT::f16 && 5090 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5091 5092 SDValue Src = Op.getOperand(0); 5093 EVT SrcVT = Src.getValueType(); 5094 if (SrcVT != MVT::f64) 5095 return Op; 5096 5097 SDLoc DL(Op); 5098 5099 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5100 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5101 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5102 } 5103 5104 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5105 SelectionDAG &DAG) const { 5106 EVT VT = Op.getValueType(); 5107 const MachineFunction &MF = DAG.getMachineFunction(); 5108 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5109 bool IsIEEEMode = Info->getMode().IEEE; 5110 5111 // FIXME: Assert during selection that this is only selected for 5112 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5113 // mode functions, but this happens to be OK since it's only done in cases 5114 // where there is known no sNaN. 5115 if (IsIEEEMode) 5116 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5117 5118 if (VT == MVT::v4f16) 5119 return splitBinaryVectorOp(Op, DAG); 5120 return Op; 5121 } 5122 5123 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5124 EVT VT = Op.getValueType(); 5125 SDLoc SL(Op); 5126 SDValue LHS = Op.getOperand(0); 5127 SDValue RHS = Op.getOperand(1); 5128 bool isSigned = Op.getOpcode() == ISD::SMULO; 5129 5130 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5131 const APInt &C = RHSC->getAPIntValue(); 5132 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5133 if (C.isPowerOf2()) { 5134 // smulo(x, signed_min) is same as umulo(x, signed_min). 5135 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5136 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5137 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5138 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5139 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5140 SL, VT, Result, ShiftAmt), 5141 LHS, ISD::SETNE); 5142 return DAG.getMergeValues({ Result, Overflow }, SL); 5143 } 5144 } 5145 5146 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5147 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5148 SL, VT, LHS, RHS); 5149 5150 SDValue Sign = isSigned 5151 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5152 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5153 : DAG.getConstant(0, SL, VT); 5154 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5155 5156 return DAG.getMergeValues({ Result, Overflow }, SL); 5157 } 5158 5159 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5160 SDLoc SL(Op); 5161 SDValue Chain = Op.getOperand(0); 5162 5163 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5164 !Subtarget->isTrapHandlerEnabled()) 5165 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5166 5167 MachineFunction &MF = DAG.getMachineFunction(); 5168 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5169 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5170 assert(UserSGPR != AMDGPU::NoRegister); 5171 SDValue QueuePtr = CreateLiveInRegister( 5172 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5173 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5174 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5175 QueuePtr, SDValue()); 5176 SDValue Ops[] = { 5177 ToReg, 5178 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5179 SGPR01, 5180 ToReg.getValue(1) 5181 }; 5182 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5183 } 5184 5185 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5186 SDLoc SL(Op); 5187 SDValue Chain = Op.getOperand(0); 5188 MachineFunction &MF = DAG.getMachineFunction(); 5189 5190 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5191 !Subtarget->isTrapHandlerEnabled()) { 5192 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5193 "debugtrap handler not supported", 5194 Op.getDebugLoc(), 5195 DS_Warning); 5196 LLVMContext &Ctx = MF.getFunction().getContext(); 5197 Ctx.diagnose(NoTrap); 5198 return Chain; 5199 } 5200 5201 SDValue Ops[] = { 5202 Chain, 5203 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5204 }; 5205 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5206 } 5207 5208 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5209 SelectionDAG &DAG) const { 5210 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5211 if (Subtarget->hasApertureRegs()) { 5212 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5213 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5214 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5215 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5216 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5217 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5218 unsigned Encoding = 5219 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5220 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5221 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5222 5223 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5224 SDValue ApertureReg = SDValue( 5225 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5226 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5227 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5228 } 5229 5230 MachineFunction &MF = DAG.getMachineFunction(); 5231 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5232 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5233 assert(UserSGPR != AMDGPU::NoRegister); 5234 5235 SDValue QueuePtr = CreateLiveInRegister( 5236 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5237 5238 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5239 // private_segment_aperture_base_hi. 5240 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5241 5242 SDValue Ptr = 5243 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5244 5245 // TODO: Use custom target PseudoSourceValue. 5246 // TODO: We should use the value from the IR intrinsic call, but it might not 5247 // be available and how do we get it? 5248 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5249 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5250 commonAlignment(Align(64), StructOffset), 5251 MachineMemOperand::MODereferenceable | 5252 MachineMemOperand::MOInvariant); 5253 } 5254 5255 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5256 SelectionDAG &DAG) const { 5257 SDLoc SL(Op); 5258 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5259 5260 SDValue Src = ASC->getOperand(0); 5261 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5262 5263 const AMDGPUTargetMachine &TM = 5264 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5265 5266 // flat -> local/private 5267 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5268 unsigned DestAS = ASC->getDestAddressSpace(); 5269 5270 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5271 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5272 unsigned NullVal = TM.getNullPointerValue(DestAS); 5273 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5274 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5275 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5276 5277 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5278 NonNull, Ptr, SegmentNullPtr); 5279 } 5280 } 5281 5282 // local/private -> flat 5283 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5284 unsigned SrcAS = ASC->getSrcAddressSpace(); 5285 5286 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5287 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5288 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5289 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5290 5291 SDValue NonNull 5292 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5293 5294 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5295 SDValue CvtPtr 5296 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5297 5298 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5299 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5300 FlatNullPtr); 5301 } 5302 } 5303 5304 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5305 Src.getValueType() == MVT::i64) 5306 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5307 5308 // global <-> flat are no-ops and never emitted. 5309 5310 const MachineFunction &MF = DAG.getMachineFunction(); 5311 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5312 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5313 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5314 5315 return DAG.getUNDEF(ASC->getValueType(0)); 5316 } 5317 5318 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5319 // the small vector and inserting them into the big vector. That is better than 5320 // the default expansion of doing it via a stack slot. Even though the use of 5321 // the stack slot would be optimized away afterwards, the stack slot itself 5322 // remains. 5323 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5324 SelectionDAG &DAG) const { 5325 SDValue Vec = Op.getOperand(0); 5326 SDValue Ins = Op.getOperand(1); 5327 SDValue Idx = Op.getOperand(2); 5328 EVT VecVT = Vec.getValueType(); 5329 EVT InsVT = Ins.getValueType(); 5330 EVT EltVT = VecVT.getVectorElementType(); 5331 unsigned InsNumElts = InsVT.getVectorNumElements(); 5332 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5333 SDLoc SL(Op); 5334 5335 for (unsigned I = 0; I != InsNumElts; ++I) { 5336 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5337 DAG.getConstant(I, SL, MVT::i32)); 5338 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5339 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5340 } 5341 return Vec; 5342 } 5343 5344 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5345 SelectionDAG &DAG) const { 5346 SDValue Vec = Op.getOperand(0); 5347 SDValue InsVal = Op.getOperand(1); 5348 SDValue Idx = Op.getOperand(2); 5349 EVT VecVT = Vec.getValueType(); 5350 EVT EltVT = VecVT.getVectorElementType(); 5351 unsigned VecSize = VecVT.getSizeInBits(); 5352 unsigned EltSize = EltVT.getSizeInBits(); 5353 5354 5355 assert(VecSize <= 64); 5356 5357 unsigned NumElts = VecVT.getVectorNumElements(); 5358 SDLoc SL(Op); 5359 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5360 5361 if (NumElts == 4 && EltSize == 16 && KIdx) { 5362 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5363 5364 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5365 DAG.getConstant(0, SL, MVT::i32)); 5366 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5367 DAG.getConstant(1, SL, MVT::i32)); 5368 5369 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5370 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5371 5372 unsigned Idx = KIdx->getZExtValue(); 5373 bool InsertLo = Idx < 2; 5374 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5375 InsertLo ? LoVec : HiVec, 5376 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5377 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5378 5379 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5380 5381 SDValue Concat = InsertLo ? 5382 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5383 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5384 5385 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5386 } 5387 5388 if (isa<ConstantSDNode>(Idx)) 5389 return SDValue(); 5390 5391 MVT IntVT = MVT::getIntegerVT(VecSize); 5392 5393 // Avoid stack access for dynamic indexing. 5394 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5395 5396 // Create a congruent vector with the target value in each element so that 5397 // the required element can be masked and ORed into the target vector. 5398 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5399 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5400 5401 assert(isPowerOf2_32(EltSize)); 5402 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5403 5404 // Convert vector index to bit-index. 5405 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5406 5407 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5408 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5409 DAG.getConstant(0xffff, SL, IntVT), 5410 ScaledIdx); 5411 5412 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5413 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5414 DAG.getNOT(SL, BFM, IntVT), BCVec); 5415 5416 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5417 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5418 } 5419 5420 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5421 SelectionDAG &DAG) const { 5422 SDLoc SL(Op); 5423 5424 EVT ResultVT = Op.getValueType(); 5425 SDValue Vec = Op.getOperand(0); 5426 SDValue Idx = Op.getOperand(1); 5427 EVT VecVT = Vec.getValueType(); 5428 unsigned VecSize = VecVT.getSizeInBits(); 5429 EVT EltVT = VecVT.getVectorElementType(); 5430 assert(VecSize <= 64); 5431 5432 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5433 5434 // Make sure we do any optimizations that will make it easier to fold 5435 // source modifiers before obscuring it with bit operations. 5436 5437 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5438 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5439 return Combined; 5440 5441 unsigned EltSize = EltVT.getSizeInBits(); 5442 assert(isPowerOf2_32(EltSize)); 5443 5444 MVT IntVT = MVT::getIntegerVT(VecSize); 5445 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5446 5447 // Convert vector index to bit-index (* EltSize) 5448 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5449 5450 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5451 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5452 5453 if (ResultVT == MVT::f16) { 5454 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5455 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5456 } 5457 5458 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5459 } 5460 5461 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5462 assert(Elt % 2 == 0); 5463 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5464 } 5465 5466 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5467 SelectionDAG &DAG) const { 5468 SDLoc SL(Op); 5469 EVT ResultVT = Op.getValueType(); 5470 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5471 5472 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5473 EVT EltVT = PackVT.getVectorElementType(); 5474 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5475 5476 // vector_shuffle <0,1,6,7> lhs, rhs 5477 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5478 // 5479 // vector_shuffle <6,7,2,3> lhs, rhs 5480 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5481 // 5482 // vector_shuffle <6,7,0,1> lhs, rhs 5483 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5484 5485 // Avoid scalarizing when both halves are reading from consecutive elements. 5486 SmallVector<SDValue, 4> Pieces; 5487 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5488 if (elementPairIsContiguous(SVN->getMask(), I)) { 5489 const int Idx = SVN->getMaskElt(I); 5490 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5491 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5492 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5493 PackVT, SVN->getOperand(VecIdx), 5494 DAG.getConstant(EltIdx, SL, MVT::i32)); 5495 Pieces.push_back(SubVec); 5496 } else { 5497 const int Idx0 = SVN->getMaskElt(I); 5498 const int Idx1 = SVN->getMaskElt(I + 1); 5499 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5500 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5501 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5502 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5503 5504 SDValue Vec0 = SVN->getOperand(VecIdx0); 5505 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5506 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5507 5508 SDValue Vec1 = SVN->getOperand(VecIdx1); 5509 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5510 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5511 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5512 } 5513 } 5514 5515 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5516 } 5517 5518 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5519 SelectionDAG &DAG) const { 5520 SDLoc SL(Op); 5521 EVT VT = Op.getValueType(); 5522 5523 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5524 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5525 5526 // Turn into pair of packed build_vectors. 5527 // TODO: Special case for constants that can be materialized with s_mov_b64. 5528 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5529 { Op.getOperand(0), Op.getOperand(1) }); 5530 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5531 { Op.getOperand(2), Op.getOperand(3) }); 5532 5533 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5534 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5535 5536 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5537 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5538 } 5539 5540 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5541 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5542 5543 SDValue Lo = Op.getOperand(0); 5544 SDValue Hi = Op.getOperand(1); 5545 5546 // Avoid adding defined bits with the zero_extend. 5547 if (Hi.isUndef()) { 5548 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5549 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5550 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5551 } 5552 5553 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5554 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5555 5556 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5557 DAG.getConstant(16, SL, MVT::i32)); 5558 if (Lo.isUndef()) 5559 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5560 5561 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5562 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5563 5564 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5565 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5566 } 5567 5568 bool 5569 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5570 // We can fold offsets for anything that doesn't require a GOT relocation. 5571 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5572 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5573 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5574 !shouldEmitGOTReloc(GA->getGlobal()); 5575 } 5576 5577 static SDValue 5578 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5579 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5580 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5581 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5582 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5583 // lowered to the following code sequence: 5584 // 5585 // For constant address space: 5586 // s_getpc_b64 s[0:1] 5587 // s_add_u32 s0, s0, $symbol 5588 // s_addc_u32 s1, s1, 0 5589 // 5590 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5591 // a fixup or relocation is emitted to replace $symbol with a literal 5592 // constant, which is a pc-relative offset from the encoding of the $symbol 5593 // operand to the global variable. 5594 // 5595 // For global address space: 5596 // s_getpc_b64 s[0:1] 5597 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5598 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5599 // 5600 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5601 // fixups or relocations are emitted to replace $symbol@*@lo and 5602 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5603 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5604 // operand to the global variable. 5605 // 5606 // What we want here is an offset from the value returned by s_getpc 5607 // (which is the address of the s_add_u32 instruction) to the global 5608 // variable, but since the encoding of $symbol starts 4 bytes after the start 5609 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5610 // small. This requires us to add 4 to the global variable offset in order to 5611 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5612 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5613 // instruction. 5614 SDValue PtrLo = 5615 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5616 SDValue PtrHi; 5617 if (GAFlags == SIInstrInfo::MO_NONE) { 5618 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5619 } else { 5620 PtrHi = 5621 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5622 } 5623 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5624 } 5625 5626 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5627 SDValue Op, 5628 SelectionDAG &DAG) const { 5629 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5630 SDLoc DL(GSD); 5631 EVT PtrVT = Op.getValueType(); 5632 5633 const GlobalValue *GV = GSD->getGlobal(); 5634 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5635 shouldUseLDSConstAddress(GV)) || 5636 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5637 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5638 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5639 GV->hasExternalLinkage()) { 5640 Type *Ty = GV->getValueType(); 5641 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5642 // zero-sized type in other languages to declare the dynamic shared 5643 // memory which size is not known at the compile time. They will be 5644 // allocated by the runtime and placed directly after the static 5645 // allocated ones. They all share the same offset. 5646 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5647 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5648 // Adjust alignment for that dynamic shared memory array. 5649 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5650 return SDValue( 5651 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5652 } 5653 } 5654 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5655 } 5656 5657 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5658 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5659 SIInstrInfo::MO_ABS32_LO); 5660 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5661 } 5662 5663 if (shouldEmitFixup(GV)) 5664 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5665 else if (shouldEmitPCReloc(GV)) 5666 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5667 SIInstrInfo::MO_REL32); 5668 5669 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5670 SIInstrInfo::MO_GOTPCREL32); 5671 5672 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5673 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5674 const DataLayout &DataLayout = DAG.getDataLayout(); 5675 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5676 MachinePointerInfo PtrInfo 5677 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5678 5679 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5680 MachineMemOperand::MODereferenceable | 5681 MachineMemOperand::MOInvariant); 5682 } 5683 5684 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5685 const SDLoc &DL, SDValue V) const { 5686 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5687 // the destination register. 5688 // 5689 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5690 // so we will end up with redundant moves to m0. 5691 // 5692 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5693 5694 // A Null SDValue creates a glue result. 5695 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5696 V, Chain); 5697 return SDValue(M0, 0); 5698 } 5699 5700 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5701 SDValue Op, 5702 MVT VT, 5703 unsigned Offset) const { 5704 SDLoc SL(Op); 5705 SDValue Param = lowerKernargMemParameter( 5706 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5707 // The local size values will have the hi 16-bits as zero. 5708 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5709 DAG.getValueType(VT)); 5710 } 5711 5712 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5713 EVT VT) { 5714 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5715 "non-hsa intrinsic with hsa target", 5716 DL.getDebugLoc()); 5717 DAG.getContext()->diagnose(BadIntrin); 5718 return DAG.getUNDEF(VT); 5719 } 5720 5721 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5722 EVT VT) { 5723 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5724 "intrinsic not supported on subtarget", 5725 DL.getDebugLoc()); 5726 DAG.getContext()->diagnose(BadIntrin); 5727 return DAG.getUNDEF(VT); 5728 } 5729 5730 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5731 ArrayRef<SDValue> Elts) { 5732 assert(!Elts.empty()); 5733 MVT Type; 5734 unsigned NumElts; 5735 5736 if (Elts.size() == 1) { 5737 Type = MVT::f32; 5738 NumElts = 1; 5739 } else if (Elts.size() == 2) { 5740 Type = MVT::v2f32; 5741 NumElts = 2; 5742 } else if (Elts.size() == 3) { 5743 Type = MVT::v3f32; 5744 NumElts = 3; 5745 } else if (Elts.size() <= 4) { 5746 Type = MVT::v4f32; 5747 NumElts = 4; 5748 } else if (Elts.size() <= 8) { 5749 Type = MVT::v8f32; 5750 NumElts = 8; 5751 } else { 5752 assert(Elts.size() <= 16); 5753 Type = MVT::v16f32; 5754 NumElts = 16; 5755 } 5756 5757 SmallVector<SDValue, 16> VecElts(NumElts); 5758 for (unsigned i = 0; i < Elts.size(); ++i) { 5759 SDValue Elt = Elts[i]; 5760 if (Elt.getValueType() != MVT::f32) 5761 Elt = DAG.getBitcast(MVT::f32, Elt); 5762 VecElts[i] = Elt; 5763 } 5764 for (unsigned i = Elts.size(); i < NumElts; ++i) 5765 VecElts[i] = DAG.getUNDEF(MVT::f32); 5766 5767 if (NumElts == 1) 5768 return VecElts[0]; 5769 return DAG.getBuildVector(Type, DL, VecElts); 5770 } 5771 5772 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5773 SDValue Src, int ExtraElts) { 5774 EVT SrcVT = Src.getValueType(); 5775 5776 SmallVector<SDValue, 8> Elts; 5777 5778 if (SrcVT.isVector()) 5779 DAG.ExtractVectorElements(Src, Elts); 5780 else 5781 Elts.push_back(Src); 5782 5783 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5784 while (ExtraElts--) 5785 Elts.push_back(Undef); 5786 5787 return DAG.getBuildVector(CastVT, DL, Elts); 5788 } 5789 5790 // Re-construct the required return value for a image load intrinsic. 5791 // This is more complicated due to the optional use TexFailCtrl which means the required 5792 // return type is an aggregate 5793 static SDValue constructRetValue(SelectionDAG &DAG, 5794 MachineSDNode *Result, 5795 ArrayRef<EVT> ResultTypes, 5796 bool IsTexFail, bool Unpacked, bool IsD16, 5797 int DMaskPop, int NumVDataDwords, 5798 const SDLoc &DL, LLVMContext &Context) { 5799 // Determine the required return type. This is the same regardless of IsTexFail flag 5800 EVT ReqRetVT = ResultTypes[0]; 5801 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5802 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5803 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5804 5805 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5806 DMaskPop : (DMaskPop + 1) / 2; 5807 5808 MVT DataDwordVT = NumDataDwords == 1 ? 5809 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5810 5811 MVT MaskPopVT = MaskPopDwords == 1 ? 5812 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5813 5814 SDValue Data(Result, 0); 5815 SDValue TexFail; 5816 5817 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5818 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5819 if (MaskPopVT.isVector()) { 5820 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5821 SDValue(Result, 0), ZeroIdx); 5822 } else { 5823 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5824 SDValue(Result, 0), ZeroIdx); 5825 } 5826 } 5827 5828 if (DataDwordVT.isVector()) 5829 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5830 NumDataDwords - MaskPopDwords); 5831 5832 if (IsD16) 5833 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5834 5835 EVT LegalReqRetVT = ReqRetVT; 5836 if (!ReqRetVT.isVector()) { 5837 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5838 } else { 5839 // We need to widen the return vector to a legal type 5840 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5841 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5842 LegalReqRetVT = 5843 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5844 ReqRetVT.getVectorNumElements() + 1); 5845 } 5846 } 5847 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5848 5849 if (IsTexFail) { 5850 TexFail = 5851 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5852 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5853 5854 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5855 } 5856 5857 if (Result->getNumValues() == 1) 5858 return Data; 5859 5860 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5861 } 5862 5863 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5864 SDValue *LWE, bool &IsTexFail) { 5865 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5866 5867 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5868 if (Value) { 5869 IsTexFail = true; 5870 } 5871 5872 SDLoc DL(TexFailCtrlConst); 5873 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5874 Value &= ~(uint64_t)0x1; 5875 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5876 Value &= ~(uint64_t)0x2; 5877 5878 return Value == 0; 5879 } 5880 5881 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5882 MVT PackVectorVT, 5883 SmallVectorImpl<SDValue> &PackedAddrs, 5884 unsigned DimIdx, unsigned EndIdx, 5885 unsigned NumGradients) { 5886 SDLoc DL(Op); 5887 for (unsigned I = DimIdx; I < EndIdx; I++) { 5888 SDValue Addr = Op.getOperand(I); 5889 5890 // Gradients are packed with undef for each coordinate. 5891 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5892 // 1D: undef,dx/dh; undef,dx/dv 5893 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5894 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5895 if (((I + 1) >= EndIdx) || 5896 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5897 I == DimIdx + NumGradients - 1))) { 5898 if (Addr.getValueType() != MVT::i16) 5899 Addr = DAG.getBitcast(MVT::i16, Addr); 5900 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5901 } else { 5902 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5903 I++; 5904 } 5905 Addr = DAG.getBitcast(MVT::f32, Addr); 5906 PackedAddrs.push_back(Addr); 5907 } 5908 } 5909 5910 SDValue SITargetLowering::lowerImage(SDValue Op, 5911 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5912 SelectionDAG &DAG, bool WithChain) const { 5913 SDLoc DL(Op); 5914 MachineFunction &MF = DAG.getMachineFunction(); 5915 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5916 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5917 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5918 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5919 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5920 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5921 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5922 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5923 unsigned IntrOpcode = Intr->BaseOpcode; 5924 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 5925 5926 SmallVector<EVT, 3> ResultTypes(Op->values()); 5927 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 5928 bool IsD16 = false; 5929 bool IsG16 = false; 5930 bool IsA16 = false; 5931 SDValue VData; 5932 int NumVDataDwords; 5933 bool AdjustRetType = false; 5934 5935 // Offset of intrinsic arguments 5936 const unsigned ArgOffset = WithChain ? 2 : 1; 5937 5938 unsigned DMask; 5939 unsigned DMaskLanes = 0; 5940 5941 if (BaseOpcode->Atomic) { 5942 VData = Op.getOperand(2); 5943 5944 bool Is64Bit = VData.getValueType() == MVT::i64; 5945 if (BaseOpcode->AtomicX2) { 5946 SDValue VData2 = Op.getOperand(3); 5947 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5948 {VData, VData2}); 5949 if (Is64Bit) 5950 VData = DAG.getBitcast(MVT::v4i32, VData); 5951 5952 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5953 DMask = Is64Bit ? 0xf : 0x3; 5954 NumVDataDwords = Is64Bit ? 4 : 2; 5955 } else { 5956 DMask = Is64Bit ? 0x3 : 0x1; 5957 NumVDataDwords = Is64Bit ? 2 : 1; 5958 } 5959 } else { 5960 auto *DMaskConst = 5961 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 5962 DMask = DMaskConst->getZExtValue(); 5963 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5964 5965 if (BaseOpcode->Store) { 5966 VData = Op.getOperand(2); 5967 5968 MVT StoreVT = VData.getSimpleValueType(); 5969 if (StoreVT.getScalarType() == MVT::f16) { 5970 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5971 return Op; // D16 is unsupported for this instruction 5972 5973 IsD16 = true; 5974 VData = handleD16VData(VData, DAG, true); 5975 } 5976 5977 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5978 } else { 5979 // Work out the num dwords based on the dmask popcount and underlying type 5980 // and whether packing is supported. 5981 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5982 if (LoadVT.getScalarType() == MVT::f16) { 5983 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5984 return Op; // D16 is unsupported for this instruction 5985 5986 IsD16 = true; 5987 } 5988 5989 // Confirm that the return type is large enough for the dmask specified 5990 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5991 (!LoadVT.isVector() && DMaskLanes > 1)) 5992 return Op; 5993 5994 // The sq block of gfx8 and gfx9 do not estimate register use correctly 5995 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 5996 // instructions. 5997 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 5998 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 5999 NumVDataDwords = (DMaskLanes + 1) / 2; 6000 else 6001 NumVDataDwords = DMaskLanes; 6002 6003 AdjustRetType = true; 6004 } 6005 } 6006 6007 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6008 SmallVector<SDValue, 4> VAddrs; 6009 6010 // Optimize _L to _LZ when _L is zero 6011 if (LZMappingInfo) { 6012 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6013 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6014 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6015 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6016 VAddrEnd--; // remove 'lod' 6017 } 6018 } 6019 } 6020 6021 // Optimize _mip away, when 'lod' is zero 6022 if (MIPMappingInfo) { 6023 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6024 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6025 if (ConstantLod->isNullValue()) { 6026 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6027 VAddrEnd--; // remove 'mip' 6028 } 6029 } 6030 } 6031 6032 // Push back extra arguments. 6033 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6034 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6035 6036 // Check for 16 bit addresses or derivatives and pack if true. 6037 MVT VAddrVT = 6038 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6039 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6040 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6041 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6042 6043 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6044 VAddrScalarVT = VAddrVT.getScalarType(); 6045 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6046 if (IsA16 || IsG16) { 6047 if (IsA16) { 6048 if (!ST->hasA16()) { 6049 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6050 "support 16 bit addresses\n"); 6051 return Op; 6052 } 6053 if (!IsG16) { 6054 LLVM_DEBUG( 6055 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6056 "need 16 bit derivatives but got 32 bit derivatives\n"); 6057 return Op; 6058 } 6059 } else if (!ST->hasG16()) { 6060 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6061 "support 16 bit derivatives\n"); 6062 return Op; 6063 } 6064 6065 if (BaseOpcode->Gradients && !IsA16) { 6066 if (!ST->hasG16()) { 6067 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6068 "support 16 bit derivatives\n"); 6069 return Op; 6070 } 6071 // Activate g16 6072 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6073 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6074 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6075 } 6076 6077 // Don't compress addresses for G16 6078 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6079 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6080 ArgOffset + Intr->GradientStart, PackEndIdx, 6081 Intr->NumGradients); 6082 6083 if (!IsA16) { 6084 // Add uncompressed address 6085 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6086 VAddrs.push_back(Op.getOperand(I)); 6087 } 6088 } else { 6089 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6090 VAddrs.push_back(Op.getOperand(I)); 6091 } 6092 6093 // If the register allocator cannot place the address registers contiguously 6094 // without introducing moves, then using the non-sequential address encoding 6095 // is always preferable, since it saves VALU instructions and is usually a 6096 // wash in terms of code size or even better. 6097 // 6098 // However, we currently have no way of hinting to the register allocator that 6099 // MIMG addresses should be placed contiguously when it is possible to do so, 6100 // so force non-NSA for the common 2-address case as a heuristic. 6101 // 6102 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6103 // allocation when possible. 6104 bool UseNSA = 6105 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6106 SDValue VAddr; 6107 if (!UseNSA) 6108 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6109 6110 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6111 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6112 SDValue Unorm; 6113 if (!BaseOpcode->Sampler) { 6114 Unorm = True; 6115 } else { 6116 auto UnormConst = 6117 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6118 6119 Unorm = UnormConst->getZExtValue() ? True : False; 6120 } 6121 6122 SDValue TFE; 6123 SDValue LWE; 6124 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6125 bool IsTexFail = false; 6126 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6127 return Op; 6128 6129 if (IsTexFail) { 6130 if (!DMaskLanes) { 6131 // Expecting to get an error flag since TFC is on - and dmask is 0 6132 // Force dmask to be at least 1 otherwise the instruction will fail 6133 DMask = 0x1; 6134 DMaskLanes = 1; 6135 NumVDataDwords = 1; 6136 } 6137 NumVDataDwords += 1; 6138 AdjustRetType = true; 6139 } 6140 6141 // Has something earlier tagged that the return type needs adjusting 6142 // This happens if the instruction is a load or has set TexFailCtrl flags 6143 if (AdjustRetType) { 6144 // NumVDataDwords reflects the true number of dwords required in the return type 6145 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6146 // This is a no-op load. This can be eliminated 6147 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6148 if (isa<MemSDNode>(Op)) 6149 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6150 return Undef; 6151 } 6152 6153 EVT NewVT = NumVDataDwords > 1 ? 6154 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6155 : MVT::i32; 6156 6157 ResultTypes[0] = NewVT; 6158 if (ResultTypes.size() == 3) { 6159 // Original result was aggregate type used for TexFailCtrl results 6160 // The actual instruction returns as a vector type which has now been 6161 // created. Remove the aggregate result. 6162 ResultTypes.erase(&ResultTypes[1]); 6163 } 6164 } 6165 6166 unsigned CPol = cast<ConstantSDNode>( 6167 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6168 if (BaseOpcode->Atomic) 6169 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6170 if (CPol & ~AMDGPU::CPol::ALL) 6171 return Op; 6172 6173 SmallVector<SDValue, 26> Ops; 6174 if (BaseOpcode->Store || BaseOpcode->Atomic) 6175 Ops.push_back(VData); // vdata 6176 if (UseNSA) 6177 append_range(Ops, VAddrs); 6178 else 6179 Ops.push_back(VAddr); 6180 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6181 if (BaseOpcode->Sampler) 6182 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6183 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6184 if (IsGFX10Plus) 6185 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6186 Ops.push_back(Unorm); 6187 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6188 Ops.push_back(IsA16 && // r128, a16 for gfx9 6189 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6190 if (IsGFX10Plus) 6191 Ops.push_back(IsA16 ? True : False); 6192 if (!Subtarget->hasGFX90AInsts()) { 6193 Ops.push_back(TFE); //tfe 6194 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6195 report_fatal_error("TFE is not supported on this GPU"); 6196 } 6197 Ops.push_back(LWE); // lwe 6198 if (!IsGFX10Plus) 6199 Ops.push_back(DimInfo->DA ? True : False); 6200 if (BaseOpcode->HasD16) 6201 Ops.push_back(IsD16 ? True : False); 6202 if (isa<MemSDNode>(Op)) 6203 Ops.push_back(Op.getOperand(0)); // chain 6204 6205 int NumVAddrDwords = 6206 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6207 int Opcode = -1; 6208 6209 if (IsGFX10Plus) { 6210 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6211 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6212 : AMDGPU::MIMGEncGfx10Default, 6213 NumVDataDwords, NumVAddrDwords); 6214 } else { 6215 if (Subtarget->hasGFX90AInsts()) { 6216 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6217 NumVDataDwords, NumVAddrDwords); 6218 if (Opcode == -1) 6219 report_fatal_error( 6220 "requested image instruction is not supported on this GPU"); 6221 } 6222 if (Opcode == -1 && 6223 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6224 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6225 NumVDataDwords, NumVAddrDwords); 6226 if (Opcode == -1) 6227 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6228 NumVDataDwords, NumVAddrDwords); 6229 } 6230 assert(Opcode != -1); 6231 6232 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6233 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6234 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6235 DAG.setNodeMemRefs(NewNode, {MemRef}); 6236 } 6237 6238 if (BaseOpcode->AtomicX2) { 6239 SmallVector<SDValue, 1> Elt; 6240 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6241 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6242 } else if (!BaseOpcode->Store) { 6243 return constructRetValue(DAG, NewNode, 6244 OrigResultTypes, IsTexFail, 6245 Subtarget->hasUnpackedD16VMem(), IsD16, 6246 DMaskLanes, NumVDataDwords, DL, 6247 *DAG.getContext()); 6248 } 6249 6250 return SDValue(NewNode, 0); 6251 } 6252 6253 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6254 SDValue Offset, SDValue CachePolicy, 6255 SelectionDAG &DAG) const { 6256 MachineFunction &MF = DAG.getMachineFunction(); 6257 6258 const DataLayout &DataLayout = DAG.getDataLayout(); 6259 Align Alignment = 6260 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6261 6262 MachineMemOperand *MMO = MF.getMachineMemOperand( 6263 MachinePointerInfo(), 6264 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6265 MachineMemOperand::MOInvariant, 6266 VT.getStoreSize(), Alignment); 6267 6268 if (!Offset->isDivergent()) { 6269 SDValue Ops[] = { 6270 Rsrc, 6271 Offset, // Offset 6272 CachePolicy 6273 }; 6274 6275 // Widen vec3 load to vec4. 6276 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6277 EVT WidenedVT = 6278 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6279 auto WidenedOp = DAG.getMemIntrinsicNode( 6280 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6281 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6282 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6283 DAG.getVectorIdxConstant(0, DL)); 6284 return Subvector; 6285 } 6286 6287 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6288 DAG.getVTList(VT), Ops, VT, MMO); 6289 } 6290 6291 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6292 // assume that the buffer is unswizzled. 6293 SmallVector<SDValue, 4> Loads; 6294 unsigned NumLoads = 1; 6295 MVT LoadVT = VT.getSimpleVT(); 6296 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6297 assert((LoadVT.getScalarType() == MVT::i32 || 6298 LoadVT.getScalarType() == MVT::f32)); 6299 6300 if (NumElts == 8 || NumElts == 16) { 6301 NumLoads = NumElts / 4; 6302 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6303 } 6304 6305 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6306 SDValue Ops[] = { 6307 DAG.getEntryNode(), // Chain 6308 Rsrc, // rsrc 6309 DAG.getConstant(0, DL, MVT::i32), // vindex 6310 {}, // voffset 6311 {}, // soffset 6312 {}, // offset 6313 CachePolicy, // cachepolicy 6314 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6315 }; 6316 6317 // Use the alignment to ensure that the required offsets will fit into the 6318 // immediate offsets. 6319 setBufferOffsets(Offset, DAG, &Ops[3], 6320 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6321 6322 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6323 for (unsigned i = 0; i < NumLoads; ++i) { 6324 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6325 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6326 LoadVT, MMO, DAG)); 6327 } 6328 6329 if (NumElts == 8 || NumElts == 16) 6330 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6331 6332 return Loads[0]; 6333 } 6334 6335 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6336 SelectionDAG &DAG) const { 6337 MachineFunction &MF = DAG.getMachineFunction(); 6338 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6339 6340 EVT VT = Op.getValueType(); 6341 SDLoc DL(Op); 6342 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6343 6344 // TODO: Should this propagate fast-math-flags? 6345 6346 switch (IntrinsicID) { 6347 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6348 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6349 return emitNonHSAIntrinsicError(DAG, DL, VT); 6350 return getPreloadedValue(DAG, *MFI, VT, 6351 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6352 } 6353 case Intrinsic::amdgcn_dispatch_ptr: 6354 case Intrinsic::amdgcn_queue_ptr: { 6355 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6356 DiagnosticInfoUnsupported BadIntrin( 6357 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6358 DL.getDebugLoc()); 6359 DAG.getContext()->diagnose(BadIntrin); 6360 return DAG.getUNDEF(VT); 6361 } 6362 6363 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6364 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6365 return getPreloadedValue(DAG, *MFI, VT, RegID); 6366 } 6367 case Intrinsic::amdgcn_implicitarg_ptr: { 6368 if (MFI->isEntryFunction()) 6369 return getImplicitArgPtr(DAG, DL); 6370 return getPreloadedValue(DAG, *MFI, VT, 6371 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6372 } 6373 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6374 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6375 // This only makes sense to call in a kernel, so just lower to null. 6376 return DAG.getConstant(0, DL, VT); 6377 } 6378 6379 return getPreloadedValue(DAG, *MFI, VT, 6380 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6381 } 6382 case Intrinsic::amdgcn_dispatch_id: { 6383 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6384 } 6385 case Intrinsic::amdgcn_rcp: 6386 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6387 case Intrinsic::amdgcn_rsq: 6388 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6389 case Intrinsic::amdgcn_rsq_legacy: 6390 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6391 return emitRemovedIntrinsicError(DAG, DL, VT); 6392 return SDValue(); 6393 case Intrinsic::amdgcn_rcp_legacy: 6394 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6395 return emitRemovedIntrinsicError(DAG, DL, VT); 6396 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6397 case Intrinsic::amdgcn_rsq_clamp: { 6398 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6399 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6400 6401 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6402 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6403 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6404 6405 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6406 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6407 DAG.getConstantFP(Max, DL, VT)); 6408 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6409 DAG.getConstantFP(Min, DL, VT)); 6410 } 6411 case Intrinsic::r600_read_ngroups_x: 6412 if (Subtarget->isAmdHsaOS()) 6413 return emitNonHSAIntrinsicError(DAG, DL, VT); 6414 6415 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6416 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6417 false); 6418 case Intrinsic::r600_read_ngroups_y: 6419 if (Subtarget->isAmdHsaOS()) 6420 return emitNonHSAIntrinsicError(DAG, DL, VT); 6421 6422 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6423 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6424 false); 6425 case Intrinsic::r600_read_ngroups_z: 6426 if (Subtarget->isAmdHsaOS()) 6427 return emitNonHSAIntrinsicError(DAG, DL, VT); 6428 6429 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6430 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6431 false); 6432 case Intrinsic::r600_read_global_size_x: 6433 if (Subtarget->isAmdHsaOS()) 6434 return emitNonHSAIntrinsicError(DAG, DL, VT); 6435 6436 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6437 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6438 Align(4), false); 6439 case Intrinsic::r600_read_global_size_y: 6440 if (Subtarget->isAmdHsaOS()) 6441 return emitNonHSAIntrinsicError(DAG, DL, VT); 6442 6443 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6444 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6445 Align(4), false); 6446 case Intrinsic::r600_read_global_size_z: 6447 if (Subtarget->isAmdHsaOS()) 6448 return emitNonHSAIntrinsicError(DAG, DL, VT); 6449 6450 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6451 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6452 Align(4), false); 6453 case Intrinsic::r600_read_local_size_x: 6454 if (Subtarget->isAmdHsaOS()) 6455 return emitNonHSAIntrinsicError(DAG, DL, VT); 6456 6457 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6458 SI::KernelInputOffsets::LOCAL_SIZE_X); 6459 case Intrinsic::r600_read_local_size_y: 6460 if (Subtarget->isAmdHsaOS()) 6461 return emitNonHSAIntrinsicError(DAG, DL, VT); 6462 6463 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6464 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6465 case Intrinsic::r600_read_local_size_z: 6466 if (Subtarget->isAmdHsaOS()) 6467 return emitNonHSAIntrinsicError(DAG, DL, VT); 6468 6469 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6470 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6471 case Intrinsic::amdgcn_workgroup_id_x: 6472 return getPreloadedValue(DAG, *MFI, VT, 6473 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6474 case Intrinsic::amdgcn_workgroup_id_y: 6475 return getPreloadedValue(DAG, *MFI, VT, 6476 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6477 case Intrinsic::amdgcn_workgroup_id_z: 6478 return getPreloadedValue(DAG, *MFI, VT, 6479 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6480 case Intrinsic::amdgcn_workitem_id_x: 6481 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6482 SDLoc(DAG.getEntryNode()), 6483 MFI->getArgInfo().WorkItemIDX); 6484 case Intrinsic::amdgcn_workitem_id_y: 6485 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6486 SDLoc(DAG.getEntryNode()), 6487 MFI->getArgInfo().WorkItemIDY); 6488 case Intrinsic::amdgcn_workitem_id_z: 6489 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6490 SDLoc(DAG.getEntryNode()), 6491 MFI->getArgInfo().WorkItemIDZ); 6492 case Intrinsic::amdgcn_wavefrontsize: 6493 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6494 SDLoc(Op), MVT::i32); 6495 case Intrinsic::amdgcn_s_buffer_load: { 6496 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6497 if (CPol & ~AMDGPU::CPol::ALL) 6498 return Op; 6499 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6500 DAG); 6501 } 6502 case Intrinsic::amdgcn_fdiv_fast: 6503 return lowerFDIV_FAST(Op, DAG); 6504 case Intrinsic::amdgcn_sin: 6505 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6506 6507 case Intrinsic::amdgcn_cos: 6508 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6509 6510 case Intrinsic::amdgcn_mul_u24: 6511 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6512 case Intrinsic::amdgcn_mul_i24: 6513 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6514 6515 case Intrinsic::amdgcn_log_clamp: { 6516 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6517 return SDValue(); 6518 6519 return emitRemovedIntrinsicError(DAG, DL, VT); 6520 } 6521 case Intrinsic::amdgcn_ldexp: 6522 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6523 Op.getOperand(1), Op.getOperand(2)); 6524 6525 case Intrinsic::amdgcn_fract: 6526 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6527 6528 case Intrinsic::amdgcn_class: 6529 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6530 Op.getOperand(1), Op.getOperand(2)); 6531 case Intrinsic::amdgcn_div_fmas: 6532 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6533 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6534 Op.getOperand(4)); 6535 6536 case Intrinsic::amdgcn_div_fixup: 6537 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6538 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6539 6540 case Intrinsic::amdgcn_div_scale: { 6541 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6542 6543 // Translate to the operands expected by the machine instruction. The 6544 // first parameter must be the same as the first instruction. 6545 SDValue Numerator = Op.getOperand(1); 6546 SDValue Denominator = Op.getOperand(2); 6547 6548 // Note this order is opposite of the machine instruction's operations, 6549 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6550 // intrinsic has the numerator as the first operand to match a normal 6551 // division operation. 6552 6553 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6554 6555 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6556 Denominator, Numerator); 6557 } 6558 case Intrinsic::amdgcn_icmp: { 6559 // There is a Pat that handles this variant, so return it as-is. 6560 if (Op.getOperand(1).getValueType() == MVT::i1 && 6561 Op.getConstantOperandVal(2) == 0 && 6562 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6563 return Op; 6564 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6565 } 6566 case Intrinsic::amdgcn_fcmp: { 6567 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6568 } 6569 case Intrinsic::amdgcn_ballot: 6570 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6571 case Intrinsic::amdgcn_fmed3: 6572 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6573 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6574 case Intrinsic::amdgcn_fdot2: 6575 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6576 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6577 Op.getOperand(4)); 6578 case Intrinsic::amdgcn_fmul_legacy: 6579 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6580 Op.getOperand(1), Op.getOperand(2)); 6581 case Intrinsic::amdgcn_sffbh: 6582 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6583 case Intrinsic::amdgcn_sbfe: 6584 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6585 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6586 case Intrinsic::amdgcn_ubfe: 6587 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6588 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6589 case Intrinsic::amdgcn_cvt_pkrtz: 6590 case Intrinsic::amdgcn_cvt_pknorm_i16: 6591 case Intrinsic::amdgcn_cvt_pknorm_u16: 6592 case Intrinsic::amdgcn_cvt_pk_i16: 6593 case Intrinsic::amdgcn_cvt_pk_u16: { 6594 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6595 EVT VT = Op.getValueType(); 6596 unsigned Opcode; 6597 6598 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6599 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6600 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6601 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6602 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6603 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6604 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6605 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6606 else 6607 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6608 6609 if (isTypeLegal(VT)) 6610 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6611 6612 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6613 Op.getOperand(1), Op.getOperand(2)); 6614 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6615 } 6616 case Intrinsic::amdgcn_fmad_ftz: 6617 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6618 Op.getOperand(2), Op.getOperand(3)); 6619 6620 case Intrinsic::amdgcn_if_break: 6621 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6622 Op->getOperand(1), Op->getOperand(2)), 0); 6623 6624 case Intrinsic::amdgcn_groupstaticsize: { 6625 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6626 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6627 return Op; 6628 6629 const Module *M = MF.getFunction().getParent(); 6630 const GlobalValue *GV = 6631 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6632 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6633 SIInstrInfo::MO_ABS32_LO); 6634 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6635 } 6636 case Intrinsic::amdgcn_is_shared: 6637 case Intrinsic::amdgcn_is_private: { 6638 SDLoc SL(Op); 6639 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6640 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6641 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6642 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6643 Op.getOperand(1)); 6644 6645 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6646 DAG.getConstant(1, SL, MVT::i32)); 6647 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6648 } 6649 case Intrinsic::amdgcn_alignbit: 6650 return DAG.getNode(ISD::FSHR, DL, VT, 6651 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6652 case Intrinsic::amdgcn_reloc_constant: { 6653 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6654 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6655 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6656 auto RelocSymbol = cast<GlobalVariable>( 6657 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6658 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6659 SIInstrInfo::MO_ABS32_LO); 6660 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6661 } 6662 default: 6663 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6664 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6665 return lowerImage(Op, ImageDimIntr, DAG, false); 6666 6667 return Op; 6668 } 6669 } 6670 6671 // This function computes an appropriate offset to pass to 6672 // MachineMemOperand::setOffset() based on the offset inputs to 6673 // an intrinsic. If any of the offsets are non-contstant or 6674 // if VIndex is non-zero then this function returns 0. Otherwise, 6675 // it returns the sum of VOffset, SOffset, and Offset. 6676 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6677 SDValue SOffset, 6678 SDValue Offset, 6679 SDValue VIndex = SDValue()) { 6680 6681 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6682 !isa<ConstantSDNode>(Offset)) 6683 return 0; 6684 6685 if (VIndex) { 6686 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6687 return 0; 6688 } 6689 6690 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6691 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6692 cast<ConstantSDNode>(Offset)->getSExtValue(); 6693 } 6694 6695 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6696 SelectionDAG &DAG, 6697 unsigned NewOpcode) const { 6698 SDLoc DL(Op); 6699 6700 SDValue VData = Op.getOperand(2); 6701 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6702 SDValue Ops[] = { 6703 Op.getOperand(0), // Chain 6704 VData, // vdata 6705 Op.getOperand(3), // rsrc 6706 DAG.getConstant(0, DL, MVT::i32), // vindex 6707 Offsets.first, // voffset 6708 Op.getOperand(5), // soffset 6709 Offsets.second, // offset 6710 Op.getOperand(6), // cachepolicy 6711 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6712 }; 6713 6714 auto *M = cast<MemSDNode>(Op); 6715 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6716 6717 EVT MemVT = VData.getValueType(); 6718 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6719 M->getMemOperand()); 6720 } 6721 6722 SDValue 6723 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6724 unsigned NewOpcode) const { 6725 SDLoc DL(Op); 6726 6727 SDValue VData = Op.getOperand(2); 6728 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6729 SDValue Ops[] = { 6730 Op.getOperand(0), // Chain 6731 VData, // vdata 6732 Op.getOperand(3), // rsrc 6733 Op.getOperand(4), // vindex 6734 Offsets.first, // voffset 6735 Op.getOperand(6), // soffset 6736 Offsets.second, // offset 6737 Op.getOperand(7), // cachepolicy 6738 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6739 }; 6740 6741 auto *M = cast<MemSDNode>(Op); 6742 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6743 Ops[3])); 6744 6745 EVT MemVT = VData.getValueType(); 6746 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6747 M->getMemOperand()); 6748 } 6749 6750 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6751 SelectionDAG &DAG) const { 6752 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6753 SDLoc DL(Op); 6754 6755 switch (IntrID) { 6756 case Intrinsic::amdgcn_ds_ordered_add: 6757 case Intrinsic::amdgcn_ds_ordered_swap: { 6758 MemSDNode *M = cast<MemSDNode>(Op); 6759 SDValue Chain = M->getOperand(0); 6760 SDValue M0 = M->getOperand(2); 6761 SDValue Value = M->getOperand(3); 6762 unsigned IndexOperand = M->getConstantOperandVal(7); 6763 unsigned WaveRelease = M->getConstantOperandVal(8); 6764 unsigned WaveDone = M->getConstantOperandVal(9); 6765 6766 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6767 IndexOperand &= ~0x3f; 6768 unsigned CountDw = 0; 6769 6770 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6771 CountDw = (IndexOperand >> 24) & 0xf; 6772 IndexOperand &= ~(0xf << 24); 6773 6774 if (CountDw < 1 || CountDw > 4) { 6775 report_fatal_error( 6776 "ds_ordered_count: dword count must be between 1 and 4"); 6777 } 6778 } 6779 6780 if (IndexOperand) 6781 report_fatal_error("ds_ordered_count: bad index operand"); 6782 6783 if (WaveDone && !WaveRelease) 6784 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6785 6786 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6787 unsigned ShaderType = 6788 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6789 unsigned Offset0 = OrderedCountIndex << 2; 6790 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6791 (Instruction << 4); 6792 6793 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6794 Offset1 |= (CountDw - 1) << 6; 6795 6796 unsigned Offset = Offset0 | (Offset1 << 8); 6797 6798 SDValue Ops[] = { 6799 Chain, 6800 Value, 6801 DAG.getTargetConstant(Offset, DL, MVT::i16), 6802 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6803 }; 6804 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6805 M->getVTList(), Ops, M->getMemoryVT(), 6806 M->getMemOperand()); 6807 } 6808 case Intrinsic::amdgcn_ds_fadd: { 6809 MemSDNode *M = cast<MemSDNode>(Op); 6810 unsigned Opc; 6811 switch (IntrID) { 6812 case Intrinsic::amdgcn_ds_fadd: 6813 Opc = ISD::ATOMIC_LOAD_FADD; 6814 break; 6815 } 6816 6817 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6818 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6819 M->getMemOperand()); 6820 } 6821 case Intrinsic::amdgcn_atomic_inc: 6822 case Intrinsic::amdgcn_atomic_dec: 6823 case Intrinsic::amdgcn_ds_fmin: 6824 case Intrinsic::amdgcn_ds_fmax: { 6825 MemSDNode *M = cast<MemSDNode>(Op); 6826 unsigned Opc; 6827 switch (IntrID) { 6828 case Intrinsic::amdgcn_atomic_inc: 6829 Opc = AMDGPUISD::ATOMIC_INC; 6830 break; 6831 case Intrinsic::amdgcn_atomic_dec: 6832 Opc = AMDGPUISD::ATOMIC_DEC; 6833 break; 6834 case Intrinsic::amdgcn_ds_fmin: 6835 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6836 break; 6837 case Intrinsic::amdgcn_ds_fmax: 6838 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6839 break; 6840 default: 6841 llvm_unreachable("Unknown intrinsic!"); 6842 } 6843 SDValue Ops[] = { 6844 M->getOperand(0), // Chain 6845 M->getOperand(2), // Ptr 6846 M->getOperand(3) // Value 6847 }; 6848 6849 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6850 M->getMemoryVT(), M->getMemOperand()); 6851 } 6852 case Intrinsic::amdgcn_buffer_load: 6853 case Intrinsic::amdgcn_buffer_load_format: { 6854 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6855 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6856 unsigned IdxEn = 1; 6857 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6858 IdxEn = Idx->getZExtValue() != 0; 6859 SDValue Ops[] = { 6860 Op.getOperand(0), // Chain 6861 Op.getOperand(2), // rsrc 6862 Op.getOperand(3), // vindex 6863 SDValue(), // voffset -- will be set by setBufferOffsets 6864 SDValue(), // soffset -- will be set by setBufferOffsets 6865 SDValue(), // offset -- will be set by setBufferOffsets 6866 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6867 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6868 }; 6869 6870 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6871 // We don't know the offset if vindex is non-zero, so clear it. 6872 if (IdxEn) 6873 Offset = 0; 6874 6875 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6876 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6877 6878 EVT VT = Op.getValueType(); 6879 EVT IntVT = VT.changeTypeToInteger(); 6880 auto *M = cast<MemSDNode>(Op); 6881 M->getMemOperand()->setOffset(Offset); 6882 EVT LoadVT = Op.getValueType(); 6883 6884 if (LoadVT.getScalarType() == MVT::f16) 6885 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6886 M, DAG, Ops); 6887 6888 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6889 if (LoadVT.getScalarType() == MVT::i8 || 6890 LoadVT.getScalarType() == MVT::i16) 6891 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6892 6893 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6894 M->getMemOperand(), DAG); 6895 } 6896 case Intrinsic::amdgcn_raw_buffer_load: 6897 case Intrinsic::amdgcn_raw_buffer_load_format: { 6898 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6899 6900 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6901 SDValue Ops[] = { 6902 Op.getOperand(0), // Chain 6903 Op.getOperand(2), // rsrc 6904 DAG.getConstant(0, DL, MVT::i32), // vindex 6905 Offsets.first, // voffset 6906 Op.getOperand(4), // soffset 6907 Offsets.second, // offset 6908 Op.getOperand(5), // cachepolicy, swizzled buffer 6909 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6910 }; 6911 6912 auto *M = cast<MemSDNode>(Op); 6913 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6914 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6915 } 6916 case Intrinsic::amdgcn_struct_buffer_load: 6917 case Intrinsic::amdgcn_struct_buffer_load_format: { 6918 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6919 6920 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6921 SDValue Ops[] = { 6922 Op.getOperand(0), // Chain 6923 Op.getOperand(2), // rsrc 6924 Op.getOperand(3), // vindex 6925 Offsets.first, // voffset 6926 Op.getOperand(5), // soffset 6927 Offsets.second, // offset 6928 Op.getOperand(6), // cachepolicy, swizzled buffer 6929 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6930 }; 6931 6932 auto *M = cast<MemSDNode>(Op); 6933 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6934 Ops[2])); 6935 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6936 } 6937 case Intrinsic::amdgcn_tbuffer_load: { 6938 MemSDNode *M = cast<MemSDNode>(Op); 6939 EVT LoadVT = Op.getValueType(); 6940 6941 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6942 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6943 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6944 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6945 unsigned IdxEn = 1; 6946 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6947 IdxEn = Idx->getZExtValue() != 0; 6948 SDValue Ops[] = { 6949 Op.getOperand(0), // Chain 6950 Op.getOperand(2), // rsrc 6951 Op.getOperand(3), // vindex 6952 Op.getOperand(4), // voffset 6953 Op.getOperand(5), // soffset 6954 Op.getOperand(6), // offset 6955 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6956 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6957 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6958 }; 6959 6960 if (LoadVT.getScalarType() == MVT::f16) 6961 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6962 M, DAG, Ops); 6963 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6964 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6965 DAG); 6966 } 6967 case Intrinsic::amdgcn_raw_tbuffer_load: { 6968 MemSDNode *M = cast<MemSDNode>(Op); 6969 EVT LoadVT = Op.getValueType(); 6970 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6971 6972 SDValue Ops[] = { 6973 Op.getOperand(0), // Chain 6974 Op.getOperand(2), // rsrc 6975 DAG.getConstant(0, DL, MVT::i32), // vindex 6976 Offsets.first, // voffset 6977 Op.getOperand(4), // soffset 6978 Offsets.second, // offset 6979 Op.getOperand(5), // format 6980 Op.getOperand(6), // cachepolicy, swizzled buffer 6981 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6982 }; 6983 6984 if (LoadVT.getScalarType() == MVT::f16) 6985 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6986 M, DAG, Ops); 6987 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6988 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6989 DAG); 6990 } 6991 case Intrinsic::amdgcn_struct_tbuffer_load: { 6992 MemSDNode *M = cast<MemSDNode>(Op); 6993 EVT LoadVT = Op.getValueType(); 6994 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6995 6996 SDValue Ops[] = { 6997 Op.getOperand(0), // Chain 6998 Op.getOperand(2), // rsrc 6999 Op.getOperand(3), // vindex 7000 Offsets.first, // voffset 7001 Op.getOperand(5), // soffset 7002 Offsets.second, // offset 7003 Op.getOperand(6), // format 7004 Op.getOperand(7), // cachepolicy, swizzled buffer 7005 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7006 }; 7007 7008 if (LoadVT.getScalarType() == MVT::f16) 7009 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7010 M, DAG, Ops); 7011 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7012 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7013 DAG); 7014 } 7015 case Intrinsic::amdgcn_buffer_atomic_swap: 7016 case Intrinsic::amdgcn_buffer_atomic_add: 7017 case Intrinsic::amdgcn_buffer_atomic_sub: 7018 case Intrinsic::amdgcn_buffer_atomic_csub: 7019 case Intrinsic::amdgcn_buffer_atomic_smin: 7020 case Intrinsic::amdgcn_buffer_atomic_umin: 7021 case Intrinsic::amdgcn_buffer_atomic_smax: 7022 case Intrinsic::amdgcn_buffer_atomic_umax: 7023 case Intrinsic::amdgcn_buffer_atomic_and: 7024 case Intrinsic::amdgcn_buffer_atomic_or: 7025 case Intrinsic::amdgcn_buffer_atomic_xor: 7026 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7027 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7028 unsigned IdxEn = 1; 7029 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7030 IdxEn = Idx->getZExtValue() != 0; 7031 SDValue Ops[] = { 7032 Op.getOperand(0), // Chain 7033 Op.getOperand(2), // vdata 7034 Op.getOperand(3), // rsrc 7035 Op.getOperand(4), // vindex 7036 SDValue(), // voffset -- will be set by setBufferOffsets 7037 SDValue(), // soffset -- will be set by setBufferOffsets 7038 SDValue(), // offset -- will be set by setBufferOffsets 7039 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7040 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7041 }; 7042 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7043 // We don't know the offset if vindex is non-zero, so clear it. 7044 if (IdxEn) 7045 Offset = 0; 7046 EVT VT = Op.getValueType(); 7047 7048 auto *M = cast<MemSDNode>(Op); 7049 M->getMemOperand()->setOffset(Offset); 7050 unsigned Opcode = 0; 7051 7052 switch (IntrID) { 7053 case Intrinsic::amdgcn_buffer_atomic_swap: 7054 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7055 break; 7056 case Intrinsic::amdgcn_buffer_atomic_add: 7057 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7058 break; 7059 case Intrinsic::amdgcn_buffer_atomic_sub: 7060 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7061 break; 7062 case Intrinsic::amdgcn_buffer_atomic_csub: 7063 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7064 break; 7065 case Intrinsic::amdgcn_buffer_atomic_smin: 7066 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7067 break; 7068 case Intrinsic::amdgcn_buffer_atomic_umin: 7069 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7070 break; 7071 case Intrinsic::amdgcn_buffer_atomic_smax: 7072 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7073 break; 7074 case Intrinsic::amdgcn_buffer_atomic_umax: 7075 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7076 break; 7077 case Intrinsic::amdgcn_buffer_atomic_and: 7078 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7079 break; 7080 case Intrinsic::amdgcn_buffer_atomic_or: 7081 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7082 break; 7083 case Intrinsic::amdgcn_buffer_atomic_xor: 7084 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7085 break; 7086 case Intrinsic::amdgcn_buffer_atomic_fadd: 7087 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7088 DiagnosticInfoUnsupported 7089 NoFpRet(DAG.getMachineFunction().getFunction(), 7090 "return versions of fp atomics not supported", 7091 DL.getDebugLoc(), DS_Error); 7092 DAG.getContext()->diagnose(NoFpRet); 7093 return SDValue(); 7094 } 7095 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7096 break; 7097 default: 7098 llvm_unreachable("unhandled atomic opcode"); 7099 } 7100 7101 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7102 M->getMemOperand()); 7103 } 7104 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7105 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7106 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7107 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7108 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7109 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7110 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7111 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7112 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7113 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7114 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7115 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7116 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7117 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7118 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7119 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7120 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7121 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7122 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7123 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7124 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7125 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7126 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7127 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7128 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7129 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7130 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7131 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7132 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7133 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7134 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7135 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7136 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7137 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7138 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7139 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7140 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7141 return lowerStructBufferAtomicIntrin(Op, DAG, 7142 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7143 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7144 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7145 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7146 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7147 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7148 return lowerStructBufferAtomicIntrin(Op, DAG, 7149 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7150 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7151 return lowerStructBufferAtomicIntrin(Op, DAG, 7152 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7153 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7154 return lowerStructBufferAtomicIntrin(Op, DAG, 7155 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7156 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7157 return lowerStructBufferAtomicIntrin(Op, DAG, 7158 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7159 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7160 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7161 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7162 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7163 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7164 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7165 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7166 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7167 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7168 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7169 7170 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7171 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7172 unsigned IdxEn = 1; 7173 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7174 IdxEn = Idx->getZExtValue() != 0; 7175 SDValue Ops[] = { 7176 Op.getOperand(0), // Chain 7177 Op.getOperand(2), // src 7178 Op.getOperand(3), // cmp 7179 Op.getOperand(4), // rsrc 7180 Op.getOperand(5), // vindex 7181 SDValue(), // voffset -- will be set by setBufferOffsets 7182 SDValue(), // soffset -- will be set by setBufferOffsets 7183 SDValue(), // offset -- will be set by setBufferOffsets 7184 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7185 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7186 }; 7187 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7188 // We don't know the offset if vindex is non-zero, so clear it. 7189 if (IdxEn) 7190 Offset = 0; 7191 EVT VT = Op.getValueType(); 7192 auto *M = cast<MemSDNode>(Op); 7193 M->getMemOperand()->setOffset(Offset); 7194 7195 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7196 Op->getVTList(), Ops, VT, M->getMemOperand()); 7197 } 7198 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7199 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7200 SDValue Ops[] = { 7201 Op.getOperand(0), // Chain 7202 Op.getOperand(2), // src 7203 Op.getOperand(3), // cmp 7204 Op.getOperand(4), // rsrc 7205 DAG.getConstant(0, DL, MVT::i32), // vindex 7206 Offsets.first, // voffset 7207 Op.getOperand(6), // soffset 7208 Offsets.second, // offset 7209 Op.getOperand(7), // cachepolicy 7210 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7211 }; 7212 EVT VT = Op.getValueType(); 7213 auto *M = cast<MemSDNode>(Op); 7214 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7215 7216 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7217 Op->getVTList(), Ops, VT, M->getMemOperand()); 7218 } 7219 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7220 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7221 SDValue Ops[] = { 7222 Op.getOperand(0), // Chain 7223 Op.getOperand(2), // src 7224 Op.getOperand(3), // cmp 7225 Op.getOperand(4), // rsrc 7226 Op.getOperand(5), // vindex 7227 Offsets.first, // voffset 7228 Op.getOperand(7), // soffset 7229 Offsets.second, // offset 7230 Op.getOperand(8), // cachepolicy 7231 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7232 }; 7233 EVT VT = Op.getValueType(); 7234 auto *M = cast<MemSDNode>(Op); 7235 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7236 Ops[4])); 7237 7238 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7239 Op->getVTList(), Ops, VT, M->getMemOperand()); 7240 } 7241 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7242 SDLoc DL(Op); 7243 MemSDNode *M = cast<MemSDNode>(Op); 7244 SDValue NodePtr = M->getOperand(2); 7245 SDValue RayExtent = M->getOperand(3); 7246 SDValue RayOrigin = M->getOperand(4); 7247 SDValue RayDir = M->getOperand(5); 7248 SDValue RayInvDir = M->getOperand(6); 7249 SDValue TDescr = M->getOperand(7); 7250 7251 assert(NodePtr.getValueType() == MVT::i32 || 7252 NodePtr.getValueType() == MVT::i64); 7253 assert(RayDir.getValueType() == MVT::v4f16 || 7254 RayDir.getValueType() == MVT::v4f32); 7255 7256 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7257 bool Is64 = NodePtr.getValueType() == MVT::i64; 7258 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7259 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7260 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7261 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7262 7263 SmallVector<SDValue, 16> Ops; 7264 7265 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7266 SmallVector<SDValue, 3> Lanes; 7267 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7268 if (Lanes[0].getValueSizeInBits() == 32) { 7269 for (unsigned I = 0; I < 3; ++I) 7270 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7271 } else { 7272 if (IsAligned) { 7273 Ops.push_back( 7274 DAG.getBitcast(MVT::i32, 7275 DAG.getBuildVector(MVT::v2f16, DL, 7276 { Lanes[0], Lanes[1] }))); 7277 Ops.push_back(Lanes[2]); 7278 } else { 7279 SDValue Elt0 = Ops.pop_back_val(); 7280 Ops.push_back( 7281 DAG.getBitcast(MVT::i32, 7282 DAG.getBuildVector(MVT::v2f16, DL, 7283 { Elt0, Lanes[0] }))); 7284 Ops.push_back( 7285 DAG.getBitcast(MVT::i32, 7286 DAG.getBuildVector(MVT::v2f16, DL, 7287 { Lanes[1], Lanes[2] }))); 7288 } 7289 } 7290 }; 7291 7292 if (Is64) 7293 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7294 else 7295 Ops.push_back(NodePtr); 7296 7297 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7298 packLanes(RayOrigin, true); 7299 packLanes(RayDir, true); 7300 packLanes(RayInvDir, false); 7301 Ops.push_back(TDescr); 7302 if (IsA16) 7303 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7304 Ops.push_back(M->getChain()); 7305 7306 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7307 MachineMemOperand *MemRef = M->getMemOperand(); 7308 DAG.setNodeMemRefs(NewNode, {MemRef}); 7309 return SDValue(NewNode, 0); 7310 } 7311 case Intrinsic::amdgcn_global_atomic_fadd: 7312 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7313 DiagnosticInfoUnsupported 7314 NoFpRet(DAG.getMachineFunction().getFunction(), 7315 "return versions of fp atomics not supported", 7316 DL.getDebugLoc(), DS_Error); 7317 DAG.getContext()->diagnose(NoFpRet); 7318 return SDValue(); 7319 } 7320 LLVM_FALLTHROUGH; 7321 case Intrinsic::amdgcn_global_atomic_fmin: 7322 case Intrinsic::amdgcn_global_atomic_fmax: 7323 case Intrinsic::amdgcn_flat_atomic_fadd: 7324 case Intrinsic::amdgcn_flat_atomic_fmin: 7325 case Intrinsic::amdgcn_flat_atomic_fmax: { 7326 MemSDNode *M = cast<MemSDNode>(Op); 7327 SDValue Ops[] = { 7328 M->getOperand(0), // Chain 7329 M->getOperand(2), // Ptr 7330 M->getOperand(3) // Value 7331 }; 7332 unsigned Opcode = 0; 7333 switch (IntrID) { 7334 case Intrinsic::amdgcn_global_atomic_fadd: 7335 case Intrinsic::amdgcn_flat_atomic_fadd: { 7336 EVT VT = Op.getOperand(3).getValueType(); 7337 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7338 DAG.getVTList(VT, MVT::Other), Ops, 7339 M->getMemOperand()); 7340 } 7341 case Intrinsic::amdgcn_global_atomic_fmin: 7342 case Intrinsic::amdgcn_flat_atomic_fmin: { 7343 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7344 break; 7345 } 7346 case Intrinsic::amdgcn_global_atomic_fmax: 7347 case Intrinsic::amdgcn_flat_atomic_fmax: { 7348 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7349 break; 7350 } 7351 default: 7352 llvm_unreachable("unhandled atomic opcode"); 7353 } 7354 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7355 M->getVTList(), Ops, M->getMemoryVT(), 7356 M->getMemOperand()); 7357 } 7358 default: 7359 7360 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7361 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7362 return lowerImage(Op, ImageDimIntr, DAG, true); 7363 7364 return SDValue(); 7365 } 7366 } 7367 7368 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7369 // dwordx4 if on SI. 7370 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7371 SDVTList VTList, 7372 ArrayRef<SDValue> Ops, EVT MemVT, 7373 MachineMemOperand *MMO, 7374 SelectionDAG &DAG) const { 7375 EVT VT = VTList.VTs[0]; 7376 EVT WidenedVT = VT; 7377 EVT WidenedMemVT = MemVT; 7378 if (!Subtarget->hasDwordx3LoadStores() && 7379 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7380 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7381 WidenedVT.getVectorElementType(), 4); 7382 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7383 WidenedMemVT.getVectorElementType(), 4); 7384 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7385 } 7386 7387 assert(VTList.NumVTs == 2); 7388 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7389 7390 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7391 WidenedMemVT, MMO); 7392 if (WidenedVT != VT) { 7393 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7394 DAG.getVectorIdxConstant(0, DL)); 7395 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7396 } 7397 return NewOp; 7398 } 7399 7400 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7401 bool ImageStore) const { 7402 EVT StoreVT = VData.getValueType(); 7403 7404 // No change for f16 and legal vector D16 types. 7405 if (!StoreVT.isVector()) 7406 return VData; 7407 7408 SDLoc DL(VData); 7409 unsigned NumElements = StoreVT.getVectorNumElements(); 7410 7411 if (Subtarget->hasUnpackedD16VMem()) { 7412 // We need to unpack the packed data to store. 7413 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7414 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7415 7416 EVT EquivStoreVT = 7417 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7418 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7419 return DAG.UnrollVectorOp(ZExt.getNode()); 7420 } 7421 7422 // The sq block of gfx8.1 does not estimate register use correctly for d16 7423 // image store instructions. The data operand is computed as if it were not a 7424 // d16 image instruction. 7425 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7426 // Bitcast to i16 7427 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7428 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7429 7430 // Decompose into scalars 7431 SmallVector<SDValue, 4> Elts; 7432 DAG.ExtractVectorElements(IntVData, Elts); 7433 7434 // Group pairs of i16 into v2i16 and bitcast to i32 7435 SmallVector<SDValue, 4> PackedElts; 7436 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7437 SDValue Pair = 7438 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7439 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7440 PackedElts.push_back(IntPair); 7441 } 7442 if ((NumElements % 2) == 1) { 7443 // Handle v3i16 7444 unsigned I = Elts.size() / 2; 7445 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7446 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7447 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7448 PackedElts.push_back(IntPair); 7449 } 7450 7451 // Pad using UNDEF 7452 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7453 7454 // Build final vector 7455 EVT VecVT = 7456 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7457 return DAG.getBuildVector(VecVT, DL, PackedElts); 7458 } 7459 7460 if (NumElements == 3) { 7461 EVT IntStoreVT = 7462 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7463 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7464 7465 EVT WidenedStoreVT = EVT::getVectorVT( 7466 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7467 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7468 WidenedStoreVT.getStoreSizeInBits()); 7469 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7470 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7471 } 7472 7473 assert(isTypeLegal(StoreVT)); 7474 return VData; 7475 } 7476 7477 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7478 SelectionDAG &DAG) const { 7479 SDLoc DL(Op); 7480 SDValue Chain = Op.getOperand(0); 7481 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7482 MachineFunction &MF = DAG.getMachineFunction(); 7483 7484 switch (IntrinsicID) { 7485 case Intrinsic::amdgcn_exp_compr: { 7486 SDValue Src0 = Op.getOperand(4); 7487 SDValue Src1 = Op.getOperand(5); 7488 // Hack around illegal type on SI by directly selecting it. 7489 if (isTypeLegal(Src0.getValueType())) 7490 return SDValue(); 7491 7492 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7493 SDValue Undef = DAG.getUNDEF(MVT::f32); 7494 const SDValue Ops[] = { 7495 Op.getOperand(2), // tgt 7496 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7497 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7498 Undef, // src2 7499 Undef, // src3 7500 Op.getOperand(7), // vm 7501 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7502 Op.getOperand(3), // en 7503 Op.getOperand(0) // Chain 7504 }; 7505 7506 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7507 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7508 } 7509 case Intrinsic::amdgcn_s_barrier: { 7510 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7511 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7512 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7513 if (WGSize <= ST.getWavefrontSize()) 7514 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7515 Op.getOperand(0)), 0); 7516 } 7517 return SDValue(); 7518 }; 7519 case Intrinsic::amdgcn_tbuffer_store: { 7520 SDValue VData = Op.getOperand(2); 7521 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7522 if (IsD16) 7523 VData = handleD16VData(VData, DAG); 7524 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7525 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7526 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7527 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7528 unsigned IdxEn = 1; 7529 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7530 IdxEn = Idx->getZExtValue() != 0; 7531 SDValue Ops[] = { 7532 Chain, 7533 VData, // vdata 7534 Op.getOperand(3), // rsrc 7535 Op.getOperand(4), // vindex 7536 Op.getOperand(5), // voffset 7537 Op.getOperand(6), // soffset 7538 Op.getOperand(7), // offset 7539 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7540 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7541 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7542 }; 7543 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7544 AMDGPUISD::TBUFFER_STORE_FORMAT; 7545 MemSDNode *M = cast<MemSDNode>(Op); 7546 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7547 M->getMemoryVT(), M->getMemOperand()); 7548 } 7549 7550 case Intrinsic::amdgcn_struct_tbuffer_store: { 7551 SDValue VData = Op.getOperand(2); 7552 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7553 if (IsD16) 7554 VData = handleD16VData(VData, DAG); 7555 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7556 SDValue Ops[] = { 7557 Chain, 7558 VData, // vdata 7559 Op.getOperand(3), // rsrc 7560 Op.getOperand(4), // vindex 7561 Offsets.first, // voffset 7562 Op.getOperand(6), // soffset 7563 Offsets.second, // offset 7564 Op.getOperand(7), // format 7565 Op.getOperand(8), // cachepolicy, swizzled buffer 7566 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7567 }; 7568 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7569 AMDGPUISD::TBUFFER_STORE_FORMAT; 7570 MemSDNode *M = cast<MemSDNode>(Op); 7571 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7572 M->getMemoryVT(), M->getMemOperand()); 7573 } 7574 7575 case Intrinsic::amdgcn_raw_tbuffer_store: { 7576 SDValue VData = Op.getOperand(2); 7577 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7578 if (IsD16) 7579 VData = handleD16VData(VData, DAG); 7580 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7581 SDValue Ops[] = { 7582 Chain, 7583 VData, // vdata 7584 Op.getOperand(3), // rsrc 7585 DAG.getConstant(0, DL, MVT::i32), // vindex 7586 Offsets.first, // voffset 7587 Op.getOperand(5), // soffset 7588 Offsets.second, // offset 7589 Op.getOperand(6), // format 7590 Op.getOperand(7), // cachepolicy, swizzled buffer 7591 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7592 }; 7593 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7594 AMDGPUISD::TBUFFER_STORE_FORMAT; 7595 MemSDNode *M = cast<MemSDNode>(Op); 7596 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7597 M->getMemoryVT(), M->getMemOperand()); 7598 } 7599 7600 case Intrinsic::amdgcn_buffer_store: 7601 case Intrinsic::amdgcn_buffer_store_format: { 7602 SDValue VData = Op.getOperand(2); 7603 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7604 if (IsD16) 7605 VData = handleD16VData(VData, DAG); 7606 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7607 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7608 unsigned IdxEn = 1; 7609 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7610 IdxEn = Idx->getZExtValue() != 0; 7611 SDValue Ops[] = { 7612 Chain, 7613 VData, 7614 Op.getOperand(3), // rsrc 7615 Op.getOperand(4), // vindex 7616 SDValue(), // voffset -- will be set by setBufferOffsets 7617 SDValue(), // soffset -- will be set by setBufferOffsets 7618 SDValue(), // offset -- will be set by setBufferOffsets 7619 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7620 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7621 }; 7622 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7623 // We don't know the offset if vindex is non-zero, so clear it. 7624 if (IdxEn) 7625 Offset = 0; 7626 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7627 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7628 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7629 MemSDNode *M = cast<MemSDNode>(Op); 7630 M->getMemOperand()->setOffset(Offset); 7631 7632 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7633 EVT VDataType = VData.getValueType().getScalarType(); 7634 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7635 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7636 7637 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7638 M->getMemoryVT(), M->getMemOperand()); 7639 } 7640 7641 case Intrinsic::amdgcn_raw_buffer_store: 7642 case Intrinsic::amdgcn_raw_buffer_store_format: { 7643 const bool IsFormat = 7644 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7645 7646 SDValue VData = Op.getOperand(2); 7647 EVT VDataVT = VData.getValueType(); 7648 EVT EltType = VDataVT.getScalarType(); 7649 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7650 if (IsD16) { 7651 VData = handleD16VData(VData, DAG); 7652 VDataVT = VData.getValueType(); 7653 } 7654 7655 if (!isTypeLegal(VDataVT)) { 7656 VData = 7657 DAG.getNode(ISD::BITCAST, DL, 7658 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7659 } 7660 7661 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7662 SDValue Ops[] = { 7663 Chain, 7664 VData, 7665 Op.getOperand(3), // rsrc 7666 DAG.getConstant(0, DL, MVT::i32), // vindex 7667 Offsets.first, // voffset 7668 Op.getOperand(5), // soffset 7669 Offsets.second, // offset 7670 Op.getOperand(6), // cachepolicy, swizzled buffer 7671 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7672 }; 7673 unsigned Opc = 7674 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7675 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7676 MemSDNode *M = cast<MemSDNode>(Op); 7677 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7678 7679 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7680 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7681 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7682 7683 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7684 M->getMemoryVT(), M->getMemOperand()); 7685 } 7686 7687 case Intrinsic::amdgcn_struct_buffer_store: 7688 case Intrinsic::amdgcn_struct_buffer_store_format: { 7689 const bool IsFormat = 7690 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7691 7692 SDValue VData = Op.getOperand(2); 7693 EVT VDataVT = VData.getValueType(); 7694 EVT EltType = VDataVT.getScalarType(); 7695 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7696 7697 if (IsD16) { 7698 VData = handleD16VData(VData, DAG); 7699 VDataVT = VData.getValueType(); 7700 } 7701 7702 if (!isTypeLegal(VDataVT)) { 7703 VData = 7704 DAG.getNode(ISD::BITCAST, DL, 7705 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7706 } 7707 7708 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7709 SDValue Ops[] = { 7710 Chain, 7711 VData, 7712 Op.getOperand(3), // rsrc 7713 Op.getOperand(4), // vindex 7714 Offsets.first, // voffset 7715 Op.getOperand(6), // soffset 7716 Offsets.second, // offset 7717 Op.getOperand(7), // cachepolicy, swizzled buffer 7718 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7719 }; 7720 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7721 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7722 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7723 MemSDNode *M = cast<MemSDNode>(Op); 7724 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7725 Ops[3])); 7726 7727 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7728 EVT VDataType = VData.getValueType().getScalarType(); 7729 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7730 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7731 7732 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7733 M->getMemoryVT(), M->getMemOperand()); 7734 } 7735 case Intrinsic::amdgcn_end_cf: 7736 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7737 Op->getOperand(2), Chain), 0); 7738 7739 default: { 7740 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7741 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7742 return lowerImage(Op, ImageDimIntr, DAG, true); 7743 7744 return Op; 7745 } 7746 } 7747 } 7748 7749 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7750 // offset (the offset that is included in bounds checking and swizzling, to be 7751 // split between the instruction's voffset and immoffset fields) and soffset 7752 // (the offset that is excluded from bounds checking and swizzling, to go in 7753 // the instruction's soffset field). This function takes the first kind of 7754 // offset and figures out how to split it between voffset and immoffset. 7755 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7756 SDValue Offset, SelectionDAG &DAG) const { 7757 SDLoc DL(Offset); 7758 const unsigned MaxImm = 4095; 7759 SDValue N0 = Offset; 7760 ConstantSDNode *C1 = nullptr; 7761 7762 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7763 N0 = SDValue(); 7764 else if (DAG.isBaseWithConstantOffset(N0)) { 7765 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7766 N0 = N0.getOperand(0); 7767 } 7768 7769 if (C1) { 7770 unsigned ImmOffset = C1->getZExtValue(); 7771 // If the immediate value is too big for the immoffset field, put the value 7772 // and -4096 into the immoffset field so that the value that is copied/added 7773 // for the voffset field is a multiple of 4096, and it stands more chance 7774 // of being CSEd with the copy/add for another similar load/store. 7775 // However, do not do that rounding down to a multiple of 4096 if that is a 7776 // negative number, as it appears to be illegal to have a negative offset 7777 // in the vgpr, even if adding the immediate offset makes it positive. 7778 unsigned Overflow = ImmOffset & ~MaxImm; 7779 ImmOffset -= Overflow; 7780 if ((int32_t)Overflow < 0) { 7781 Overflow += ImmOffset; 7782 ImmOffset = 0; 7783 } 7784 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7785 if (Overflow) { 7786 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7787 if (!N0) 7788 N0 = OverflowVal; 7789 else { 7790 SDValue Ops[] = { N0, OverflowVal }; 7791 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7792 } 7793 } 7794 } 7795 if (!N0) 7796 N0 = DAG.getConstant(0, DL, MVT::i32); 7797 if (!C1) 7798 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7799 return {N0, SDValue(C1, 0)}; 7800 } 7801 7802 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7803 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7804 // pointed to by Offsets. 7805 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7806 SelectionDAG &DAG, SDValue *Offsets, 7807 Align Alignment) const { 7808 SDLoc DL(CombinedOffset); 7809 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7810 uint32_t Imm = C->getZExtValue(); 7811 uint32_t SOffset, ImmOffset; 7812 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7813 Alignment)) { 7814 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7815 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7816 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7817 return SOffset + ImmOffset; 7818 } 7819 } 7820 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7821 SDValue N0 = CombinedOffset.getOperand(0); 7822 SDValue N1 = CombinedOffset.getOperand(1); 7823 uint32_t SOffset, ImmOffset; 7824 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7825 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7826 Subtarget, Alignment)) { 7827 Offsets[0] = N0; 7828 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7829 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7830 return 0; 7831 } 7832 } 7833 Offsets[0] = CombinedOffset; 7834 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7835 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7836 return 0; 7837 } 7838 7839 // Handle 8 bit and 16 bit buffer loads 7840 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7841 EVT LoadVT, SDLoc DL, 7842 ArrayRef<SDValue> Ops, 7843 MemSDNode *M) const { 7844 EVT IntVT = LoadVT.changeTypeToInteger(); 7845 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7846 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7847 7848 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7849 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7850 Ops, IntVT, 7851 M->getMemOperand()); 7852 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7853 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7854 7855 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7856 } 7857 7858 // Handle 8 bit and 16 bit buffer stores 7859 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7860 EVT VDataType, SDLoc DL, 7861 SDValue Ops[], 7862 MemSDNode *M) const { 7863 if (VDataType == MVT::f16) 7864 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7865 7866 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7867 Ops[1] = BufferStoreExt; 7868 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7869 AMDGPUISD::BUFFER_STORE_SHORT; 7870 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7871 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7872 M->getMemOperand()); 7873 } 7874 7875 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7876 ISD::LoadExtType ExtType, SDValue Op, 7877 const SDLoc &SL, EVT VT) { 7878 if (VT.bitsLT(Op.getValueType())) 7879 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7880 7881 switch (ExtType) { 7882 case ISD::SEXTLOAD: 7883 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7884 case ISD::ZEXTLOAD: 7885 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7886 case ISD::EXTLOAD: 7887 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7888 case ISD::NON_EXTLOAD: 7889 return Op; 7890 } 7891 7892 llvm_unreachable("invalid ext type"); 7893 } 7894 7895 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7896 SelectionDAG &DAG = DCI.DAG; 7897 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7898 return SDValue(); 7899 7900 // FIXME: Constant loads should all be marked invariant. 7901 unsigned AS = Ld->getAddressSpace(); 7902 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7903 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7904 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7905 return SDValue(); 7906 7907 // Don't do this early, since it may interfere with adjacent load merging for 7908 // illegal types. We can avoid losing alignment information for exotic types 7909 // pre-legalize. 7910 EVT MemVT = Ld->getMemoryVT(); 7911 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7912 MemVT.getSizeInBits() >= 32) 7913 return SDValue(); 7914 7915 SDLoc SL(Ld); 7916 7917 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7918 "unexpected vector extload"); 7919 7920 // TODO: Drop only high part of range. 7921 SDValue Ptr = Ld->getBasePtr(); 7922 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7923 MVT::i32, SL, Ld->getChain(), Ptr, 7924 Ld->getOffset(), 7925 Ld->getPointerInfo(), MVT::i32, 7926 Ld->getAlignment(), 7927 Ld->getMemOperand()->getFlags(), 7928 Ld->getAAInfo(), 7929 nullptr); // Drop ranges 7930 7931 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7932 if (MemVT.isFloatingPoint()) { 7933 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7934 "unexpected fp extload"); 7935 TruncVT = MemVT.changeTypeToInteger(); 7936 } 7937 7938 SDValue Cvt = NewLoad; 7939 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7940 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7941 DAG.getValueType(TruncVT)); 7942 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7943 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7944 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7945 } else { 7946 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7947 } 7948 7949 EVT VT = Ld->getValueType(0); 7950 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7951 7952 DCI.AddToWorklist(Cvt.getNode()); 7953 7954 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7955 // the appropriate extension from the 32-bit load. 7956 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7957 DCI.AddToWorklist(Cvt.getNode()); 7958 7959 // Handle conversion back to floating point if necessary. 7960 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7961 7962 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7963 } 7964 7965 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7966 SDLoc DL(Op); 7967 LoadSDNode *Load = cast<LoadSDNode>(Op); 7968 ISD::LoadExtType ExtType = Load->getExtensionType(); 7969 EVT MemVT = Load->getMemoryVT(); 7970 7971 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7972 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7973 return SDValue(); 7974 7975 // FIXME: Copied from PPC 7976 // First, load into 32 bits, then truncate to 1 bit. 7977 7978 SDValue Chain = Load->getChain(); 7979 SDValue BasePtr = Load->getBasePtr(); 7980 MachineMemOperand *MMO = Load->getMemOperand(); 7981 7982 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7983 7984 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7985 BasePtr, RealMemVT, MMO); 7986 7987 if (!MemVT.isVector()) { 7988 SDValue Ops[] = { 7989 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7990 NewLD.getValue(1) 7991 }; 7992 7993 return DAG.getMergeValues(Ops, DL); 7994 } 7995 7996 SmallVector<SDValue, 3> Elts; 7997 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7998 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7999 DAG.getConstant(I, DL, MVT::i32)); 8000 8001 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8002 } 8003 8004 SDValue Ops[] = { 8005 DAG.getBuildVector(MemVT, DL, Elts), 8006 NewLD.getValue(1) 8007 }; 8008 8009 return DAG.getMergeValues(Ops, DL); 8010 } 8011 8012 if (!MemVT.isVector()) 8013 return SDValue(); 8014 8015 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8016 "Custom lowering for non-i32 vectors hasn't been implemented."); 8017 8018 unsigned Alignment = Load->getAlignment(); 8019 unsigned AS = Load->getAddressSpace(); 8020 if (Subtarget->hasLDSMisalignedBug() && 8021 AS == AMDGPUAS::FLAT_ADDRESS && 8022 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8023 return SplitVectorLoad(Op, DAG); 8024 } 8025 8026 MachineFunction &MF = DAG.getMachineFunction(); 8027 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8028 // If there is a possibilty that flat instruction access scratch memory 8029 // then we need to use the same legalization rules we use for private. 8030 if (AS == AMDGPUAS::FLAT_ADDRESS && 8031 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8032 AS = MFI->hasFlatScratchInit() ? 8033 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8034 8035 unsigned NumElements = MemVT.getVectorNumElements(); 8036 8037 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8038 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8039 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8040 if (MemVT.isPow2VectorType()) 8041 return SDValue(); 8042 return WidenOrSplitVectorLoad(Op, DAG); 8043 } 8044 // Non-uniform loads will be selected to MUBUF instructions, so they 8045 // have the same legalization requirements as global and private 8046 // loads. 8047 // 8048 } 8049 8050 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8051 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8052 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8053 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8054 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8055 Alignment >= 4 && NumElements < 32) { 8056 if (MemVT.isPow2VectorType()) 8057 return SDValue(); 8058 return WidenOrSplitVectorLoad(Op, DAG); 8059 } 8060 // Non-uniform loads will be selected to MUBUF instructions, so they 8061 // have the same legalization requirements as global and private 8062 // loads. 8063 // 8064 } 8065 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8066 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8067 AS == AMDGPUAS::GLOBAL_ADDRESS || 8068 AS == AMDGPUAS::FLAT_ADDRESS) { 8069 if (NumElements > 4) 8070 return SplitVectorLoad(Op, DAG); 8071 // v3 loads not supported on SI. 8072 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8073 return WidenOrSplitVectorLoad(Op, DAG); 8074 8075 // v3 and v4 loads are supported for private and global memory. 8076 return SDValue(); 8077 } 8078 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8079 // Depending on the setting of the private_element_size field in the 8080 // resource descriptor, we can only make private accesses up to a certain 8081 // size. 8082 switch (Subtarget->getMaxPrivateElementSize()) { 8083 case 4: { 8084 SDValue Ops[2]; 8085 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8086 return DAG.getMergeValues(Ops, DL); 8087 } 8088 case 8: 8089 if (NumElements > 2) 8090 return SplitVectorLoad(Op, DAG); 8091 return SDValue(); 8092 case 16: 8093 // Same as global/flat 8094 if (NumElements > 4) 8095 return SplitVectorLoad(Op, DAG); 8096 // v3 loads not supported on SI. 8097 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8098 return WidenOrSplitVectorLoad(Op, DAG); 8099 8100 return SDValue(); 8101 default: 8102 llvm_unreachable("unsupported private_element_size"); 8103 } 8104 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8105 // Use ds_read_b128 or ds_read_b96 when possible. 8106 if (Subtarget->hasDS96AndDS128() && 8107 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8108 MemVT.getStoreSize() == 12) && 8109 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8110 Load->getAlign())) 8111 return SDValue(); 8112 8113 if (NumElements > 2) 8114 return SplitVectorLoad(Op, DAG); 8115 8116 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8117 // address is negative, then the instruction is incorrectly treated as 8118 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8119 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8120 // load later in the SILoadStoreOptimizer. 8121 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8122 NumElements == 2 && MemVT.getStoreSize() == 8 && 8123 Load->getAlignment() < 8) { 8124 return SplitVectorLoad(Op, DAG); 8125 } 8126 } 8127 8128 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8129 MemVT, *Load->getMemOperand())) { 8130 SDValue Ops[2]; 8131 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8132 return DAG.getMergeValues(Ops, DL); 8133 } 8134 8135 return SDValue(); 8136 } 8137 8138 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8139 EVT VT = Op.getValueType(); 8140 assert(VT.getSizeInBits() == 64); 8141 8142 SDLoc DL(Op); 8143 SDValue Cond = Op.getOperand(0); 8144 8145 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8146 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8147 8148 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8149 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8150 8151 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8152 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8153 8154 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8155 8156 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8157 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8158 8159 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8160 8161 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8162 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8163 } 8164 8165 // Catch division cases where we can use shortcuts with rcp and rsq 8166 // instructions. 8167 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8168 SelectionDAG &DAG) const { 8169 SDLoc SL(Op); 8170 SDValue LHS = Op.getOperand(0); 8171 SDValue RHS = Op.getOperand(1); 8172 EVT VT = Op.getValueType(); 8173 const SDNodeFlags Flags = Op->getFlags(); 8174 8175 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8176 8177 // Without !fpmath accuracy information, we can't do more because we don't 8178 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8179 if (!AllowInaccurateRcp) 8180 return SDValue(); 8181 8182 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8183 if (CLHS->isExactlyValue(1.0)) { 8184 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8185 // the CI documentation has a worst case error of 1 ulp. 8186 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8187 // use it as long as we aren't trying to use denormals. 8188 // 8189 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8190 8191 // 1.0 / sqrt(x) -> rsq(x) 8192 8193 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8194 // error seems really high at 2^29 ULP. 8195 if (RHS.getOpcode() == ISD::FSQRT) 8196 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8197 8198 // 1.0 / x -> rcp(x) 8199 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8200 } 8201 8202 // Same as for 1.0, but expand the sign out of the constant. 8203 if (CLHS->isExactlyValue(-1.0)) { 8204 // -1.0 / x -> rcp (fneg x) 8205 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8206 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8207 } 8208 } 8209 8210 // Turn into multiply by the reciprocal. 8211 // x / y -> x * (1.0 / y) 8212 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8213 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8214 } 8215 8216 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8217 SelectionDAG &DAG) const { 8218 SDLoc SL(Op); 8219 SDValue X = Op.getOperand(0); 8220 SDValue Y = Op.getOperand(1); 8221 EVT VT = Op.getValueType(); 8222 const SDNodeFlags Flags = Op->getFlags(); 8223 8224 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8225 DAG.getTarget().Options.UnsafeFPMath; 8226 if (!AllowInaccurateDiv) 8227 return SDValue(); 8228 8229 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8230 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8231 8232 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8233 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8234 8235 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8236 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8237 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8238 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8239 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8240 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8241 } 8242 8243 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8244 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8245 SDNodeFlags Flags) { 8246 if (GlueChain->getNumValues() <= 1) { 8247 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8248 } 8249 8250 assert(GlueChain->getNumValues() == 3); 8251 8252 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8253 switch (Opcode) { 8254 default: llvm_unreachable("no chain equivalent for opcode"); 8255 case ISD::FMUL: 8256 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8257 break; 8258 } 8259 8260 return DAG.getNode(Opcode, SL, VTList, 8261 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8262 Flags); 8263 } 8264 8265 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8266 EVT VT, SDValue A, SDValue B, SDValue C, 8267 SDValue GlueChain, SDNodeFlags Flags) { 8268 if (GlueChain->getNumValues() <= 1) { 8269 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8270 } 8271 8272 assert(GlueChain->getNumValues() == 3); 8273 8274 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8275 switch (Opcode) { 8276 default: llvm_unreachable("no chain equivalent for opcode"); 8277 case ISD::FMA: 8278 Opcode = AMDGPUISD::FMA_W_CHAIN; 8279 break; 8280 } 8281 8282 return DAG.getNode(Opcode, SL, VTList, 8283 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8284 Flags); 8285 } 8286 8287 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8288 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8289 return FastLowered; 8290 8291 SDLoc SL(Op); 8292 SDValue Src0 = Op.getOperand(0); 8293 SDValue Src1 = Op.getOperand(1); 8294 8295 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8296 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8297 8298 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8299 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8300 8301 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8302 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8303 8304 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8305 } 8306 8307 // Faster 2.5 ULP division that does not support denormals. 8308 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8309 SDLoc SL(Op); 8310 SDValue LHS = Op.getOperand(1); 8311 SDValue RHS = Op.getOperand(2); 8312 8313 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8314 8315 const APFloat K0Val(BitsToFloat(0x6f800000)); 8316 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8317 8318 const APFloat K1Val(BitsToFloat(0x2f800000)); 8319 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8320 8321 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8322 8323 EVT SetCCVT = 8324 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8325 8326 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8327 8328 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8329 8330 // TODO: Should this propagate fast-math-flags? 8331 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8332 8333 // rcp does not support denormals. 8334 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8335 8336 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8337 8338 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8339 } 8340 8341 // Returns immediate value for setting the F32 denorm mode when using the 8342 // S_DENORM_MODE instruction. 8343 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8344 const SDLoc &SL, const GCNSubtarget *ST) { 8345 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8346 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8347 ? FP_DENORM_FLUSH_NONE 8348 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8349 8350 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8351 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8352 } 8353 8354 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8355 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8356 return FastLowered; 8357 8358 // The selection matcher assumes anything with a chain selecting to a 8359 // mayRaiseFPException machine instruction. Since we're introducing a chain 8360 // here, we need to explicitly report nofpexcept for the regular fdiv 8361 // lowering. 8362 SDNodeFlags Flags = Op->getFlags(); 8363 Flags.setNoFPExcept(true); 8364 8365 SDLoc SL(Op); 8366 SDValue LHS = Op.getOperand(0); 8367 SDValue RHS = Op.getOperand(1); 8368 8369 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8370 8371 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8372 8373 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8374 {RHS, RHS, LHS}, Flags); 8375 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8376 {LHS, RHS, LHS}, Flags); 8377 8378 // Denominator is scaled to not be denormal, so using rcp is ok. 8379 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8380 DenominatorScaled, Flags); 8381 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8382 DenominatorScaled, Flags); 8383 8384 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8385 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8386 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8387 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8388 8389 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8390 8391 if (!HasFP32Denormals) { 8392 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8393 // lowering. The chain dependence is insufficient, and we need glue. We do 8394 // not need the glue variants in a strictfp function. 8395 8396 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8397 8398 SDNode *EnableDenorm; 8399 if (Subtarget->hasDenormModeInst()) { 8400 const SDValue EnableDenormValue = 8401 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8402 8403 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8404 DAG.getEntryNode(), EnableDenormValue).getNode(); 8405 } else { 8406 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8407 SL, MVT::i32); 8408 EnableDenorm = 8409 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8410 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8411 } 8412 8413 SDValue Ops[3] = { 8414 NegDivScale0, 8415 SDValue(EnableDenorm, 0), 8416 SDValue(EnableDenorm, 1) 8417 }; 8418 8419 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8420 } 8421 8422 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8423 ApproxRcp, One, NegDivScale0, Flags); 8424 8425 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8426 ApproxRcp, Fma0, Flags); 8427 8428 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8429 Fma1, Fma1, Flags); 8430 8431 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8432 NumeratorScaled, Mul, Flags); 8433 8434 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8435 Fma2, Fma1, Mul, Fma2, Flags); 8436 8437 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8438 NumeratorScaled, Fma3, Flags); 8439 8440 if (!HasFP32Denormals) { 8441 SDNode *DisableDenorm; 8442 if (Subtarget->hasDenormModeInst()) { 8443 const SDValue DisableDenormValue = 8444 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8445 8446 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8447 Fma4.getValue(1), DisableDenormValue, 8448 Fma4.getValue(2)).getNode(); 8449 } else { 8450 const SDValue DisableDenormValue = 8451 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8452 8453 DisableDenorm = DAG.getMachineNode( 8454 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8455 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8456 } 8457 8458 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8459 SDValue(DisableDenorm, 0), DAG.getRoot()); 8460 DAG.setRoot(OutputChain); 8461 } 8462 8463 SDValue Scale = NumeratorScaled.getValue(1); 8464 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8465 {Fma4, Fma1, Fma3, Scale}, Flags); 8466 8467 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8468 } 8469 8470 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8471 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8472 return FastLowered; 8473 8474 SDLoc SL(Op); 8475 SDValue X = Op.getOperand(0); 8476 SDValue Y = Op.getOperand(1); 8477 8478 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8479 8480 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8481 8482 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8483 8484 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8485 8486 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8487 8488 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8489 8490 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8491 8492 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8493 8494 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8495 8496 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8497 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8498 8499 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8500 NegDivScale0, Mul, DivScale1); 8501 8502 SDValue Scale; 8503 8504 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8505 // Workaround a hardware bug on SI where the condition output from div_scale 8506 // is not usable. 8507 8508 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8509 8510 // Figure out if the scale to use for div_fmas. 8511 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8512 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8513 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8514 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8515 8516 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8517 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8518 8519 SDValue Scale0Hi 8520 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8521 SDValue Scale1Hi 8522 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8523 8524 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8525 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8526 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8527 } else { 8528 Scale = DivScale1.getValue(1); 8529 } 8530 8531 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8532 Fma4, Fma3, Mul, Scale); 8533 8534 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8535 } 8536 8537 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8538 EVT VT = Op.getValueType(); 8539 8540 if (VT == MVT::f32) 8541 return LowerFDIV32(Op, DAG); 8542 8543 if (VT == MVT::f64) 8544 return LowerFDIV64(Op, DAG); 8545 8546 if (VT == MVT::f16) 8547 return LowerFDIV16(Op, DAG); 8548 8549 llvm_unreachable("Unexpected type for fdiv"); 8550 } 8551 8552 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8553 SDLoc DL(Op); 8554 StoreSDNode *Store = cast<StoreSDNode>(Op); 8555 EVT VT = Store->getMemoryVT(); 8556 8557 if (VT == MVT::i1) { 8558 return DAG.getTruncStore(Store->getChain(), DL, 8559 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8560 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8561 } 8562 8563 assert(VT.isVector() && 8564 Store->getValue().getValueType().getScalarType() == MVT::i32); 8565 8566 unsigned AS = Store->getAddressSpace(); 8567 if (Subtarget->hasLDSMisalignedBug() && 8568 AS == AMDGPUAS::FLAT_ADDRESS && 8569 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8570 return SplitVectorStore(Op, DAG); 8571 } 8572 8573 MachineFunction &MF = DAG.getMachineFunction(); 8574 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8575 // If there is a possibilty that flat instruction access scratch memory 8576 // then we need to use the same legalization rules we use for private. 8577 if (AS == AMDGPUAS::FLAT_ADDRESS && 8578 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8579 AS = MFI->hasFlatScratchInit() ? 8580 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8581 8582 unsigned NumElements = VT.getVectorNumElements(); 8583 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8584 AS == AMDGPUAS::FLAT_ADDRESS) { 8585 if (NumElements > 4) 8586 return SplitVectorStore(Op, DAG); 8587 // v3 stores not supported on SI. 8588 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8589 return SplitVectorStore(Op, DAG); 8590 8591 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8592 VT, *Store->getMemOperand())) 8593 return expandUnalignedStore(Store, DAG); 8594 8595 return SDValue(); 8596 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8597 switch (Subtarget->getMaxPrivateElementSize()) { 8598 case 4: 8599 return scalarizeVectorStore(Store, DAG); 8600 case 8: 8601 if (NumElements > 2) 8602 return SplitVectorStore(Op, DAG); 8603 return SDValue(); 8604 case 16: 8605 if (NumElements > 4 || 8606 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8607 return SplitVectorStore(Op, DAG); 8608 return SDValue(); 8609 default: 8610 llvm_unreachable("unsupported private_element_size"); 8611 } 8612 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8613 // Use ds_write_b128 or ds_write_b96 when possible. 8614 if (Subtarget->hasDS96AndDS128() && 8615 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8616 (VT.getStoreSize() == 12)) && 8617 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8618 Store->getAlign())) 8619 return SDValue(); 8620 8621 if (NumElements > 2) 8622 return SplitVectorStore(Op, DAG); 8623 8624 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8625 // address is negative, then the instruction is incorrectly treated as 8626 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8627 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8628 // store later in the SILoadStoreOptimizer. 8629 if (!Subtarget->hasUsableDSOffset() && 8630 NumElements == 2 && VT.getStoreSize() == 8 && 8631 Store->getAlignment() < 8) { 8632 return SplitVectorStore(Op, DAG); 8633 } 8634 8635 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8636 VT, *Store->getMemOperand())) { 8637 if (VT.isVector()) 8638 return SplitVectorStore(Op, DAG); 8639 return expandUnalignedStore(Store, DAG); 8640 } 8641 8642 return SDValue(); 8643 } else { 8644 llvm_unreachable("unhandled address space"); 8645 } 8646 } 8647 8648 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8649 SDLoc DL(Op); 8650 EVT VT = Op.getValueType(); 8651 SDValue Arg = Op.getOperand(0); 8652 SDValue TrigVal; 8653 8654 // Propagate fast-math flags so that the multiply we introduce can be folded 8655 // if Arg is already the result of a multiply by constant. 8656 auto Flags = Op->getFlags(); 8657 8658 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8659 8660 if (Subtarget->hasTrigReducedRange()) { 8661 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8662 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8663 } else { 8664 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8665 } 8666 8667 switch (Op.getOpcode()) { 8668 case ISD::FCOS: 8669 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8670 case ISD::FSIN: 8671 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8672 default: 8673 llvm_unreachable("Wrong trig opcode"); 8674 } 8675 } 8676 8677 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8678 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8679 assert(AtomicNode->isCompareAndSwap()); 8680 unsigned AS = AtomicNode->getAddressSpace(); 8681 8682 // No custom lowering required for local address space 8683 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8684 return Op; 8685 8686 // Non-local address space requires custom lowering for atomic compare 8687 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8688 SDLoc DL(Op); 8689 SDValue ChainIn = Op.getOperand(0); 8690 SDValue Addr = Op.getOperand(1); 8691 SDValue Old = Op.getOperand(2); 8692 SDValue New = Op.getOperand(3); 8693 EVT VT = Op.getValueType(); 8694 MVT SimpleVT = VT.getSimpleVT(); 8695 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8696 8697 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8698 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8699 8700 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8701 Ops, VT, AtomicNode->getMemOperand()); 8702 } 8703 8704 //===----------------------------------------------------------------------===// 8705 // Custom DAG optimizations 8706 //===----------------------------------------------------------------------===// 8707 8708 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8709 DAGCombinerInfo &DCI) const { 8710 EVT VT = N->getValueType(0); 8711 EVT ScalarVT = VT.getScalarType(); 8712 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8713 return SDValue(); 8714 8715 SelectionDAG &DAG = DCI.DAG; 8716 SDLoc DL(N); 8717 8718 SDValue Src = N->getOperand(0); 8719 EVT SrcVT = Src.getValueType(); 8720 8721 // TODO: We could try to match extracting the higher bytes, which would be 8722 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8723 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8724 // about in practice. 8725 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8726 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8727 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8728 DCI.AddToWorklist(Cvt.getNode()); 8729 8730 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8731 if (ScalarVT != MVT::f32) { 8732 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8733 DAG.getTargetConstant(0, DL, MVT::i32)); 8734 } 8735 return Cvt; 8736 } 8737 } 8738 8739 return SDValue(); 8740 } 8741 8742 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8743 8744 // This is a variant of 8745 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8746 // 8747 // The normal DAG combiner will do this, but only if the add has one use since 8748 // that would increase the number of instructions. 8749 // 8750 // This prevents us from seeing a constant offset that can be folded into a 8751 // memory instruction's addressing mode. If we know the resulting add offset of 8752 // a pointer can be folded into an addressing offset, we can replace the pointer 8753 // operand with the add of new constant offset. This eliminates one of the uses, 8754 // and may allow the remaining use to also be simplified. 8755 // 8756 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8757 unsigned AddrSpace, 8758 EVT MemVT, 8759 DAGCombinerInfo &DCI) const { 8760 SDValue N0 = N->getOperand(0); 8761 SDValue N1 = N->getOperand(1); 8762 8763 // We only do this to handle cases where it's profitable when there are 8764 // multiple uses of the add, so defer to the standard combine. 8765 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8766 N0->hasOneUse()) 8767 return SDValue(); 8768 8769 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8770 if (!CN1) 8771 return SDValue(); 8772 8773 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8774 if (!CAdd) 8775 return SDValue(); 8776 8777 // If the resulting offset is too large, we can't fold it into the addressing 8778 // mode offset. 8779 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8780 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8781 8782 AddrMode AM; 8783 AM.HasBaseReg = true; 8784 AM.BaseOffs = Offset.getSExtValue(); 8785 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8786 return SDValue(); 8787 8788 SelectionDAG &DAG = DCI.DAG; 8789 SDLoc SL(N); 8790 EVT VT = N->getValueType(0); 8791 8792 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8793 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8794 8795 SDNodeFlags Flags; 8796 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8797 (N0.getOpcode() == ISD::OR || 8798 N0->getFlags().hasNoUnsignedWrap())); 8799 8800 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8801 } 8802 8803 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8804 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8805 /// specific intrinsic, but they all place the pointer operand first. 8806 static unsigned getBasePtrIndex(const MemSDNode *N) { 8807 switch (N->getOpcode()) { 8808 case ISD::STORE: 8809 case ISD::INTRINSIC_W_CHAIN: 8810 case ISD::INTRINSIC_VOID: 8811 return 2; 8812 default: 8813 return 1; 8814 } 8815 } 8816 8817 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8818 DAGCombinerInfo &DCI) const { 8819 SelectionDAG &DAG = DCI.DAG; 8820 SDLoc SL(N); 8821 8822 unsigned PtrIdx = getBasePtrIndex(N); 8823 SDValue Ptr = N->getOperand(PtrIdx); 8824 8825 // TODO: We could also do this for multiplies. 8826 if (Ptr.getOpcode() == ISD::SHL) { 8827 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8828 N->getMemoryVT(), DCI); 8829 if (NewPtr) { 8830 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8831 8832 NewOps[PtrIdx] = NewPtr; 8833 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8834 } 8835 } 8836 8837 return SDValue(); 8838 } 8839 8840 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8841 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8842 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8843 (Opc == ISD::XOR && Val == 0); 8844 } 8845 8846 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8847 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8848 // integer combine opportunities since most 64-bit operations are decomposed 8849 // this way. TODO: We won't want this for SALU especially if it is an inline 8850 // immediate. 8851 SDValue SITargetLowering::splitBinaryBitConstantOp( 8852 DAGCombinerInfo &DCI, 8853 const SDLoc &SL, 8854 unsigned Opc, SDValue LHS, 8855 const ConstantSDNode *CRHS) const { 8856 uint64_t Val = CRHS->getZExtValue(); 8857 uint32_t ValLo = Lo_32(Val); 8858 uint32_t ValHi = Hi_32(Val); 8859 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8860 8861 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8862 bitOpWithConstantIsReducible(Opc, ValHi)) || 8863 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8864 // If we need to materialize a 64-bit immediate, it will be split up later 8865 // anyway. Avoid creating the harder to understand 64-bit immediate 8866 // materialization. 8867 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8868 } 8869 8870 return SDValue(); 8871 } 8872 8873 // Returns true if argument is a boolean value which is not serialized into 8874 // memory or argument and does not require v_cndmask_b32 to be deserialized. 8875 static bool isBoolSGPR(SDValue V) { 8876 if (V.getValueType() != MVT::i1) 8877 return false; 8878 switch (V.getOpcode()) { 8879 default: 8880 break; 8881 case ISD::SETCC: 8882 case AMDGPUISD::FP_CLASS: 8883 return true; 8884 case ISD::AND: 8885 case ISD::OR: 8886 case ISD::XOR: 8887 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 8888 } 8889 return false; 8890 } 8891 8892 // If a constant has all zeroes or all ones within each byte return it. 8893 // Otherwise return 0. 8894 static uint32_t getConstantPermuteMask(uint32_t C) { 8895 // 0xff for any zero byte in the mask 8896 uint32_t ZeroByteMask = 0; 8897 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8898 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8899 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8900 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8901 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8902 if ((NonZeroByteMask & C) != NonZeroByteMask) 8903 return 0; // Partial bytes selected. 8904 return C; 8905 } 8906 8907 // Check if a node selects whole bytes from its operand 0 starting at a byte 8908 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8909 // or -1 if not succeeded. 8910 // Note byte select encoding: 8911 // value 0-3 selects corresponding source byte; 8912 // value 0xc selects zero; 8913 // value 0xff selects 0xff. 8914 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8915 assert(V.getValueSizeInBits() == 32); 8916 8917 if (V.getNumOperands() != 2) 8918 return ~0; 8919 8920 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8921 if (!N1) 8922 return ~0; 8923 8924 uint32_t C = N1->getZExtValue(); 8925 8926 switch (V.getOpcode()) { 8927 default: 8928 break; 8929 case ISD::AND: 8930 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8931 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8932 } 8933 break; 8934 8935 case ISD::OR: 8936 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8937 return (0x03020100 & ~ConstMask) | ConstMask; 8938 } 8939 break; 8940 8941 case ISD::SHL: 8942 if (C % 8) 8943 return ~0; 8944 8945 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8946 8947 case ISD::SRL: 8948 if (C % 8) 8949 return ~0; 8950 8951 return uint32_t(0x0c0c0c0c03020100ull >> C); 8952 } 8953 8954 return ~0; 8955 } 8956 8957 SDValue SITargetLowering::performAndCombine(SDNode *N, 8958 DAGCombinerInfo &DCI) const { 8959 if (DCI.isBeforeLegalize()) 8960 return SDValue(); 8961 8962 SelectionDAG &DAG = DCI.DAG; 8963 EVT VT = N->getValueType(0); 8964 SDValue LHS = N->getOperand(0); 8965 SDValue RHS = N->getOperand(1); 8966 8967 8968 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8969 if (VT == MVT::i64 && CRHS) { 8970 if (SDValue Split 8971 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8972 return Split; 8973 } 8974 8975 if (CRHS && VT == MVT::i32) { 8976 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8977 // nb = number of trailing zeroes in mask 8978 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8979 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8980 uint64_t Mask = CRHS->getZExtValue(); 8981 unsigned Bits = countPopulation(Mask); 8982 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8983 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8984 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8985 unsigned Shift = CShift->getZExtValue(); 8986 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8987 unsigned Offset = NB + Shift; 8988 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8989 SDLoc SL(N); 8990 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8991 LHS->getOperand(0), 8992 DAG.getConstant(Offset, SL, MVT::i32), 8993 DAG.getConstant(Bits, SL, MVT::i32)); 8994 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8995 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8996 DAG.getValueType(NarrowVT)); 8997 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8998 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8999 return Shl; 9000 } 9001 } 9002 } 9003 9004 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9005 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9006 isa<ConstantSDNode>(LHS.getOperand(2))) { 9007 uint32_t Sel = getConstantPermuteMask(Mask); 9008 if (!Sel) 9009 return SDValue(); 9010 9011 // Select 0xc for all zero bytes 9012 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9013 SDLoc DL(N); 9014 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9015 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9016 } 9017 } 9018 9019 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9020 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9021 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9022 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9023 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9024 9025 SDValue X = LHS.getOperand(0); 9026 SDValue Y = RHS.getOperand(0); 9027 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9028 return SDValue(); 9029 9030 if (LCC == ISD::SETO) { 9031 if (X != LHS.getOperand(1)) 9032 return SDValue(); 9033 9034 if (RCC == ISD::SETUNE) { 9035 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9036 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9037 return SDValue(); 9038 9039 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9040 SIInstrFlags::N_SUBNORMAL | 9041 SIInstrFlags::N_ZERO | 9042 SIInstrFlags::P_ZERO | 9043 SIInstrFlags::P_SUBNORMAL | 9044 SIInstrFlags::P_NORMAL; 9045 9046 static_assert(((~(SIInstrFlags::S_NAN | 9047 SIInstrFlags::Q_NAN | 9048 SIInstrFlags::N_INFINITY | 9049 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9050 "mask not equal"); 9051 9052 SDLoc DL(N); 9053 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9054 X, DAG.getConstant(Mask, DL, MVT::i32)); 9055 } 9056 } 9057 } 9058 9059 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9060 std::swap(LHS, RHS); 9061 9062 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9063 RHS.hasOneUse()) { 9064 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9065 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9066 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9067 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9068 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9069 (RHS.getOperand(0) == LHS.getOperand(0) && 9070 LHS.getOperand(0) == LHS.getOperand(1))) { 9071 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9072 unsigned NewMask = LCC == ISD::SETO ? 9073 Mask->getZExtValue() & ~OrdMask : 9074 Mask->getZExtValue() & OrdMask; 9075 9076 SDLoc DL(N); 9077 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9078 DAG.getConstant(NewMask, DL, MVT::i32)); 9079 } 9080 } 9081 9082 if (VT == MVT::i32 && 9083 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9084 // and x, (sext cc from i1) => select cc, x, 0 9085 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9086 std::swap(LHS, RHS); 9087 if (isBoolSGPR(RHS.getOperand(0))) 9088 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9089 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9090 } 9091 9092 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9093 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9094 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9095 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9096 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9097 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9098 if (LHSMask != ~0u && RHSMask != ~0u) { 9099 // Canonicalize the expression in an attempt to have fewer unique masks 9100 // and therefore fewer registers used to hold the masks. 9101 if (LHSMask > RHSMask) { 9102 std::swap(LHSMask, RHSMask); 9103 std::swap(LHS, RHS); 9104 } 9105 9106 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9107 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9108 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9109 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9110 9111 // Check of we need to combine values from two sources within a byte. 9112 if (!(LHSUsedLanes & RHSUsedLanes) && 9113 // If we select high and lower word keep it for SDWA. 9114 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9115 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9116 // Each byte in each mask is either selector mask 0-3, or has higher 9117 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9118 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9119 // mask which is not 0xff wins. By anding both masks we have a correct 9120 // result except that 0x0c shall be corrected to give 0x0c only. 9121 uint32_t Mask = LHSMask & RHSMask; 9122 for (unsigned I = 0; I < 32; I += 8) { 9123 uint32_t ByteSel = 0xff << I; 9124 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9125 Mask &= (0x0c << I) & 0xffffffff; 9126 } 9127 9128 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9129 // or 0x0c. 9130 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9131 SDLoc DL(N); 9132 9133 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9134 LHS.getOperand(0), RHS.getOperand(0), 9135 DAG.getConstant(Sel, DL, MVT::i32)); 9136 } 9137 } 9138 } 9139 9140 return SDValue(); 9141 } 9142 9143 SDValue SITargetLowering::performOrCombine(SDNode *N, 9144 DAGCombinerInfo &DCI) const { 9145 SelectionDAG &DAG = DCI.DAG; 9146 SDValue LHS = N->getOperand(0); 9147 SDValue RHS = N->getOperand(1); 9148 9149 EVT VT = N->getValueType(0); 9150 if (VT == MVT::i1) { 9151 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9152 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9153 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9154 SDValue Src = LHS.getOperand(0); 9155 if (Src != RHS.getOperand(0)) 9156 return SDValue(); 9157 9158 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9159 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9160 if (!CLHS || !CRHS) 9161 return SDValue(); 9162 9163 // Only 10 bits are used. 9164 static const uint32_t MaxMask = 0x3ff; 9165 9166 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9167 SDLoc DL(N); 9168 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9169 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9170 } 9171 9172 return SDValue(); 9173 } 9174 9175 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9176 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9177 LHS.getOpcode() == AMDGPUISD::PERM && 9178 isa<ConstantSDNode>(LHS.getOperand(2))) { 9179 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9180 if (!Sel) 9181 return SDValue(); 9182 9183 Sel |= LHS.getConstantOperandVal(2); 9184 SDLoc DL(N); 9185 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9186 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9187 } 9188 9189 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9190 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9191 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9192 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9193 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9194 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9195 if (LHSMask != ~0u && RHSMask != ~0u) { 9196 // Canonicalize the expression in an attempt to have fewer unique masks 9197 // and therefore fewer registers used to hold the masks. 9198 if (LHSMask > RHSMask) { 9199 std::swap(LHSMask, RHSMask); 9200 std::swap(LHS, RHS); 9201 } 9202 9203 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9204 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9205 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9206 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9207 9208 // Check of we need to combine values from two sources within a byte. 9209 if (!(LHSUsedLanes & RHSUsedLanes) && 9210 // If we select high and lower word keep it for SDWA. 9211 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9212 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9213 // Kill zero bytes selected by other mask. Zero value is 0xc. 9214 LHSMask &= ~RHSUsedLanes; 9215 RHSMask &= ~LHSUsedLanes; 9216 // Add 4 to each active LHS lane 9217 LHSMask |= LHSUsedLanes & 0x04040404; 9218 // Combine masks 9219 uint32_t Sel = LHSMask | RHSMask; 9220 SDLoc DL(N); 9221 9222 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9223 LHS.getOperand(0), RHS.getOperand(0), 9224 DAG.getConstant(Sel, DL, MVT::i32)); 9225 } 9226 } 9227 } 9228 9229 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9230 return SDValue(); 9231 9232 // TODO: This could be a generic combine with a predicate for extracting the 9233 // high half of an integer being free. 9234 9235 // (or i64:x, (zero_extend i32:y)) -> 9236 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9237 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9238 RHS.getOpcode() != ISD::ZERO_EXTEND) 9239 std::swap(LHS, RHS); 9240 9241 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9242 SDValue ExtSrc = RHS.getOperand(0); 9243 EVT SrcVT = ExtSrc.getValueType(); 9244 if (SrcVT == MVT::i32) { 9245 SDLoc SL(N); 9246 SDValue LowLHS, HiBits; 9247 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9248 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9249 9250 DCI.AddToWorklist(LowOr.getNode()); 9251 DCI.AddToWorklist(HiBits.getNode()); 9252 9253 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9254 LowOr, HiBits); 9255 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9256 } 9257 } 9258 9259 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9260 if (CRHS) { 9261 if (SDValue Split 9262 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9263 return Split; 9264 } 9265 9266 return SDValue(); 9267 } 9268 9269 SDValue SITargetLowering::performXorCombine(SDNode *N, 9270 DAGCombinerInfo &DCI) const { 9271 EVT VT = N->getValueType(0); 9272 if (VT != MVT::i64) 9273 return SDValue(); 9274 9275 SDValue LHS = N->getOperand(0); 9276 SDValue RHS = N->getOperand(1); 9277 9278 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9279 if (CRHS) { 9280 if (SDValue Split 9281 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9282 return Split; 9283 } 9284 9285 return SDValue(); 9286 } 9287 9288 // Instructions that will be lowered with a final instruction that zeros the 9289 // high result bits. 9290 // XXX - probably only need to list legal operations. 9291 static bool fp16SrcZerosHighBits(unsigned Opc) { 9292 switch (Opc) { 9293 case ISD::FADD: 9294 case ISD::FSUB: 9295 case ISD::FMUL: 9296 case ISD::FDIV: 9297 case ISD::FREM: 9298 case ISD::FMA: 9299 case ISD::FMAD: 9300 case ISD::FCANONICALIZE: 9301 case ISD::FP_ROUND: 9302 case ISD::UINT_TO_FP: 9303 case ISD::SINT_TO_FP: 9304 case ISD::FABS: 9305 // Fabs is lowered to a bit operation, but it's an and which will clear the 9306 // high bits anyway. 9307 case ISD::FSQRT: 9308 case ISD::FSIN: 9309 case ISD::FCOS: 9310 case ISD::FPOWI: 9311 case ISD::FPOW: 9312 case ISD::FLOG: 9313 case ISD::FLOG2: 9314 case ISD::FLOG10: 9315 case ISD::FEXP: 9316 case ISD::FEXP2: 9317 case ISD::FCEIL: 9318 case ISD::FTRUNC: 9319 case ISD::FRINT: 9320 case ISD::FNEARBYINT: 9321 case ISD::FROUND: 9322 case ISD::FFLOOR: 9323 case ISD::FMINNUM: 9324 case ISD::FMAXNUM: 9325 case AMDGPUISD::FRACT: 9326 case AMDGPUISD::CLAMP: 9327 case AMDGPUISD::COS_HW: 9328 case AMDGPUISD::SIN_HW: 9329 case AMDGPUISD::FMIN3: 9330 case AMDGPUISD::FMAX3: 9331 case AMDGPUISD::FMED3: 9332 case AMDGPUISD::FMAD_FTZ: 9333 case AMDGPUISD::RCP: 9334 case AMDGPUISD::RSQ: 9335 case AMDGPUISD::RCP_IFLAG: 9336 case AMDGPUISD::LDEXP: 9337 return true; 9338 default: 9339 // fcopysign, select and others may be lowered to 32-bit bit operations 9340 // which don't zero the high bits. 9341 return false; 9342 } 9343 } 9344 9345 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9346 DAGCombinerInfo &DCI) const { 9347 if (!Subtarget->has16BitInsts() || 9348 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9349 return SDValue(); 9350 9351 EVT VT = N->getValueType(0); 9352 if (VT != MVT::i32) 9353 return SDValue(); 9354 9355 SDValue Src = N->getOperand(0); 9356 if (Src.getValueType() != MVT::i16) 9357 return SDValue(); 9358 9359 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9360 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9361 if (Src.getOpcode() == ISD::BITCAST) { 9362 SDValue BCSrc = Src.getOperand(0); 9363 if (BCSrc.getValueType() == MVT::f16 && 9364 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9365 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9366 } 9367 9368 return SDValue(); 9369 } 9370 9371 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9372 DAGCombinerInfo &DCI) 9373 const { 9374 SDValue Src = N->getOperand(0); 9375 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9376 9377 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9378 VTSign->getVT() == MVT::i8) || 9379 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9380 VTSign->getVT() == MVT::i16)) && 9381 Src.hasOneUse()) { 9382 auto *M = cast<MemSDNode>(Src); 9383 SDValue Ops[] = { 9384 Src.getOperand(0), // Chain 9385 Src.getOperand(1), // rsrc 9386 Src.getOperand(2), // vindex 9387 Src.getOperand(3), // voffset 9388 Src.getOperand(4), // soffset 9389 Src.getOperand(5), // offset 9390 Src.getOperand(6), 9391 Src.getOperand(7) 9392 }; 9393 // replace with BUFFER_LOAD_BYTE/SHORT 9394 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9395 Src.getOperand(0).getValueType()); 9396 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9397 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9398 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9399 ResList, 9400 Ops, M->getMemoryVT(), 9401 M->getMemOperand()); 9402 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9403 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9404 } 9405 return SDValue(); 9406 } 9407 9408 SDValue SITargetLowering::performClassCombine(SDNode *N, 9409 DAGCombinerInfo &DCI) const { 9410 SelectionDAG &DAG = DCI.DAG; 9411 SDValue Mask = N->getOperand(1); 9412 9413 // fp_class x, 0 -> false 9414 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9415 if (CMask->isNullValue()) 9416 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9417 } 9418 9419 if (N->getOperand(0).isUndef()) 9420 return DAG.getUNDEF(MVT::i1); 9421 9422 return SDValue(); 9423 } 9424 9425 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9426 DAGCombinerInfo &DCI) const { 9427 EVT VT = N->getValueType(0); 9428 SDValue N0 = N->getOperand(0); 9429 9430 if (N0.isUndef()) 9431 return N0; 9432 9433 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9434 N0.getOpcode() == ISD::SINT_TO_FP)) { 9435 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9436 N->getFlags()); 9437 } 9438 9439 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9440 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9441 N0.getOperand(0), N->getFlags()); 9442 } 9443 9444 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9445 } 9446 9447 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9448 unsigned MaxDepth) const { 9449 unsigned Opcode = Op.getOpcode(); 9450 if (Opcode == ISD::FCANONICALIZE) 9451 return true; 9452 9453 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9454 auto F = CFP->getValueAPF(); 9455 if (F.isNaN() && F.isSignaling()) 9456 return false; 9457 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9458 } 9459 9460 // If source is a result of another standard FP operation it is already in 9461 // canonical form. 9462 if (MaxDepth == 0) 9463 return false; 9464 9465 switch (Opcode) { 9466 // These will flush denorms if required. 9467 case ISD::FADD: 9468 case ISD::FSUB: 9469 case ISD::FMUL: 9470 case ISD::FCEIL: 9471 case ISD::FFLOOR: 9472 case ISD::FMA: 9473 case ISD::FMAD: 9474 case ISD::FSQRT: 9475 case ISD::FDIV: 9476 case ISD::FREM: 9477 case ISD::FP_ROUND: 9478 case ISD::FP_EXTEND: 9479 case AMDGPUISD::FMUL_LEGACY: 9480 case AMDGPUISD::FMAD_FTZ: 9481 case AMDGPUISD::RCP: 9482 case AMDGPUISD::RSQ: 9483 case AMDGPUISD::RSQ_CLAMP: 9484 case AMDGPUISD::RCP_LEGACY: 9485 case AMDGPUISD::RCP_IFLAG: 9486 case AMDGPUISD::DIV_SCALE: 9487 case AMDGPUISD::DIV_FMAS: 9488 case AMDGPUISD::DIV_FIXUP: 9489 case AMDGPUISD::FRACT: 9490 case AMDGPUISD::LDEXP: 9491 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9492 case AMDGPUISD::CVT_F32_UBYTE0: 9493 case AMDGPUISD::CVT_F32_UBYTE1: 9494 case AMDGPUISD::CVT_F32_UBYTE2: 9495 case AMDGPUISD::CVT_F32_UBYTE3: 9496 return true; 9497 9498 // It can/will be lowered or combined as a bit operation. 9499 // Need to check their input recursively to handle. 9500 case ISD::FNEG: 9501 case ISD::FABS: 9502 case ISD::FCOPYSIGN: 9503 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9504 9505 case ISD::FSIN: 9506 case ISD::FCOS: 9507 case ISD::FSINCOS: 9508 return Op.getValueType().getScalarType() != MVT::f16; 9509 9510 case ISD::FMINNUM: 9511 case ISD::FMAXNUM: 9512 case ISD::FMINNUM_IEEE: 9513 case ISD::FMAXNUM_IEEE: 9514 case AMDGPUISD::CLAMP: 9515 case AMDGPUISD::FMED3: 9516 case AMDGPUISD::FMAX3: 9517 case AMDGPUISD::FMIN3: { 9518 // FIXME: Shouldn't treat the generic operations different based these. 9519 // However, we aren't really required to flush the result from 9520 // minnum/maxnum.. 9521 9522 // snans will be quieted, so we only need to worry about denormals. 9523 if (Subtarget->supportsMinMaxDenormModes() || 9524 denormalsEnabledForType(DAG, Op.getValueType())) 9525 return true; 9526 9527 // Flushing may be required. 9528 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9529 // targets need to check their input recursively. 9530 9531 // FIXME: Does this apply with clamp? It's implemented with max. 9532 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9533 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9534 return false; 9535 } 9536 9537 return true; 9538 } 9539 case ISD::SELECT: { 9540 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9541 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9542 } 9543 case ISD::BUILD_VECTOR: { 9544 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9545 SDValue SrcOp = Op.getOperand(i); 9546 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9547 return false; 9548 } 9549 9550 return true; 9551 } 9552 case ISD::EXTRACT_VECTOR_ELT: 9553 case ISD::EXTRACT_SUBVECTOR: { 9554 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9555 } 9556 case ISD::INSERT_VECTOR_ELT: { 9557 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9558 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9559 } 9560 case ISD::UNDEF: 9561 // Could be anything. 9562 return false; 9563 9564 case ISD::BITCAST: { 9565 // Hack round the mess we make when legalizing extract_vector_elt 9566 SDValue Src = Op.getOperand(0); 9567 if (Src.getValueType() == MVT::i16 && 9568 Src.getOpcode() == ISD::TRUNCATE) { 9569 SDValue TruncSrc = Src.getOperand(0); 9570 if (TruncSrc.getValueType() == MVT::i32 && 9571 TruncSrc.getOpcode() == ISD::BITCAST && 9572 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9573 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9574 } 9575 } 9576 9577 return false; 9578 } 9579 case ISD::INTRINSIC_WO_CHAIN: { 9580 unsigned IntrinsicID 9581 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9582 // TODO: Handle more intrinsics 9583 switch (IntrinsicID) { 9584 case Intrinsic::amdgcn_cvt_pkrtz: 9585 case Intrinsic::amdgcn_cubeid: 9586 case Intrinsic::amdgcn_frexp_mant: 9587 case Intrinsic::amdgcn_fdot2: 9588 case Intrinsic::amdgcn_rcp: 9589 case Intrinsic::amdgcn_rsq: 9590 case Intrinsic::amdgcn_rsq_clamp: 9591 case Intrinsic::amdgcn_rcp_legacy: 9592 case Intrinsic::amdgcn_rsq_legacy: 9593 case Intrinsic::amdgcn_trig_preop: 9594 return true; 9595 default: 9596 break; 9597 } 9598 9599 LLVM_FALLTHROUGH; 9600 } 9601 default: 9602 return denormalsEnabledForType(DAG, Op.getValueType()) && 9603 DAG.isKnownNeverSNaN(Op); 9604 } 9605 9606 llvm_unreachable("invalid operation"); 9607 } 9608 9609 // Constant fold canonicalize. 9610 SDValue SITargetLowering::getCanonicalConstantFP( 9611 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9612 // Flush denormals to 0 if not enabled. 9613 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9614 return DAG.getConstantFP(0.0, SL, VT); 9615 9616 if (C.isNaN()) { 9617 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9618 if (C.isSignaling()) { 9619 // Quiet a signaling NaN. 9620 // FIXME: Is this supposed to preserve payload bits? 9621 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9622 } 9623 9624 // Make sure it is the canonical NaN bitpattern. 9625 // 9626 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9627 // immediate? 9628 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9629 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9630 } 9631 9632 // Already canonical. 9633 return DAG.getConstantFP(C, SL, VT); 9634 } 9635 9636 static bool vectorEltWillFoldAway(SDValue Op) { 9637 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9638 } 9639 9640 SDValue SITargetLowering::performFCanonicalizeCombine( 9641 SDNode *N, 9642 DAGCombinerInfo &DCI) const { 9643 SelectionDAG &DAG = DCI.DAG; 9644 SDValue N0 = N->getOperand(0); 9645 EVT VT = N->getValueType(0); 9646 9647 // fcanonicalize undef -> qnan 9648 if (N0.isUndef()) { 9649 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9650 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9651 } 9652 9653 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9654 EVT VT = N->getValueType(0); 9655 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9656 } 9657 9658 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9659 // (fcanonicalize k) 9660 // 9661 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9662 9663 // TODO: This could be better with wider vectors that will be split to v2f16, 9664 // and to consider uses since there aren't that many packed operations. 9665 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9666 isTypeLegal(MVT::v2f16)) { 9667 SDLoc SL(N); 9668 SDValue NewElts[2]; 9669 SDValue Lo = N0.getOperand(0); 9670 SDValue Hi = N0.getOperand(1); 9671 EVT EltVT = Lo.getValueType(); 9672 9673 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9674 for (unsigned I = 0; I != 2; ++I) { 9675 SDValue Op = N0.getOperand(I); 9676 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9677 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9678 CFP->getValueAPF()); 9679 } else if (Op.isUndef()) { 9680 // Handled below based on what the other operand is. 9681 NewElts[I] = Op; 9682 } else { 9683 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9684 } 9685 } 9686 9687 // If one half is undef, and one is constant, perfer a splat vector rather 9688 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9689 // cheaper to use and may be free with a packed operation. 9690 if (NewElts[0].isUndef()) { 9691 if (isa<ConstantFPSDNode>(NewElts[1])) 9692 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9693 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9694 } 9695 9696 if (NewElts[1].isUndef()) { 9697 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9698 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9699 } 9700 9701 return DAG.getBuildVector(VT, SL, NewElts); 9702 } 9703 } 9704 9705 unsigned SrcOpc = N0.getOpcode(); 9706 9707 // If it's free to do so, push canonicalizes further up the source, which may 9708 // find a canonical source. 9709 // 9710 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9711 // sNaNs. 9712 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9713 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9714 if (CRHS && N0.hasOneUse()) { 9715 SDLoc SL(N); 9716 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9717 N0.getOperand(0)); 9718 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9719 DCI.AddToWorklist(Canon0.getNode()); 9720 9721 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9722 } 9723 } 9724 9725 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9726 } 9727 9728 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9729 switch (Opc) { 9730 case ISD::FMAXNUM: 9731 case ISD::FMAXNUM_IEEE: 9732 return AMDGPUISD::FMAX3; 9733 case ISD::SMAX: 9734 return AMDGPUISD::SMAX3; 9735 case ISD::UMAX: 9736 return AMDGPUISD::UMAX3; 9737 case ISD::FMINNUM: 9738 case ISD::FMINNUM_IEEE: 9739 return AMDGPUISD::FMIN3; 9740 case ISD::SMIN: 9741 return AMDGPUISD::SMIN3; 9742 case ISD::UMIN: 9743 return AMDGPUISD::UMIN3; 9744 default: 9745 llvm_unreachable("Not a min/max opcode"); 9746 } 9747 } 9748 9749 SDValue SITargetLowering::performIntMed3ImmCombine( 9750 SelectionDAG &DAG, const SDLoc &SL, 9751 SDValue Op0, SDValue Op1, bool Signed) const { 9752 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9753 if (!K1) 9754 return SDValue(); 9755 9756 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9757 if (!K0) 9758 return SDValue(); 9759 9760 if (Signed) { 9761 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9762 return SDValue(); 9763 } else { 9764 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9765 return SDValue(); 9766 } 9767 9768 EVT VT = K0->getValueType(0); 9769 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9770 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9771 return DAG.getNode(Med3Opc, SL, VT, 9772 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9773 } 9774 9775 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9776 if (VT == MVT::i16) { 9777 MVT NVT = MVT::i32; 9778 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9779 9780 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9781 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9782 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9783 9784 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9785 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9786 } 9787 9788 return SDValue(); 9789 } 9790 9791 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9792 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9793 return C; 9794 9795 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9796 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9797 return C; 9798 } 9799 9800 return nullptr; 9801 } 9802 9803 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9804 const SDLoc &SL, 9805 SDValue Op0, 9806 SDValue Op1) const { 9807 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9808 if (!K1) 9809 return SDValue(); 9810 9811 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9812 if (!K0) 9813 return SDValue(); 9814 9815 // Ordered >= (although NaN inputs should have folded away by now). 9816 if (K0->getValueAPF() > K1->getValueAPF()) 9817 return SDValue(); 9818 9819 const MachineFunction &MF = DAG.getMachineFunction(); 9820 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9821 9822 // TODO: Check IEEE bit enabled? 9823 EVT VT = Op0.getValueType(); 9824 if (Info->getMode().DX10Clamp) { 9825 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9826 // hardware fmed3 behavior converting to a min. 9827 // FIXME: Should this be allowing -0.0? 9828 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9829 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9830 } 9831 9832 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9833 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9834 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9835 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9836 // then give the other result, which is different from med3 with a NaN 9837 // input. 9838 SDValue Var = Op0.getOperand(0); 9839 if (!DAG.isKnownNeverSNaN(Var)) 9840 return SDValue(); 9841 9842 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9843 9844 if ((!K0->hasOneUse() || 9845 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9846 (!K1->hasOneUse() || 9847 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9848 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9849 Var, SDValue(K0, 0), SDValue(K1, 0)); 9850 } 9851 } 9852 9853 return SDValue(); 9854 } 9855 9856 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9857 DAGCombinerInfo &DCI) const { 9858 SelectionDAG &DAG = DCI.DAG; 9859 9860 EVT VT = N->getValueType(0); 9861 unsigned Opc = N->getOpcode(); 9862 SDValue Op0 = N->getOperand(0); 9863 SDValue Op1 = N->getOperand(1); 9864 9865 // Only do this if the inner op has one use since this will just increases 9866 // register pressure for no benefit. 9867 9868 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9869 !VT.isVector() && 9870 (VT == MVT::i32 || VT == MVT::f32 || 9871 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9872 // max(max(a, b), c) -> max3(a, b, c) 9873 // min(min(a, b), c) -> min3(a, b, c) 9874 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9875 SDLoc DL(N); 9876 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9877 DL, 9878 N->getValueType(0), 9879 Op0.getOperand(0), 9880 Op0.getOperand(1), 9881 Op1); 9882 } 9883 9884 // Try commuted. 9885 // max(a, max(b, c)) -> max3(a, b, c) 9886 // min(a, min(b, c)) -> min3(a, b, c) 9887 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9888 SDLoc DL(N); 9889 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9890 DL, 9891 N->getValueType(0), 9892 Op0, 9893 Op1.getOperand(0), 9894 Op1.getOperand(1)); 9895 } 9896 } 9897 9898 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9899 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9900 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9901 return Med3; 9902 } 9903 9904 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9905 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9906 return Med3; 9907 } 9908 9909 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9910 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9911 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9912 (Opc == AMDGPUISD::FMIN_LEGACY && 9913 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9914 (VT == MVT::f32 || VT == MVT::f64 || 9915 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9916 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9917 Op0.hasOneUse()) { 9918 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9919 return Res; 9920 } 9921 9922 return SDValue(); 9923 } 9924 9925 static bool isClampZeroToOne(SDValue A, SDValue B) { 9926 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9927 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9928 // FIXME: Should this be allowing -0.0? 9929 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9930 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9931 } 9932 } 9933 9934 return false; 9935 } 9936 9937 // FIXME: Should only worry about snans for version with chain. 9938 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9939 DAGCombinerInfo &DCI) const { 9940 EVT VT = N->getValueType(0); 9941 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9942 // NaNs. With a NaN input, the order of the operands may change the result. 9943 9944 SelectionDAG &DAG = DCI.DAG; 9945 SDLoc SL(N); 9946 9947 SDValue Src0 = N->getOperand(0); 9948 SDValue Src1 = N->getOperand(1); 9949 SDValue Src2 = N->getOperand(2); 9950 9951 if (isClampZeroToOne(Src0, Src1)) { 9952 // const_a, const_b, x -> clamp is safe in all cases including signaling 9953 // nans. 9954 // FIXME: Should this be allowing -0.0? 9955 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9956 } 9957 9958 const MachineFunction &MF = DAG.getMachineFunction(); 9959 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9960 9961 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9962 // handling no dx10-clamp? 9963 if (Info->getMode().DX10Clamp) { 9964 // If NaNs is clamped to 0, we are free to reorder the inputs. 9965 9966 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9967 std::swap(Src0, Src1); 9968 9969 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9970 std::swap(Src1, Src2); 9971 9972 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9973 std::swap(Src0, Src1); 9974 9975 if (isClampZeroToOne(Src1, Src2)) 9976 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9977 } 9978 9979 return SDValue(); 9980 } 9981 9982 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9983 DAGCombinerInfo &DCI) const { 9984 SDValue Src0 = N->getOperand(0); 9985 SDValue Src1 = N->getOperand(1); 9986 if (Src0.isUndef() && Src1.isUndef()) 9987 return DCI.DAG.getUNDEF(N->getValueType(0)); 9988 return SDValue(); 9989 } 9990 9991 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9992 // expanded into a set of cmp/select instructions. 9993 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9994 unsigned NumElem, 9995 bool IsDivergentIdx) { 9996 if (UseDivergentRegisterIndexing) 9997 return false; 9998 9999 unsigned VecSize = EltSize * NumElem; 10000 10001 // Sub-dword vectors of size 2 dword or less have better implementation. 10002 if (VecSize <= 64 && EltSize < 32) 10003 return false; 10004 10005 // Always expand the rest of sub-dword instructions, otherwise it will be 10006 // lowered via memory. 10007 if (EltSize < 32) 10008 return true; 10009 10010 // Always do this if var-idx is divergent, otherwise it will become a loop. 10011 if (IsDivergentIdx) 10012 return true; 10013 10014 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10015 unsigned NumInsts = NumElem /* Number of compares */ + 10016 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10017 return NumInsts <= 16; 10018 } 10019 10020 static bool shouldExpandVectorDynExt(SDNode *N) { 10021 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10022 if (isa<ConstantSDNode>(Idx)) 10023 return false; 10024 10025 SDValue Vec = N->getOperand(0); 10026 EVT VecVT = Vec.getValueType(); 10027 EVT EltVT = VecVT.getVectorElementType(); 10028 unsigned EltSize = EltVT.getSizeInBits(); 10029 unsigned NumElem = VecVT.getVectorNumElements(); 10030 10031 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10032 Idx->isDivergent()); 10033 } 10034 10035 SDValue SITargetLowering::performExtractVectorEltCombine( 10036 SDNode *N, DAGCombinerInfo &DCI) const { 10037 SDValue Vec = N->getOperand(0); 10038 SelectionDAG &DAG = DCI.DAG; 10039 10040 EVT VecVT = Vec.getValueType(); 10041 EVT EltVT = VecVT.getVectorElementType(); 10042 10043 if ((Vec.getOpcode() == ISD::FNEG || 10044 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10045 SDLoc SL(N); 10046 EVT EltVT = N->getValueType(0); 10047 SDValue Idx = N->getOperand(1); 10048 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10049 Vec.getOperand(0), Idx); 10050 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10051 } 10052 10053 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10054 // => 10055 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10056 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10057 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10058 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10059 SDLoc SL(N); 10060 EVT EltVT = N->getValueType(0); 10061 SDValue Idx = N->getOperand(1); 10062 unsigned Opc = Vec.getOpcode(); 10063 10064 switch(Opc) { 10065 default: 10066 break; 10067 // TODO: Support other binary operations. 10068 case ISD::FADD: 10069 case ISD::FSUB: 10070 case ISD::FMUL: 10071 case ISD::ADD: 10072 case ISD::UMIN: 10073 case ISD::UMAX: 10074 case ISD::SMIN: 10075 case ISD::SMAX: 10076 case ISD::FMAXNUM: 10077 case ISD::FMINNUM: 10078 case ISD::FMAXNUM_IEEE: 10079 case ISD::FMINNUM_IEEE: { 10080 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10081 Vec.getOperand(0), Idx); 10082 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10083 Vec.getOperand(1), Idx); 10084 10085 DCI.AddToWorklist(Elt0.getNode()); 10086 DCI.AddToWorklist(Elt1.getNode()); 10087 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10088 } 10089 } 10090 } 10091 10092 unsigned VecSize = VecVT.getSizeInBits(); 10093 unsigned EltSize = EltVT.getSizeInBits(); 10094 10095 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10096 if (::shouldExpandVectorDynExt(N)) { 10097 SDLoc SL(N); 10098 SDValue Idx = N->getOperand(1); 10099 SDValue V; 10100 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10101 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10102 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10103 if (I == 0) 10104 V = Elt; 10105 else 10106 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10107 } 10108 return V; 10109 } 10110 10111 if (!DCI.isBeforeLegalize()) 10112 return SDValue(); 10113 10114 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10115 // elements. This exposes more load reduction opportunities by replacing 10116 // multiple small extract_vector_elements with a single 32-bit extract. 10117 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10118 if (isa<MemSDNode>(Vec) && 10119 EltSize <= 16 && 10120 EltVT.isByteSized() && 10121 VecSize > 32 && 10122 VecSize % 32 == 0 && 10123 Idx) { 10124 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10125 10126 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10127 unsigned EltIdx = BitIndex / 32; 10128 unsigned LeftoverBitIdx = BitIndex % 32; 10129 SDLoc SL(N); 10130 10131 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10132 DCI.AddToWorklist(Cast.getNode()); 10133 10134 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10135 DAG.getConstant(EltIdx, SL, MVT::i32)); 10136 DCI.AddToWorklist(Elt.getNode()); 10137 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10138 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10139 DCI.AddToWorklist(Srl.getNode()); 10140 10141 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10142 DCI.AddToWorklist(Trunc.getNode()); 10143 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10144 } 10145 10146 return SDValue(); 10147 } 10148 10149 SDValue 10150 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10151 DAGCombinerInfo &DCI) const { 10152 SDValue Vec = N->getOperand(0); 10153 SDValue Idx = N->getOperand(2); 10154 EVT VecVT = Vec.getValueType(); 10155 EVT EltVT = VecVT.getVectorElementType(); 10156 10157 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10158 // => BUILD_VECTOR n x select (e, const-idx) 10159 if (!::shouldExpandVectorDynExt(N)) 10160 return SDValue(); 10161 10162 SelectionDAG &DAG = DCI.DAG; 10163 SDLoc SL(N); 10164 SDValue Ins = N->getOperand(1); 10165 EVT IdxVT = Idx.getValueType(); 10166 10167 SmallVector<SDValue, 16> Ops; 10168 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10169 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10170 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10171 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10172 Ops.push_back(V); 10173 } 10174 10175 return DAG.getBuildVector(VecVT, SL, Ops); 10176 } 10177 10178 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10179 const SDNode *N0, 10180 const SDNode *N1) const { 10181 EVT VT = N0->getValueType(0); 10182 10183 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10184 // support denormals ever. 10185 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10186 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10187 getSubtarget()->hasMadF16())) && 10188 isOperationLegal(ISD::FMAD, VT)) 10189 return ISD::FMAD; 10190 10191 const TargetOptions &Options = DAG.getTarget().Options; 10192 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10193 (N0->getFlags().hasAllowContract() && 10194 N1->getFlags().hasAllowContract())) && 10195 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10196 return ISD::FMA; 10197 } 10198 10199 return 0; 10200 } 10201 10202 // For a reassociatable opcode perform: 10203 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10204 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10205 SelectionDAG &DAG) const { 10206 EVT VT = N->getValueType(0); 10207 if (VT != MVT::i32 && VT != MVT::i64) 10208 return SDValue(); 10209 10210 unsigned Opc = N->getOpcode(); 10211 SDValue Op0 = N->getOperand(0); 10212 SDValue Op1 = N->getOperand(1); 10213 10214 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10215 return SDValue(); 10216 10217 if (Op0->isDivergent()) 10218 std::swap(Op0, Op1); 10219 10220 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10221 return SDValue(); 10222 10223 SDValue Op2 = Op1.getOperand(1); 10224 Op1 = Op1.getOperand(0); 10225 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10226 return SDValue(); 10227 10228 if (Op1->isDivergent()) 10229 std::swap(Op1, Op2); 10230 10231 // If either operand is constant this will conflict with 10232 // DAGCombiner::ReassociateOps(). 10233 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10234 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10235 return SDValue(); 10236 10237 SDLoc SL(N); 10238 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10239 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10240 } 10241 10242 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10243 EVT VT, 10244 SDValue N0, SDValue N1, SDValue N2, 10245 bool Signed) { 10246 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10247 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10248 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10249 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10250 } 10251 10252 SDValue SITargetLowering::performAddCombine(SDNode *N, 10253 DAGCombinerInfo &DCI) const { 10254 SelectionDAG &DAG = DCI.DAG; 10255 EVT VT = N->getValueType(0); 10256 SDLoc SL(N); 10257 SDValue LHS = N->getOperand(0); 10258 SDValue RHS = N->getOperand(1); 10259 10260 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10261 && Subtarget->hasMad64_32() && 10262 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10263 VT.getScalarSizeInBits() <= 64) { 10264 if (LHS.getOpcode() != ISD::MUL) 10265 std::swap(LHS, RHS); 10266 10267 SDValue MulLHS = LHS.getOperand(0); 10268 SDValue MulRHS = LHS.getOperand(1); 10269 SDValue AddRHS = RHS; 10270 10271 // TODO: Maybe restrict if SGPR inputs. 10272 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10273 numBitsUnsigned(MulRHS, DAG) <= 32) { 10274 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10275 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10276 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10277 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10278 } 10279 10280 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10281 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10282 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10283 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10284 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10285 } 10286 10287 return SDValue(); 10288 } 10289 10290 if (SDValue V = reassociateScalarOps(N, DAG)) { 10291 return V; 10292 } 10293 10294 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10295 return SDValue(); 10296 10297 // add x, zext (setcc) => addcarry x, 0, setcc 10298 // add x, sext (setcc) => subcarry x, 0, setcc 10299 unsigned Opc = LHS.getOpcode(); 10300 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10301 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10302 std::swap(RHS, LHS); 10303 10304 Opc = RHS.getOpcode(); 10305 switch (Opc) { 10306 default: break; 10307 case ISD::ZERO_EXTEND: 10308 case ISD::SIGN_EXTEND: 10309 case ISD::ANY_EXTEND: { 10310 auto Cond = RHS.getOperand(0); 10311 // If this won't be a real VOPC output, we would still need to insert an 10312 // extra instruction anyway. 10313 if (!isBoolSGPR(Cond)) 10314 break; 10315 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10316 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10317 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10318 return DAG.getNode(Opc, SL, VTList, Args); 10319 } 10320 case ISD::ADDCARRY: { 10321 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10322 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10323 if (!C || C->getZExtValue() != 0) break; 10324 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10325 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10326 } 10327 } 10328 return SDValue(); 10329 } 10330 10331 SDValue SITargetLowering::performSubCombine(SDNode *N, 10332 DAGCombinerInfo &DCI) const { 10333 SelectionDAG &DAG = DCI.DAG; 10334 EVT VT = N->getValueType(0); 10335 10336 if (VT != MVT::i32) 10337 return SDValue(); 10338 10339 SDLoc SL(N); 10340 SDValue LHS = N->getOperand(0); 10341 SDValue RHS = N->getOperand(1); 10342 10343 // sub x, zext (setcc) => subcarry x, 0, setcc 10344 // sub x, sext (setcc) => addcarry x, 0, setcc 10345 unsigned Opc = RHS.getOpcode(); 10346 switch (Opc) { 10347 default: break; 10348 case ISD::ZERO_EXTEND: 10349 case ISD::SIGN_EXTEND: 10350 case ISD::ANY_EXTEND: { 10351 auto Cond = RHS.getOperand(0); 10352 // If this won't be a real VOPC output, we would still need to insert an 10353 // extra instruction anyway. 10354 if (!isBoolSGPR(Cond)) 10355 break; 10356 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10357 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10358 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10359 return DAG.getNode(Opc, SL, VTList, Args); 10360 } 10361 } 10362 10363 if (LHS.getOpcode() == ISD::SUBCARRY) { 10364 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10365 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10366 if (!C || !C->isNullValue()) 10367 return SDValue(); 10368 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10369 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10370 } 10371 return SDValue(); 10372 } 10373 10374 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10375 DAGCombinerInfo &DCI) const { 10376 10377 if (N->getValueType(0) != MVT::i32) 10378 return SDValue(); 10379 10380 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10381 if (!C || C->getZExtValue() != 0) 10382 return SDValue(); 10383 10384 SelectionDAG &DAG = DCI.DAG; 10385 SDValue LHS = N->getOperand(0); 10386 10387 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10388 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10389 unsigned LHSOpc = LHS.getOpcode(); 10390 unsigned Opc = N->getOpcode(); 10391 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10392 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10393 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10394 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10395 } 10396 return SDValue(); 10397 } 10398 10399 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10400 DAGCombinerInfo &DCI) const { 10401 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10402 return SDValue(); 10403 10404 SelectionDAG &DAG = DCI.DAG; 10405 EVT VT = N->getValueType(0); 10406 10407 SDLoc SL(N); 10408 SDValue LHS = N->getOperand(0); 10409 SDValue RHS = N->getOperand(1); 10410 10411 // These should really be instruction patterns, but writing patterns with 10412 // source modiifiers is a pain. 10413 10414 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10415 if (LHS.getOpcode() == ISD::FADD) { 10416 SDValue A = LHS.getOperand(0); 10417 if (A == LHS.getOperand(1)) { 10418 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10419 if (FusedOp != 0) { 10420 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10421 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10422 } 10423 } 10424 } 10425 10426 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10427 if (RHS.getOpcode() == ISD::FADD) { 10428 SDValue A = RHS.getOperand(0); 10429 if (A == RHS.getOperand(1)) { 10430 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10431 if (FusedOp != 0) { 10432 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10433 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10434 } 10435 } 10436 } 10437 10438 return SDValue(); 10439 } 10440 10441 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10442 DAGCombinerInfo &DCI) const { 10443 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10444 return SDValue(); 10445 10446 SelectionDAG &DAG = DCI.DAG; 10447 SDLoc SL(N); 10448 EVT VT = N->getValueType(0); 10449 assert(!VT.isVector()); 10450 10451 // Try to get the fneg to fold into the source modifier. This undoes generic 10452 // DAG combines and folds them into the mad. 10453 // 10454 // Only do this if we are not trying to support denormals. v_mad_f32 does 10455 // not support denormals ever. 10456 SDValue LHS = N->getOperand(0); 10457 SDValue RHS = N->getOperand(1); 10458 if (LHS.getOpcode() == ISD::FADD) { 10459 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10460 SDValue A = LHS.getOperand(0); 10461 if (A == LHS.getOperand(1)) { 10462 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10463 if (FusedOp != 0){ 10464 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10465 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10466 10467 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10468 } 10469 } 10470 } 10471 10472 if (RHS.getOpcode() == ISD::FADD) { 10473 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10474 10475 SDValue A = RHS.getOperand(0); 10476 if (A == RHS.getOperand(1)) { 10477 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10478 if (FusedOp != 0){ 10479 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10480 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10481 } 10482 } 10483 } 10484 10485 return SDValue(); 10486 } 10487 10488 SDValue SITargetLowering::performFMACombine(SDNode *N, 10489 DAGCombinerInfo &DCI) const { 10490 SelectionDAG &DAG = DCI.DAG; 10491 EVT VT = N->getValueType(0); 10492 SDLoc SL(N); 10493 10494 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10495 return SDValue(); 10496 10497 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10498 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10499 SDValue Op1 = N->getOperand(0); 10500 SDValue Op2 = N->getOperand(1); 10501 SDValue FMA = N->getOperand(2); 10502 10503 if (FMA.getOpcode() != ISD::FMA || 10504 Op1.getOpcode() != ISD::FP_EXTEND || 10505 Op2.getOpcode() != ISD::FP_EXTEND) 10506 return SDValue(); 10507 10508 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10509 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10510 // is sufficient to allow generaing fdot2. 10511 const TargetOptions &Options = DAG.getTarget().Options; 10512 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10513 (N->getFlags().hasAllowContract() && 10514 FMA->getFlags().hasAllowContract())) { 10515 Op1 = Op1.getOperand(0); 10516 Op2 = Op2.getOperand(0); 10517 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10518 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10519 return SDValue(); 10520 10521 SDValue Vec1 = Op1.getOperand(0); 10522 SDValue Idx1 = Op1.getOperand(1); 10523 SDValue Vec2 = Op2.getOperand(0); 10524 10525 SDValue FMAOp1 = FMA.getOperand(0); 10526 SDValue FMAOp2 = FMA.getOperand(1); 10527 SDValue FMAAcc = FMA.getOperand(2); 10528 10529 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10530 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10531 return SDValue(); 10532 10533 FMAOp1 = FMAOp1.getOperand(0); 10534 FMAOp2 = FMAOp2.getOperand(0); 10535 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10536 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10537 return SDValue(); 10538 10539 SDValue Vec3 = FMAOp1.getOperand(0); 10540 SDValue Vec4 = FMAOp2.getOperand(0); 10541 SDValue Idx2 = FMAOp1.getOperand(1); 10542 10543 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10544 // Idx1 and Idx2 cannot be the same. 10545 Idx1 == Idx2) 10546 return SDValue(); 10547 10548 if (Vec1 == Vec2 || Vec3 == Vec4) 10549 return SDValue(); 10550 10551 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10552 return SDValue(); 10553 10554 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10555 (Vec1 == Vec4 && Vec2 == Vec3)) { 10556 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10557 DAG.getTargetConstant(0, SL, MVT::i1)); 10558 } 10559 } 10560 return SDValue(); 10561 } 10562 10563 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10564 DAGCombinerInfo &DCI) const { 10565 SelectionDAG &DAG = DCI.DAG; 10566 SDLoc SL(N); 10567 10568 SDValue LHS = N->getOperand(0); 10569 SDValue RHS = N->getOperand(1); 10570 EVT VT = LHS.getValueType(); 10571 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10572 10573 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10574 if (!CRHS) { 10575 CRHS = dyn_cast<ConstantSDNode>(LHS); 10576 if (CRHS) { 10577 std::swap(LHS, RHS); 10578 CC = getSetCCSwappedOperands(CC); 10579 } 10580 } 10581 10582 if (CRHS) { 10583 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10584 isBoolSGPR(LHS.getOperand(0))) { 10585 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10586 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10587 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10588 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10589 if ((CRHS->isAllOnesValue() && 10590 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10591 (CRHS->isNullValue() && 10592 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10593 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10594 DAG.getConstant(-1, SL, MVT::i1)); 10595 if ((CRHS->isAllOnesValue() && 10596 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10597 (CRHS->isNullValue() && 10598 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10599 return LHS.getOperand(0); 10600 } 10601 10602 uint64_t CRHSVal = CRHS->getZExtValue(); 10603 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10604 LHS.getOpcode() == ISD::SELECT && 10605 isa<ConstantSDNode>(LHS.getOperand(1)) && 10606 isa<ConstantSDNode>(LHS.getOperand(2)) && 10607 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10608 isBoolSGPR(LHS.getOperand(0))) { 10609 // Given CT != FT: 10610 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10611 // setcc (select cc, CT, CF), CF, ne => cc 10612 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10613 // setcc (select cc, CT, CF), CT, eq => cc 10614 uint64_t CT = LHS.getConstantOperandVal(1); 10615 uint64_t CF = LHS.getConstantOperandVal(2); 10616 10617 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10618 (CT == CRHSVal && CC == ISD::SETNE)) 10619 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10620 DAG.getConstant(-1, SL, MVT::i1)); 10621 if ((CF == CRHSVal && CC == ISD::SETNE) || 10622 (CT == CRHSVal && CC == ISD::SETEQ)) 10623 return LHS.getOperand(0); 10624 } 10625 } 10626 10627 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10628 VT != MVT::f16)) 10629 return SDValue(); 10630 10631 // Match isinf/isfinite pattern 10632 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10633 // (fcmp one (fabs x), inf) -> (fp_class x, 10634 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10635 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10636 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10637 if (!CRHS) 10638 return SDValue(); 10639 10640 const APFloat &APF = CRHS->getValueAPF(); 10641 if (APF.isInfinity() && !APF.isNegative()) { 10642 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10643 SIInstrFlags::N_INFINITY; 10644 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10645 SIInstrFlags::P_ZERO | 10646 SIInstrFlags::N_NORMAL | 10647 SIInstrFlags::P_NORMAL | 10648 SIInstrFlags::N_SUBNORMAL | 10649 SIInstrFlags::P_SUBNORMAL; 10650 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10651 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10652 DAG.getConstant(Mask, SL, MVT::i32)); 10653 } 10654 } 10655 10656 return SDValue(); 10657 } 10658 10659 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10660 DAGCombinerInfo &DCI) const { 10661 SelectionDAG &DAG = DCI.DAG; 10662 SDLoc SL(N); 10663 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10664 10665 SDValue Src = N->getOperand(0); 10666 SDValue Shift = N->getOperand(0); 10667 10668 // TODO: Extend type shouldn't matter (assuming legal types). 10669 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10670 Shift = Shift.getOperand(0); 10671 10672 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10673 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10674 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10675 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10676 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10677 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10678 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10679 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10680 SDLoc(Shift.getOperand(0)), MVT::i32); 10681 10682 unsigned ShiftOffset = 8 * Offset; 10683 if (Shift.getOpcode() == ISD::SHL) 10684 ShiftOffset -= C->getZExtValue(); 10685 else 10686 ShiftOffset += C->getZExtValue(); 10687 10688 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10689 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10690 MVT::f32, Shift); 10691 } 10692 } 10693 } 10694 10695 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10696 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10697 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10698 // We simplified Src. If this node is not dead, visit it again so it is 10699 // folded properly. 10700 if (N->getOpcode() != ISD::DELETED_NODE) 10701 DCI.AddToWorklist(N); 10702 return SDValue(N, 0); 10703 } 10704 10705 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10706 if (SDValue DemandedSrc = 10707 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10708 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10709 10710 return SDValue(); 10711 } 10712 10713 SDValue SITargetLowering::performClampCombine(SDNode *N, 10714 DAGCombinerInfo &DCI) const { 10715 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10716 if (!CSrc) 10717 return SDValue(); 10718 10719 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10720 const APFloat &F = CSrc->getValueAPF(); 10721 APFloat Zero = APFloat::getZero(F.getSemantics()); 10722 if (F < Zero || 10723 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10724 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10725 } 10726 10727 APFloat One(F.getSemantics(), "1.0"); 10728 if (F > One) 10729 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10730 10731 return SDValue(CSrc, 0); 10732 } 10733 10734 10735 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10736 DAGCombinerInfo &DCI) const { 10737 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10738 return SDValue(); 10739 switch (N->getOpcode()) { 10740 case ISD::ADD: 10741 return performAddCombine(N, DCI); 10742 case ISD::SUB: 10743 return performSubCombine(N, DCI); 10744 case ISD::ADDCARRY: 10745 case ISD::SUBCARRY: 10746 return performAddCarrySubCarryCombine(N, DCI); 10747 case ISD::FADD: 10748 return performFAddCombine(N, DCI); 10749 case ISD::FSUB: 10750 return performFSubCombine(N, DCI); 10751 case ISD::SETCC: 10752 return performSetCCCombine(N, DCI); 10753 case ISD::FMAXNUM: 10754 case ISD::FMINNUM: 10755 case ISD::FMAXNUM_IEEE: 10756 case ISD::FMINNUM_IEEE: 10757 case ISD::SMAX: 10758 case ISD::SMIN: 10759 case ISD::UMAX: 10760 case ISD::UMIN: 10761 case AMDGPUISD::FMIN_LEGACY: 10762 case AMDGPUISD::FMAX_LEGACY: 10763 return performMinMaxCombine(N, DCI); 10764 case ISD::FMA: 10765 return performFMACombine(N, DCI); 10766 case ISD::AND: 10767 return performAndCombine(N, DCI); 10768 case ISD::OR: 10769 return performOrCombine(N, DCI); 10770 case ISD::XOR: 10771 return performXorCombine(N, DCI); 10772 case ISD::ZERO_EXTEND: 10773 return performZeroExtendCombine(N, DCI); 10774 case ISD::SIGN_EXTEND_INREG: 10775 return performSignExtendInRegCombine(N , DCI); 10776 case AMDGPUISD::FP_CLASS: 10777 return performClassCombine(N, DCI); 10778 case ISD::FCANONICALIZE: 10779 return performFCanonicalizeCombine(N, DCI); 10780 case AMDGPUISD::RCP: 10781 return performRcpCombine(N, DCI); 10782 case AMDGPUISD::FRACT: 10783 case AMDGPUISD::RSQ: 10784 case AMDGPUISD::RCP_LEGACY: 10785 case AMDGPUISD::RCP_IFLAG: 10786 case AMDGPUISD::RSQ_CLAMP: 10787 case AMDGPUISD::LDEXP: { 10788 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10789 SDValue Src = N->getOperand(0); 10790 if (Src.isUndef()) 10791 return Src; 10792 break; 10793 } 10794 case ISD::SINT_TO_FP: 10795 case ISD::UINT_TO_FP: 10796 return performUCharToFloatCombine(N, DCI); 10797 case AMDGPUISD::CVT_F32_UBYTE0: 10798 case AMDGPUISD::CVT_F32_UBYTE1: 10799 case AMDGPUISD::CVT_F32_UBYTE2: 10800 case AMDGPUISD::CVT_F32_UBYTE3: 10801 return performCvtF32UByteNCombine(N, DCI); 10802 case AMDGPUISD::FMED3: 10803 return performFMed3Combine(N, DCI); 10804 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10805 return performCvtPkRTZCombine(N, DCI); 10806 case AMDGPUISD::CLAMP: 10807 return performClampCombine(N, DCI); 10808 case ISD::SCALAR_TO_VECTOR: { 10809 SelectionDAG &DAG = DCI.DAG; 10810 EVT VT = N->getValueType(0); 10811 10812 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10813 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10814 SDLoc SL(N); 10815 SDValue Src = N->getOperand(0); 10816 EVT EltVT = Src.getValueType(); 10817 if (EltVT == MVT::f16) 10818 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10819 10820 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10821 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10822 } 10823 10824 break; 10825 } 10826 case ISD::EXTRACT_VECTOR_ELT: 10827 return performExtractVectorEltCombine(N, DCI); 10828 case ISD::INSERT_VECTOR_ELT: 10829 return performInsertVectorEltCombine(N, DCI); 10830 case ISD::LOAD: { 10831 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10832 return Widended; 10833 LLVM_FALLTHROUGH; 10834 } 10835 default: { 10836 if (!DCI.isBeforeLegalize()) { 10837 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10838 return performMemSDNodeCombine(MemNode, DCI); 10839 } 10840 10841 break; 10842 } 10843 } 10844 10845 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10846 } 10847 10848 /// Helper function for adjustWritemask 10849 static unsigned SubIdx2Lane(unsigned Idx) { 10850 switch (Idx) { 10851 default: return ~0u; 10852 case AMDGPU::sub0: return 0; 10853 case AMDGPU::sub1: return 1; 10854 case AMDGPU::sub2: return 2; 10855 case AMDGPU::sub3: return 3; 10856 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10857 } 10858 } 10859 10860 /// Adjust the writemask of MIMG instructions 10861 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10862 SelectionDAG &DAG) const { 10863 unsigned Opcode = Node->getMachineOpcode(); 10864 10865 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10866 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10867 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10868 return Node; // not implemented for D16 10869 10870 SDNode *Users[5] = { nullptr }; 10871 unsigned Lane = 0; 10872 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10873 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10874 unsigned NewDmask = 0; 10875 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10876 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10877 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10878 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10879 unsigned TFCLane = 0; 10880 bool HasChain = Node->getNumValues() > 1; 10881 10882 if (OldDmask == 0) { 10883 // These are folded out, but on the chance it happens don't assert. 10884 return Node; 10885 } 10886 10887 unsigned OldBitsSet = countPopulation(OldDmask); 10888 // Work out which is the TFE/LWE lane if that is enabled. 10889 if (UsesTFC) { 10890 TFCLane = OldBitsSet; 10891 } 10892 10893 // Try to figure out the used register components 10894 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10895 I != E; ++I) { 10896 10897 // Don't look at users of the chain. 10898 if (I.getUse().getResNo() != 0) 10899 continue; 10900 10901 // Abort if we can't understand the usage 10902 if (!I->isMachineOpcode() || 10903 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10904 return Node; 10905 10906 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10907 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10908 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10909 // set, etc. 10910 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10911 if (Lane == ~0u) 10912 return Node; 10913 10914 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10915 if (UsesTFC && Lane == TFCLane) { 10916 Users[Lane] = *I; 10917 } else { 10918 // Set which texture component corresponds to the lane. 10919 unsigned Comp; 10920 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10921 Comp = countTrailingZeros(Dmask); 10922 Dmask &= ~(1 << Comp); 10923 } 10924 10925 // Abort if we have more than one user per component. 10926 if (Users[Lane]) 10927 return Node; 10928 10929 Users[Lane] = *I; 10930 NewDmask |= 1 << Comp; 10931 } 10932 } 10933 10934 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10935 bool NoChannels = !NewDmask; 10936 if (NoChannels) { 10937 if (!UsesTFC) { 10938 // No uses of the result and not using TFC. Then do nothing. 10939 return Node; 10940 } 10941 // If the original dmask has one channel - then nothing to do 10942 if (OldBitsSet == 1) 10943 return Node; 10944 // Use an arbitrary dmask - required for the instruction to work 10945 NewDmask = 1; 10946 } 10947 // Abort if there's no change 10948 if (NewDmask == OldDmask) 10949 return Node; 10950 10951 unsigned BitsSet = countPopulation(NewDmask); 10952 10953 // Check for TFE or LWE - increase the number of channels by one to account 10954 // for the extra return value 10955 // This will need adjustment for D16 if this is also included in 10956 // adjustWriteMask (this function) but at present D16 are excluded. 10957 unsigned NewChannels = BitsSet + UsesTFC; 10958 10959 int NewOpcode = 10960 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10961 assert(NewOpcode != -1 && 10962 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10963 "failed to find equivalent MIMG op"); 10964 10965 // Adjust the writemask in the node 10966 SmallVector<SDValue, 12> Ops; 10967 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10968 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10969 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10970 10971 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10972 10973 MVT ResultVT = NewChannels == 1 ? 10974 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10975 NewChannels == 5 ? 8 : NewChannels); 10976 SDVTList NewVTList = HasChain ? 10977 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10978 10979 10980 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10981 NewVTList, Ops); 10982 10983 if (HasChain) { 10984 // Update chain. 10985 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10986 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10987 } 10988 10989 if (NewChannels == 1) { 10990 assert(Node->hasNUsesOfValue(1, 0)); 10991 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10992 SDLoc(Node), Users[Lane]->getValueType(0), 10993 SDValue(NewNode, 0)); 10994 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10995 return nullptr; 10996 } 10997 10998 // Update the users of the node with the new indices 10999 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11000 SDNode *User = Users[i]; 11001 if (!User) { 11002 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11003 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11004 if (i || !NoChannels) 11005 continue; 11006 } else { 11007 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11008 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11009 } 11010 11011 switch (Idx) { 11012 default: break; 11013 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11014 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11015 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11016 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11017 } 11018 } 11019 11020 DAG.RemoveDeadNode(Node); 11021 return nullptr; 11022 } 11023 11024 static bool isFrameIndexOp(SDValue Op) { 11025 if (Op.getOpcode() == ISD::AssertZext) 11026 Op = Op.getOperand(0); 11027 11028 return isa<FrameIndexSDNode>(Op); 11029 } 11030 11031 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11032 /// with frame index operands. 11033 /// LLVM assumes that inputs are to these instructions are registers. 11034 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11035 SelectionDAG &DAG) const { 11036 if (Node->getOpcode() == ISD::CopyToReg) { 11037 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11038 SDValue SrcVal = Node->getOperand(2); 11039 11040 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11041 // to try understanding copies to physical registers. 11042 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11043 SDLoc SL(Node); 11044 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11045 SDValue VReg = DAG.getRegister( 11046 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11047 11048 SDNode *Glued = Node->getGluedNode(); 11049 SDValue ToVReg 11050 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11051 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11052 SDValue ToResultReg 11053 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11054 VReg, ToVReg.getValue(1)); 11055 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11056 DAG.RemoveDeadNode(Node); 11057 return ToResultReg.getNode(); 11058 } 11059 } 11060 11061 SmallVector<SDValue, 8> Ops; 11062 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11063 if (!isFrameIndexOp(Node->getOperand(i))) { 11064 Ops.push_back(Node->getOperand(i)); 11065 continue; 11066 } 11067 11068 SDLoc DL(Node); 11069 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11070 Node->getOperand(i).getValueType(), 11071 Node->getOperand(i)), 0)); 11072 } 11073 11074 return DAG.UpdateNodeOperands(Node, Ops); 11075 } 11076 11077 /// Fold the instructions after selecting them. 11078 /// Returns null if users were already updated. 11079 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11080 SelectionDAG &DAG) const { 11081 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11082 unsigned Opcode = Node->getMachineOpcode(); 11083 11084 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11085 !TII->isGather4(Opcode) && 11086 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11087 return adjustWritemask(Node, DAG); 11088 } 11089 11090 if (Opcode == AMDGPU::INSERT_SUBREG || 11091 Opcode == AMDGPU::REG_SEQUENCE) { 11092 legalizeTargetIndependentNode(Node, DAG); 11093 return Node; 11094 } 11095 11096 switch (Opcode) { 11097 case AMDGPU::V_DIV_SCALE_F32_e64: 11098 case AMDGPU::V_DIV_SCALE_F64_e64: { 11099 // Satisfy the operand register constraint when one of the inputs is 11100 // undefined. Ordinarily each undef value will have its own implicit_def of 11101 // a vreg, so force these to use a single register. 11102 SDValue Src0 = Node->getOperand(1); 11103 SDValue Src1 = Node->getOperand(3); 11104 SDValue Src2 = Node->getOperand(5); 11105 11106 if ((Src0.isMachineOpcode() && 11107 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11108 (Src0 == Src1 || Src0 == Src2)) 11109 break; 11110 11111 MVT VT = Src0.getValueType().getSimpleVT(); 11112 const TargetRegisterClass *RC = 11113 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11114 11115 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11116 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11117 11118 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11119 UndefReg, Src0, SDValue()); 11120 11121 // src0 must be the same register as src1 or src2, even if the value is 11122 // undefined, so make sure we don't violate this constraint. 11123 if (Src0.isMachineOpcode() && 11124 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11125 if (Src1.isMachineOpcode() && 11126 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11127 Src0 = Src1; 11128 else if (Src2.isMachineOpcode() && 11129 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11130 Src0 = Src2; 11131 else { 11132 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11133 Src0 = UndefReg; 11134 Src1 = UndefReg; 11135 } 11136 } else 11137 break; 11138 11139 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11140 Ops[1] = Src0; 11141 Ops[3] = Src1; 11142 Ops[5] = Src2; 11143 Ops.push_back(ImpDef.getValue(1)); 11144 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11145 } 11146 default: 11147 break; 11148 } 11149 11150 return Node; 11151 } 11152 11153 /// Assign the register class depending on the number of 11154 /// bits set in the writemask 11155 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11156 SDNode *Node) const { 11157 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11158 11159 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11160 11161 if (TII->isVOP3(MI.getOpcode())) { 11162 // Make sure constant bus requirements are respected. 11163 TII->legalizeOperandsVOP3(MRI, MI); 11164 11165 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11166 // This saves a chain-copy of registers and better ballance register 11167 // use between vgpr and agpr as agpr tuples tend to be big. 11168 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11169 unsigned Opc = MI.getOpcode(); 11170 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11171 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11172 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11173 if (I == -1) 11174 break; 11175 MachineOperand &Op = MI.getOperand(I); 11176 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11177 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11178 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11179 continue; 11180 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11181 if (!Src || !Src->isCopy() || 11182 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11183 continue; 11184 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11185 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11186 // All uses of agpr64 and agpr32 can also accept vgpr except for 11187 // v_accvgpr_read, but we do not produce agpr reads during selection, 11188 // so no use checks are needed. 11189 MRI.setRegClass(Op.getReg(), NewRC); 11190 } 11191 } 11192 11193 return; 11194 } 11195 11196 // Replace unused atomics with the no return version. 11197 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11198 if (NoRetAtomicOp != -1) { 11199 if (!Node->hasAnyUseOfValue(0)) { 11200 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11201 AMDGPU::OpName::cpol); 11202 if (CPolIdx != -1) { 11203 MachineOperand &CPol = MI.getOperand(CPolIdx); 11204 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11205 } 11206 MI.RemoveOperand(0); 11207 MI.setDesc(TII->get(NoRetAtomicOp)); 11208 return; 11209 } 11210 11211 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11212 // instruction, because the return type of these instructions is a vec2 of 11213 // the memory type, so it can be tied to the input operand. 11214 // This means these instructions always have a use, so we need to add a 11215 // special case to check if the atomic has only one extract_subreg use, 11216 // which itself has no uses. 11217 if ((Node->hasNUsesOfValue(1, 0) && 11218 Node->use_begin()->isMachineOpcode() && 11219 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11220 !Node->use_begin()->hasAnyUseOfValue(0))) { 11221 Register Def = MI.getOperand(0).getReg(); 11222 11223 // Change this into a noret atomic. 11224 MI.setDesc(TII->get(NoRetAtomicOp)); 11225 MI.RemoveOperand(0); 11226 11227 // If we only remove the def operand from the atomic instruction, the 11228 // extract_subreg will be left with a use of a vreg without a def. 11229 // So we need to insert an implicit_def to avoid machine verifier 11230 // errors. 11231 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11232 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11233 } 11234 return; 11235 } 11236 } 11237 11238 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11239 uint64_t Val) { 11240 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11241 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11242 } 11243 11244 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11245 const SDLoc &DL, 11246 SDValue Ptr) const { 11247 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11248 11249 // Build the half of the subregister with the constants before building the 11250 // full 128-bit register. If we are building multiple resource descriptors, 11251 // this will allow CSEing of the 2-component register. 11252 const SDValue Ops0[] = { 11253 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11254 buildSMovImm32(DAG, DL, 0), 11255 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11256 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11257 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11258 }; 11259 11260 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11261 MVT::v2i32, Ops0), 0); 11262 11263 // Combine the constants and the pointer. 11264 const SDValue Ops1[] = { 11265 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11266 Ptr, 11267 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11268 SubRegHi, 11269 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11270 }; 11271 11272 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11273 } 11274 11275 /// Return a resource descriptor with the 'Add TID' bit enabled 11276 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11277 /// of the resource descriptor) to create an offset, which is added to 11278 /// the resource pointer. 11279 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11280 SDValue Ptr, uint32_t RsrcDword1, 11281 uint64_t RsrcDword2And3) const { 11282 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11283 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11284 if (RsrcDword1) { 11285 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11286 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11287 0); 11288 } 11289 11290 SDValue DataLo = buildSMovImm32(DAG, DL, 11291 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11292 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11293 11294 const SDValue Ops[] = { 11295 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11296 PtrLo, 11297 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11298 PtrHi, 11299 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11300 DataLo, 11301 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11302 DataHi, 11303 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11304 }; 11305 11306 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11307 } 11308 11309 //===----------------------------------------------------------------------===// 11310 // SI Inline Assembly Support 11311 //===----------------------------------------------------------------------===// 11312 11313 std::pair<unsigned, const TargetRegisterClass *> 11314 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11315 StringRef Constraint, 11316 MVT VT) const { 11317 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11318 11319 const TargetRegisterClass *RC = nullptr; 11320 if (Constraint.size() == 1) { 11321 const unsigned BitWidth = VT.getSizeInBits(); 11322 switch (Constraint[0]) { 11323 default: 11324 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11325 case 's': 11326 case 'r': 11327 switch (BitWidth) { 11328 case 16: 11329 RC = &AMDGPU::SReg_32RegClass; 11330 break; 11331 case 64: 11332 RC = &AMDGPU::SGPR_64RegClass; 11333 break; 11334 default: 11335 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11336 if (!RC) 11337 return std::make_pair(0U, nullptr); 11338 break; 11339 } 11340 break; 11341 case 'v': 11342 switch (BitWidth) { 11343 case 16: 11344 RC = &AMDGPU::VGPR_32RegClass; 11345 break; 11346 default: 11347 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11348 if (!RC) 11349 return std::make_pair(0U, nullptr); 11350 break; 11351 } 11352 break; 11353 case 'a': 11354 if (!Subtarget->hasMAIInsts()) 11355 break; 11356 switch (BitWidth) { 11357 case 16: 11358 RC = &AMDGPU::AGPR_32RegClass; 11359 break; 11360 default: 11361 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11362 if (!RC) 11363 return std::make_pair(0U, nullptr); 11364 break; 11365 } 11366 break; 11367 } 11368 // We actually support i128, i16 and f16 as inline parameters 11369 // even if they are not reported as legal 11370 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11371 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11372 return std::make_pair(0U, RC); 11373 } 11374 11375 if (Constraint.size() > 1) { 11376 if (Constraint[1] == 'v') { 11377 RC = &AMDGPU::VGPR_32RegClass; 11378 } else if (Constraint[1] == 's') { 11379 RC = &AMDGPU::SGPR_32RegClass; 11380 } else if (Constraint[1] == 'a') { 11381 RC = &AMDGPU::AGPR_32RegClass; 11382 } 11383 11384 if (RC) { 11385 uint32_t Idx; 11386 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11387 if (!Failed && Idx < RC->getNumRegs()) 11388 return std::make_pair(RC->getRegister(Idx), RC); 11389 } 11390 } 11391 11392 // FIXME: Returns VS_32 for physical SGPR constraints 11393 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11394 } 11395 11396 static bool isImmConstraint(StringRef Constraint) { 11397 if (Constraint.size() == 1) { 11398 switch (Constraint[0]) { 11399 default: break; 11400 case 'I': 11401 case 'J': 11402 case 'A': 11403 case 'B': 11404 case 'C': 11405 return true; 11406 } 11407 } else if (Constraint == "DA" || 11408 Constraint == "DB") { 11409 return true; 11410 } 11411 return false; 11412 } 11413 11414 SITargetLowering::ConstraintType 11415 SITargetLowering::getConstraintType(StringRef Constraint) const { 11416 if (Constraint.size() == 1) { 11417 switch (Constraint[0]) { 11418 default: break; 11419 case 's': 11420 case 'v': 11421 case 'a': 11422 return C_RegisterClass; 11423 } 11424 } 11425 if (isImmConstraint(Constraint)) { 11426 return C_Other; 11427 } 11428 return TargetLowering::getConstraintType(Constraint); 11429 } 11430 11431 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11432 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11433 Val = Val & maskTrailingOnes<uint64_t>(Size); 11434 } 11435 return Val; 11436 } 11437 11438 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11439 std::string &Constraint, 11440 std::vector<SDValue> &Ops, 11441 SelectionDAG &DAG) const { 11442 if (isImmConstraint(Constraint)) { 11443 uint64_t Val; 11444 if (getAsmOperandConstVal(Op, Val) && 11445 checkAsmConstraintVal(Op, Constraint, Val)) { 11446 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11447 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11448 } 11449 } else { 11450 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11451 } 11452 } 11453 11454 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11455 unsigned Size = Op.getScalarValueSizeInBits(); 11456 if (Size > 64) 11457 return false; 11458 11459 if (Size == 16 && !Subtarget->has16BitInsts()) 11460 return false; 11461 11462 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11463 Val = C->getSExtValue(); 11464 return true; 11465 } 11466 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11467 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11468 return true; 11469 } 11470 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11471 if (Size != 16 || Op.getNumOperands() != 2) 11472 return false; 11473 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11474 return false; 11475 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11476 Val = C->getSExtValue(); 11477 return true; 11478 } 11479 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11480 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11481 return true; 11482 } 11483 } 11484 11485 return false; 11486 } 11487 11488 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11489 const std::string &Constraint, 11490 uint64_t Val) const { 11491 if (Constraint.size() == 1) { 11492 switch (Constraint[0]) { 11493 case 'I': 11494 return AMDGPU::isInlinableIntLiteral(Val); 11495 case 'J': 11496 return isInt<16>(Val); 11497 case 'A': 11498 return checkAsmConstraintValA(Op, Val); 11499 case 'B': 11500 return isInt<32>(Val); 11501 case 'C': 11502 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11503 AMDGPU::isInlinableIntLiteral(Val); 11504 default: 11505 break; 11506 } 11507 } else if (Constraint.size() == 2) { 11508 if (Constraint == "DA") { 11509 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11510 int64_t LoBits = static_cast<int32_t>(Val); 11511 return checkAsmConstraintValA(Op, HiBits, 32) && 11512 checkAsmConstraintValA(Op, LoBits, 32); 11513 } 11514 if (Constraint == "DB") { 11515 return true; 11516 } 11517 } 11518 llvm_unreachable("Invalid asm constraint"); 11519 } 11520 11521 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11522 uint64_t Val, 11523 unsigned MaxSize) const { 11524 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11525 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11526 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11527 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11528 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11529 return true; 11530 } 11531 return false; 11532 } 11533 11534 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11535 switch (UnalignedClassID) { 11536 case AMDGPU::VReg_64RegClassID: 11537 return AMDGPU::VReg_64_Align2RegClassID; 11538 case AMDGPU::VReg_96RegClassID: 11539 return AMDGPU::VReg_96_Align2RegClassID; 11540 case AMDGPU::VReg_128RegClassID: 11541 return AMDGPU::VReg_128_Align2RegClassID; 11542 case AMDGPU::VReg_160RegClassID: 11543 return AMDGPU::VReg_160_Align2RegClassID; 11544 case AMDGPU::VReg_192RegClassID: 11545 return AMDGPU::VReg_192_Align2RegClassID; 11546 case AMDGPU::VReg_256RegClassID: 11547 return AMDGPU::VReg_256_Align2RegClassID; 11548 case AMDGPU::VReg_512RegClassID: 11549 return AMDGPU::VReg_512_Align2RegClassID; 11550 case AMDGPU::VReg_1024RegClassID: 11551 return AMDGPU::VReg_1024_Align2RegClassID; 11552 case AMDGPU::AReg_64RegClassID: 11553 return AMDGPU::AReg_64_Align2RegClassID; 11554 case AMDGPU::AReg_96RegClassID: 11555 return AMDGPU::AReg_96_Align2RegClassID; 11556 case AMDGPU::AReg_128RegClassID: 11557 return AMDGPU::AReg_128_Align2RegClassID; 11558 case AMDGPU::AReg_160RegClassID: 11559 return AMDGPU::AReg_160_Align2RegClassID; 11560 case AMDGPU::AReg_192RegClassID: 11561 return AMDGPU::AReg_192_Align2RegClassID; 11562 case AMDGPU::AReg_256RegClassID: 11563 return AMDGPU::AReg_256_Align2RegClassID; 11564 case AMDGPU::AReg_512RegClassID: 11565 return AMDGPU::AReg_512_Align2RegClassID; 11566 case AMDGPU::AReg_1024RegClassID: 11567 return AMDGPU::AReg_1024_Align2RegClassID; 11568 default: 11569 return -1; 11570 } 11571 } 11572 11573 // Figure out which registers should be reserved for stack access. Only after 11574 // the function is legalized do we know all of the non-spill stack objects or if 11575 // calls are present. 11576 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11577 MachineRegisterInfo &MRI = MF.getRegInfo(); 11578 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11579 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11580 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11581 const SIInstrInfo *TII = ST.getInstrInfo(); 11582 11583 if (Info->isEntryFunction()) { 11584 // Callable functions have fixed registers used for stack access. 11585 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11586 } 11587 11588 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11589 Info->getStackPtrOffsetReg())); 11590 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11591 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11592 11593 // We need to worry about replacing the default register with itself in case 11594 // of MIR testcases missing the MFI. 11595 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11596 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11597 11598 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11599 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11600 11601 Info->limitOccupancy(MF); 11602 11603 if (ST.isWave32() && !MF.empty()) { 11604 for (auto &MBB : MF) { 11605 for (auto &MI : MBB) { 11606 TII->fixImplicitOperands(MI); 11607 } 11608 } 11609 } 11610 11611 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11612 // classes if required. Ideally the register class constraints would differ 11613 // per-subtarget, but there's no easy way to achieve that right now. This is 11614 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11615 // from using them as the register class for legal types. 11616 if (ST.needsAlignedVGPRs()) { 11617 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11618 const Register Reg = Register::index2VirtReg(I); 11619 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11620 if (!RC) 11621 continue; 11622 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11623 if (NewClassID != -1) 11624 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11625 } 11626 } 11627 11628 TargetLoweringBase::finalizeLowering(MF); 11629 11630 // Allocate a VGPR for future SGPR Spill if 11631 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11632 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11633 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11634 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11635 Info->reserveVGPRforSGPRSpills(MF); 11636 } 11637 11638 void SITargetLowering::computeKnownBitsForFrameIndex( 11639 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11640 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11641 11642 // Set the high bits to zero based on the maximum allowed scratch size per 11643 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11644 // calculation won't overflow, so assume the sign bit is never set. 11645 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11646 } 11647 11648 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11649 KnownBits &Known, unsigned Dim) { 11650 unsigned MaxValue = 11651 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11652 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11653 } 11654 11655 void SITargetLowering::computeKnownBitsForTargetInstr( 11656 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11657 const MachineRegisterInfo &MRI, unsigned Depth) const { 11658 const MachineInstr *MI = MRI.getVRegDef(R); 11659 switch (MI->getOpcode()) { 11660 case AMDGPU::G_INTRINSIC: { 11661 switch (MI->getIntrinsicID()) { 11662 case Intrinsic::amdgcn_workitem_id_x: 11663 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11664 break; 11665 case Intrinsic::amdgcn_workitem_id_y: 11666 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11667 break; 11668 case Intrinsic::amdgcn_workitem_id_z: 11669 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11670 break; 11671 case Intrinsic::amdgcn_mbcnt_lo: 11672 case Intrinsic::amdgcn_mbcnt_hi: { 11673 // These return at most the wavefront size - 1. 11674 unsigned Size = MRI.getType(R).getSizeInBits(); 11675 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11676 break; 11677 } 11678 case Intrinsic::amdgcn_groupstaticsize: { 11679 // We can report everything over the maximum size as 0. We can't report 11680 // based on the actual size because we don't know if it's accurate or not 11681 // at any given point. 11682 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11683 break; 11684 } 11685 } 11686 break; 11687 } 11688 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11689 Known.Zero.setHighBits(24); 11690 break; 11691 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11692 Known.Zero.setHighBits(16); 11693 break; 11694 } 11695 } 11696 11697 Align SITargetLowering::computeKnownAlignForTargetInstr( 11698 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11699 unsigned Depth) const { 11700 const MachineInstr *MI = MRI.getVRegDef(R); 11701 switch (MI->getOpcode()) { 11702 case AMDGPU::G_INTRINSIC: 11703 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11704 // FIXME: Can this move to generic code? What about the case where the call 11705 // site specifies a lower alignment? 11706 Intrinsic::ID IID = MI->getIntrinsicID(); 11707 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11708 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11709 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11710 return *RetAlign; 11711 return Align(1); 11712 } 11713 default: 11714 return Align(1); 11715 } 11716 } 11717 11718 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11719 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11720 const Align CacheLineAlign = Align(64); 11721 11722 // Pre-GFX10 target did not benefit from loop alignment 11723 if (!ML || DisableLoopAlignment || 11724 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11725 getSubtarget()->hasInstFwdPrefetchBug()) 11726 return PrefAlign; 11727 11728 // On GFX10 I$ is 4 x 64 bytes cache lines. 11729 // By default prefetcher keeps one cache line behind and reads two ahead. 11730 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11731 // behind and one ahead. 11732 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11733 // If loop fits 64 bytes it always spans no more than two cache lines and 11734 // does not need an alignment. 11735 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11736 // Else if loop is less or equal 192 bytes we need two lines behind. 11737 11738 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11739 const MachineBasicBlock *Header = ML->getHeader(); 11740 if (Header->getAlignment() != PrefAlign) 11741 return Header->getAlignment(); // Already processed. 11742 11743 unsigned LoopSize = 0; 11744 for (const MachineBasicBlock *MBB : ML->blocks()) { 11745 // If inner loop block is aligned assume in average half of the alignment 11746 // size to be added as nops. 11747 if (MBB != Header) 11748 LoopSize += MBB->getAlignment().value() / 2; 11749 11750 for (const MachineInstr &MI : *MBB) { 11751 LoopSize += TII->getInstSizeInBytes(MI); 11752 if (LoopSize > 192) 11753 return PrefAlign; 11754 } 11755 } 11756 11757 if (LoopSize <= 64) 11758 return PrefAlign; 11759 11760 if (LoopSize <= 128) 11761 return CacheLineAlign; 11762 11763 // If any of parent loops is surrounded by prefetch instructions do not 11764 // insert new for inner loop, which would reset parent's settings. 11765 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11766 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11767 auto I = Exit->getFirstNonDebugInstr(); 11768 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11769 return CacheLineAlign; 11770 } 11771 } 11772 11773 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11774 MachineBasicBlock *Exit = ML->getExitBlock(); 11775 11776 if (Pre && Exit) { 11777 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11778 TII->get(AMDGPU::S_INST_PREFETCH)) 11779 .addImm(1); // prefetch 2 lines behind PC 11780 11781 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11782 TII->get(AMDGPU::S_INST_PREFETCH)) 11783 .addImm(2); // prefetch 1 line behind PC 11784 } 11785 11786 return CacheLineAlign; 11787 } 11788 11789 LLVM_ATTRIBUTE_UNUSED 11790 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11791 assert(N->getOpcode() == ISD::CopyFromReg); 11792 do { 11793 // Follow the chain until we find an INLINEASM node. 11794 N = N->getOperand(0).getNode(); 11795 if (N->getOpcode() == ISD::INLINEASM || 11796 N->getOpcode() == ISD::INLINEASM_BR) 11797 return true; 11798 } while (N->getOpcode() == ISD::CopyFromReg); 11799 return false; 11800 } 11801 11802 bool SITargetLowering::isSDNodeSourceOfDivergence( 11803 const SDNode *N, FunctionLoweringInfo *FLI, 11804 LegacyDivergenceAnalysis *KDA) const { 11805 switch (N->getOpcode()) { 11806 case ISD::CopyFromReg: { 11807 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11808 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11809 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11810 Register Reg = R->getReg(); 11811 11812 // FIXME: Why does this need to consider isLiveIn? 11813 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11814 return !TRI->isSGPRReg(MRI, Reg); 11815 11816 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11817 return KDA->isDivergent(V); 11818 11819 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11820 return !TRI->isSGPRReg(MRI, Reg); 11821 } 11822 case ISD::LOAD: { 11823 const LoadSDNode *L = cast<LoadSDNode>(N); 11824 unsigned AS = L->getAddressSpace(); 11825 // A flat load may access private memory. 11826 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11827 } 11828 case ISD::CALLSEQ_END: 11829 return true; 11830 case ISD::INTRINSIC_WO_CHAIN: 11831 return AMDGPU::isIntrinsicSourceOfDivergence( 11832 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11833 case ISD::INTRINSIC_W_CHAIN: 11834 return AMDGPU::isIntrinsicSourceOfDivergence( 11835 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11836 case AMDGPUISD::ATOMIC_CMP_SWAP: 11837 case AMDGPUISD::ATOMIC_INC: 11838 case AMDGPUISD::ATOMIC_DEC: 11839 case AMDGPUISD::ATOMIC_LOAD_FMIN: 11840 case AMDGPUISD::ATOMIC_LOAD_FMAX: 11841 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 11842 case AMDGPUISD::BUFFER_ATOMIC_ADD: 11843 case AMDGPUISD::BUFFER_ATOMIC_SUB: 11844 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 11845 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 11846 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 11847 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 11848 case AMDGPUISD::BUFFER_ATOMIC_AND: 11849 case AMDGPUISD::BUFFER_ATOMIC_OR: 11850 case AMDGPUISD::BUFFER_ATOMIC_XOR: 11851 case AMDGPUISD::BUFFER_ATOMIC_INC: 11852 case AMDGPUISD::BUFFER_ATOMIC_DEC: 11853 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 11854 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 11855 case AMDGPUISD::BUFFER_ATOMIC_FADD: 11856 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 11857 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 11858 // Target-specific read-modify-write atomics are sources of divergence. 11859 return true; 11860 default: 11861 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 11862 // Generic read-modify-write atomics are sources of divergence. 11863 return A->readMem() && A->writeMem(); 11864 } 11865 return false; 11866 } 11867 } 11868 11869 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11870 EVT VT) const { 11871 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11872 case MVT::f32: 11873 return hasFP32Denormals(DAG.getMachineFunction()); 11874 case MVT::f64: 11875 case MVT::f16: 11876 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11877 default: 11878 return false; 11879 } 11880 } 11881 11882 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11883 const SelectionDAG &DAG, 11884 bool SNaN, 11885 unsigned Depth) const { 11886 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11887 const MachineFunction &MF = DAG.getMachineFunction(); 11888 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11889 11890 if (Info->getMode().DX10Clamp) 11891 return true; // Clamped to 0. 11892 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11893 } 11894 11895 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11896 SNaN, Depth); 11897 } 11898 11899 // Global FP atomic instructions have a hardcoded FP mode and do not support 11900 // FP32 denormals, and only support v2f16 denormals. 11901 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11902 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11903 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11904 if (&Flt == &APFloat::IEEEsingle()) 11905 return DenormMode == DenormalMode::getPreserveSign(); 11906 return DenormMode == DenormalMode::getIEEE(); 11907 } 11908 11909 TargetLowering::AtomicExpansionKind 11910 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11911 switch (RMW->getOperation()) { 11912 case AtomicRMWInst::FAdd: { 11913 Type *Ty = RMW->getType(); 11914 11915 // We don't have a way to support 16-bit atomics now, so just leave them 11916 // as-is. 11917 if (Ty->isHalfTy()) 11918 return AtomicExpansionKind::None; 11919 11920 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 11921 return AtomicExpansionKind::CmpXChg; 11922 11923 // TODO: Do have these for flat. Older targets also had them for buffers. 11924 unsigned AS = RMW->getPointerAddressSpace(); 11925 11926 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 11927 Subtarget->hasAtomicFaddInsts()) { 11928 if (!fpModeMatchesGlobalFPAtomicMode(RMW) || 11929 RMW->getFunction()->getFnAttribute("amdgpu-unsafe-fp-atomics") 11930 .getValueAsString() != "true") 11931 return AtomicExpansionKind::CmpXChg; 11932 11933 if (Subtarget->hasGFX90AInsts()) { 11934 auto SSID = RMW->getSyncScopeID(); 11935 if (SSID == SyncScope::System || 11936 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 11937 return AtomicExpansionKind::CmpXChg; 11938 11939 return (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) ? 11940 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 11941 } 11942 11943 if (!Subtarget->hasGFX90AInsts() && AS != AMDGPUAS::GLOBAL_ADDRESS) 11944 return AtomicExpansionKind::CmpXChg; 11945 11946 return RMW->use_empty() ? AtomicExpansionKind::None : 11947 AtomicExpansionKind::CmpXChg; 11948 } 11949 11950 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11951 // to round-to-nearest-even. 11952 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 11953 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 11954 return (Ty->isDoubleTy() && !fpModeMatchesGlobalFPAtomicMode(RMW)) ? 11955 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 11956 } 11957 11958 return AtomicExpansionKind::CmpXChg; 11959 } 11960 default: 11961 break; 11962 } 11963 11964 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11965 } 11966 11967 const TargetRegisterClass * 11968 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11969 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11970 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11971 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11972 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11973 : &AMDGPU::SReg_32RegClass; 11974 if (!TRI->isSGPRClass(RC) && !isDivergent) 11975 return TRI->getEquivalentSGPRClass(RC); 11976 else if (TRI->isSGPRClass(RC) && isDivergent) 11977 return TRI->getEquivalentVGPRClass(RC); 11978 11979 return RC; 11980 } 11981 11982 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11983 // uniform values (as produced by the mask results of control flow intrinsics) 11984 // used outside of divergent blocks. The phi users need to also be treated as 11985 // always uniform. 11986 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11987 unsigned WaveSize) { 11988 // FIXME: We asssume we never cast the mask results of a control flow 11989 // intrinsic. 11990 // Early exit if the type won't be consistent as a compile time hack. 11991 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11992 if (!IT || IT->getBitWidth() != WaveSize) 11993 return false; 11994 11995 if (!isa<Instruction>(V)) 11996 return false; 11997 if (!Visited.insert(V).second) 11998 return false; 11999 bool Result = false; 12000 for (auto U : V->users()) { 12001 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12002 if (V == U->getOperand(1)) { 12003 switch (Intrinsic->getIntrinsicID()) { 12004 default: 12005 Result = false; 12006 break; 12007 case Intrinsic::amdgcn_if_break: 12008 case Intrinsic::amdgcn_if: 12009 case Intrinsic::amdgcn_else: 12010 Result = true; 12011 break; 12012 } 12013 } 12014 if (V == U->getOperand(0)) { 12015 switch (Intrinsic->getIntrinsicID()) { 12016 default: 12017 Result = false; 12018 break; 12019 case Intrinsic::amdgcn_end_cf: 12020 case Intrinsic::amdgcn_loop: 12021 Result = true; 12022 break; 12023 } 12024 } 12025 } else { 12026 Result = hasCFUser(U, Visited, WaveSize); 12027 } 12028 if (Result) 12029 break; 12030 } 12031 return Result; 12032 } 12033 12034 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12035 const Value *V) const { 12036 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12037 if (CI->isInlineAsm()) { 12038 // FIXME: This cannot give a correct answer. This should only trigger in 12039 // the case where inline asm returns mixed SGPR and VGPR results, used 12040 // outside the defining block. We don't have a specific result to 12041 // consider, so this assumes if any value is SGPR, the overall register 12042 // also needs to be SGPR. 12043 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12044 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12045 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12046 for (auto &TC : TargetConstraints) { 12047 if (TC.Type == InlineAsm::isOutput) { 12048 ComputeConstraintToUse(TC, SDValue()); 12049 unsigned AssignedReg; 12050 const TargetRegisterClass *RC; 12051 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12052 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12053 if (RC) { 12054 MachineRegisterInfo &MRI = MF.getRegInfo(); 12055 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12056 return true; 12057 else if (SIRI->isSGPRClass(RC)) 12058 return true; 12059 } 12060 } 12061 } 12062 } 12063 } 12064 SmallPtrSet<const Value *, 16> Visited; 12065 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12066 } 12067 12068 std::pair<int, MVT> 12069 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12070 Type *Ty) const { 12071 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12072 auto Size = DL.getTypeSizeInBits(Ty); 12073 // Maximum load or store can handle 8 dwords for scalar and 4 for 12074 // vector ALU. Let's assume anything above 8 dwords is expensive 12075 // even if legal. 12076 if (Size <= 256) 12077 return Cost; 12078 12079 Cost.first = (Size + 255) / 256; 12080 return Cost; 12081 } 12082