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 "AMDGPUSubtarget.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 19 #include "SIDefines.h" 20 #include "SIInstrInfo.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "SIRegisterInfo.h" 23 #include "Utils/AMDGPUBaseInfo.h" 24 #include "llvm/ADT/APFloat.h" 25 #include "llvm/ADT/APInt.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/BitVector.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/ADT/StringSwitch.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CallingConvLower.h" 36 #include "llvm/CodeGen/DAGCombine.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineLoopInfo.h" 45 #include "llvm/CodeGen/MachineMemOperand.h" 46 #include "llvm/CodeGen/MachineModuleInfo.h" 47 #include "llvm/CodeGen/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/SelectionDAG.h" 50 #include "llvm/CodeGen/SelectionDAGNodes.h" 51 #include "llvm/CodeGen/TargetCallingConv.h" 52 #include "llvm/CodeGen/TargetRegisterInfo.h" 53 #include "llvm/CodeGen/ValueTypes.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DebugLoc.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/DiagnosticInfo.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/GlobalValue.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Type.h" 66 #include "llvm/Support/Casting.h" 67 #include "llvm/Support/CodeGen.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Support/Compiler.h" 70 #include "llvm/Support/ErrorHandling.h" 71 #include "llvm/Support/KnownBits.h" 72 #include "llvm/Support/MachineValueType.h" 73 #include "llvm/Support/MathExtras.h" 74 #include "llvm/Target/TargetOptions.h" 75 #include <cassert> 76 #include <cmath> 77 #include <cstdint> 78 #include <iterator> 79 #include <tuple> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 #define DEBUG_TYPE "si-lower" 86 87 STATISTIC(NumTailCalls, "Number of tail calls"); 88 89 static cl::opt<bool> DisableLoopAlignment( 90 "amdgpu-disable-loop-alignment", 91 cl::desc("Do not align and prefetch loops"), 92 cl::init(false)); 93 94 static cl::opt<bool> VGPRReserveforSGPRSpill( 95 "amdgpu-reserve-vgpr-for-sgpr-spill", 96 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 97 98 static cl::opt<bool> UseDivergentRegisterIndexing( 99 "amdgpu-use-divergent-register-indexing", 100 cl::Hidden, 101 cl::desc("Use indirect register addressing for divergent indexes"), 102 cl::init(false)); 103 104 static bool hasFP32Denormals(const MachineFunction &MF) { 105 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 106 return Info->getMode().allFP32Denormals(); 107 } 108 109 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 110 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 111 return Info->getMode().allFP64FP16Denormals(); 112 } 113 114 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 115 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 116 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 117 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 118 return AMDGPU::SGPR0 + Reg; 119 } 120 } 121 llvm_unreachable("Cannot allocate sgpr"); 122 } 123 124 SITargetLowering::SITargetLowering(const TargetMachine &TM, 125 const GCNSubtarget &STI) 126 : AMDGPUTargetLowering(TM, STI), 127 Subtarget(&STI) { 128 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 129 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 130 131 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 132 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 133 134 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 135 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 136 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 137 138 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 139 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 140 141 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 142 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 143 144 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 145 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 146 147 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 148 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 149 150 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 151 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 152 153 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 154 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 155 156 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 157 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 158 159 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 160 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 161 162 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 163 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 164 165 if (Subtarget->has16BitInsts()) { 166 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 167 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 168 169 // Unless there are also VOP3P operations, not operations are really legal. 170 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 171 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 172 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 173 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 174 } 175 176 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 177 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 178 179 computeRegisterProperties(Subtarget->getRegisterInfo()); 180 181 // The boolean content concept here is too inflexible. Compares only ever 182 // really produce a 1-bit result. Any copy/extend from these will turn into a 183 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 184 // it's what most targets use. 185 setBooleanContents(ZeroOrOneBooleanContent); 186 setBooleanVectorContents(ZeroOrOneBooleanContent); 187 188 // We need to custom lower vector stores from local memory 189 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 190 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::i1, Custom); 196 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 197 198 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 199 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 204 setOperationAction(ISD::STORE, MVT::i1, Custom); 205 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 206 207 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 208 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 209 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 210 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 211 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 212 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 213 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 214 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 215 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 216 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 217 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 218 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 219 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 220 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 221 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 222 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 223 224 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 225 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 227 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 228 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 229 230 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 231 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 232 233 setOperationAction(ISD::SELECT, MVT::i1, Promote); 234 setOperationAction(ISD::SELECT, MVT::i64, Custom); 235 setOperationAction(ISD::SELECT, MVT::f64, Promote); 236 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 237 238 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 239 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 242 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 243 244 setOperationAction(ISD::SETCC, MVT::i1, Promote); 245 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 246 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 247 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 248 249 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 250 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 251 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 252 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 253 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 254 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 255 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 256 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 257 258 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 266 267 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 268 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 269 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 270 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 271 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 272 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 273 274 setOperationAction(ISD::UADDO, MVT::i32, Legal); 275 setOperationAction(ISD::USUBO, MVT::i32, Legal); 276 277 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 278 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 279 280 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 281 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 282 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 283 284 #if 0 285 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 286 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 287 #endif 288 289 // We only support LOAD/STORE and vector manipulation ops for vectors 290 // with > 4 elements. 291 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 292 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 293 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 294 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 295 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 296 switch (Op) { 297 case ISD::LOAD: 298 case ISD::STORE: 299 case ISD::BUILD_VECTOR: 300 case ISD::BITCAST: 301 case ISD::EXTRACT_VECTOR_ELT: 302 case ISD::INSERT_VECTOR_ELT: 303 case ISD::INSERT_SUBVECTOR: 304 case ISD::EXTRACT_SUBVECTOR: 305 case ISD::SCALAR_TO_VECTOR: 306 break; 307 case ISD::CONCAT_VECTORS: 308 setOperationAction(Op, VT, Custom); 309 break; 310 default: 311 setOperationAction(Op, VT, Expand); 312 break; 313 } 314 } 315 } 316 317 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 318 319 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 320 // is expanded to avoid having two separate loops in case the index is a VGPR. 321 322 // Most operations are naturally 32-bit vector operations. We only support 323 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 324 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 325 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 326 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 327 328 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 329 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 330 331 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 332 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 333 334 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 335 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 336 } 337 338 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 339 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 340 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 341 342 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 343 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 344 345 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 346 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 347 348 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 349 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 350 } 351 352 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 353 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 354 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 355 356 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 357 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 358 359 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 360 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 361 362 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 363 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 364 } 365 366 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 367 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 368 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 369 370 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 371 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 372 373 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 374 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 375 376 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 377 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 378 } 379 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 383 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 384 385 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 387 388 // Avoid stack access for these. 389 // TODO: Generalize to more vector types. 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 394 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 400 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 404 405 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 407 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 409 410 // Deal with vec3 vector operations when widened to vec4. 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 415 416 // Deal with vec5 vector operations when widened to vec8. 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 420 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 421 422 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 423 // and output demarshalling 424 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 425 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 426 427 // We can't return success/failure, only the old value, 428 // let LLVM add the comparison 429 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 430 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 431 432 if (Subtarget->hasFlatAddressSpace()) { 433 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 434 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 435 } 436 437 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 438 439 // FIXME: This should be narrowed to i32, but that only happens if i64 is 440 // illegal. 441 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 442 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 443 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 444 445 // On SI this is s_memtime and s_memrealtime on VI. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 447 setOperationAction(ISD::TRAP, MVT::Other, Custom); 448 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 449 450 if (Subtarget->has16BitInsts()) { 451 setOperationAction(ISD::FPOW, MVT::f16, Promote); 452 setOperationAction(ISD::FLOG, MVT::f16, Custom); 453 setOperationAction(ISD::FEXP, MVT::f16, Custom); 454 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 455 } 456 457 if (Subtarget->hasMadMacF32Insts()) 458 setOperationAction(ISD::FMAD, MVT::f32, Legal); 459 460 if (!Subtarget->hasBFI()) { 461 // fcopysign can be done in a single instruction with BFI. 462 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 463 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 464 } 465 466 if (!Subtarget->hasBCNT(32)) 467 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 468 469 if (!Subtarget->hasBCNT(64)) 470 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 471 472 if (Subtarget->hasFFBH()) 473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 474 475 if (Subtarget->hasFFBL()) 476 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 477 478 // We only really have 32-bit BFE instructions (and 16-bit on VI). 479 // 480 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 481 // effort to match them now. We want this to be false for i64 cases when the 482 // extraction isn't restricted to the upper or lower half. Ideally we would 483 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 484 // span the midpoint are probably relatively rare, so don't worry about them 485 // for now. 486 if (Subtarget->hasBFE()) 487 setHasExtractBitsInsn(true); 488 489 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 490 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 491 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 492 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 493 494 495 // These are really only legal for ieee_mode functions. We should be avoiding 496 // them for functions that don't have ieee_mode enabled, so just say they are 497 // legal. 498 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 499 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 500 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 501 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 502 503 504 if (Subtarget->haveRoundOpsF64()) { 505 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 506 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 507 setOperationAction(ISD::FRINT, MVT::f64, Legal); 508 } else { 509 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 510 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 511 setOperationAction(ISD::FRINT, MVT::f64, Custom); 512 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 513 } 514 515 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 516 517 setOperationAction(ISD::FSIN, MVT::f32, Custom); 518 setOperationAction(ISD::FCOS, MVT::f32, Custom); 519 setOperationAction(ISD::FDIV, MVT::f32, Custom); 520 setOperationAction(ISD::FDIV, MVT::f64, Custom); 521 522 if (Subtarget->has16BitInsts()) { 523 setOperationAction(ISD::Constant, MVT::i16, Legal); 524 525 setOperationAction(ISD::SMIN, MVT::i16, Legal); 526 setOperationAction(ISD::SMAX, MVT::i16, Legal); 527 528 setOperationAction(ISD::UMIN, MVT::i16, Legal); 529 setOperationAction(ISD::UMAX, MVT::i16, Legal); 530 531 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 532 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 533 534 setOperationAction(ISD::ROTR, MVT::i16, Promote); 535 setOperationAction(ISD::ROTL, MVT::i16, Promote); 536 537 setOperationAction(ISD::SDIV, MVT::i16, Promote); 538 setOperationAction(ISD::UDIV, MVT::i16, Promote); 539 setOperationAction(ISD::SREM, MVT::i16, Promote); 540 setOperationAction(ISD::UREM, MVT::i16, Promote); 541 542 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 543 544 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 545 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 546 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 547 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 548 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 549 550 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 551 552 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 553 554 setOperationAction(ISD::LOAD, MVT::i16, Custom); 555 556 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 557 558 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 559 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 560 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 561 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 562 563 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 564 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 565 566 // F16 - Constant Actions. 567 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 568 569 // F16 - Load/Store Actions. 570 setOperationAction(ISD::LOAD, MVT::f16, Promote); 571 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 572 setOperationAction(ISD::STORE, MVT::f16, Promote); 573 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 574 575 // F16 - VOP1 Actions. 576 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 577 setOperationAction(ISD::FCOS, MVT::f16, Custom); 578 setOperationAction(ISD::FSIN, MVT::f16, Custom); 579 580 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 581 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 582 583 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 584 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 585 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 586 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 587 setOperationAction(ISD::FROUND, MVT::f16, Custom); 588 589 // F16 - VOP2 Actions. 590 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 591 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 592 593 setOperationAction(ISD::FDIV, MVT::f16, Custom); 594 595 // F16 - VOP3 Actions. 596 setOperationAction(ISD::FMA, MVT::f16, Legal); 597 if (STI.hasMadF16()) 598 setOperationAction(ISD::FMAD, MVT::f16, Legal); 599 600 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 601 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 602 switch (Op) { 603 case ISD::LOAD: 604 case ISD::STORE: 605 case ISD::BUILD_VECTOR: 606 case ISD::BITCAST: 607 case ISD::EXTRACT_VECTOR_ELT: 608 case ISD::INSERT_VECTOR_ELT: 609 case ISD::INSERT_SUBVECTOR: 610 case ISD::EXTRACT_SUBVECTOR: 611 case ISD::SCALAR_TO_VECTOR: 612 break; 613 case ISD::CONCAT_VECTORS: 614 setOperationAction(Op, VT, Custom); 615 break; 616 default: 617 setOperationAction(Op, VT, Expand); 618 break; 619 } 620 } 621 } 622 623 // v_perm_b32 can handle either of these. 624 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 625 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 626 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 627 628 // XXX - Do these do anything? Vector constants turn into build_vector. 629 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 630 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 631 632 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 633 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 634 635 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 636 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 637 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 638 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 639 640 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 641 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 642 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 643 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 644 645 setOperationAction(ISD::AND, MVT::v2i16, Promote); 646 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 647 setOperationAction(ISD::OR, MVT::v2i16, Promote); 648 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 649 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 650 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 651 652 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 653 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 654 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 655 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 656 657 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 658 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 659 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 660 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 661 662 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 663 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 664 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 665 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 666 667 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 668 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 669 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 670 671 if (!Subtarget->hasVOP3PInsts()) { 672 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 673 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 674 } 675 676 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 677 // This isn't really legal, but this avoids the legalizer unrolling it (and 678 // allows matching fneg (fabs x) patterns) 679 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 680 681 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 682 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 683 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 684 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 685 686 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 687 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 688 689 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 690 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 691 } 692 693 if (Subtarget->hasVOP3PInsts()) { 694 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 695 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 696 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 697 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 698 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 699 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 700 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 701 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 702 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 703 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 704 705 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 706 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 707 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 708 709 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 710 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 711 712 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 713 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 716 717 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 718 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 719 720 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 721 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 722 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 723 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 724 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 725 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 726 727 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 728 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 729 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 730 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 731 732 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 733 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 734 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 735 736 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 737 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 740 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 741 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 742 743 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 744 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 745 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 746 } 747 748 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 749 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 750 751 if (Subtarget->has16BitInsts()) { 752 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 753 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 754 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 755 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 756 } else { 757 // Legalization hack. 758 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 759 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 760 761 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 762 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 763 } 764 765 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 766 setOperationAction(ISD::SELECT, VT, Custom); 767 } 768 769 setOperationAction(ISD::SMULO, MVT::i64, Custom); 770 setOperationAction(ISD::UMULO, MVT::i64, Custom); 771 772 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 773 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 774 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 775 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 776 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 777 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 778 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 779 780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 785 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 786 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 787 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 788 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 789 790 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 795 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 796 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 797 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 798 799 setTargetDAGCombine(ISD::ADD); 800 setTargetDAGCombine(ISD::ADDCARRY); 801 setTargetDAGCombine(ISD::SUB); 802 setTargetDAGCombine(ISD::SUBCARRY); 803 setTargetDAGCombine(ISD::FADD); 804 setTargetDAGCombine(ISD::FSUB); 805 setTargetDAGCombine(ISD::FMINNUM); 806 setTargetDAGCombine(ISD::FMAXNUM); 807 setTargetDAGCombine(ISD::FMINNUM_IEEE); 808 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 809 setTargetDAGCombine(ISD::FMA); 810 setTargetDAGCombine(ISD::SMIN); 811 setTargetDAGCombine(ISD::SMAX); 812 setTargetDAGCombine(ISD::UMIN); 813 setTargetDAGCombine(ISD::UMAX); 814 setTargetDAGCombine(ISD::SETCC); 815 setTargetDAGCombine(ISD::AND); 816 setTargetDAGCombine(ISD::OR); 817 setTargetDAGCombine(ISD::XOR); 818 setTargetDAGCombine(ISD::SINT_TO_FP); 819 setTargetDAGCombine(ISD::UINT_TO_FP); 820 setTargetDAGCombine(ISD::FCANONICALIZE); 821 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 822 setTargetDAGCombine(ISD::ZERO_EXTEND); 823 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 824 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 825 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 826 827 // All memory operations. Some folding on the pointer operand is done to help 828 // matching the constant offsets in the addressing modes. 829 setTargetDAGCombine(ISD::LOAD); 830 setTargetDAGCombine(ISD::STORE); 831 setTargetDAGCombine(ISD::ATOMIC_LOAD); 832 setTargetDAGCombine(ISD::ATOMIC_STORE); 833 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 834 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 835 setTargetDAGCombine(ISD::ATOMIC_SWAP); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 844 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 845 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 846 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 847 848 // FIXME: In other contexts we pretend this is a per-function property. 849 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 850 851 setSchedulingPreference(Sched::RegPressure); 852 } 853 854 const GCNSubtarget *SITargetLowering::getSubtarget() const { 855 return Subtarget; 856 } 857 858 //===----------------------------------------------------------------------===// 859 // TargetLowering queries 860 //===----------------------------------------------------------------------===// 861 862 // v_mad_mix* support a conversion from f16 to f32. 863 // 864 // There is only one special case when denormals are enabled we don't currently, 865 // where this is OK to use. 866 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 867 EVT DestVT, EVT SrcVT) const { 868 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 869 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 870 DestVT.getScalarType() == MVT::f32 && 871 SrcVT.getScalarType() == MVT::f16 && 872 // TODO: This probably only requires no input flushing? 873 !hasFP32Denormals(DAG.getMachineFunction()); 874 } 875 876 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 877 // SI has some legal vector types, but no legal vector operations. Say no 878 // shuffles are legal in order to prefer scalarizing some vector operations. 879 return false; 880 } 881 882 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 883 CallingConv::ID CC, 884 EVT VT) const { 885 if (CC == CallingConv::AMDGPU_KERNEL) 886 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 887 888 if (VT.isVector()) { 889 EVT ScalarVT = VT.getScalarType(); 890 unsigned Size = ScalarVT.getSizeInBits(); 891 if (Size == 32) 892 return ScalarVT.getSimpleVT(); 893 894 if (Size > 32) 895 return MVT::i32; 896 897 if (Size == 16 && Subtarget->has16BitInsts()) 898 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 899 } else if (VT.getSizeInBits() > 32) 900 return MVT::i32; 901 902 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 903 } 904 905 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 906 CallingConv::ID CC, 907 EVT VT) const { 908 if (CC == CallingConv::AMDGPU_KERNEL) 909 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 910 911 if (VT.isVector()) { 912 unsigned NumElts = VT.getVectorNumElements(); 913 EVT ScalarVT = VT.getScalarType(); 914 unsigned Size = ScalarVT.getSizeInBits(); 915 916 if (Size == 32) 917 return NumElts; 918 919 if (Size > 32) 920 return NumElts * ((Size + 31) / 32); 921 922 if (Size == 16 && Subtarget->has16BitInsts()) 923 return (NumElts + 1) / 2; 924 } else if (VT.getSizeInBits() > 32) 925 return (VT.getSizeInBits() + 31) / 32; 926 927 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 928 } 929 930 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 931 LLVMContext &Context, CallingConv::ID CC, 932 EVT VT, EVT &IntermediateVT, 933 unsigned &NumIntermediates, MVT &RegisterVT) const { 934 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 935 unsigned NumElts = VT.getVectorNumElements(); 936 EVT ScalarVT = VT.getScalarType(); 937 unsigned Size = ScalarVT.getSizeInBits(); 938 if (Size == 32) { 939 RegisterVT = ScalarVT.getSimpleVT(); 940 IntermediateVT = RegisterVT; 941 NumIntermediates = NumElts; 942 return NumIntermediates; 943 } 944 945 if (Size > 32) { 946 RegisterVT = MVT::i32; 947 IntermediateVT = RegisterVT; 948 NumIntermediates = NumElts * ((Size + 31) / 32); 949 return NumIntermediates; 950 } 951 952 // FIXME: We should fix the ABI to be the same on targets without 16-bit 953 // support, but unless we can properly handle 3-vectors, it will be still be 954 // inconsistent. 955 if (Size == 16 && Subtarget->has16BitInsts()) { 956 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 957 IntermediateVT = RegisterVT; 958 NumIntermediates = (NumElts + 1) / 2; 959 return NumIntermediates; 960 } 961 } 962 963 return TargetLowering::getVectorTypeBreakdownForCallingConv( 964 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 965 } 966 967 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 968 assert(DMaskLanes != 0); 969 970 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 971 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 972 return EVT::getVectorVT(Ty->getContext(), 973 EVT::getEVT(VT->getElementType()), 974 NumElts); 975 } 976 977 return EVT::getEVT(Ty); 978 } 979 980 // Peek through TFE struct returns to only use the data size. 981 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 982 auto *ST = dyn_cast<StructType>(Ty); 983 if (!ST) 984 return memVTFromImageData(Ty, DMaskLanes); 985 986 // Some intrinsics return an aggregate type - special case to work out the 987 // correct memVT. 988 // 989 // Only limited forms of aggregate type currently expected. 990 if (ST->getNumContainedTypes() != 2 || 991 !ST->getContainedType(1)->isIntegerTy(32)) 992 return EVT(); 993 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 994 } 995 996 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 997 const CallInst &CI, 998 MachineFunction &MF, 999 unsigned IntrID) const { 1000 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1001 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1002 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1003 (Intrinsic::ID)IntrID); 1004 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1005 return false; 1006 1007 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1008 1009 if (RsrcIntr->IsImage) { 1010 Info.ptrVal = MFI->getImagePSV( 1011 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1012 CI.getArgOperand(RsrcIntr->RsrcArg)); 1013 Info.align.reset(); 1014 } else { 1015 Info.ptrVal = MFI->getBufferPSV( 1016 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1017 CI.getArgOperand(RsrcIntr->RsrcArg)); 1018 } 1019 1020 Info.flags = MachineMemOperand::MODereferenceable; 1021 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1022 unsigned DMaskLanes = 4; 1023 1024 if (RsrcIntr->IsImage) { 1025 const AMDGPU::ImageDimIntrinsicInfo *Intr 1026 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1027 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1028 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1029 1030 if (!BaseOpcode->Gather4) { 1031 // If this isn't a gather, we may have excess loaded elements in the 1032 // IR type. Check the dmask for the real number of elements loaded. 1033 unsigned DMask 1034 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1035 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1036 } 1037 1038 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1039 } else 1040 Info.memVT = EVT::getEVT(CI.getType()); 1041 1042 // FIXME: What does alignment mean for an image? 1043 Info.opc = ISD::INTRINSIC_W_CHAIN; 1044 Info.flags |= MachineMemOperand::MOLoad; 1045 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1046 Info.opc = ISD::INTRINSIC_VOID; 1047 1048 Type *DataTy = CI.getArgOperand(0)->getType(); 1049 if (RsrcIntr->IsImage) { 1050 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1051 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1052 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1053 } else 1054 Info.memVT = EVT::getEVT(DataTy); 1055 1056 Info.flags |= MachineMemOperand::MOStore; 1057 } else { 1058 // Atomic 1059 Info.opc = ISD::INTRINSIC_W_CHAIN; 1060 Info.memVT = MVT::getVT(CI.getType()); 1061 Info.flags = MachineMemOperand::MOLoad | 1062 MachineMemOperand::MOStore | 1063 MachineMemOperand::MODereferenceable; 1064 1065 // XXX - Should this be volatile without known ordering? 1066 Info.flags |= MachineMemOperand::MOVolatile; 1067 } 1068 return true; 1069 } 1070 1071 switch (IntrID) { 1072 case Intrinsic::amdgcn_atomic_inc: 1073 case Intrinsic::amdgcn_atomic_dec: 1074 case Intrinsic::amdgcn_ds_ordered_add: 1075 case Intrinsic::amdgcn_ds_ordered_swap: 1076 case Intrinsic::amdgcn_ds_fadd: 1077 case Intrinsic::amdgcn_ds_fmin: 1078 case Intrinsic::amdgcn_ds_fmax: { 1079 Info.opc = ISD::INTRINSIC_W_CHAIN; 1080 Info.memVT = MVT::getVT(CI.getType()); 1081 Info.ptrVal = CI.getOperand(0); 1082 Info.align.reset(); 1083 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1084 1085 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1086 if (!Vol->isZero()) 1087 Info.flags |= MachineMemOperand::MOVolatile; 1088 1089 return true; 1090 } 1091 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1092 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1093 1094 Info.opc = ISD::INTRINSIC_VOID; 1095 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1096 Info.ptrVal = MFI->getBufferPSV( 1097 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1098 CI.getArgOperand(1)); 1099 Info.align.reset(); 1100 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1101 1102 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1103 if (!Vol || !Vol->isZero()) 1104 Info.flags |= MachineMemOperand::MOVolatile; 1105 1106 return true; 1107 } 1108 case Intrinsic::amdgcn_global_atomic_fadd: { 1109 Info.opc = ISD::INTRINSIC_VOID; 1110 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1111 ->getPointerElementType()); 1112 Info.ptrVal = CI.getOperand(0); 1113 Info.align.reset(); 1114 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1115 1116 return true; 1117 } 1118 case Intrinsic::amdgcn_ds_append: 1119 case Intrinsic::amdgcn_ds_consume: { 1120 Info.opc = ISD::INTRINSIC_W_CHAIN; 1121 Info.memVT = MVT::getVT(CI.getType()); 1122 Info.ptrVal = CI.getOperand(0); 1123 Info.align.reset(); 1124 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1125 1126 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1127 if (!Vol->isZero()) 1128 Info.flags |= MachineMemOperand::MOVolatile; 1129 1130 return true; 1131 } 1132 case Intrinsic::amdgcn_global_atomic_csub: { 1133 Info.opc = ISD::INTRINSIC_W_CHAIN; 1134 Info.memVT = MVT::getVT(CI.getType()); 1135 Info.ptrVal = CI.getOperand(0); 1136 Info.align.reset(); 1137 Info.flags = MachineMemOperand::MOLoad | 1138 MachineMemOperand::MOStore | 1139 MachineMemOperand::MODereferenceable | 1140 MachineMemOperand::MOVolatile; 1141 return true; 1142 } 1143 case Intrinsic::amdgcn_ds_gws_init: 1144 case Intrinsic::amdgcn_ds_gws_barrier: 1145 case Intrinsic::amdgcn_ds_gws_sema_v: 1146 case Intrinsic::amdgcn_ds_gws_sema_br: 1147 case Intrinsic::amdgcn_ds_gws_sema_p: 1148 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1149 Info.opc = ISD::INTRINSIC_VOID; 1150 1151 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1152 Info.ptrVal = 1153 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1154 1155 // This is an abstract access, but we need to specify a type and size. 1156 Info.memVT = MVT::i32; 1157 Info.size = 4; 1158 Info.align = Align(4); 1159 1160 Info.flags = MachineMemOperand::MOStore; 1161 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1162 Info.flags = MachineMemOperand::MOLoad; 1163 return true; 1164 } 1165 default: 1166 return false; 1167 } 1168 } 1169 1170 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1171 SmallVectorImpl<Value*> &Ops, 1172 Type *&AccessTy) const { 1173 switch (II->getIntrinsicID()) { 1174 case Intrinsic::amdgcn_atomic_inc: 1175 case Intrinsic::amdgcn_atomic_dec: 1176 case Intrinsic::amdgcn_ds_ordered_add: 1177 case Intrinsic::amdgcn_ds_ordered_swap: 1178 case Intrinsic::amdgcn_ds_fadd: 1179 case Intrinsic::amdgcn_ds_fmin: 1180 case Intrinsic::amdgcn_ds_fmax: { 1181 Value *Ptr = II->getArgOperand(0); 1182 AccessTy = II->getType(); 1183 Ops.push_back(Ptr); 1184 return true; 1185 } 1186 default: 1187 return false; 1188 } 1189 } 1190 1191 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1192 if (!Subtarget->hasFlatInstOffsets()) { 1193 // Flat instructions do not have offsets, and only have the register 1194 // address. 1195 return AM.BaseOffs == 0 && AM.Scale == 0; 1196 } 1197 1198 return AM.Scale == 0 && 1199 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1200 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1201 /*Signed=*/false)); 1202 } 1203 1204 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1205 if (Subtarget->hasFlatGlobalInsts()) 1206 return AM.Scale == 0 && 1207 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1208 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1209 /*Signed=*/true)); 1210 1211 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1212 // Assume the we will use FLAT for all global memory accesses 1213 // on VI. 1214 // FIXME: This assumption is currently wrong. On VI we still use 1215 // MUBUF instructions for the r + i addressing mode. As currently 1216 // implemented, the MUBUF instructions only work on buffer < 4GB. 1217 // It may be possible to support > 4GB buffers with MUBUF instructions, 1218 // by setting the stride value in the resource descriptor which would 1219 // increase the size limit to (stride * 4GB). However, this is risky, 1220 // because it has never been validated. 1221 return isLegalFlatAddressingMode(AM); 1222 } 1223 1224 return isLegalMUBUFAddressingMode(AM); 1225 } 1226 1227 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1228 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1229 // additionally can do r + r + i with addr64. 32-bit has more addressing 1230 // mode options. Depending on the resource constant, it can also do 1231 // (i64 r0) + (i32 r1) * (i14 i). 1232 // 1233 // Private arrays end up using a scratch buffer most of the time, so also 1234 // assume those use MUBUF instructions. Scratch loads / stores are currently 1235 // implemented as mubuf instructions with offen bit set, so slightly 1236 // different than the normal addr64. 1237 if (!isUInt<12>(AM.BaseOffs)) 1238 return false; 1239 1240 // FIXME: Since we can split immediate into soffset and immediate offset, 1241 // would it make sense to allow any immediate? 1242 1243 switch (AM.Scale) { 1244 case 0: // r + i or just i, depending on HasBaseReg. 1245 return true; 1246 case 1: 1247 return true; // We have r + r or r + i. 1248 case 2: 1249 if (AM.HasBaseReg) { 1250 // Reject 2 * r + r. 1251 return false; 1252 } 1253 1254 // Allow 2 * r as r + r 1255 // Or 2 * r + i is allowed as r + r + i. 1256 return true; 1257 default: // Don't allow n * r 1258 return false; 1259 } 1260 } 1261 1262 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1263 const AddrMode &AM, Type *Ty, 1264 unsigned AS, Instruction *I) const { 1265 // No global is ever allowed as a base. 1266 if (AM.BaseGV) 1267 return false; 1268 1269 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1270 return isLegalGlobalAddressingMode(AM); 1271 1272 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1273 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1274 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1275 // If the offset isn't a multiple of 4, it probably isn't going to be 1276 // correctly aligned. 1277 // FIXME: Can we get the real alignment here? 1278 if (AM.BaseOffs % 4 != 0) 1279 return isLegalMUBUFAddressingMode(AM); 1280 1281 // There are no SMRD extloads, so if we have to do a small type access we 1282 // will use a MUBUF load. 1283 // FIXME?: We also need to do this if unaligned, but we don't know the 1284 // alignment here. 1285 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1286 return isLegalGlobalAddressingMode(AM); 1287 1288 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1289 // SMRD instructions have an 8-bit, dword offset on SI. 1290 if (!isUInt<8>(AM.BaseOffs / 4)) 1291 return false; 1292 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1293 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1294 // in 8-bits, it can use a smaller encoding. 1295 if (!isUInt<32>(AM.BaseOffs / 4)) 1296 return false; 1297 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1298 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1299 if (!isUInt<20>(AM.BaseOffs)) 1300 return false; 1301 } else 1302 llvm_unreachable("unhandled generation"); 1303 1304 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1305 return true; 1306 1307 if (AM.Scale == 1 && AM.HasBaseReg) 1308 return true; 1309 1310 return false; 1311 1312 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1313 return isLegalMUBUFAddressingMode(AM); 1314 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1315 AS == AMDGPUAS::REGION_ADDRESS) { 1316 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1317 // field. 1318 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1319 // an 8-bit dword offset but we don't know the alignment here. 1320 if (!isUInt<16>(AM.BaseOffs)) 1321 return false; 1322 1323 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1324 return true; 1325 1326 if (AM.Scale == 1 && AM.HasBaseReg) 1327 return true; 1328 1329 return false; 1330 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1331 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1332 // For an unknown address space, this usually means that this is for some 1333 // reason being used for pure arithmetic, and not based on some addressing 1334 // computation. We don't have instructions that compute pointers with any 1335 // addressing modes, so treat them as having no offset like flat 1336 // instructions. 1337 return isLegalFlatAddressingMode(AM); 1338 } 1339 1340 // Assume a user alias of global for unknown address spaces. 1341 return isLegalGlobalAddressingMode(AM); 1342 } 1343 1344 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1345 const SelectionDAG &DAG) const { 1346 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1347 return (MemVT.getSizeInBits() <= 4 * 32); 1348 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1349 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1350 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1351 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1352 return (MemVT.getSizeInBits() <= 2 * 32); 1353 } 1354 return true; 1355 } 1356 1357 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1358 unsigned Size, unsigned AddrSpace, unsigned Align, 1359 MachineMemOperand::Flags Flags, bool *IsFast) const { 1360 if (IsFast) 1361 *IsFast = false; 1362 1363 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1364 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1365 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1366 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1367 // with adjacent offsets. 1368 bool AlignedBy4 = (Align % 4 == 0); 1369 if (IsFast) 1370 *IsFast = AlignedBy4; 1371 1372 return AlignedBy4; 1373 } 1374 1375 // FIXME: We have to be conservative here and assume that flat operations 1376 // will access scratch. If we had access to the IR function, then we 1377 // could determine if any private memory was used in the function. 1378 if (!Subtarget->hasUnalignedScratchAccess() && 1379 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1380 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1381 bool AlignedBy4 = Align >= 4; 1382 if (IsFast) 1383 *IsFast = AlignedBy4; 1384 1385 return AlignedBy4; 1386 } 1387 1388 if (Subtarget->hasUnalignedBufferAccess()) { 1389 // If we have an uniform constant load, it still requires using a slow 1390 // buffer instruction if unaligned. 1391 if (IsFast) { 1392 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1393 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1394 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1395 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1396 Align >= 4 : Align != 2; 1397 } 1398 1399 return true; 1400 } 1401 1402 // Smaller than dword value must be aligned. 1403 if (Size < 32) 1404 return false; 1405 1406 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1407 // byte-address are ignored, thus forcing Dword alignment. 1408 // This applies to private, global, and constant memory. 1409 if (IsFast) 1410 *IsFast = true; 1411 1412 return Size >= 32 && Align >= 4; 1413 } 1414 1415 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1416 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1417 bool *IsFast) const { 1418 if (IsFast) 1419 *IsFast = false; 1420 1421 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1422 // which isn't a simple VT. 1423 // Until MVT is extended to handle this, simply check for the size and 1424 // rely on the condition below: allow accesses if the size is a multiple of 4. 1425 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1426 VT.getStoreSize() > 16)) { 1427 return false; 1428 } 1429 1430 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1431 Align, Flags, IsFast); 1432 } 1433 1434 EVT SITargetLowering::getOptimalMemOpType( 1435 const MemOp &Op, const AttributeList &FuncAttributes) const { 1436 // FIXME: Should account for address space here. 1437 1438 // The default fallback uses the private pointer size as a guess for a type to 1439 // use. Make sure we switch these to 64-bit accesses. 1440 1441 if (Op.size() >= 16 && 1442 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1443 return MVT::v4i32; 1444 1445 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1446 return MVT::v2i32; 1447 1448 // Use the default. 1449 return MVT::Other; 1450 } 1451 1452 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1453 unsigned DestAS) const { 1454 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1455 } 1456 1457 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1458 const MemSDNode *MemNode = cast<MemSDNode>(N); 1459 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1460 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1461 return I && I->getMetadata("amdgpu.noclobber"); 1462 } 1463 1464 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1465 unsigned DestAS) const { 1466 // Flat -> private/local is a simple truncate. 1467 // Flat -> global is no-op 1468 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1469 return true; 1470 1471 return isNoopAddrSpaceCast(SrcAS, DestAS); 1472 } 1473 1474 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1475 const MemSDNode *MemNode = cast<MemSDNode>(N); 1476 1477 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1478 } 1479 1480 TargetLoweringBase::LegalizeTypeAction 1481 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1482 int NumElts = VT.getVectorNumElements(); 1483 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1484 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1485 return TargetLoweringBase::getPreferredVectorAction(VT); 1486 } 1487 1488 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1489 Type *Ty) const { 1490 // FIXME: Could be smarter if called for vector constants. 1491 return true; 1492 } 1493 1494 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1495 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1496 switch (Op) { 1497 case ISD::LOAD: 1498 case ISD::STORE: 1499 1500 // These operations are done with 32-bit instructions anyway. 1501 case ISD::AND: 1502 case ISD::OR: 1503 case ISD::XOR: 1504 case ISD::SELECT: 1505 // TODO: Extensions? 1506 return true; 1507 default: 1508 return false; 1509 } 1510 } 1511 1512 // SimplifySetCC uses this function to determine whether or not it should 1513 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1514 if (VT == MVT::i1 && Op == ISD::SETCC) 1515 return false; 1516 1517 return TargetLowering::isTypeDesirableForOp(Op, VT); 1518 } 1519 1520 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1521 const SDLoc &SL, 1522 SDValue Chain, 1523 uint64_t Offset) const { 1524 const DataLayout &DL = DAG.getDataLayout(); 1525 MachineFunction &MF = DAG.getMachineFunction(); 1526 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1527 1528 const ArgDescriptor *InputPtrReg; 1529 const TargetRegisterClass *RC; 1530 LLT ArgTy; 1531 1532 std::tie(InputPtrReg, RC, ArgTy) = 1533 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1534 1535 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1536 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1537 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1538 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1539 1540 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1541 } 1542 1543 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1544 const SDLoc &SL) const { 1545 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1546 FIRST_IMPLICIT); 1547 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1548 } 1549 1550 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1551 const SDLoc &SL, SDValue Val, 1552 bool Signed, 1553 const ISD::InputArg *Arg) const { 1554 // First, if it is a widened vector, narrow it. 1555 if (VT.isVector() && 1556 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1557 EVT NarrowedVT = 1558 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1559 VT.getVectorNumElements()); 1560 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1561 DAG.getConstant(0, SL, MVT::i32)); 1562 } 1563 1564 // Then convert the vector elements or scalar value. 1565 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1566 VT.bitsLT(MemVT)) { 1567 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1568 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1569 } 1570 1571 if (MemVT.isFloatingPoint()) 1572 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1573 else if (Signed) 1574 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1575 else 1576 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1577 1578 return Val; 1579 } 1580 1581 SDValue SITargetLowering::lowerKernargMemParameter( 1582 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1583 uint64_t Offset, Align Alignment, bool Signed, 1584 const ISD::InputArg *Arg) const { 1585 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1586 1587 // Try to avoid using an extload by loading earlier than the argument address, 1588 // and extracting the relevant bits. The load should hopefully be merged with 1589 // the previous argument. 1590 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1591 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1592 int64_t AlignDownOffset = alignDown(Offset, 4); 1593 int64_t OffsetDiff = Offset - AlignDownOffset; 1594 1595 EVT IntVT = MemVT.changeTypeToInteger(); 1596 1597 // TODO: If we passed in the base kernel offset we could have a better 1598 // alignment than 4, but we don't really need it. 1599 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1600 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1601 MachineMemOperand::MODereferenceable | 1602 MachineMemOperand::MOInvariant); 1603 1604 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1605 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1606 1607 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1608 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1609 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1610 1611 1612 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1613 } 1614 1615 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1616 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1617 MachineMemOperand::MODereferenceable | 1618 MachineMemOperand::MOInvariant); 1619 1620 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1621 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1622 } 1623 1624 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1625 const SDLoc &SL, SDValue Chain, 1626 const ISD::InputArg &Arg) const { 1627 MachineFunction &MF = DAG.getMachineFunction(); 1628 MachineFrameInfo &MFI = MF.getFrameInfo(); 1629 1630 if (Arg.Flags.isByVal()) { 1631 unsigned Size = Arg.Flags.getByValSize(); 1632 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1633 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1634 } 1635 1636 unsigned ArgOffset = VA.getLocMemOffset(); 1637 unsigned ArgSize = VA.getValVT().getStoreSize(); 1638 1639 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1640 1641 // Create load nodes to retrieve arguments from the stack. 1642 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1643 SDValue ArgValue; 1644 1645 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1646 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1647 MVT MemVT = VA.getValVT(); 1648 1649 switch (VA.getLocInfo()) { 1650 default: 1651 break; 1652 case CCValAssign::BCvt: 1653 MemVT = VA.getLocVT(); 1654 break; 1655 case CCValAssign::SExt: 1656 ExtType = ISD::SEXTLOAD; 1657 break; 1658 case CCValAssign::ZExt: 1659 ExtType = ISD::ZEXTLOAD; 1660 break; 1661 case CCValAssign::AExt: 1662 ExtType = ISD::EXTLOAD; 1663 break; 1664 } 1665 1666 ArgValue = DAG.getExtLoad( 1667 ExtType, SL, VA.getLocVT(), Chain, FIN, 1668 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1669 MemVT); 1670 return ArgValue; 1671 } 1672 1673 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1674 const SIMachineFunctionInfo &MFI, 1675 EVT VT, 1676 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1677 const ArgDescriptor *Reg; 1678 const TargetRegisterClass *RC; 1679 LLT Ty; 1680 1681 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1682 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1683 } 1684 1685 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1686 CallingConv::ID CallConv, 1687 ArrayRef<ISD::InputArg> Ins, 1688 BitVector &Skipped, 1689 FunctionType *FType, 1690 SIMachineFunctionInfo *Info) { 1691 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1692 const ISD::InputArg *Arg = &Ins[I]; 1693 1694 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1695 "vector type argument should have been split"); 1696 1697 // First check if it's a PS input addr. 1698 if (CallConv == CallingConv::AMDGPU_PS && 1699 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1700 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1701 1702 // Inconveniently only the first part of the split is marked as isSplit, 1703 // so skip to the end. We only want to increment PSInputNum once for the 1704 // entire split argument. 1705 if (Arg->Flags.isSplit()) { 1706 while (!Arg->Flags.isSplitEnd()) { 1707 assert((!Arg->VT.isVector() || 1708 Arg->VT.getScalarSizeInBits() == 16) && 1709 "unexpected vector split in ps argument type"); 1710 if (!SkipArg) 1711 Splits.push_back(*Arg); 1712 Arg = &Ins[++I]; 1713 } 1714 } 1715 1716 if (SkipArg) { 1717 // We can safely skip PS inputs. 1718 Skipped.set(Arg->getOrigArgIndex()); 1719 ++PSInputNum; 1720 continue; 1721 } 1722 1723 Info->markPSInputAllocated(PSInputNum); 1724 if (Arg->Used) 1725 Info->markPSInputEnabled(PSInputNum); 1726 1727 ++PSInputNum; 1728 } 1729 1730 Splits.push_back(*Arg); 1731 } 1732 } 1733 1734 // Allocate special inputs passed in VGPRs. 1735 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1736 MachineFunction &MF, 1737 const SIRegisterInfo &TRI, 1738 SIMachineFunctionInfo &Info) const { 1739 const LLT S32 = LLT::scalar(32); 1740 MachineRegisterInfo &MRI = MF.getRegInfo(); 1741 1742 if (Info.hasWorkItemIDX()) { 1743 Register Reg = AMDGPU::VGPR0; 1744 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1745 1746 CCInfo.AllocateReg(Reg); 1747 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1748 } 1749 1750 if (Info.hasWorkItemIDY()) { 1751 Register Reg = AMDGPU::VGPR1; 1752 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1753 1754 CCInfo.AllocateReg(Reg); 1755 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1756 } 1757 1758 if (Info.hasWorkItemIDZ()) { 1759 Register Reg = AMDGPU::VGPR2; 1760 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1761 1762 CCInfo.AllocateReg(Reg); 1763 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1764 } 1765 } 1766 1767 // Try to allocate a VGPR at the end of the argument list, or if no argument 1768 // VGPRs are left allocating a stack slot. 1769 // If \p Mask is is given it indicates bitfield position in the register. 1770 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1771 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1772 ArgDescriptor Arg = ArgDescriptor()) { 1773 if (Arg.isSet()) 1774 return ArgDescriptor::createArg(Arg, Mask); 1775 1776 ArrayRef<MCPhysReg> ArgVGPRs 1777 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1778 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1779 if (RegIdx == ArgVGPRs.size()) { 1780 // Spill to stack required. 1781 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1782 1783 return ArgDescriptor::createStack(Offset, Mask); 1784 } 1785 1786 unsigned Reg = ArgVGPRs[RegIdx]; 1787 Reg = CCInfo.AllocateReg(Reg); 1788 assert(Reg != AMDGPU::NoRegister); 1789 1790 MachineFunction &MF = CCInfo.getMachineFunction(); 1791 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1792 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1793 return ArgDescriptor::createRegister(Reg, Mask); 1794 } 1795 1796 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1797 const TargetRegisterClass *RC, 1798 unsigned NumArgRegs) { 1799 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1800 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1801 if (RegIdx == ArgSGPRs.size()) 1802 report_fatal_error("ran out of SGPRs for arguments"); 1803 1804 unsigned Reg = ArgSGPRs[RegIdx]; 1805 Reg = CCInfo.AllocateReg(Reg); 1806 assert(Reg != AMDGPU::NoRegister); 1807 1808 MachineFunction &MF = CCInfo.getMachineFunction(); 1809 MF.addLiveIn(Reg, RC); 1810 return ArgDescriptor::createRegister(Reg); 1811 } 1812 1813 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1814 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1815 } 1816 1817 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1818 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1819 } 1820 1821 /// Allocate implicit function VGPR arguments at the end of allocated user 1822 /// arguments. 1823 void SITargetLowering::allocateSpecialInputVGPRs( 1824 CCState &CCInfo, MachineFunction &MF, 1825 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1826 const unsigned Mask = 0x3ff; 1827 ArgDescriptor Arg; 1828 1829 if (Info.hasWorkItemIDX()) { 1830 Arg = allocateVGPR32Input(CCInfo, Mask); 1831 Info.setWorkItemIDX(Arg); 1832 } 1833 1834 if (Info.hasWorkItemIDY()) { 1835 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1836 Info.setWorkItemIDY(Arg); 1837 } 1838 1839 if (Info.hasWorkItemIDZ()) 1840 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1841 } 1842 1843 /// Allocate implicit function VGPR arguments in fixed registers. 1844 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1845 CCState &CCInfo, MachineFunction &MF, 1846 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1847 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1848 if (!Reg) 1849 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1850 1851 const unsigned Mask = 0x3ff; 1852 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1853 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1854 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1855 } 1856 1857 void SITargetLowering::allocateSpecialInputSGPRs( 1858 CCState &CCInfo, 1859 MachineFunction &MF, 1860 const SIRegisterInfo &TRI, 1861 SIMachineFunctionInfo &Info) const { 1862 auto &ArgInfo = Info.getArgInfo(); 1863 1864 // TODO: Unify handling with private memory pointers. 1865 1866 if (Info.hasDispatchPtr()) 1867 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1868 1869 if (Info.hasQueuePtr()) 1870 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1871 1872 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1873 // constant offset from the kernarg segment. 1874 if (Info.hasImplicitArgPtr()) 1875 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1876 1877 if (Info.hasDispatchID()) 1878 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1879 1880 // flat_scratch_init is not applicable for non-kernel functions. 1881 1882 if (Info.hasWorkGroupIDX()) 1883 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1884 1885 if (Info.hasWorkGroupIDY()) 1886 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1887 1888 if (Info.hasWorkGroupIDZ()) 1889 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1890 } 1891 1892 // Allocate special inputs passed in user SGPRs. 1893 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1894 MachineFunction &MF, 1895 const SIRegisterInfo &TRI, 1896 SIMachineFunctionInfo &Info) const { 1897 if (Info.hasImplicitBufferPtr()) { 1898 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1899 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1900 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1901 } 1902 1903 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1904 if (Info.hasPrivateSegmentBuffer()) { 1905 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1906 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1907 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1908 } 1909 1910 if (Info.hasDispatchPtr()) { 1911 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1912 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1913 CCInfo.AllocateReg(DispatchPtrReg); 1914 } 1915 1916 if (Info.hasQueuePtr()) { 1917 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1918 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1919 CCInfo.AllocateReg(QueuePtrReg); 1920 } 1921 1922 if (Info.hasKernargSegmentPtr()) { 1923 MachineRegisterInfo &MRI = MF.getRegInfo(); 1924 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1925 CCInfo.AllocateReg(InputPtrReg); 1926 1927 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1928 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1929 } 1930 1931 if (Info.hasDispatchID()) { 1932 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1933 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1934 CCInfo.AllocateReg(DispatchIDReg); 1935 } 1936 1937 if (Info.hasFlatScratchInit()) { 1938 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1939 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1940 CCInfo.AllocateReg(FlatScratchInitReg); 1941 } 1942 1943 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1944 // these from the dispatch pointer. 1945 } 1946 1947 // Allocate special input registers that are initialized per-wave. 1948 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1949 MachineFunction &MF, 1950 SIMachineFunctionInfo &Info, 1951 CallingConv::ID CallConv, 1952 bool IsShader) const { 1953 if (Info.hasWorkGroupIDX()) { 1954 unsigned Reg = Info.addWorkGroupIDX(); 1955 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1956 CCInfo.AllocateReg(Reg); 1957 } 1958 1959 if (Info.hasWorkGroupIDY()) { 1960 unsigned Reg = Info.addWorkGroupIDY(); 1961 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1962 CCInfo.AllocateReg(Reg); 1963 } 1964 1965 if (Info.hasWorkGroupIDZ()) { 1966 unsigned Reg = Info.addWorkGroupIDZ(); 1967 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1968 CCInfo.AllocateReg(Reg); 1969 } 1970 1971 if (Info.hasWorkGroupInfo()) { 1972 unsigned Reg = Info.addWorkGroupInfo(); 1973 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1974 CCInfo.AllocateReg(Reg); 1975 } 1976 1977 if (Info.hasPrivateSegmentWaveByteOffset()) { 1978 // Scratch wave offset passed in system SGPR. 1979 unsigned PrivateSegmentWaveByteOffsetReg; 1980 1981 if (IsShader) { 1982 PrivateSegmentWaveByteOffsetReg = 1983 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1984 1985 // This is true if the scratch wave byte offset doesn't have a fixed 1986 // location. 1987 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1988 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1989 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1990 } 1991 } else 1992 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1993 1994 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1995 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1996 } 1997 } 1998 1999 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2000 MachineFunction &MF, 2001 const SIRegisterInfo &TRI, 2002 SIMachineFunctionInfo &Info) { 2003 // Now that we've figured out where the scratch register inputs are, see if 2004 // should reserve the arguments and use them directly. 2005 MachineFrameInfo &MFI = MF.getFrameInfo(); 2006 bool HasStackObjects = MFI.hasStackObjects(); 2007 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2008 2009 // Record that we know we have non-spill stack objects so we don't need to 2010 // check all stack objects later. 2011 if (HasStackObjects) 2012 Info.setHasNonSpillStackObjects(true); 2013 2014 // Everything live out of a block is spilled with fast regalloc, so it's 2015 // almost certain that spilling will be required. 2016 if (TM.getOptLevel() == CodeGenOpt::None) 2017 HasStackObjects = true; 2018 2019 // For now assume stack access is needed in any callee functions, so we need 2020 // the scratch registers to pass in. 2021 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2022 2023 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2024 // If we have stack objects, we unquestionably need the private buffer 2025 // resource. For the Code Object V2 ABI, this will be the first 4 user 2026 // SGPR inputs. We can reserve those and use them directly. 2027 2028 Register PrivateSegmentBufferReg = 2029 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2030 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2031 } else { 2032 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2033 // We tentatively reserve the last registers (skipping the last registers 2034 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2035 // we'll replace these with the ones immediately after those which were 2036 // really allocated. In the prologue copies will be inserted from the 2037 // argument to these reserved registers. 2038 2039 // Without HSA, relocations are used for the scratch pointer and the 2040 // buffer resource setup is always inserted in the prologue. Scratch wave 2041 // offset is still in an input SGPR. 2042 Info.setScratchRSrcReg(ReservedBufferReg); 2043 } 2044 2045 MachineRegisterInfo &MRI = MF.getRegInfo(); 2046 2047 // For entry functions we have to set up the stack pointer if we use it, 2048 // whereas non-entry functions get this "for free". This means there is no 2049 // intrinsic advantage to using S32 over S34 in cases where we do not have 2050 // calls but do need a frame pointer (i.e. if we are requested to have one 2051 // because frame pointer elimination is disabled). To keep things simple we 2052 // only ever use S32 as the call ABI stack pointer, and so using it does not 2053 // imply we need a separate frame pointer. 2054 // 2055 // Try to use s32 as the SP, but move it if it would interfere with input 2056 // arguments. This won't work with calls though. 2057 // 2058 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2059 // registers. 2060 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2061 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2062 } else { 2063 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2064 2065 if (MFI.hasCalls()) 2066 report_fatal_error("call in graphics shader with too many input SGPRs"); 2067 2068 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2069 if (!MRI.isLiveIn(Reg)) { 2070 Info.setStackPtrOffsetReg(Reg); 2071 break; 2072 } 2073 } 2074 2075 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2076 report_fatal_error("failed to find register for SP"); 2077 } 2078 2079 // hasFP should be accurate for entry functions even before the frame is 2080 // finalized, because it does not rely on the known stack size, only 2081 // properties like whether variable sized objects are present. 2082 if (ST.getFrameLowering()->hasFP(MF)) { 2083 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2084 } 2085 } 2086 2087 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2088 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2089 return !Info->isEntryFunction(); 2090 } 2091 2092 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2093 2094 } 2095 2096 void SITargetLowering::insertCopiesSplitCSR( 2097 MachineBasicBlock *Entry, 2098 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2099 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2100 2101 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2102 if (!IStart) 2103 return; 2104 2105 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2106 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2107 MachineBasicBlock::iterator MBBI = Entry->begin(); 2108 for (const MCPhysReg *I = IStart; *I; ++I) { 2109 const TargetRegisterClass *RC = nullptr; 2110 if (AMDGPU::SReg_64RegClass.contains(*I)) 2111 RC = &AMDGPU::SGPR_64RegClass; 2112 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2113 RC = &AMDGPU::SGPR_32RegClass; 2114 else 2115 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2116 2117 Register NewVR = MRI->createVirtualRegister(RC); 2118 // Create copy from CSR to a virtual register. 2119 Entry->addLiveIn(*I); 2120 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2121 .addReg(*I); 2122 2123 // Insert the copy-back instructions right before the terminator. 2124 for (auto *Exit : Exits) 2125 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2126 TII->get(TargetOpcode::COPY), *I) 2127 .addReg(NewVR); 2128 } 2129 } 2130 2131 SDValue SITargetLowering::LowerFormalArguments( 2132 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2133 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2134 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2135 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2136 2137 MachineFunction &MF = DAG.getMachineFunction(); 2138 const Function &Fn = MF.getFunction(); 2139 FunctionType *FType = MF.getFunction().getFunctionType(); 2140 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2141 2142 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2143 DiagnosticInfoUnsupported NoGraphicsHSA( 2144 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2145 DAG.getContext()->diagnose(NoGraphicsHSA); 2146 return DAG.getEntryNode(); 2147 } 2148 2149 SmallVector<ISD::InputArg, 16> Splits; 2150 SmallVector<CCValAssign, 16> ArgLocs; 2151 BitVector Skipped(Ins.size()); 2152 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2153 *DAG.getContext()); 2154 2155 bool IsShader = AMDGPU::isShader(CallConv); 2156 bool IsKernel = AMDGPU::isKernel(CallConv); 2157 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2158 2159 if (IsShader) { 2160 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2161 2162 // At least one interpolation mode must be enabled or else the GPU will 2163 // hang. 2164 // 2165 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2166 // set PSInputAddr, the user wants to enable some bits after the compilation 2167 // based on run-time states. Since we can't know what the final PSInputEna 2168 // will look like, so we shouldn't do anything here and the user should take 2169 // responsibility for the correct programming. 2170 // 2171 // Otherwise, the following restrictions apply: 2172 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2173 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2174 // enabled too. 2175 if (CallConv == CallingConv::AMDGPU_PS) { 2176 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2177 ((Info->getPSInputAddr() & 0xF) == 0 && 2178 Info->isPSInputAllocated(11))) { 2179 CCInfo.AllocateReg(AMDGPU::VGPR0); 2180 CCInfo.AllocateReg(AMDGPU::VGPR1); 2181 Info->markPSInputAllocated(0); 2182 Info->markPSInputEnabled(0); 2183 } 2184 if (Subtarget->isAmdPalOS()) { 2185 // For isAmdPalOS, the user does not enable some bits after compilation 2186 // based on run-time states; the register values being generated here are 2187 // the final ones set in hardware. Therefore we need to apply the 2188 // workaround to PSInputAddr and PSInputEnable together. (The case where 2189 // a bit is set in PSInputAddr but not PSInputEnable is where the 2190 // frontend set up an input arg for a particular interpolation mode, but 2191 // nothing uses that input arg. Really we should have an earlier pass 2192 // that removes such an arg.) 2193 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2194 if ((PsInputBits & 0x7F) == 0 || 2195 ((PsInputBits & 0xF) == 0 && 2196 (PsInputBits >> 11 & 1))) 2197 Info->markPSInputEnabled( 2198 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2199 } 2200 } 2201 2202 assert(!Info->hasDispatchPtr() && 2203 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2204 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2205 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2206 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2207 !Info->hasWorkItemIDZ()); 2208 } else if (IsKernel) { 2209 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2210 } else { 2211 Splits.append(Ins.begin(), Ins.end()); 2212 } 2213 2214 if (IsEntryFunc) { 2215 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2216 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2217 } else { 2218 // For the fixed ABI, pass workitem IDs in the last argument register. 2219 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2220 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2221 } 2222 2223 if (IsKernel) { 2224 analyzeFormalArgumentsCompute(CCInfo, Ins); 2225 } else { 2226 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2227 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2228 } 2229 2230 SmallVector<SDValue, 16> Chains; 2231 2232 // FIXME: This is the minimum kernel argument alignment. We should improve 2233 // this to the maximum alignment of the arguments. 2234 // 2235 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2236 // kern arg offset. 2237 const Align KernelArgBaseAlign = Align(16); 2238 2239 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2240 const ISD::InputArg &Arg = Ins[i]; 2241 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2242 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2243 continue; 2244 } 2245 2246 CCValAssign &VA = ArgLocs[ArgIdx++]; 2247 MVT VT = VA.getLocVT(); 2248 2249 if (IsEntryFunc && VA.isMemLoc()) { 2250 VT = Ins[i].VT; 2251 EVT MemVT = VA.getLocVT(); 2252 2253 const uint64_t Offset = VA.getLocMemOffset(); 2254 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2255 2256 SDValue Arg = 2257 lowerKernargMemParameter(DAG, VT, MemVT, DL, Chain, Offset, Alignment, 2258 Ins[i].Flags.isSExt(), &Ins[i]); 2259 Chains.push_back(Arg.getValue(1)); 2260 2261 auto *ParamTy = 2262 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2263 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2264 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2265 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2266 // On SI local pointers are just offsets into LDS, so they are always 2267 // less than 16-bits. On CI and newer they could potentially be 2268 // real pointers, so we can't guarantee their size. 2269 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2270 DAG.getValueType(MVT::i16)); 2271 } 2272 2273 InVals.push_back(Arg); 2274 continue; 2275 } else if (!IsEntryFunc && VA.isMemLoc()) { 2276 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2277 InVals.push_back(Val); 2278 if (!Arg.Flags.isByVal()) 2279 Chains.push_back(Val.getValue(1)); 2280 continue; 2281 } 2282 2283 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2284 2285 Register Reg = VA.getLocReg(); 2286 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2287 EVT ValVT = VA.getValVT(); 2288 2289 Reg = MF.addLiveIn(Reg, RC); 2290 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2291 2292 if (Arg.Flags.isSRet()) { 2293 // The return object should be reasonably addressable. 2294 2295 // FIXME: This helps when the return is a real sret. If it is a 2296 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2297 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2298 unsigned NumBits 2299 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2300 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2301 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2302 } 2303 2304 // If this is an 8 or 16-bit value, it is really passed promoted 2305 // to 32 bits. Insert an assert[sz]ext to capture this, then 2306 // truncate to the right size. 2307 switch (VA.getLocInfo()) { 2308 case CCValAssign::Full: 2309 break; 2310 case CCValAssign::BCvt: 2311 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2312 break; 2313 case CCValAssign::SExt: 2314 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2315 DAG.getValueType(ValVT)); 2316 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2317 break; 2318 case CCValAssign::ZExt: 2319 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2320 DAG.getValueType(ValVT)); 2321 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2322 break; 2323 case CCValAssign::AExt: 2324 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2325 break; 2326 default: 2327 llvm_unreachable("Unknown loc info!"); 2328 } 2329 2330 InVals.push_back(Val); 2331 } 2332 2333 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2334 // Special inputs come after user arguments. 2335 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2336 } 2337 2338 // Start adding system SGPRs. 2339 if (IsEntryFunc) { 2340 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2341 } else { 2342 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2343 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2344 } 2345 2346 auto &ArgUsageInfo = 2347 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2348 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2349 2350 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2351 Info->setBytesInStackArgArea(StackArgSize); 2352 2353 return Chains.empty() ? Chain : 2354 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2355 } 2356 2357 // TODO: If return values can't fit in registers, we should return as many as 2358 // possible in registers before passing on stack. 2359 bool SITargetLowering::CanLowerReturn( 2360 CallingConv::ID CallConv, 2361 MachineFunction &MF, bool IsVarArg, 2362 const SmallVectorImpl<ISD::OutputArg> &Outs, 2363 LLVMContext &Context) const { 2364 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2365 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2366 // for shaders. Vector types should be explicitly handled by CC. 2367 if (AMDGPU::isEntryFunctionCC(CallConv)) 2368 return true; 2369 2370 SmallVector<CCValAssign, 16> RVLocs; 2371 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2372 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2373 } 2374 2375 SDValue 2376 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2377 bool isVarArg, 2378 const SmallVectorImpl<ISD::OutputArg> &Outs, 2379 const SmallVectorImpl<SDValue> &OutVals, 2380 const SDLoc &DL, SelectionDAG &DAG) const { 2381 MachineFunction &MF = DAG.getMachineFunction(); 2382 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2383 2384 if (AMDGPU::isKernel(CallConv)) { 2385 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2386 OutVals, DL, DAG); 2387 } 2388 2389 bool IsShader = AMDGPU::isShader(CallConv); 2390 2391 Info->setIfReturnsVoid(Outs.empty()); 2392 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2393 2394 // CCValAssign - represent the assignment of the return value to a location. 2395 SmallVector<CCValAssign, 48> RVLocs; 2396 SmallVector<ISD::OutputArg, 48> Splits; 2397 2398 // CCState - Info about the registers and stack slots. 2399 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2400 *DAG.getContext()); 2401 2402 // Analyze outgoing return values. 2403 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2404 2405 SDValue Flag; 2406 SmallVector<SDValue, 48> RetOps; 2407 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2408 2409 // Add return address for callable functions. 2410 if (!Info->isEntryFunction()) { 2411 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2412 SDValue ReturnAddrReg = CreateLiveInRegister( 2413 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2414 2415 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2416 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2417 MVT::i64); 2418 Chain = 2419 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2420 Flag = Chain.getValue(1); 2421 RetOps.push_back(ReturnAddrVirtualReg); 2422 } 2423 2424 // Copy the result values into the output registers. 2425 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2426 ++I, ++RealRVLocIdx) { 2427 CCValAssign &VA = RVLocs[I]; 2428 assert(VA.isRegLoc() && "Can only return in registers!"); 2429 // TODO: Partially return in registers if return values don't fit. 2430 SDValue Arg = OutVals[RealRVLocIdx]; 2431 2432 // Copied from other backends. 2433 switch (VA.getLocInfo()) { 2434 case CCValAssign::Full: 2435 break; 2436 case CCValAssign::BCvt: 2437 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2438 break; 2439 case CCValAssign::SExt: 2440 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2441 break; 2442 case CCValAssign::ZExt: 2443 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2444 break; 2445 case CCValAssign::AExt: 2446 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2447 break; 2448 default: 2449 llvm_unreachable("Unknown loc info!"); 2450 } 2451 2452 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2453 Flag = Chain.getValue(1); 2454 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2455 } 2456 2457 // FIXME: Does sret work properly? 2458 if (!Info->isEntryFunction()) { 2459 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2460 const MCPhysReg *I = 2461 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2462 if (I) { 2463 for (; *I; ++I) { 2464 if (AMDGPU::SReg_64RegClass.contains(*I)) 2465 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2466 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2467 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2468 else 2469 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2470 } 2471 } 2472 } 2473 2474 // Update chain and glue. 2475 RetOps[0] = Chain; 2476 if (Flag.getNode()) 2477 RetOps.push_back(Flag); 2478 2479 unsigned Opc = AMDGPUISD::ENDPGM; 2480 if (!IsWaveEnd) 2481 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2482 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2483 } 2484 2485 SDValue SITargetLowering::LowerCallResult( 2486 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2487 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2488 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2489 SDValue ThisVal) const { 2490 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2491 2492 // Assign locations to each value returned by this call. 2493 SmallVector<CCValAssign, 16> RVLocs; 2494 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2495 *DAG.getContext()); 2496 CCInfo.AnalyzeCallResult(Ins, RetCC); 2497 2498 // Copy all of the result registers out of their specified physreg. 2499 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2500 CCValAssign VA = RVLocs[i]; 2501 SDValue Val; 2502 2503 if (VA.isRegLoc()) { 2504 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2505 Chain = Val.getValue(1); 2506 InFlag = Val.getValue(2); 2507 } else if (VA.isMemLoc()) { 2508 report_fatal_error("TODO: return values in memory"); 2509 } else 2510 llvm_unreachable("unknown argument location type"); 2511 2512 switch (VA.getLocInfo()) { 2513 case CCValAssign::Full: 2514 break; 2515 case CCValAssign::BCvt: 2516 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2517 break; 2518 case CCValAssign::ZExt: 2519 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2520 DAG.getValueType(VA.getValVT())); 2521 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2522 break; 2523 case CCValAssign::SExt: 2524 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2525 DAG.getValueType(VA.getValVT())); 2526 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2527 break; 2528 case CCValAssign::AExt: 2529 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2530 break; 2531 default: 2532 llvm_unreachable("Unknown loc info!"); 2533 } 2534 2535 InVals.push_back(Val); 2536 } 2537 2538 return Chain; 2539 } 2540 2541 // Add code to pass special inputs required depending on used features separate 2542 // from the explicit user arguments present in the IR. 2543 void SITargetLowering::passSpecialInputs( 2544 CallLoweringInfo &CLI, 2545 CCState &CCInfo, 2546 const SIMachineFunctionInfo &Info, 2547 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2548 SmallVectorImpl<SDValue> &MemOpChains, 2549 SDValue Chain) const { 2550 // If we don't have a call site, this was a call inserted by 2551 // legalization. These can never use special inputs. 2552 if (!CLI.CB) 2553 return; 2554 2555 SelectionDAG &DAG = CLI.DAG; 2556 const SDLoc &DL = CLI.DL; 2557 2558 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2559 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2560 2561 const AMDGPUFunctionArgInfo *CalleeArgInfo 2562 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2563 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2564 auto &ArgUsageInfo = 2565 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2566 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2567 } 2568 2569 // TODO: Unify with private memory register handling. This is complicated by 2570 // the fact that at least in kernels, the input argument is not necessarily 2571 // in the same location as the input. 2572 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2573 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2574 AMDGPUFunctionArgInfo::QUEUE_PTR, 2575 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2576 AMDGPUFunctionArgInfo::DISPATCH_ID, 2577 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2578 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2579 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2580 }; 2581 2582 for (auto InputID : InputRegs) { 2583 const ArgDescriptor *OutgoingArg; 2584 const TargetRegisterClass *ArgRC; 2585 LLT ArgTy; 2586 2587 std::tie(OutgoingArg, ArgRC, ArgTy) = 2588 CalleeArgInfo->getPreloadedValue(InputID); 2589 if (!OutgoingArg) 2590 continue; 2591 2592 const ArgDescriptor *IncomingArg; 2593 const TargetRegisterClass *IncomingArgRC; 2594 LLT Ty; 2595 std::tie(IncomingArg, IncomingArgRC, Ty) = 2596 CallerArgInfo.getPreloadedValue(InputID); 2597 assert(IncomingArgRC == ArgRC); 2598 2599 // All special arguments are ints for now. 2600 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2601 SDValue InputReg; 2602 2603 if (IncomingArg) { 2604 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2605 } else { 2606 // The implicit arg ptr is special because it doesn't have a corresponding 2607 // input for kernels, and is computed from the kernarg segment pointer. 2608 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2609 InputReg = getImplicitArgPtr(DAG, DL); 2610 } 2611 2612 if (OutgoingArg->isRegister()) { 2613 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2614 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2615 report_fatal_error("failed to allocate implicit input argument"); 2616 } else { 2617 unsigned SpecialArgOffset = 2618 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2619 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2620 SpecialArgOffset); 2621 MemOpChains.push_back(ArgStore); 2622 } 2623 } 2624 2625 // Pack workitem IDs into a single register or pass it as is if already 2626 // packed. 2627 const ArgDescriptor *OutgoingArg; 2628 const TargetRegisterClass *ArgRC; 2629 LLT Ty; 2630 2631 std::tie(OutgoingArg, ArgRC, Ty) = 2632 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2633 if (!OutgoingArg) 2634 std::tie(OutgoingArg, ArgRC, Ty) = 2635 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2636 if (!OutgoingArg) 2637 std::tie(OutgoingArg, ArgRC, Ty) = 2638 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2639 if (!OutgoingArg) 2640 return; 2641 2642 const ArgDescriptor *IncomingArgX = std::get<0>( 2643 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2644 const ArgDescriptor *IncomingArgY = std::get<0>( 2645 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2646 const ArgDescriptor *IncomingArgZ = std::get<0>( 2647 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2648 2649 SDValue InputReg; 2650 SDLoc SL; 2651 2652 // If incoming ids are not packed we need to pack them. 2653 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2654 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2655 2656 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2657 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2658 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2659 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2660 InputReg = InputReg.getNode() ? 2661 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2662 } 2663 2664 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2665 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2666 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2667 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2668 InputReg = InputReg.getNode() ? 2669 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2670 } 2671 2672 if (!InputReg.getNode()) { 2673 // Workitem ids are already packed, any of present incoming arguments 2674 // will carry all required fields. 2675 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2676 IncomingArgX ? *IncomingArgX : 2677 IncomingArgY ? *IncomingArgY : 2678 *IncomingArgZ, ~0u); 2679 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2680 } 2681 2682 if (OutgoingArg->isRegister()) { 2683 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2684 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2685 } else { 2686 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2687 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2688 SpecialArgOffset); 2689 MemOpChains.push_back(ArgStore); 2690 } 2691 } 2692 2693 static bool canGuaranteeTCO(CallingConv::ID CC) { 2694 return CC == CallingConv::Fast; 2695 } 2696 2697 /// Return true if we might ever do TCO for calls with this calling convention. 2698 static bool mayTailCallThisCC(CallingConv::ID CC) { 2699 switch (CC) { 2700 case CallingConv::C: 2701 return true; 2702 default: 2703 return canGuaranteeTCO(CC); 2704 } 2705 } 2706 2707 bool SITargetLowering::isEligibleForTailCallOptimization( 2708 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2709 const SmallVectorImpl<ISD::OutputArg> &Outs, 2710 const SmallVectorImpl<SDValue> &OutVals, 2711 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2712 if (!mayTailCallThisCC(CalleeCC)) 2713 return false; 2714 2715 MachineFunction &MF = DAG.getMachineFunction(); 2716 const Function &CallerF = MF.getFunction(); 2717 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2718 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2719 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2720 2721 // Kernels aren't callable, and don't have a live in return address so it 2722 // doesn't make sense to do a tail call with entry functions. 2723 if (!CallerPreserved) 2724 return false; 2725 2726 bool CCMatch = CallerCC == CalleeCC; 2727 2728 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2729 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2730 return true; 2731 return false; 2732 } 2733 2734 // TODO: Can we handle var args? 2735 if (IsVarArg) 2736 return false; 2737 2738 for (const Argument &Arg : CallerF.args()) { 2739 if (Arg.hasByValAttr()) 2740 return false; 2741 } 2742 2743 LLVMContext &Ctx = *DAG.getContext(); 2744 2745 // Check that the call results are passed in the same way. 2746 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2747 CCAssignFnForCall(CalleeCC, IsVarArg), 2748 CCAssignFnForCall(CallerCC, IsVarArg))) 2749 return false; 2750 2751 // The callee has to preserve all registers the caller needs to preserve. 2752 if (!CCMatch) { 2753 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2754 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2755 return false; 2756 } 2757 2758 // Nothing more to check if the callee is taking no arguments. 2759 if (Outs.empty()) 2760 return true; 2761 2762 SmallVector<CCValAssign, 16> ArgLocs; 2763 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2764 2765 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2766 2767 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2768 // If the stack arguments for this call do not fit into our own save area then 2769 // the call cannot be made tail. 2770 // TODO: Is this really necessary? 2771 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2772 return false; 2773 2774 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2775 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2776 } 2777 2778 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2779 if (!CI->isTailCall()) 2780 return false; 2781 2782 const Function *ParentFn = CI->getParent()->getParent(); 2783 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2784 return false; 2785 return true; 2786 } 2787 2788 // The wave scratch offset register is used as the global base pointer. 2789 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2790 SmallVectorImpl<SDValue> &InVals) const { 2791 SelectionDAG &DAG = CLI.DAG; 2792 const SDLoc &DL = CLI.DL; 2793 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2794 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2795 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2796 SDValue Chain = CLI.Chain; 2797 SDValue Callee = CLI.Callee; 2798 bool &IsTailCall = CLI.IsTailCall; 2799 CallingConv::ID CallConv = CLI.CallConv; 2800 bool IsVarArg = CLI.IsVarArg; 2801 bool IsSibCall = false; 2802 bool IsThisReturn = false; 2803 MachineFunction &MF = DAG.getMachineFunction(); 2804 2805 if (Callee.isUndef() || isNullConstant(Callee)) { 2806 if (!CLI.IsTailCall) { 2807 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2808 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2809 } 2810 2811 return Chain; 2812 } 2813 2814 if (IsVarArg) { 2815 return lowerUnhandledCall(CLI, InVals, 2816 "unsupported call to variadic function "); 2817 } 2818 2819 if (!CLI.CB) 2820 report_fatal_error("unsupported libcall legalization"); 2821 2822 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2823 !CLI.CB->getCalledFunction()) { 2824 return lowerUnhandledCall(CLI, InVals, 2825 "unsupported indirect call to function "); 2826 } 2827 2828 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2829 return lowerUnhandledCall(CLI, InVals, 2830 "unsupported required tail call to function "); 2831 } 2832 2833 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2834 // Note the issue is with the CC of the calling function, not of the call 2835 // itself. 2836 return lowerUnhandledCall(CLI, InVals, 2837 "unsupported call from graphics shader of function "); 2838 } 2839 2840 if (IsTailCall) { 2841 IsTailCall = isEligibleForTailCallOptimization( 2842 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2843 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2844 report_fatal_error("failed to perform tail call elimination on a call " 2845 "site marked musttail"); 2846 } 2847 2848 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2849 2850 // A sibling call is one where we're under the usual C ABI and not planning 2851 // to change that but can still do a tail call: 2852 if (!TailCallOpt && IsTailCall) 2853 IsSibCall = true; 2854 2855 if (IsTailCall) 2856 ++NumTailCalls; 2857 } 2858 2859 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2860 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2861 SmallVector<SDValue, 8> MemOpChains; 2862 2863 // Analyze operands of the call, assigning locations to each operand. 2864 SmallVector<CCValAssign, 16> ArgLocs; 2865 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2866 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2867 2868 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2869 // With a fixed ABI, allocate fixed registers before user arguments. 2870 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2871 } 2872 2873 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2874 2875 // Get a count of how many bytes are to be pushed on the stack. 2876 unsigned NumBytes = CCInfo.getNextStackOffset(); 2877 2878 if (IsSibCall) { 2879 // Since we're not changing the ABI to make this a tail call, the memory 2880 // operands are already available in the caller's incoming argument space. 2881 NumBytes = 0; 2882 } 2883 2884 // FPDiff is the byte offset of the call's argument area from the callee's. 2885 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2886 // by this amount for a tail call. In a sibling call it must be 0 because the 2887 // caller will deallocate the entire stack and the callee still expects its 2888 // arguments to begin at SP+0. Completely unused for non-tail calls. 2889 int32_t FPDiff = 0; 2890 MachineFrameInfo &MFI = MF.getFrameInfo(); 2891 2892 // Adjust the stack pointer for the new arguments... 2893 // These operations are automatically eliminated by the prolog/epilog pass 2894 if (!IsSibCall) { 2895 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2896 2897 SmallVector<SDValue, 4> CopyFromChains; 2898 2899 // In the HSA case, this should be an identity copy. 2900 SDValue ScratchRSrcReg 2901 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2902 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2903 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2904 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2905 } 2906 2907 MVT PtrVT = MVT::i32; 2908 2909 // Walk the register/memloc assignments, inserting copies/loads. 2910 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2911 CCValAssign &VA = ArgLocs[i]; 2912 SDValue Arg = OutVals[i]; 2913 2914 // Promote the value if needed. 2915 switch (VA.getLocInfo()) { 2916 case CCValAssign::Full: 2917 break; 2918 case CCValAssign::BCvt: 2919 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2920 break; 2921 case CCValAssign::ZExt: 2922 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2923 break; 2924 case CCValAssign::SExt: 2925 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2926 break; 2927 case CCValAssign::AExt: 2928 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2929 break; 2930 case CCValAssign::FPExt: 2931 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2932 break; 2933 default: 2934 llvm_unreachable("Unknown loc info!"); 2935 } 2936 2937 if (VA.isRegLoc()) { 2938 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2939 } else { 2940 assert(VA.isMemLoc()); 2941 2942 SDValue DstAddr; 2943 MachinePointerInfo DstInfo; 2944 2945 unsigned LocMemOffset = VA.getLocMemOffset(); 2946 int32_t Offset = LocMemOffset; 2947 2948 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2949 MaybeAlign Alignment; 2950 2951 if (IsTailCall) { 2952 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2953 unsigned OpSize = Flags.isByVal() ? 2954 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2955 2956 // FIXME: We can have better than the minimum byval required alignment. 2957 Alignment = 2958 Flags.isByVal() 2959 ? Flags.getNonZeroByValAlign() 2960 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2961 2962 Offset = Offset + FPDiff; 2963 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2964 2965 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2966 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2967 2968 // Make sure any stack arguments overlapping with where we're storing 2969 // are loaded before this eventual operation. Otherwise they'll be 2970 // clobbered. 2971 2972 // FIXME: Why is this really necessary? This seems to just result in a 2973 // lot of code to copy the stack and write them back to the same 2974 // locations, which are supposed to be immutable? 2975 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2976 } else { 2977 DstAddr = PtrOff; 2978 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2979 Alignment = 2980 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2981 } 2982 2983 if (Outs[i].Flags.isByVal()) { 2984 SDValue SizeNode = 2985 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2986 SDValue Cpy = 2987 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2988 Outs[i].Flags.getNonZeroByValAlign(), 2989 /*isVol = */ false, /*AlwaysInline = */ true, 2990 /*isTailCall = */ false, DstInfo, 2991 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2992 2993 MemOpChains.push_back(Cpy); 2994 } else { 2995 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2996 Alignment ? Alignment->value() : 0); 2997 MemOpChains.push_back(Store); 2998 } 2999 } 3000 } 3001 3002 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3003 // Copy special input registers after user input arguments. 3004 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3005 } 3006 3007 if (!MemOpChains.empty()) 3008 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3009 3010 // Build a sequence of copy-to-reg nodes chained together with token chain 3011 // and flag operands which copy the outgoing args into the appropriate regs. 3012 SDValue InFlag; 3013 for (auto &RegToPass : RegsToPass) { 3014 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3015 RegToPass.second, InFlag); 3016 InFlag = Chain.getValue(1); 3017 } 3018 3019 3020 SDValue PhysReturnAddrReg; 3021 if (IsTailCall) { 3022 // Since the return is being combined with the call, we need to pass on the 3023 // return address. 3024 3025 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3026 SDValue ReturnAddrReg = CreateLiveInRegister( 3027 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3028 3029 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3030 MVT::i64); 3031 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3032 InFlag = Chain.getValue(1); 3033 } 3034 3035 // We don't usually want to end the call-sequence here because we would tidy 3036 // the frame up *after* the call, however in the ABI-changing tail-call case 3037 // we've carefully laid out the parameters so that when sp is reset they'll be 3038 // in the correct location. 3039 if (IsTailCall && !IsSibCall) { 3040 Chain = DAG.getCALLSEQ_END(Chain, 3041 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3042 DAG.getTargetConstant(0, DL, MVT::i32), 3043 InFlag, DL); 3044 InFlag = Chain.getValue(1); 3045 } 3046 3047 std::vector<SDValue> Ops; 3048 Ops.push_back(Chain); 3049 Ops.push_back(Callee); 3050 // Add a redundant copy of the callee global which will not be legalized, as 3051 // we need direct access to the callee later. 3052 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3053 const GlobalValue *GV = GSD->getGlobal(); 3054 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3055 } else { 3056 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3057 } 3058 3059 if (IsTailCall) { 3060 // Each tail call may have to adjust the stack by a different amount, so 3061 // this information must travel along with the operation for eventual 3062 // consumption by emitEpilogue. 3063 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3064 3065 Ops.push_back(PhysReturnAddrReg); 3066 } 3067 3068 // Add argument registers to the end of the list so that they are known live 3069 // into the call. 3070 for (auto &RegToPass : RegsToPass) { 3071 Ops.push_back(DAG.getRegister(RegToPass.first, 3072 RegToPass.second.getValueType())); 3073 } 3074 3075 // Add a register mask operand representing the call-preserved registers. 3076 3077 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3078 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3079 assert(Mask && "Missing call preserved mask for calling convention"); 3080 Ops.push_back(DAG.getRegisterMask(Mask)); 3081 3082 if (InFlag.getNode()) 3083 Ops.push_back(InFlag); 3084 3085 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3086 3087 // If we're doing a tall call, use a TC_RETURN here rather than an 3088 // actual call instruction. 3089 if (IsTailCall) { 3090 MFI.setHasTailCall(); 3091 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3092 } 3093 3094 // Returns a chain and a flag for retval copy to use. 3095 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3096 Chain = Call.getValue(0); 3097 InFlag = Call.getValue(1); 3098 3099 uint64_t CalleePopBytes = NumBytes; 3100 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3101 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3102 InFlag, DL); 3103 if (!Ins.empty()) 3104 InFlag = Chain.getValue(1); 3105 3106 // Handle result values, copying them out of physregs into vregs that we 3107 // return. 3108 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3109 InVals, IsThisReturn, 3110 IsThisReturn ? OutVals[0] : SDValue()); 3111 } 3112 3113 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3114 // except for applying the wave size scale to the increment amount. 3115 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3116 SDValue Op, SelectionDAG &DAG) const { 3117 const MachineFunction &MF = DAG.getMachineFunction(); 3118 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3119 3120 SDLoc dl(Op); 3121 EVT VT = Op.getValueType(); 3122 SDValue Tmp1 = Op; 3123 SDValue Tmp2 = Op.getValue(1); 3124 SDValue Tmp3 = Op.getOperand(2); 3125 SDValue Chain = Tmp1.getOperand(0); 3126 3127 Register SPReg = Info->getStackPtrOffsetReg(); 3128 3129 // Chain the dynamic stack allocation so that it doesn't modify the stack 3130 // pointer when other instructions are using the stack. 3131 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3132 3133 SDValue Size = Tmp2.getOperand(1); 3134 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3135 Chain = SP.getValue(1); 3136 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3137 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3138 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3139 unsigned Opc = 3140 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3141 ISD::ADD : ISD::SUB; 3142 3143 SDValue ScaledSize = DAG.getNode( 3144 ISD::SHL, dl, VT, Size, 3145 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3146 3147 Align StackAlign = TFL->getStackAlign(); 3148 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3149 if (Alignment && *Alignment > StackAlign) { 3150 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3151 DAG.getConstant(-(uint64_t)Alignment->value() 3152 << ST.getWavefrontSizeLog2(), 3153 dl, VT)); 3154 } 3155 3156 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3157 Tmp2 = DAG.getCALLSEQ_END( 3158 Chain, DAG.getIntPtrConstant(0, dl, true), 3159 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3160 3161 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3162 } 3163 3164 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3165 SelectionDAG &DAG) const { 3166 // We only handle constant sizes here to allow non-entry block, static sized 3167 // allocas. A truly dynamic value is more difficult to support because we 3168 // don't know if the size value is uniform or not. If the size isn't uniform, 3169 // we would need to do a wave reduction to get the maximum size to know how 3170 // much to increment the uniform stack pointer. 3171 SDValue Size = Op.getOperand(1); 3172 if (isa<ConstantSDNode>(Size)) 3173 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3174 3175 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3176 } 3177 3178 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3179 const MachineFunction &MF) const { 3180 Register Reg = StringSwitch<Register>(RegName) 3181 .Case("m0", AMDGPU::M0) 3182 .Case("exec", AMDGPU::EXEC) 3183 .Case("exec_lo", AMDGPU::EXEC_LO) 3184 .Case("exec_hi", AMDGPU::EXEC_HI) 3185 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3186 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3187 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3188 .Default(Register()); 3189 3190 if (Reg == AMDGPU::NoRegister) { 3191 report_fatal_error(Twine("invalid register name \"" 3192 + StringRef(RegName) + "\".")); 3193 3194 } 3195 3196 if (!Subtarget->hasFlatScrRegister() && 3197 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3198 report_fatal_error(Twine("invalid register \"" 3199 + StringRef(RegName) + "\" for subtarget.")); 3200 } 3201 3202 switch (Reg) { 3203 case AMDGPU::M0: 3204 case AMDGPU::EXEC_LO: 3205 case AMDGPU::EXEC_HI: 3206 case AMDGPU::FLAT_SCR_LO: 3207 case AMDGPU::FLAT_SCR_HI: 3208 if (VT.getSizeInBits() == 32) 3209 return Reg; 3210 break; 3211 case AMDGPU::EXEC: 3212 case AMDGPU::FLAT_SCR: 3213 if (VT.getSizeInBits() == 64) 3214 return Reg; 3215 break; 3216 default: 3217 llvm_unreachable("missing register type checking"); 3218 } 3219 3220 report_fatal_error(Twine("invalid type for register \"" 3221 + StringRef(RegName) + "\".")); 3222 } 3223 3224 // If kill is not the last instruction, split the block so kill is always a 3225 // proper terminator. 3226 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3227 MachineBasicBlock *BB) const { 3228 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3229 3230 MachineBasicBlock::iterator SplitPoint(&MI); 3231 ++SplitPoint; 3232 3233 if (SplitPoint == BB->end()) { 3234 // Don't bother with a new block. 3235 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3236 return BB; 3237 } 3238 3239 MachineFunction *MF = BB->getParent(); 3240 MachineBasicBlock *SplitBB 3241 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3242 3243 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3244 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3245 3246 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3247 BB->addSuccessor(SplitBB); 3248 3249 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3250 return SplitBB; 3251 } 3252 3253 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3254 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3255 // be the first instruction in the remainder block. 3256 // 3257 /// \returns { LoopBody, Remainder } 3258 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3259 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3260 MachineFunction *MF = MBB.getParent(); 3261 MachineBasicBlock::iterator I(&MI); 3262 3263 // To insert the loop we need to split the block. Move everything after this 3264 // point to a new block, and insert a new empty block between the two. 3265 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3266 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3267 MachineFunction::iterator MBBI(MBB); 3268 ++MBBI; 3269 3270 MF->insert(MBBI, LoopBB); 3271 MF->insert(MBBI, RemainderBB); 3272 3273 LoopBB->addSuccessor(LoopBB); 3274 LoopBB->addSuccessor(RemainderBB); 3275 3276 // Move the rest of the block into a new block. 3277 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3278 3279 if (InstInLoop) { 3280 auto Next = std::next(I); 3281 3282 // Move instruction to loop body. 3283 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3284 3285 // Move the rest of the block. 3286 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3287 } else { 3288 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3289 } 3290 3291 MBB.addSuccessor(LoopBB); 3292 3293 return std::make_pair(LoopBB, RemainderBB); 3294 } 3295 3296 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3297 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3298 MachineBasicBlock *MBB = MI.getParent(); 3299 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3300 auto I = MI.getIterator(); 3301 auto E = std::next(I); 3302 3303 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3304 .addImm(0); 3305 3306 MIBundleBuilder Bundler(*MBB, I, E); 3307 finalizeBundle(*MBB, Bundler.begin()); 3308 } 3309 3310 MachineBasicBlock * 3311 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3312 MachineBasicBlock *BB) const { 3313 const DebugLoc &DL = MI.getDebugLoc(); 3314 3315 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3316 3317 MachineBasicBlock *LoopBB; 3318 MachineBasicBlock *RemainderBB; 3319 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3320 3321 // Apparently kill flags are only valid if the def is in the same block? 3322 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3323 Src->setIsKill(false); 3324 3325 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3326 3327 MachineBasicBlock::iterator I = LoopBB->end(); 3328 3329 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3330 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3331 3332 // Clear TRAP_STS.MEM_VIOL 3333 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3334 .addImm(0) 3335 .addImm(EncodedReg); 3336 3337 bundleInstWithWaitcnt(MI); 3338 3339 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3340 3341 // Load and check TRAP_STS.MEM_VIOL 3342 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3343 .addImm(EncodedReg); 3344 3345 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3346 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3347 .addReg(Reg, RegState::Kill) 3348 .addImm(0); 3349 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3350 .addMBB(LoopBB); 3351 3352 return RemainderBB; 3353 } 3354 3355 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3356 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3357 // will only do one iteration. In the worst case, this will loop 64 times. 3358 // 3359 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3360 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3361 const SIInstrInfo *TII, 3362 MachineRegisterInfo &MRI, 3363 MachineBasicBlock &OrigBB, 3364 MachineBasicBlock &LoopBB, 3365 const DebugLoc &DL, 3366 const MachineOperand &IdxReg, 3367 unsigned InitReg, 3368 unsigned ResultReg, 3369 unsigned PhiReg, 3370 unsigned InitSaveExecReg, 3371 int Offset, 3372 bool UseGPRIdxMode, 3373 bool IsIndirectSrc) { 3374 MachineFunction *MF = OrigBB.getParent(); 3375 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3376 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3377 MachineBasicBlock::iterator I = LoopBB.begin(); 3378 3379 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3380 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3381 Register NewExec = MRI.createVirtualRegister(BoolRC); 3382 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3383 Register CondReg = MRI.createVirtualRegister(BoolRC); 3384 3385 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3386 .addReg(InitReg) 3387 .addMBB(&OrigBB) 3388 .addReg(ResultReg) 3389 .addMBB(&LoopBB); 3390 3391 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3392 .addReg(InitSaveExecReg) 3393 .addMBB(&OrigBB) 3394 .addReg(NewExec) 3395 .addMBB(&LoopBB); 3396 3397 // Read the next variant <- also loop target. 3398 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3399 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3400 3401 // Compare the just read M0 value to all possible Idx values. 3402 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3403 .addReg(CurrentIdxReg) 3404 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3405 3406 // Update EXEC, save the original EXEC value to VCC. 3407 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3408 : AMDGPU::S_AND_SAVEEXEC_B64), 3409 NewExec) 3410 .addReg(CondReg, RegState::Kill); 3411 3412 MRI.setSimpleHint(NewExec, CondReg); 3413 3414 if (UseGPRIdxMode) { 3415 unsigned IdxReg; 3416 if (Offset == 0) { 3417 IdxReg = CurrentIdxReg; 3418 } else { 3419 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3420 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3421 .addReg(CurrentIdxReg, RegState::Kill) 3422 .addImm(Offset); 3423 } 3424 unsigned IdxMode = IsIndirectSrc ? 3425 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3426 MachineInstr *SetOn = 3427 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3428 .addReg(IdxReg, RegState::Kill) 3429 .addImm(IdxMode); 3430 SetOn->getOperand(3).setIsUndef(); 3431 } else { 3432 // Move index from VCC into M0 3433 if (Offset == 0) { 3434 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3435 .addReg(CurrentIdxReg, RegState::Kill); 3436 } else { 3437 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3438 .addReg(CurrentIdxReg, RegState::Kill) 3439 .addImm(Offset); 3440 } 3441 } 3442 3443 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3444 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3445 MachineInstr *InsertPt = 3446 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3447 : AMDGPU::S_XOR_B64_term), Exec) 3448 .addReg(Exec) 3449 .addReg(NewExec); 3450 3451 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3452 // s_cbranch_scc0? 3453 3454 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3455 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3456 .addMBB(&LoopBB); 3457 3458 return InsertPt->getIterator(); 3459 } 3460 3461 // This has slightly sub-optimal regalloc when the source vector is killed by 3462 // the read. The register allocator does not understand that the kill is 3463 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3464 // subregister from it, using 1 more VGPR than necessary. This was saved when 3465 // this was expanded after register allocation. 3466 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3467 MachineBasicBlock &MBB, 3468 MachineInstr &MI, 3469 unsigned InitResultReg, 3470 unsigned PhiReg, 3471 int Offset, 3472 bool UseGPRIdxMode, 3473 bool IsIndirectSrc) { 3474 MachineFunction *MF = MBB.getParent(); 3475 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3476 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3477 MachineRegisterInfo &MRI = MF->getRegInfo(); 3478 const DebugLoc &DL = MI.getDebugLoc(); 3479 MachineBasicBlock::iterator I(&MI); 3480 3481 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3482 Register DstReg = MI.getOperand(0).getReg(); 3483 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3484 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3485 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3486 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3487 3488 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3489 3490 // Save the EXEC mask 3491 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3492 .addReg(Exec); 3493 3494 MachineBasicBlock *LoopBB; 3495 MachineBasicBlock *RemainderBB; 3496 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3497 3498 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3499 3500 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3501 InitResultReg, DstReg, PhiReg, TmpExec, 3502 Offset, UseGPRIdxMode, IsIndirectSrc); 3503 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3504 MachineFunction::iterator MBBI(LoopBB); 3505 ++MBBI; 3506 MF->insert(MBBI, LandingPad); 3507 LoopBB->removeSuccessor(RemainderBB); 3508 LandingPad->addSuccessor(RemainderBB); 3509 LoopBB->addSuccessor(LandingPad); 3510 MachineBasicBlock::iterator First = LandingPad->begin(); 3511 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3512 .addReg(SaveExec); 3513 3514 return InsPt; 3515 } 3516 3517 // Returns subreg index, offset 3518 static std::pair<unsigned, int> 3519 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3520 const TargetRegisterClass *SuperRC, 3521 unsigned VecReg, 3522 int Offset) { 3523 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3524 3525 // Skip out of bounds offsets, or else we would end up using an undefined 3526 // register. 3527 if (Offset >= NumElts || Offset < 0) 3528 return std::make_pair(AMDGPU::sub0, Offset); 3529 3530 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3531 } 3532 3533 // Return true if the index is an SGPR and was set. 3534 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3535 MachineRegisterInfo &MRI, 3536 MachineInstr &MI, 3537 int Offset, 3538 bool UseGPRIdxMode, 3539 bool IsIndirectSrc) { 3540 MachineBasicBlock *MBB = MI.getParent(); 3541 const DebugLoc &DL = MI.getDebugLoc(); 3542 MachineBasicBlock::iterator I(&MI); 3543 3544 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3545 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3546 3547 assert(Idx->getReg() != AMDGPU::NoRegister); 3548 3549 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3550 return false; 3551 3552 if (UseGPRIdxMode) { 3553 unsigned IdxMode = IsIndirectSrc ? 3554 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3555 if (Offset == 0) { 3556 MachineInstr *SetOn = 3557 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3558 .add(*Idx) 3559 .addImm(IdxMode); 3560 3561 SetOn->getOperand(3).setIsUndef(); 3562 } else { 3563 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3564 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3565 .add(*Idx) 3566 .addImm(Offset); 3567 MachineInstr *SetOn = 3568 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3569 .addReg(Tmp, RegState::Kill) 3570 .addImm(IdxMode); 3571 3572 SetOn->getOperand(3).setIsUndef(); 3573 } 3574 3575 return true; 3576 } 3577 3578 if (Offset == 0) { 3579 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3580 .add(*Idx); 3581 } else { 3582 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3583 .add(*Idx) 3584 .addImm(Offset); 3585 } 3586 3587 return true; 3588 } 3589 3590 // Control flow needs to be inserted if indexing with a VGPR. 3591 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3592 MachineBasicBlock &MBB, 3593 const GCNSubtarget &ST) { 3594 const SIInstrInfo *TII = ST.getInstrInfo(); 3595 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3596 MachineFunction *MF = MBB.getParent(); 3597 MachineRegisterInfo &MRI = MF->getRegInfo(); 3598 3599 Register Dst = MI.getOperand(0).getReg(); 3600 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3601 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3602 3603 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3604 3605 unsigned SubReg; 3606 std::tie(SubReg, Offset) 3607 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3608 3609 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3610 3611 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3612 MachineBasicBlock::iterator I(&MI); 3613 const DebugLoc &DL = MI.getDebugLoc(); 3614 3615 if (UseGPRIdxMode) { 3616 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3617 // to avoid interfering with other uses, so probably requires a new 3618 // optimization pass. 3619 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3620 .addReg(SrcReg, RegState::Undef, SubReg) 3621 .addReg(SrcReg, RegState::Implicit) 3622 .addReg(AMDGPU::M0, RegState::Implicit); 3623 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3624 } else { 3625 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3626 .addReg(SrcReg, RegState::Undef, SubReg) 3627 .addReg(SrcReg, RegState::Implicit); 3628 } 3629 3630 MI.eraseFromParent(); 3631 3632 return &MBB; 3633 } 3634 3635 const DebugLoc &DL = MI.getDebugLoc(); 3636 MachineBasicBlock::iterator I(&MI); 3637 3638 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3639 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3640 3641 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3642 3643 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3644 Offset, UseGPRIdxMode, true); 3645 MachineBasicBlock *LoopBB = InsPt->getParent(); 3646 3647 if (UseGPRIdxMode) { 3648 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3649 .addReg(SrcReg, RegState::Undef, SubReg) 3650 .addReg(SrcReg, RegState::Implicit) 3651 .addReg(AMDGPU::M0, RegState::Implicit); 3652 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3653 } else { 3654 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3655 .addReg(SrcReg, RegState::Undef, SubReg) 3656 .addReg(SrcReg, RegState::Implicit); 3657 } 3658 3659 MI.eraseFromParent(); 3660 3661 return LoopBB; 3662 } 3663 3664 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3665 MachineBasicBlock &MBB, 3666 const GCNSubtarget &ST) { 3667 const SIInstrInfo *TII = ST.getInstrInfo(); 3668 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3669 MachineFunction *MF = MBB.getParent(); 3670 MachineRegisterInfo &MRI = MF->getRegInfo(); 3671 3672 Register Dst = MI.getOperand(0).getReg(); 3673 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3674 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3675 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3676 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3677 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3678 3679 // This can be an immediate, but will be folded later. 3680 assert(Val->getReg()); 3681 3682 unsigned SubReg; 3683 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3684 SrcVec->getReg(), 3685 Offset); 3686 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3687 3688 if (Idx->getReg() == AMDGPU::NoRegister) { 3689 MachineBasicBlock::iterator I(&MI); 3690 const DebugLoc &DL = MI.getDebugLoc(); 3691 3692 assert(Offset == 0); 3693 3694 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3695 .add(*SrcVec) 3696 .add(*Val) 3697 .addImm(SubReg); 3698 3699 MI.eraseFromParent(); 3700 return &MBB; 3701 } 3702 3703 const MCInstrDesc &MovRelDesc 3704 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3705 3706 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3707 MachineBasicBlock::iterator I(&MI); 3708 const DebugLoc &DL = MI.getDebugLoc(); 3709 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3710 .addReg(SrcVec->getReg()) 3711 .add(*Val) 3712 .addImm(SubReg); 3713 if (UseGPRIdxMode) 3714 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3715 3716 MI.eraseFromParent(); 3717 return &MBB; 3718 } 3719 3720 if (Val->isReg()) 3721 MRI.clearKillFlags(Val->getReg()); 3722 3723 const DebugLoc &DL = MI.getDebugLoc(); 3724 3725 Register PhiReg = MRI.createVirtualRegister(VecRC); 3726 3727 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3728 Offset, UseGPRIdxMode, false); 3729 MachineBasicBlock *LoopBB = InsPt->getParent(); 3730 3731 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3732 .addReg(PhiReg) 3733 .add(*Val) 3734 .addImm(AMDGPU::sub0); 3735 if (UseGPRIdxMode) 3736 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3737 3738 MI.eraseFromParent(); 3739 return LoopBB; 3740 } 3741 3742 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3743 MachineInstr &MI, MachineBasicBlock *BB) const { 3744 3745 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3746 MachineFunction *MF = BB->getParent(); 3747 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3748 3749 switch (MI.getOpcode()) { 3750 case AMDGPU::S_UADDO_PSEUDO: 3751 case AMDGPU::S_USUBO_PSEUDO: { 3752 const DebugLoc &DL = MI.getDebugLoc(); 3753 MachineOperand &Dest0 = MI.getOperand(0); 3754 MachineOperand &Dest1 = MI.getOperand(1); 3755 MachineOperand &Src0 = MI.getOperand(2); 3756 MachineOperand &Src1 = MI.getOperand(3); 3757 3758 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3759 ? AMDGPU::S_ADD_I32 3760 : AMDGPU::S_SUB_I32; 3761 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3762 3763 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3764 .addImm(1) 3765 .addImm(0); 3766 3767 MI.eraseFromParent(); 3768 return BB; 3769 } 3770 case AMDGPU::S_ADD_U64_PSEUDO: 3771 case AMDGPU::S_SUB_U64_PSEUDO: { 3772 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3773 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3774 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3775 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3776 const DebugLoc &DL = MI.getDebugLoc(); 3777 3778 MachineOperand &Dest = MI.getOperand(0); 3779 MachineOperand &Src0 = MI.getOperand(1); 3780 MachineOperand &Src1 = MI.getOperand(2); 3781 3782 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3783 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3784 3785 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3786 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3787 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3788 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3789 3790 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3791 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3792 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3793 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3794 3795 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3796 3797 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3798 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3799 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3800 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3801 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3802 .addReg(DestSub0) 3803 .addImm(AMDGPU::sub0) 3804 .addReg(DestSub1) 3805 .addImm(AMDGPU::sub1); 3806 MI.eraseFromParent(); 3807 return BB; 3808 } 3809 case AMDGPU::V_ADD_U64_PSEUDO: 3810 case AMDGPU::V_SUB_U64_PSEUDO: { 3811 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3812 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3813 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3814 const DebugLoc &DL = MI.getDebugLoc(); 3815 3816 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3817 3818 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3819 3820 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3821 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3822 3823 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3824 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3825 3826 MachineOperand &Dest = MI.getOperand(0); 3827 MachineOperand &Src0 = MI.getOperand(1); 3828 MachineOperand &Src1 = MI.getOperand(2); 3829 3830 const TargetRegisterClass *Src0RC = Src0.isReg() 3831 ? MRI.getRegClass(Src0.getReg()) 3832 : &AMDGPU::VReg_64RegClass; 3833 const TargetRegisterClass *Src1RC = Src1.isReg() 3834 ? MRI.getRegClass(Src1.getReg()) 3835 : &AMDGPU::VReg_64RegClass; 3836 3837 const TargetRegisterClass *Src0SubRC = 3838 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3839 const TargetRegisterClass *Src1SubRC = 3840 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3841 3842 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3843 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3844 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3845 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3846 3847 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3848 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3849 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3850 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3851 3852 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3853 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3854 .addReg(CarryReg, RegState::Define) 3855 .add(SrcReg0Sub0) 3856 .add(SrcReg1Sub0) 3857 .addImm(0); // clamp bit 3858 3859 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3860 MachineInstr *HiHalf = 3861 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3862 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3863 .add(SrcReg0Sub1) 3864 .add(SrcReg1Sub1) 3865 .addReg(CarryReg, RegState::Kill) 3866 .addImm(0); // clamp bit 3867 3868 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3869 .addReg(DestSub0) 3870 .addImm(AMDGPU::sub0) 3871 .addReg(DestSub1) 3872 .addImm(AMDGPU::sub1); 3873 TII->legalizeOperands(*LoHalf); 3874 TII->legalizeOperands(*HiHalf); 3875 MI.eraseFromParent(); 3876 return BB; 3877 } 3878 case AMDGPU::S_ADD_CO_PSEUDO: 3879 case AMDGPU::S_SUB_CO_PSEUDO: { 3880 // This pseudo has a chance to be selected 3881 // only from uniform add/subcarry node. All the VGPR operands 3882 // therefore assumed to be splat vectors. 3883 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3884 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3885 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3886 MachineBasicBlock::iterator MII = MI; 3887 const DebugLoc &DL = MI.getDebugLoc(); 3888 MachineOperand &Dest = MI.getOperand(0); 3889 MachineOperand &CarryDest = MI.getOperand(1); 3890 MachineOperand &Src0 = MI.getOperand(2); 3891 MachineOperand &Src1 = MI.getOperand(3); 3892 MachineOperand &Src2 = MI.getOperand(4); 3893 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3894 ? AMDGPU::S_ADDC_U32 3895 : AMDGPU::S_SUBB_U32; 3896 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3897 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3898 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3899 .addReg(Src0.getReg()); 3900 Src0.setReg(RegOp0); 3901 } 3902 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3903 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3904 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3905 .addReg(Src1.getReg()); 3906 Src1.setReg(RegOp1); 3907 } 3908 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3909 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3910 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3911 .addReg(Src2.getReg()); 3912 Src2.setReg(RegOp2); 3913 } 3914 3915 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3916 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3917 .addReg(Src2.getReg()) 3918 .addImm(0); 3919 } else { 3920 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3921 .addReg(Src2.getReg()) 3922 .addImm(0); 3923 } 3924 3925 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3926 3927 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 3928 .addReg(AMDGPU::SCC); 3929 MI.eraseFromParent(); 3930 return BB; 3931 } 3932 case AMDGPU::SI_INIT_M0: { 3933 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3934 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3935 .add(MI.getOperand(0)); 3936 MI.eraseFromParent(); 3937 return BB; 3938 } 3939 case AMDGPU::SI_INIT_EXEC: 3940 // This should be before all vector instructions. 3941 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3942 AMDGPU::EXEC) 3943 .addImm(MI.getOperand(0).getImm()); 3944 MI.eraseFromParent(); 3945 return BB; 3946 3947 case AMDGPU::SI_INIT_EXEC_LO: 3948 // This should be before all vector instructions. 3949 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3950 AMDGPU::EXEC_LO) 3951 .addImm(MI.getOperand(0).getImm()); 3952 MI.eraseFromParent(); 3953 return BB; 3954 3955 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3956 // Extract the thread count from an SGPR input and set EXEC accordingly. 3957 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3958 // 3959 // S_BFE_U32 count, input, {shift, 7} 3960 // S_BFM_B64 exec, count, 0 3961 // S_CMP_EQ_U32 count, 64 3962 // S_CMOV_B64 exec, -1 3963 MachineInstr *FirstMI = &*BB->begin(); 3964 MachineRegisterInfo &MRI = MF->getRegInfo(); 3965 Register InputReg = MI.getOperand(0).getReg(); 3966 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3967 bool Found = false; 3968 3969 // Move the COPY of the input reg to the beginning, so that we can use it. 3970 for (auto I = BB->begin(); I != &MI; I++) { 3971 if (I->getOpcode() != TargetOpcode::COPY || 3972 I->getOperand(0).getReg() != InputReg) 3973 continue; 3974 3975 if (I == FirstMI) { 3976 FirstMI = &*++BB->begin(); 3977 } else { 3978 I->removeFromParent(); 3979 BB->insert(FirstMI, &*I); 3980 } 3981 Found = true; 3982 break; 3983 } 3984 assert(Found); 3985 (void)Found; 3986 3987 // This should be before all vector instructions. 3988 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3989 bool isWave32 = getSubtarget()->isWave32(); 3990 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3991 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3992 .addReg(InputReg) 3993 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3994 BuildMI(*BB, FirstMI, DebugLoc(), 3995 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3996 Exec) 3997 .addReg(CountReg) 3998 .addImm(0); 3999 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4000 .addReg(CountReg, RegState::Kill) 4001 .addImm(getSubtarget()->getWavefrontSize()); 4002 BuildMI(*BB, FirstMI, DebugLoc(), 4003 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4004 Exec) 4005 .addImm(-1); 4006 MI.eraseFromParent(); 4007 return BB; 4008 } 4009 4010 case AMDGPU::GET_GROUPSTATICSIZE: { 4011 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4012 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4013 DebugLoc DL = MI.getDebugLoc(); 4014 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4015 .add(MI.getOperand(0)) 4016 .addImm(MFI->getLDSSize()); 4017 MI.eraseFromParent(); 4018 return BB; 4019 } 4020 case AMDGPU::SI_INDIRECT_SRC_V1: 4021 case AMDGPU::SI_INDIRECT_SRC_V2: 4022 case AMDGPU::SI_INDIRECT_SRC_V4: 4023 case AMDGPU::SI_INDIRECT_SRC_V8: 4024 case AMDGPU::SI_INDIRECT_SRC_V16: 4025 case AMDGPU::SI_INDIRECT_SRC_V32: 4026 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4027 case AMDGPU::SI_INDIRECT_DST_V1: 4028 case AMDGPU::SI_INDIRECT_DST_V2: 4029 case AMDGPU::SI_INDIRECT_DST_V4: 4030 case AMDGPU::SI_INDIRECT_DST_V8: 4031 case AMDGPU::SI_INDIRECT_DST_V16: 4032 case AMDGPU::SI_INDIRECT_DST_V32: 4033 return emitIndirectDst(MI, *BB, *getSubtarget()); 4034 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4035 case AMDGPU::SI_KILL_I1_PSEUDO: 4036 return splitKillBlock(MI, BB); 4037 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4038 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4039 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4040 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4041 4042 Register Dst = MI.getOperand(0).getReg(); 4043 Register Src0 = MI.getOperand(1).getReg(); 4044 Register Src1 = MI.getOperand(2).getReg(); 4045 const DebugLoc &DL = MI.getDebugLoc(); 4046 Register SrcCond = MI.getOperand(3).getReg(); 4047 4048 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4049 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4050 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4051 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4052 4053 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4054 .addReg(SrcCond); 4055 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4056 .addImm(0) 4057 .addReg(Src0, 0, AMDGPU::sub0) 4058 .addImm(0) 4059 .addReg(Src1, 0, AMDGPU::sub0) 4060 .addReg(SrcCondCopy); 4061 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4062 .addImm(0) 4063 .addReg(Src0, 0, AMDGPU::sub1) 4064 .addImm(0) 4065 .addReg(Src1, 0, AMDGPU::sub1) 4066 .addReg(SrcCondCopy); 4067 4068 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4069 .addReg(DstLo) 4070 .addImm(AMDGPU::sub0) 4071 .addReg(DstHi) 4072 .addImm(AMDGPU::sub1); 4073 MI.eraseFromParent(); 4074 return BB; 4075 } 4076 case AMDGPU::SI_BR_UNDEF: { 4077 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4078 const DebugLoc &DL = MI.getDebugLoc(); 4079 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4080 .add(MI.getOperand(0)); 4081 Br->getOperand(1).setIsUndef(true); // read undef SCC 4082 MI.eraseFromParent(); 4083 return BB; 4084 } 4085 case AMDGPU::ADJCALLSTACKUP: 4086 case AMDGPU::ADJCALLSTACKDOWN: { 4087 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4088 MachineInstrBuilder MIB(*MF, &MI); 4089 4090 // Add an implicit use of the frame offset reg to prevent the restore copy 4091 // inserted after the call from being reorderd after stack operations in the 4092 // the caller's frame. 4093 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4094 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4095 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4096 return BB; 4097 } 4098 case AMDGPU::SI_CALL_ISEL: { 4099 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4100 const DebugLoc &DL = MI.getDebugLoc(); 4101 4102 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4103 4104 MachineInstrBuilder MIB; 4105 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4106 4107 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4108 MIB.add(MI.getOperand(I)); 4109 4110 MIB.cloneMemRefs(MI); 4111 MI.eraseFromParent(); 4112 return BB; 4113 } 4114 case AMDGPU::V_ADD_I32_e32: 4115 case AMDGPU::V_SUB_I32_e32: 4116 case AMDGPU::V_SUBREV_I32_e32: { 4117 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4118 const DebugLoc &DL = MI.getDebugLoc(); 4119 unsigned Opc = MI.getOpcode(); 4120 4121 bool NeedClampOperand = false; 4122 if (TII->pseudoToMCOpcode(Opc) == -1) { 4123 Opc = AMDGPU::getVOPe64(Opc); 4124 NeedClampOperand = true; 4125 } 4126 4127 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4128 if (TII->isVOP3(*I)) { 4129 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4130 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4131 I.addReg(TRI->getVCC(), RegState::Define); 4132 } 4133 I.add(MI.getOperand(1)) 4134 .add(MI.getOperand(2)); 4135 if (NeedClampOperand) 4136 I.addImm(0); // clamp bit for e64 encoding 4137 4138 TII->legalizeOperands(*I); 4139 4140 MI.eraseFromParent(); 4141 return BB; 4142 } 4143 case AMDGPU::DS_GWS_INIT: 4144 case AMDGPU::DS_GWS_SEMA_V: 4145 case AMDGPU::DS_GWS_SEMA_BR: 4146 case AMDGPU::DS_GWS_SEMA_P: 4147 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4148 case AMDGPU::DS_GWS_BARRIER: 4149 // A s_waitcnt 0 is required to be the instruction immediately following. 4150 if (getSubtarget()->hasGWSAutoReplay()) { 4151 bundleInstWithWaitcnt(MI); 4152 return BB; 4153 } 4154 4155 return emitGWSMemViolTestLoop(MI, BB); 4156 case AMDGPU::S_SETREG_B32: { 4157 if (!getSubtarget()->hasDenormModeInst()) 4158 return BB; 4159 4160 // Try to optimize cases that only set the denormal mode or rounding mode. 4161 // 4162 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4163 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4164 // instead. 4165 // 4166 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4167 // allow you to have a no side effect instruction in the output of a 4168 // sideeffecting pattern. 4169 4170 // TODO: Should also emit a no side effects pseudo if only FP bits are 4171 // touched, even if not all of them or to a variable. 4172 unsigned ID, Offset, Width; 4173 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4174 if (ID != AMDGPU::Hwreg::ID_MODE) 4175 return BB; 4176 4177 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4178 const unsigned SetMask = WidthMask << Offset; 4179 unsigned SetDenormOp = 0; 4180 unsigned SetRoundOp = 0; 4181 4182 // The dedicated instructions can only set the whole denorm or round mode at 4183 // once, not a subset of bits in either. 4184 if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4185 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) { 4186 // If this fully sets both the round and denorm mode, emit the two 4187 // dedicated instructions for these. 4188 assert(Offset == 0); 4189 SetRoundOp = AMDGPU::S_ROUND_MODE; 4190 SetDenormOp = AMDGPU::S_DENORM_MODE; 4191 } else if (Width == 4) { 4192 if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) { 4193 SetRoundOp = AMDGPU::S_ROUND_MODE; 4194 assert(Offset == 0); 4195 } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) { 4196 SetDenormOp = AMDGPU::S_DENORM_MODE; 4197 assert(Offset == 4); 4198 } 4199 } 4200 4201 if (SetRoundOp || SetDenormOp) { 4202 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4203 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4204 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4205 unsigned ImmVal = Def->getOperand(1).getImm(); 4206 if (SetRoundOp) { 4207 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4208 .addImm(ImmVal & 0xf); 4209 4210 // If we also have the denorm mode, get just the denorm mode bits. 4211 ImmVal >>= 4; 4212 } 4213 4214 if (SetDenormOp) { 4215 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4216 .addImm(ImmVal & 0xf); 4217 } 4218 4219 MI.eraseFromParent(); 4220 } 4221 } 4222 4223 return BB; 4224 } 4225 default: 4226 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4227 } 4228 } 4229 4230 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4231 return isTypeLegal(VT.getScalarType()); 4232 } 4233 4234 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4235 // This currently forces unfolding various combinations of fsub into fma with 4236 // free fneg'd operands. As long as we have fast FMA (controlled by 4237 // isFMAFasterThanFMulAndFAdd), we should perform these. 4238 4239 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4240 // most of these combines appear to be cycle neutral but save on instruction 4241 // count / code size. 4242 return true; 4243 } 4244 4245 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4246 EVT VT) const { 4247 if (!VT.isVector()) { 4248 return MVT::i1; 4249 } 4250 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4251 } 4252 4253 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4254 // TODO: Should i16 be used always if legal? For now it would force VALU 4255 // shifts. 4256 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4257 } 4258 4259 // Answering this is somewhat tricky and depends on the specific device which 4260 // have different rates for fma or all f64 operations. 4261 // 4262 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4263 // regardless of which device (although the number of cycles differs between 4264 // devices), so it is always profitable for f64. 4265 // 4266 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4267 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4268 // which we can always do even without fused FP ops since it returns the same 4269 // result as the separate operations and since it is always full 4270 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4271 // however does not support denormals, so we do report fma as faster if we have 4272 // a fast fma device and require denormals. 4273 // 4274 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4275 EVT VT) const { 4276 VT = VT.getScalarType(); 4277 4278 switch (VT.getSimpleVT().SimpleTy) { 4279 case MVT::f32: { 4280 // If mad is not available this depends only on if f32 fma is full rate. 4281 if (!Subtarget->hasMadMacF32Insts()) 4282 return Subtarget->hasFastFMAF32(); 4283 4284 // Otherwise f32 mad is always full rate and returns the same result as 4285 // the separate operations so should be preferred over fma. 4286 // However does not support denomals. 4287 if (hasFP32Denormals(MF)) 4288 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4289 4290 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4291 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4292 } 4293 case MVT::f64: 4294 return true; 4295 case MVT::f16: 4296 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4297 default: 4298 break; 4299 } 4300 4301 return false; 4302 } 4303 4304 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4305 const SDNode *N) const { 4306 // TODO: Check future ftz flag 4307 // v_mad_f32/v_mac_f32 do not support denormals. 4308 EVT VT = N->getValueType(0); 4309 if (VT == MVT::f32) 4310 return Subtarget->hasMadMacF32Insts() && 4311 !hasFP32Denormals(DAG.getMachineFunction()); 4312 if (VT == MVT::f16) { 4313 return Subtarget->hasMadF16() && 4314 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4315 } 4316 4317 return false; 4318 } 4319 4320 //===----------------------------------------------------------------------===// 4321 // Custom DAG Lowering Operations 4322 //===----------------------------------------------------------------------===// 4323 4324 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4325 // wider vector type is legal. 4326 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4327 SelectionDAG &DAG) const { 4328 unsigned Opc = Op.getOpcode(); 4329 EVT VT = Op.getValueType(); 4330 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4331 4332 SDValue Lo, Hi; 4333 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4334 4335 SDLoc SL(Op); 4336 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4337 Op->getFlags()); 4338 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4339 Op->getFlags()); 4340 4341 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4342 } 4343 4344 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4345 // wider vector type is legal. 4346 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4347 SelectionDAG &DAG) const { 4348 unsigned Opc = Op.getOpcode(); 4349 EVT VT = Op.getValueType(); 4350 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4351 4352 SDValue Lo0, Hi0; 4353 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4354 SDValue Lo1, Hi1; 4355 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4356 4357 SDLoc SL(Op); 4358 4359 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4360 Op->getFlags()); 4361 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4362 Op->getFlags()); 4363 4364 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4365 } 4366 4367 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4368 SelectionDAG &DAG) const { 4369 unsigned Opc = Op.getOpcode(); 4370 EVT VT = Op.getValueType(); 4371 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4372 4373 SDValue Lo0, Hi0; 4374 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4375 SDValue Lo1, Hi1; 4376 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4377 SDValue Lo2, Hi2; 4378 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4379 4380 SDLoc SL(Op); 4381 4382 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4383 Op->getFlags()); 4384 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4385 Op->getFlags()); 4386 4387 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4388 } 4389 4390 4391 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4392 switch (Op.getOpcode()) { 4393 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4394 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4395 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4396 case ISD::LOAD: { 4397 SDValue Result = LowerLOAD(Op, DAG); 4398 assert((!Result.getNode() || 4399 Result.getNode()->getNumValues() == 2) && 4400 "Load should return a value and a chain"); 4401 return Result; 4402 } 4403 4404 case ISD::FSIN: 4405 case ISD::FCOS: 4406 return LowerTrig(Op, DAG); 4407 case ISD::SELECT: return LowerSELECT(Op, DAG); 4408 case ISD::FDIV: return LowerFDIV(Op, DAG); 4409 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4410 case ISD::STORE: return LowerSTORE(Op, DAG); 4411 case ISD::GlobalAddress: { 4412 MachineFunction &MF = DAG.getMachineFunction(); 4413 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4414 return LowerGlobalAddress(MFI, Op, DAG); 4415 } 4416 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4417 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4418 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4419 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4420 case ISD::INSERT_SUBVECTOR: 4421 return lowerINSERT_SUBVECTOR(Op, DAG); 4422 case ISD::INSERT_VECTOR_ELT: 4423 return lowerINSERT_VECTOR_ELT(Op, DAG); 4424 case ISD::EXTRACT_VECTOR_ELT: 4425 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4426 case ISD::VECTOR_SHUFFLE: 4427 return lowerVECTOR_SHUFFLE(Op, DAG); 4428 case ISD::BUILD_VECTOR: 4429 return lowerBUILD_VECTOR(Op, DAG); 4430 case ISD::FP_ROUND: 4431 return lowerFP_ROUND(Op, DAG); 4432 case ISD::TRAP: 4433 return lowerTRAP(Op, DAG); 4434 case ISD::DEBUGTRAP: 4435 return lowerDEBUGTRAP(Op, DAG); 4436 case ISD::FABS: 4437 case ISD::FNEG: 4438 case ISD::FCANONICALIZE: 4439 case ISD::BSWAP: 4440 return splitUnaryVectorOp(Op, DAG); 4441 case ISD::FMINNUM: 4442 case ISD::FMAXNUM: 4443 return lowerFMINNUM_FMAXNUM(Op, DAG); 4444 case ISD::FMA: 4445 return splitTernaryVectorOp(Op, DAG); 4446 case ISD::SHL: 4447 case ISD::SRA: 4448 case ISD::SRL: 4449 case ISD::ADD: 4450 case ISD::SUB: 4451 case ISD::MUL: 4452 case ISD::SMIN: 4453 case ISD::SMAX: 4454 case ISD::UMIN: 4455 case ISD::UMAX: 4456 case ISD::FADD: 4457 case ISD::FMUL: 4458 case ISD::FMINNUM_IEEE: 4459 case ISD::FMAXNUM_IEEE: 4460 return splitBinaryVectorOp(Op, DAG); 4461 case ISD::SMULO: 4462 case ISD::UMULO: 4463 return lowerXMULO(Op, DAG); 4464 case ISD::DYNAMIC_STACKALLOC: 4465 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4466 } 4467 return SDValue(); 4468 } 4469 4470 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4471 const SDLoc &DL, 4472 SelectionDAG &DAG, bool Unpacked) { 4473 if (!LoadVT.isVector()) 4474 return Result; 4475 4476 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4477 // Truncate to v2i16/v4i16. 4478 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4479 4480 // Workaround legalizer not scalarizing truncate after vector op 4481 // legalization byt not creating intermediate vector trunc. 4482 SmallVector<SDValue, 4> Elts; 4483 DAG.ExtractVectorElements(Result, Elts); 4484 for (SDValue &Elt : Elts) 4485 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4486 4487 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4488 4489 // Bitcast to original type (v2f16/v4f16). 4490 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4491 } 4492 4493 // Cast back to the original packed type. 4494 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4495 } 4496 4497 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4498 MemSDNode *M, 4499 SelectionDAG &DAG, 4500 ArrayRef<SDValue> Ops, 4501 bool IsIntrinsic) const { 4502 SDLoc DL(M); 4503 4504 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4505 EVT LoadVT = M->getValueType(0); 4506 4507 EVT EquivLoadVT = LoadVT; 4508 if (Unpacked && LoadVT.isVector()) { 4509 EquivLoadVT = LoadVT.isVector() ? 4510 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4511 LoadVT.getVectorNumElements()) : LoadVT; 4512 } 4513 4514 // Change from v4f16/v2f16 to EquivLoadVT. 4515 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4516 4517 SDValue Load 4518 = DAG.getMemIntrinsicNode( 4519 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4520 VTList, Ops, M->getMemoryVT(), 4521 M->getMemOperand()); 4522 if (!Unpacked) // Just adjusted the opcode. 4523 return Load; 4524 4525 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4526 4527 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4528 } 4529 4530 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4531 SelectionDAG &DAG, 4532 ArrayRef<SDValue> Ops) const { 4533 SDLoc DL(M); 4534 EVT LoadVT = M->getValueType(0); 4535 EVT EltType = LoadVT.getScalarType(); 4536 EVT IntVT = LoadVT.changeTypeToInteger(); 4537 4538 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4539 4540 unsigned Opc = 4541 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4542 4543 if (IsD16) { 4544 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4545 } 4546 4547 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4548 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4549 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4550 4551 if (isTypeLegal(LoadVT)) { 4552 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4553 M->getMemOperand(), DAG); 4554 } 4555 4556 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4557 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4558 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4559 M->getMemOperand(), DAG); 4560 return DAG.getMergeValues( 4561 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4562 DL); 4563 } 4564 4565 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4566 SDNode *N, SelectionDAG &DAG) { 4567 EVT VT = N->getValueType(0); 4568 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4569 unsigned CondCode = CD->getZExtValue(); 4570 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4571 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4572 return DAG.getUNDEF(VT); 4573 4574 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4575 4576 SDValue LHS = N->getOperand(1); 4577 SDValue RHS = N->getOperand(2); 4578 4579 SDLoc DL(N); 4580 4581 EVT CmpVT = LHS.getValueType(); 4582 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4583 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4584 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4585 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4586 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4587 } 4588 4589 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4590 4591 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4592 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4593 4594 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4595 DAG.getCondCode(CCOpcode)); 4596 if (VT.bitsEq(CCVT)) 4597 return SetCC; 4598 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4599 } 4600 4601 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4602 SDNode *N, SelectionDAG &DAG) { 4603 EVT VT = N->getValueType(0); 4604 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4605 4606 unsigned CondCode = CD->getZExtValue(); 4607 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4608 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4609 return DAG.getUNDEF(VT); 4610 } 4611 4612 SDValue Src0 = N->getOperand(1); 4613 SDValue Src1 = N->getOperand(2); 4614 EVT CmpVT = Src0.getValueType(); 4615 SDLoc SL(N); 4616 4617 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4618 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4619 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4620 } 4621 4622 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4623 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4624 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4625 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4626 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4627 Src1, DAG.getCondCode(CCOpcode)); 4628 if (VT.bitsEq(CCVT)) 4629 return SetCC; 4630 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4631 } 4632 4633 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4634 SelectionDAG &DAG) { 4635 EVT VT = N->getValueType(0); 4636 SDValue Src = N->getOperand(1); 4637 SDLoc SL(N); 4638 4639 if (Src.getOpcode() == ISD::SETCC) { 4640 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4641 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4642 Src.getOperand(1), Src.getOperand(2)); 4643 } 4644 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4645 // (ballot 0) -> 0 4646 if (Arg->isNullValue()) 4647 return DAG.getConstant(0, SL, VT); 4648 4649 // (ballot 1) -> EXEC/EXEC_LO 4650 if (Arg->isOne()) { 4651 Register Exec; 4652 if (VT.getScalarSizeInBits() == 32) 4653 Exec = AMDGPU::EXEC_LO; 4654 else if (VT.getScalarSizeInBits() == 64) 4655 Exec = AMDGPU::EXEC; 4656 else 4657 return SDValue(); 4658 4659 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4660 } 4661 } 4662 4663 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4664 // ISD::SETNE) 4665 return DAG.getNode( 4666 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4667 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4668 } 4669 4670 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4671 SmallVectorImpl<SDValue> &Results, 4672 SelectionDAG &DAG) const { 4673 switch (N->getOpcode()) { 4674 case ISD::INSERT_VECTOR_ELT: { 4675 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4676 Results.push_back(Res); 4677 return; 4678 } 4679 case ISD::EXTRACT_VECTOR_ELT: { 4680 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4681 Results.push_back(Res); 4682 return; 4683 } 4684 case ISD::INTRINSIC_WO_CHAIN: { 4685 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4686 switch (IID) { 4687 case Intrinsic::amdgcn_cvt_pkrtz: { 4688 SDValue Src0 = N->getOperand(1); 4689 SDValue Src1 = N->getOperand(2); 4690 SDLoc SL(N); 4691 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4692 Src0, Src1); 4693 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4694 return; 4695 } 4696 case Intrinsic::amdgcn_cvt_pknorm_i16: 4697 case Intrinsic::amdgcn_cvt_pknorm_u16: 4698 case Intrinsic::amdgcn_cvt_pk_i16: 4699 case Intrinsic::amdgcn_cvt_pk_u16: { 4700 SDValue Src0 = N->getOperand(1); 4701 SDValue Src1 = N->getOperand(2); 4702 SDLoc SL(N); 4703 unsigned Opcode; 4704 4705 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4706 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4707 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4708 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4709 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4710 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4711 else 4712 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4713 4714 EVT VT = N->getValueType(0); 4715 if (isTypeLegal(VT)) 4716 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4717 else { 4718 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4719 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4720 } 4721 return; 4722 } 4723 } 4724 break; 4725 } 4726 case ISD::INTRINSIC_W_CHAIN: { 4727 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4728 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4729 // FIXME: Hacky 4730 Results.push_back(Res.getOperand(0)); 4731 Results.push_back(Res.getOperand(1)); 4732 } else { 4733 Results.push_back(Res); 4734 Results.push_back(Res.getValue(1)); 4735 } 4736 return; 4737 } 4738 4739 break; 4740 } 4741 case ISD::SELECT: { 4742 SDLoc SL(N); 4743 EVT VT = N->getValueType(0); 4744 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4745 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4746 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4747 4748 EVT SelectVT = NewVT; 4749 if (NewVT.bitsLT(MVT::i32)) { 4750 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4751 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4752 SelectVT = MVT::i32; 4753 } 4754 4755 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4756 N->getOperand(0), LHS, RHS); 4757 4758 if (NewVT != SelectVT) 4759 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4760 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4761 return; 4762 } 4763 case ISD::FNEG: { 4764 if (N->getValueType(0) != MVT::v2f16) 4765 break; 4766 4767 SDLoc SL(N); 4768 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4769 4770 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4771 BC, 4772 DAG.getConstant(0x80008000, SL, MVT::i32)); 4773 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4774 return; 4775 } 4776 case ISD::FABS: { 4777 if (N->getValueType(0) != MVT::v2f16) 4778 break; 4779 4780 SDLoc SL(N); 4781 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4782 4783 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4784 BC, 4785 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4786 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4787 return; 4788 } 4789 default: 4790 break; 4791 } 4792 } 4793 4794 /// Helper function for LowerBRCOND 4795 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4796 4797 SDNode *Parent = Value.getNode(); 4798 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4799 I != E; ++I) { 4800 4801 if (I.getUse().get() != Value) 4802 continue; 4803 4804 if (I->getOpcode() == Opcode) 4805 return *I; 4806 } 4807 return nullptr; 4808 } 4809 4810 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4811 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4812 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4813 case Intrinsic::amdgcn_if: 4814 return AMDGPUISD::IF; 4815 case Intrinsic::amdgcn_else: 4816 return AMDGPUISD::ELSE; 4817 case Intrinsic::amdgcn_loop: 4818 return AMDGPUISD::LOOP; 4819 case Intrinsic::amdgcn_end_cf: 4820 llvm_unreachable("should not occur"); 4821 default: 4822 return 0; 4823 } 4824 } 4825 4826 // break, if_break, else_break are all only used as inputs to loop, not 4827 // directly as branch conditions. 4828 return 0; 4829 } 4830 4831 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4832 const Triple &TT = getTargetMachine().getTargetTriple(); 4833 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4834 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4835 AMDGPU::shouldEmitConstantsToTextSection(TT); 4836 } 4837 4838 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4839 // FIXME: Either avoid relying on address space here or change the default 4840 // address space for functions to avoid the explicit check. 4841 return (GV->getValueType()->isFunctionTy() || 4842 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4843 !shouldEmitFixup(GV) && 4844 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4845 } 4846 4847 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4848 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4849 } 4850 4851 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4852 if (!GV->hasExternalLinkage()) 4853 return true; 4854 4855 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4856 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4857 } 4858 4859 /// This transforms the control flow intrinsics to get the branch destination as 4860 /// last parameter, also switches branch target with BR if the need arise 4861 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4862 SelectionDAG &DAG) const { 4863 SDLoc DL(BRCOND); 4864 4865 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4866 SDValue Target = BRCOND.getOperand(2); 4867 SDNode *BR = nullptr; 4868 SDNode *SetCC = nullptr; 4869 4870 if (Intr->getOpcode() == ISD::SETCC) { 4871 // As long as we negate the condition everything is fine 4872 SetCC = Intr; 4873 Intr = SetCC->getOperand(0).getNode(); 4874 4875 } else { 4876 // Get the target from BR if we don't negate the condition 4877 BR = findUser(BRCOND, ISD::BR); 4878 assert(BR && "brcond missing unconditional branch user"); 4879 Target = BR->getOperand(1); 4880 } 4881 4882 unsigned CFNode = isCFIntrinsic(Intr); 4883 if (CFNode == 0) { 4884 // This is a uniform branch so we don't need to legalize. 4885 return BRCOND; 4886 } 4887 4888 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4889 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4890 4891 assert(!SetCC || 4892 (SetCC->getConstantOperandVal(1) == 1 && 4893 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4894 ISD::SETNE)); 4895 4896 // operands of the new intrinsic call 4897 SmallVector<SDValue, 4> Ops; 4898 if (HaveChain) 4899 Ops.push_back(BRCOND.getOperand(0)); 4900 4901 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4902 Ops.push_back(Target); 4903 4904 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4905 4906 // build the new intrinsic call 4907 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4908 4909 if (!HaveChain) { 4910 SDValue Ops[] = { 4911 SDValue(Result, 0), 4912 BRCOND.getOperand(0) 4913 }; 4914 4915 Result = DAG.getMergeValues(Ops, DL).getNode(); 4916 } 4917 4918 if (BR) { 4919 // Give the branch instruction our target 4920 SDValue Ops[] = { 4921 BR->getOperand(0), 4922 BRCOND.getOperand(2) 4923 }; 4924 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4925 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4926 } 4927 4928 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4929 4930 // Copy the intrinsic results to registers 4931 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4932 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4933 if (!CopyToReg) 4934 continue; 4935 4936 Chain = DAG.getCopyToReg( 4937 Chain, DL, 4938 CopyToReg->getOperand(1), 4939 SDValue(Result, i - 1), 4940 SDValue()); 4941 4942 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4943 } 4944 4945 // Remove the old intrinsic from the chain 4946 DAG.ReplaceAllUsesOfValueWith( 4947 SDValue(Intr, Intr->getNumValues() - 1), 4948 Intr->getOperand(0)); 4949 4950 return Chain; 4951 } 4952 4953 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4954 SelectionDAG &DAG) const { 4955 MVT VT = Op.getSimpleValueType(); 4956 SDLoc DL(Op); 4957 // Checking the depth 4958 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4959 return DAG.getConstant(0, DL, VT); 4960 4961 MachineFunction &MF = DAG.getMachineFunction(); 4962 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4963 // Check for kernel and shader functions 4964 if (Info->isEntryFunction()) 4965 return DAG.getConstant(0, DL, VT); 4966 4967 MachineFrameInfo &MFI = MF.getFrameInfo(); 4968 // There is a call to @llvm.returnaddress in this function 4969 MFI.setReturnAddressIsTaken(true); 4970 4971 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4972 // Get the return address reg and mark it as an implicit live-in 4973 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4974 4975 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4976 } 4977 4978 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4979 SDValue Op, 4980 const SDLoc &DL, 4981 EVT VT) const { 4982 return Op.getValueType().bitsLE(VT) ? 4983 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4984 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4985 DAG.getTargetConstant(0, DL, MVT::i32)); 4986 } 4987 4988 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4989 assert(Op.getValueType() == MVT::f16 && 4990 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4991 4992 SDValue Src = Op.getOperand(0); 4993 EVT SrcVT = Src.getValueType(); 4994 if (SrcVT != MVT::f64) 4995 return Op; 4996 4997 SDLoc DL(Op); 4998 4999 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5000 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5001 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5002 } 5003 5004 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5005 SelectionDAG &DAG) const { 5006 EVT VT = Op.getValueType(); 5007 const MachineFunction &MF = DAG.getMachineFunction(); 5008 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5009 bool IsIEEEMode = Info->getMode().IEEE; 5010 5011 // FIXME: Assert during selection that this is only selected for 5012 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5013 // mode functions, but this happens to be OK since it's only done in cases 5014 // where there is known no sNaN. 5015 if (IsIEEEMode) 5016 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5017 5018 if (VT == MVT::v4f16) 5019 return splitBinaryVectorOp(Op, DAG); 5020 return Op; 5021 } 5022 5023 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5024 EVT VT = Op.getValueType(); 5025 SDLoc SL(Op); 5026 SDValue LHS = Op.getOperand(0); 5027 SDValue RHS = Op.getOperand(1); 5028 bool isSigned = Op.getOpcode() == ISD::SMULO; 5029 5030 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5031 const APInt &C = RHSC->getAPIntValue(); 5032 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5033 if (C.isPowerOf2()) { 5034 // smulo(x, signed_min) is same as umulo(x, signed_min). 5035 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5036 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5037 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5038 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5039 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5040 SL, VT, Result, ShiftAmt), 5041 LHS, ISD::SETNE); 5042 return DAG.getMergeValues({ Result, Overflow }, SL); 5043 } 5044 } 5045 5046 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5047 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5048 SL, VT, LHS, RHS); 5049 5050 SDValue Sign = isSigned 5051 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5052 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5053 : DAG.getConstant(0, SL, VT); 5054 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5055 5056 return DAG.getMergeValues({ Result, Overflow }, SL); 5057 } 5058 5059 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5060 SDLoc SL(Op); 5061 SDValue Chain = Op.getOperand(0); 5062 5063 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5064 !Subtarget->isTrapHandlerEnabled()) 5065 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5066 5067 MachineFunction &MF = DAG.getMachineFunction(); 5068 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5069 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 5070 assert(UserSGPR != AMDGPU::NoRegister); 5071 SDValue QueuePtr = CreateLiveInRegister( 5072 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5073 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5074 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5075 QueuePtr, SDValue()); 5076 SDValue Ops[] = { 5077 ToReg, 5078 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5079 SGPR01, 5080 ToReg.getValue(1) 5081 }; 5082 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5083 } 5084 5085 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5086 SDLoc SL(Op); 5087 SDValue Chain = Op.getOperand(0); 5088 MachineFunction &MF = DAG.getMachineFunction(); 5089 5090 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5091 !Subtarget->isTrapHandlerEnabled()) { 5092 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5093 "debugtrap handler not supported", 5094 Op.getDebugLoc(), 5095 DS_Warning); 5096 LLVMContext &Ctx = MF.getFunction().getContext(); 5097 Ctx.diagnose(NoTrap); 5098 return Chain; 5099 } 5100 5101 SDValue Ops[] = { 5102 Chain, 5103 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5104 }; 5105 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5106 } 5107 5108 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5109 SelectionDAG &DAG) const { 5110 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5111 if (Subtarget->hasApertureRegs()) { 5112 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5113 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5114 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5115 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5116 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5117 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5118 unsigned Encoding = 5119 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5120 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5121 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5122 5123 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5124 SDValue ApertureReg = SDValue( 5125 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5126 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5127 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5128 } 5129 5130 MachineFunction &MF = DAG.getMachineFunction(); 5131 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5132 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5133 assert(UserSGPR != AMDGPU::NoRegister); 5134 5135 SDValue QueuePtr = CreateLiveInRegister( 5136 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5137 5138 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5139 // private_segment_aperture_base_hi. 5140 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5141 5142 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 5143 5144 // TODO: Use custom target PseudoSourceValue. 5145 // TODO: We should use the value from the IR intrinsic call, but it might not 5146 // be available and how do we get it? 5147 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5148 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5149 MinAlign(64, StructOffset), 5150 MachineMemOperand::MODereferenceable | 5151 MachineMemOperand::MOInvariant); 5152 } 5153 5154 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5155 SelectionDAG &DAG) const { 5156 SDLoc SL(Op); 5157 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5158 5159 SDValue Src = ASC->getOperand(0); 5160 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5161 5162 const AMDGPUTargetMachine &TM = 5163 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5164 5165 // flat -> local/private 5166 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5167 unsigned DestAS = ASC->getDestAddressSpace(); 5168 5169 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5170 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5171 unsigned NullVal = TM.getNullPointerValue(DestAS); 5172 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5173 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5174 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5175 5176 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5177 NonNull, Ptr, SegmentNullPtr); 5178 } 5179 } 5180 5181 // local/private -> flat 5182 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5183 unsigned SrcAS = ASC->getSrcAddressSpace(); 5184 5185 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5186 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5187 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5188 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5189 5190 SDValue NonNull 5191 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5192 5193 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5194 SDValue CvtPtr 5195 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5196 5197 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5198 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5199 FlatNullPtr); 5200 } 5201 } 5202 5203 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5204 Src.getValueType() == MVT::i64) 5205 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5206 5207 // global <-> flat are no-ops and never emitted. 5208 5209 const MachineFunction &MF = DAG.getMachineFunction(); 5210 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5211 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5212 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5213 5214 return DAG.getUNDEF(ASC->getValueType(0)); 5215 } 5216 5217 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5218 // the small vector and inserting them into the big vector. That is better than 5219 // the default expansion of doing it via a stack slot. Even though the use of 5220 // the stack slot would be optimized away afterwards, the stack slot itself 5221 // remains. 5222 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5223 SelectionDAG &DAG) const { 5224 SDValue Vec = Op.getOperand(0); 5225 SDValue Ins = Op.getOperand(1); 5226 SDValue Idx = Op.getOperand(2); 5227 EVT VecVT = Vec.getValueType(); 5228 EVT InsVT = Ins.getValueType(); 5229 EVT EltVT = VecVT.getVectorElementType(); 5230 unsigned InsNumElts = InsVT.getVectorNumElements(); 5231 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5232 SDLoc SL(Op); 5233 5234 for (unsigned I = 0; I != InsNumElts; ++I) { 5235 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5236 DAG.getConstant(I, SL, MVT::i32)); 5237 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5238 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5239 } 5240 return Vec; 5241 } 5242 5243 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5244 SelectionDAG &DAG) const { 5245 SDValue Vec = Op.getOperand(0); 5246 SDValue InsVal = Op.getOperand(1); 5247 SDValue Idx = Op.getOperand(2); 5248 EVT VecVT = Vec.getValueType(); 5249 EVT EltVT = VecVT.getVectorElementType(); 5250 unsigned VecSize = VecVT.getSizeInBits(); 5251 unsigned EltSize = EltVT.getSizeInBits(); 5252 5253 5254 assert(VecSize <= 64); 5255 5256 unsigned NumElts = VecVT.getVectorNumElements(); 5257 SDLoc SL(Op); 5258 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5259 5260 if (NumElts == 4 && EltSize == 16 && KIdx) { 5261 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5262 5263 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5264 DAG.getConstant(0, SL, MVT::i32)); 5265 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5266 DAG.getConstant(1, SL, MVT::i32)); 5267 5268 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5269 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5270 5271 unsigned Idx = KIdx->getZExtValue(); 5272 bool InsertLo = Idx < 2; 5273 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5274 InsertLo ? LoVec : HiVec, 5275 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5276 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5277 5278 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5279 5280 SDValue Concat = InsertLo ? 5281 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5282 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5283 5284 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5285 } 5286 5287 if (isa<ConstantSDNode>(Idx)) 5288 return SDValue(); 5289 5290 MVT IntVT = MVT::getIntegerVT(VecSize); 5291 5292 // Avoid stack access for dynamic indexing. 5293 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5294 5295 // Create a congruent vector with the target value in each element so that 5296 // the required element can be masked and ORed into the target vector. 5297 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5298 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5299 5300 assert(isPowerOf2_32(EltSize)); 5301 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5302 5303 // Convert vector index to bit-index. 5304 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5305 5306 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5307 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5308 DAG.getConstant(0xffff, SL, IntVT), 5309 ScaledIdx); 5310 5311 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5312 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5313 DAG.getNOT(SL, BFM, IntVT), BCVec); 5314 5315 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5316 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5317 } 5318 5319 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5320 SelectionDAG &DAG) const { 5321 SDLoc SL(Op); 5322 5323 EVT ResultVT = Op.getValueType(); 5324 SDValue Vec = Op.getOperand(0); 5325 SDValue Idx = Op.getOperand(1); 5326 EVT VecVT = Vec.getValueType(); 5327 unsigned VecSize = VecVT.getSizeInBits(); 5328 EVT EltVT = VecVT.getVectorElementType(); 5329 assert(VecSize <= 64); 5330 5331 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5332 5333 // Make sure we do any optimizations that will make it easier to fold 5334 // source modifiers before obscuring it with bit operations. 5335 5336 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5337 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5338 return Combined; 5339 5340 unsigned EltSize = EltVT.getSizeInBits(); 5341 assert(isPowerOf2_32(EltSize)); 5342 5343 MVT IntVT = MVT::getIntegerVT(VecSize); 5344 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5345 5346 // Convert vector index to bit-index (* EltSize) 5347 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5348 5349 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5350 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5351 5352 if (ResultVT == MVT::f16) { 5353 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5354 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5355 } 5356 5357 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5358 } 5359 5360 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5361 assert(Elt % 2 == 0); 5362 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5363 } 5364 5365 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5366 SelectionDAG &DAG) const { 5367 SDLoc SL(Op); 5368 EVT ResultVT = Op.getValueType(); 5369 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5370 5371 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5372 EVT EltVT = PackVT.getVectorElementType(); 5373 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5374 5375 // vector_shuffle <0,1,6,7> lhs, rhs 5376 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5377 // 5378 // vector_shuffle <6,7,2,3> lhs, rhs 5379 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5380 // 5381 // vector_shuffle <6,7,0,1> lhs, rhs 5382 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5383 5384 // Avoid scalarizing when both halves are reading from consecutive elements. 5385 SmallVector<SDValue, 4> Pieces; 5386 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5387 if (elementPairIsContiguous(SVN->getMask(), I)) { 5388 const int Idx = SVN->getMaskElt(I); 5389 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5390 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5391 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5392 PackVT, SVN->getOperand(VecIdx), 5393 DAG.getConstant(EltIdx, SL, MVT::i32)); 5394 Pieces.push_back(SubVec); 5395 } else { 5396 const int Idx0 = SVN->getMaskElt(I); 5397 const int Idx1 = SVN->getMaskElt(I + 1); 5398 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5399 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5400 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5401 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5402 5403 SDValue Vec0 = SVN->getOperand(VecIdx0); 5404 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5405 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5406 5407 SDValue Vec1 = SVN->getOperand(VecIdx1); 5408 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5409 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5410 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5411 } 5412 } 5413 5414 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5415 } 5416 5417 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5418 SelectionDAG &DAG) const { 5419 SDLoc SL(Op); 5420 EVT VT = Op.getValueType(); 5421 5422 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5423 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5424 5425 // Turn into pair of packed build_vectors. 5426 // TODO: Special case for constants that can be materialized with s_mov_b64. 5427 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5428 { Op.getOperand(0), Op.getOperand(1) }); 5429 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5430 { Op.getOperand(2), Op.getOperand(3) }); 5431 5432 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5433 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5434 5435 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5436 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5437 } 5438 5439 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5440 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5441 5442 SDValue Lo = Op.getOperand(0); 5443 SDValue Hi = Op.getOperand(1); 5444 5445 // Avoid adding defined bits with the zero_extend. 5446 if (Hi.isUndef()) { 5447 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5448 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5449 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5450 } 5451 5452 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5453 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5454 5455 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5456 DAG.getConstant(16, SL, MVT::i32)); 5457 if (Lo.isUndef()) 5458 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5459 5460 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5461 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5462 5463 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5464 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5465 } 5466 5467 bool 5468 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5469 // We can fold offsets for anything that doesn't require a GOT relocation. 5470 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5471 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5472 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5473 !shouldEmitGOTReloc(GA->getGlobal()); 5474 } 5475 5476 static SDValue 5477 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5478 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5479 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5480 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5481 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5482 // lowered to the following code sequence: 5483 // 5484 // For constant address space: 5485 // s_getpc_b64 s[0:1] 5486 // s_add_u32 s0, s0, $symbol 5487 // s_addc_u32 s1, s1, 0 5488 // 5489 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5490 // a fixup or relocation is emitted to replace $symbol with a literal 5491 // constant, which is a pc-relative offset from the encoding of the $symbol 5492 // operand to the global variable. 5493 // 5494 // For global address space: 5495 // s_getpc_b64 s[0:1] 5496 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5497 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5498 // 5499 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5500 // fixups or relocations are emitted to replace $symbol@*@lo and 5501 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5502 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5503 // operand to the global variable. 5504 // 5505 // What we want here is an offset from the value returned by s_getpc 5506 // (which is the address of the s_add_u32 instruction) to the global 5507 // variable, but since the encoding of $symbol starts 4 bytes after the start 5508 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5509 // small. This requires us to add 4 to the global variable offset in order to 5510 // compute the correct address. 5511 SDValue PtrLo = 5512 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5513 SDValue PtrHi; 5514 if (GAFlags == SIInstrInfo::MO_NONE) { 5515 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5516 } else { 5517 PtrHi = 5518 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5519 } 5520 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5521 } 5522 5523 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5524 SDValue Op, 5525 SelectionDAG &DAG) const { 5526 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5527 const GlobalValue *GV = GSD->getGlobal(); 5528 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5529 shouldUseLDSConstAddress(GV)) || 5530 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5531 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5532 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5533 5534 SDLoc DL(GSD); 5535 EVT PtrVT = Op.getValueType(); 5536 5537 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5538 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5539 SIInstrInfo::MO_ABS32_LO); 5540 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5541 } 5542 5543 if (shouldEmitFixup(GV)) 5544 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5545 else if (shouldEmitPCReloc(GV)) 5546 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5547 SIInstrInfo::MO_REL32); 5548 5549 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5550 SIInstrInfo::MO_GOTPCREL32); 5551 5552 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5553 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5554 const DataLayout &DataLayout = DAG.getDataLayout(); 5555 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5556 MachinePointerInfo PtrInfo 5557 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5558 5559 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5560 MachineMemOperand::MODereferenceable | 5561 MachineMemOperand::MOInvariant); 5562 } 5563 5564 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5565 const SDLoc &DL, SDValue V) const { 5566 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5567 // the destination register. 5568 // 5569 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5570 // so we will end up with redundant moves to m0. 5571 // 5572 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5573 5574 // A Null SDValue creates a glue result. 5575 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5576 V, Chain); 5577 return SDValue(M0, 0); 5578 } 5579 5580 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5581 SDValue Op, 5582 MVT VT, 5583 unsigned Offset) const { 5584 SDLoc SL(Op); 5585 SDValue Param = lowerKernargMemParameter( 5586 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5587 // The local size values will have the hi 16-bits as zero. 5588 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5589 DAG.getValueType(VT)); 5590 } 5591 5592 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5593 EVT VT) { 5594 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5595 "non-hsa intrinsic with hsa target", 5596 DL.getDebugLoc()); 5597 DAG.getContext()->diagnose(BadIntrin); 5598 return DAG.getUNDEF(VT); 5599 } 5600 5601 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5602 EVT VT) { 5603 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5604 "intrinsic not supported on subtarget", 5605 DL.getDebugLoc()); 5606 DAG.getContext()->diagnose(BadIntrin); 5607 return DAG.getUNDEF(VT); 5608 } 5609 5610 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5611 ArrayRef<SDValue> Elts) { 5612 assert(!Elts.empty()); 5613 MVT Type; 5614 unsigned NumElts; 5615 5616 if (Elts.size() == 1) { 5617 Type = MVT::f32; 5618 NumElts = 1; 5619 } else if (Elts.size() == 2) { 5620 Type = MVT::v2f32; 5621 NumElts = 2; 5622 } else if (Elts.size() == 3) { 5623 Type = MVT::v3f32; 5624 NumElts = 3; 5625 } else if (Elts.size() <= 4) { 5626 Type = MVT::v4f32; 5627 NumElts = 4; 5628 } else if (Elts.size() <= 8) { 5629 Type = MVT::v8f32; 5630 NumElts = 8; 5631 } else { 5632 assert(Elts.size() <= 16); 5633 Type = MVT::v16f32; 5634 NumElts = 16; 5635 } 5636 5637 SmallVector<SDValue, 16> VecElts(NumElts); 5638 for (unsigned i = 0; i < Elts.size(); ++i) { 5639 SDValue Elt = Elts[i]; 5640 if (Elt.getValueType() != MVT::f32) 5641 Elt = DAG.getBitcast(MVT::f32, Elt); 5642 VecElts[i] = Elt; 5643 } 5644 for (unsigned i = Elts.size(); i < NumElts; ++i) 5645 VecElts[i] = DAG.getUNDEF(MVT::f32); 5646 5647 if (NumElts == 1) 5648 return VecElts[0]; 5649 return DAG.getBuildVector(Type, DL, VecElts); 5650 } 5651 5652 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5653 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5654 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5655 5656 uint64_t Value = CachePolicyConst->getZExtValue(); 5657 SDLoc DL(CachePolicy); 5658 if (GLC) { 5659 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5660 Value &= ~(uint64_t)0x1; 5661 } 5662 if (SLC) { 5663 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5664 Value &= ~(uint64_t)0x2; 5665 } 5666 if (DLC) { 5667 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5668 Value &= ~(uint64_t)0x4; 5669 } 5670 5671 return Value == 0; 5672 } 5673 5674 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5675 SDValue Src, int ExtraElts) { 5676 EVT SrcVT = Src.getValueType(); 5677 5678 SmallVector<SDValue, 8> Elts; 5679 5680 if (SrcVT.isVector()) 5681 DAG.ExtractVectorElements(Src, Elts); 5682 else 5683 Elts.push_back(Src); 5684 5685 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5686 while (ExtraElts--) 5687 Elts.push_back(Undef); 5688 5689 return DAG.getBuildVector(CastVT, DL, Elts); 5690 } 5691 5692 // Re-construct the required return value for a image load intrinsic. 5693 // This is more complicated due to the optional use TexFailCtrl which means the required 5694 // return type is an aggregate 5695 static SDValue constructRetValue(SelectionDAG &DAG, 5696 MachineSDNode *Result, 5697 ArrayRef<EVT> ResultTypes, 5698 bool IsTexFail, bool Unpacked, bool IsD16, 5699 int DMaskPop, int NumVDataDwords, 5700 const SDLoc &DL, LLVMContext &Context) { 5701 // Determine the required return type. This is the same regardless of IsTexFail flag 5702 EVT ReqRetVT = ResultTypes[0]; 5703 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5704 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5705 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5706 5707 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5708 DMaskPop : (DMaskPop + 1) / 2; 5709 5710 MVT DataDwordVT = NumDataDwords == 1 ? 5711 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5712 5713 MVT MaskPopVT = MaskPopDwords == 1 ? 5714 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5715 5716 SDValue Data(Result, 0); 5717 SDValue TexFail; 5718 5719 if (IsTexFail) { 5720 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5721 if (MaskPopVT.isVector()) { 5722 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5723 SDValue(Result, 0), ZeroIdx); 5724 } else { 5725 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5726 SDValue(Result, 0), ZeroIdx); 5727 } 5728 5729 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5730 SDValue(Result, 0), 5731 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5732 } 5733 5734 if (DataDwordVT.isVector()) 5735 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5736 NumDataDwords - MaskPopDwords); 5737 5738 if (IsD16) 5739 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5740 5741 if (!ReqRetVT.isVector()) 5742 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5743 5744 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5745 5746 if (TexFail) 5747 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5748 5749 if (Result->getNumValues() == 1) 5750 return Data; 5751 5752 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5753 } 5754 5755 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5756 SDValue *LWE, bool &IsTexFail) { 5757 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5758 5759 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5760 if (Value) { 5761 IsTexFail = true; 5762 } 5763 5764 SDLoc DL(TexFailCtrlConst); 5765 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5766 Value &= ~(uint64_t)0x1; 5767 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5768 Value &= ~(uint64_t)0x2; 5769 5770 return Value == 0; 5771 } 5772 5773 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5774 MVT PackVectorVT, 5775 SmallVectorImpl<SDValue> &PackedAddrs, 5776 unsigned DimIdx, unsigned EndIdx, 5777 unsigned NumGradients) { 5778 SDLoc DL(Op); 5779 for (unsigned I = DimIdx; I < EndIdx; I++) { 5780 SDValue Addr = Op.getOperand(I); 5781 5782 // Gradients are packed with undef for each coordinate. 5783 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5784 // 1D: undef,dx/dh; undef,dx/dv 5785 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5786 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5787 if (((I + 1) >= EndIdx) || 5788 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5789 I == DimIdx + NumGradients - 1))) { 5790 if (Addr.getValueType() != MVT::i16) 5791 Addr = DAG.getBitcast(MVT::i16, Addr); 5792 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5793 } else { 5794 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5795 I++; 5796 } 5797 Addr = DAG.getBitcast(MVT::f32, Addr); 5798 PackedAddrs.push_back(Addr); 5799 } 5800 } 5801 5802 SDValue SITargetLowering::lowerImage(SDValue Op, 5803 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5804 SelectionDAG &DAG) const { 5805 SDLoc DL(Op); 5806 MachineFunction &MF = DAG.getMachineFunction(); 5807 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5808 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5809 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5810 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5811 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5812 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5813 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5814 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5815 unsigned IntrOpcode = Intr->BaseOpcode; 5816 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5817 5818 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5819 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5820 bool IsD16 = false; 5821 bool IsG16 = false; 5822 bool IsA16 = false; 5823 SDValue VData; 5824 int NumVDataDwords; 5825 bool AdjustRetType = false; 5826 5827 unsigned AddrIdx; // Index of first address argument 5828 unsigned DMask; 5829 unsigned DMaskLanes = 0; 5830 5831 if (BaseOpcode->Atomic) { 5832 VData = Op.getOperand(2); 5833 5834 bool Is64Bit = VData.getValueType() == MVT::i64; 5835 if (BaseOpcode->AtomicX2) { 5836 SDValue VData2 = Op.getOperand(3); 5837 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5838 {VData, VData2}); 5839 if (Is64Bit) 5840 VData = DAG.getBitcast(MVT::v4i32, VData); 5841 5842 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5843 DMask = Is64Bit ? 0xf : 0x3; 5844 NumVDataDwords = Is64Bit ? 4 : 2; 5845 AddrIdx = 4; 5846 } else { 5847 DMask = Is64Bit ? 0x3 : 0x1; 5848 NumVDataDwords = Is64Bit ? 2 : 1; 5849 AddrIdx = 3; 5850 } 5851 } else { 5852 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5853 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5854 DMask = DMaskConst->getZExtValue(); 5855 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5856 5857 if (BaseOpcode->Store) { 5858 VData = Op.getOperand(2); 5859 5860 MVT StoreVT = VData.getSimpleValueType(); 5861 if (StoreVT.getScalarType() == MVT::f16) { 5862 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5863 return Op; // D16 is unsupported for this instruction 5864 5865 IsD16 = true; 5866 VData = handleD16VData(VData, DAG); 5867 } 5868 5869 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5870 } else { 5871 // Work out the num dwords based on the dmask popcount and underlying type 5872 // and whether packing is supported. 5873 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5874 if (LoadVT.getScalarType() == MVT::f16) { 5875 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5876 return Op; // D16 is unsupported for this instruction 5877 5878 IsD16 = true; 5879 } 5880 5881 // Confirm that the return type is large enough for the dmask specified 5882 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5883 (!LoadVT.isVector() && DMaskLanes > 1)) 5884 return Op; 5885 5886 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5887 NumVDataDwords = (DMaskLanes + 1) / 2; 5888 else 5889 NumVDataDwords = DMaskLanes; 5890 5891 AdjustRetType = true; 5892 } 5893 5894 AddrIdx = DMaskIdx + 1; 5895 } 5896 5897 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5898 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5899 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5900 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5901 NumCoords + NumLCM; 5902 unsigned NumMIVAddrs = NumVAddrs; 5903 5904 SmallVector<SDValue, 4> VAddrs; 5905 5906 // Optimize _L to _LZ when _L is zero 5907 if (LZMappingInfo) { 5908 if (auto ConstantLod = 5909 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5910 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5911 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5912 NumMIVAddrs--; // remove 'lod' 5913 } 5914 } 5915 } 5916 5917 // Optimize _mip away, when 'lod' is zero 5918 if (MIPMappingInfo) { 5919 if (auto ConstantLod = 5920 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5921 if (ConstantLod->isNullValue()) { 5922 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5923 NumMIVAddrs--; // remove 'lod' 5924 } 5925 } 5926 } 5927 5928 // Push back extra arguments. 5929 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 5930 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 5931 5932 // Check for 16 bit addresses or derivatives and pack if true. 5933 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5934 unsigned CoordIdx = DimIdx + NumGradients; 5935 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 5936 5937 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5938 MVT VAddrScalarVT = VAddrVT.getScalarType(); 5939 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5940 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5941 5942 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 5943 VAddrScalarVT = VAddrVT.getScalarType(); 5944 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5945 if (IsA16 || IsG16) { 5946 if (IsA16) { 5947 if (!ST->hasA16()) { 5948 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5949 "support 16 bit addresses\n"); 5950 return Op; 5951 } 5952 if (!IsG16) { 5953 LLVM_DEBUG( 5954 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 5955 "need 16 bit derivatives but got 32 bit derivatives\n"); 5956 return Op; 5957 } 5958 } else if (!ST->hasG16()) { 5959 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5960 "support 16 bit derivatives\n"); 5961 return Op; 5962 } 5963 5964 if (BaseOpcode->Gradients && !IsA16) { 5965 if (!ST->hasG16()) { 5966 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5967 "support 16 bit derivatives\n"); 5968 return Op; 5969 } 5970 // Activate g16 5971 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 5972 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 5973 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 5974 } 5975 5976 // Don't compress addresses for G16 5977 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 5978 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 5979 PackEndIdx, NumGradients); 5980 5981 if (!IsA16) { 5982 // Add uncompressed address 5983 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 5984 VAddrs.push_back(Op.getOperand(I)); 5985 } 5986 } else { 5987 for (unsigned I = DimIdx; I < CoordsEnd; I++) 5988 VAddrs.push_back(Op.getOperand(I)); 5989 } 5990 5991 // If the register allocator cannot place the address registers contiguously 5992 // without introducing moves, then using the non-sequential address encoding 5993 // is always preferable, since it saves VALU instructions and is usually a 5994 // wash in terms of code size or even better. 5995 // 5996 // However, we currently have no way of hinting to the register allocator that 5997 // MIMG addresses should be placed contiguously when it is possible to do so, 5998 // so force non-NSA for the common 2-address case as a heuristic. 5999 // 6000 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6001 // allocation when possible. 6002 bool UseNSA = 6003 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6004 SDValue VAddr; 6005 if (!UseNSA) 6006 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6007 6008 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6009 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6010 unsigned CtrlIdx; // Index of texfailctrl argument 6011 SDValue Unorm; 6012 if (!BaseOpcode->Sampler) { 6013 Unorm = True; 6014 CtrlIdx = AddrIdx + NumVAddrs + 1; 6015 } else { 6016 auto UnormConst = 6017 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6018 6019 Unorm = UnormConst->getZExtValue() ? True : False; 6020 CtrlIdx = AddrIdx + NumVAddrs + 3; 6021 } 6022 6023 SDValue TFE; 6024 SDValue LWE; 6025 SDValue TexFail = Op.getOperand(CtrlIdx); 6026 bool IsTexFail = false; 6027 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6028 return Op; 6029 6030 if (IsTexFail) { 6031 if (!DMaskLanes) { 6032 // Expecting to get an error flag since TFC is on - and dmask is 0 6033 // Force dmask to be at least 1 otherwise the instruction will fail 6034 DMask = 0x1; 6035 DMaskLanes = 1; 6036 NumVDataDwords = 1; 6037 } 6038 NumVDataDwords += 1; 6039 AdjustRetType = true; 6040 } 6041 6042 // Has something earlier tagged that the return type needs adjusting 6043 // This happens if the instruction is a load or has set TexFailCtrl flags 6044 if (AdjustRetType) { 6045 // NumVDataDwords reflects the true number of dwords required in the return type 6046 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6047 // This is a no-op load. This can be eliminated 6048 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6049 if (isa<MemSDNode>(Op)) 6050 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6051 return Undef; 6052 } 6053 6054 EVT NewVT = NumVDataDwords > 1 ? 6055 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6056 : MVT::i32; 6057 6058 ResultTypes[0] = NewVT; 6059 if (ResultTypes.size() == 3) { 6060 // Original result was aggregate type used for TexFailCtrl results 6061 // The actual instruction returns as a vector type which has now been 6062 // created. Remove the aggregate result. 6063 ResultTypes.erase(&ResultTypes[1]); 6064 } 6065 } 6066 6067 SDValue GLC; 6068 SDValue SLC; 6069 SDValue DLC; 6070 if (BaseOpcode->Atomic) { 6071 GLC = True; // TODO no-return optimization 6072 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6073 IsGFX10 ? &DLC : nullptr)) 6074 return Op; 6075 } else { 6076 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6077 IsGFX10 ? &DLC : nullptr)) 6078 return Op; 6079 } 6080 6081 SmallVector<SDValue, 26> Ops; 6082 if (BaseOpcode->Store || BaseOpcode->Atomic) 6083 Ops.push_back(VData); // vdata 6084 if (UseNSA) { 6085 for (const SDValue &Addr : VAddrs) 6086 Ops.push_back(Addr); 6087 } else { 6088 Ops.push_back(VAddr); 6089 } 6090 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6091 if (BaseOpcode->Sampler) 6092 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6093 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6094 if (IsGFX10) 6095 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6096 Ops.push_back(Unorm); 6097 if (IsGFX10) 6098 Ops.push_back(DLC); 6099 Ops.push_back(GLC); 6100 Ops.push_back(SLC); 6101 Ops.push_back(IsA16 && // r128, a16 for gfx9 6102 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6103 if (IsGFX10) 6104 Ops.push_back(IsA16 ? True : False); 6105 Ops.push_back(TFE); 6106 Ops.push_back(LWE); 6107 if (!IsGFX10) 6108 Ops.push_back(DimInfo->DA ? True : False); 6109 if (BaseOpcode->HasD16) 6110 Ops.push_back(IsD16 ? True : False); 6111 if (isa<MemSDNode>(Op)) 6112 Ops.push_back(Op.getOperand(0)); // chain 6113 6114 int NumVAddrDwords = 6115 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6116 int Opcode = -1; 6117 6118 if (IsGFX10) { 6119 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6120 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6121 : AMDGPU::MIMGEncGfx10Default, 6122 NumVDataDwords, NumVAddrDwords); 6123 } else { 6124 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6125 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6126 NumVDataDwords, NumVAddrDwords); 6127 if (Opcode == -1) 6128 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6129 NumVDataDwords, NumVAddrDwords); 6130 } 6131 assert(Opcode != -1); 6132 6133 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6134 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6135 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6136 DAG.setNodeMemRefs(NewNode, {MemRef}); 6137 } 6138 6139 if (BaseOpcode->AtomicX2) { 6140 SmallVector<SDValue, 1> Elt; 6141 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6142 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6143 } else if (!BaseOpcode->Store) { 6144 return constructRetValue(DAG, NewNode, 6145 OrigResultTypes, IsTexFail, 6146 Subtarget->hasUnpackedD16VMem(), IsD16, 6147 DMaskLanes, NumVDataDwords, DL, 6148 *DAG.getContext()); 6149 } 6150 6151 return SDValue(NewNode, 0); 6152 } 6153 6154 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6155 SDValue Offset, SDValue CachePolicy, 6156 SelectionDAG &DAG) const { 6157 MachineFunction &MF = DAG.getMachineFunction(); 6158 6159 const DataLayout &DataLayout = DAG.getDataLayout(); 6160 Align Alignment = 6161 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6162 6163 MachineMemOperand *MMO = MF.getMachineMemOperand( 6164 MachinePointerInfo(), 6165 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6166 MachineMemOperand::MOInvariant, 6167 VT.getStoreSize(), Alignment); 6168 6169 if (!Offset->isDivergent()) { 6170 SDValue Ops[] = { 6171 Rsrc, 6172 Offset, // Offset 6173 CachePolicy 6174 }; 6175 6176 // Widen vec3 load to vec4. 6177 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6178 EVT WidenedVT = 6179 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6180 auto WidenedOp = DAG.getMemIntrinsicNode( 6181 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6182 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6183 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6184 DAG.getVectorIdxConstant(0, DL)); 6185 return Subvector; 6186 } 6187 6188 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6189 DAG.getVTList(VT), Ops, VT, MMO); 6190 } 6191 6192 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6193 // assume that the buffer is unswizzled. 6194 SmallVector<SDValue, 4> Loads; 6195 unsigned NumLoads = 1; 6196 MVT LoadVT = VT.getSimpleVT(); 6197 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6198 assert((LoadVT.getScalarType() == MVT::i32 || 6199 LoadVT.getScalarType() == MVT::f32)); 6200 6201 if (NumElts == 8 || NumElts == 16) { 6202 NumLoads = NumElts / 4; 6203 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6204 } 6205 6206 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6207 SDValue Ops[] = { 6208 DAG.getEntryNode(), // Chain 6209 Rsrc, // rsrc 6210 DAG.getConstant(0, DL, MVT::i32), // vindex 6211 {}, // voffset 6212 {}, // soffset 6213 {}, // offset 6214 CachePolicy, // cachepolicy 6215 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6216 }; 6217 6218 // Use the alignment to ensure that the required offsets will fit into the 6219 // immediate offsets. 6220 setBufferOffsets(Offset, DAG, &Ops[3], 6221 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6222 6223 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6224 for (unsigned i = 0; i < NumLoads; ++i) { 6225 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6226 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6227 LoadVT, MMO, DAG)); 6228 } 6229 6230 if (NumElts == 8 || NumElts == 16) 6231 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6232 6233 return Loads[0]; 6234 } 6235 6236 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6237 SelectionDAG &DAG) const { 6238 MachineFunction &MF = DAG.getMachineFunction(); 6239 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6240 6241 EVT VT = Op.getValueType(); 6242 SDLoc DL(Op); 6243 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6244 6245 // TODO: Should this propagate fast-math-flags? 6246 6247 switch (IntrinsicID) { 6248 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6249 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6250 return emitNonHSAIntrinsicError(DAG, DL, VT); 6251 return getPreloadedValue(DAG, *MFI, VT, 6252 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6253 } 6254 case Intrinsic::amdgcn_dispatch_ptr: 6255 case Intrinsic::amdgcn_queue_ptr: { 6256 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6257 DiagnosticInfoUnsupported BadIntrin( 6258 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6259 DL.getDebugLoc()); 6260 DAG.getContext()->diagnose(BadIntrin); 6261 return DAG.getUNDEF(VT); 6262 } 6263 6264 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6265 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6266 return getPreloadedValue(DAG, *MFI, VT, RegID); 6267 } 6268 case Intrinsic::amdgcn_implicitarg_ptr: { 6269 if (MFI->isEntryFunction()) 6270 return getImplicitArgPtr(DAG, DL); 6271 return getPreloadedValue(DAG, *MFI, VT, 6272 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6273 } 6274 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6275 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6276 // This only makes sense to call in a kernel, so just lower to null. 6277 return DAG.getConstant(0, DL, VT); 6278 } 6279 6280 return getPreloadedValue(DAG, *MFI, VT, 6281 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6282 } 6283 case Intrinsic::amdgcn_dispatch_id: { 6284 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6285 } 6286 case Intrinsic::amdgcn_rcp: 6287 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6288 case Intrinsic::amdgcn_rsq: 6289 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6290 case Intrinsic::amdgcn_rsq_legacy: 6291 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6292 return emitRemovedIntrinsicError(DAG, DL, VT); 6293 return SDValue(); 6294 case Intrinsic::amdgcn_rcp_legacy: 6295 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6296 return emitRemovedIntrinsicError(DAG, DL, VT); 6297 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6298 case Intrinsic::amdgcn_rsq_clamp: { 6299 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6300 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6301 6302 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6303 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6304 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6305 6306 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6307 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6308 DAG.getConstantFP(Max, DL, VT)); 6309 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6310 DAG.getConstantFP(Min, DL, VT)); 6311 } 6312 case Intrinsic::r600_read_ngroups_x: 6313 if (Subtarget->isAmdHsaOS()) 6314 return emitNonHSAIntrinsicError(DAG, DL, VT); 6315 6316 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6317 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6318 false); 6319 case Intrinsic::r600_read_ngroups_y: 6320 if (Subtarget->isAmdHsaOS()) 6321 return emitNonHSAIntrinsicError(DAG, DL, VT); 6322 6323 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6324 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6325 false); 6326 case Intrinsic::r600_read_ngroups_z: 6327 if (Subtarget->isAmdHsaOS()) 6328 return emitNonHSAIntrinsicError(DAG, DL, VT); 6329 6330 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6331 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6332 false); 6333 case Intrinsic::r600_read_global_size_x: 6334 if (Subtarget->isAmdHsaOS()) 6335 return emitNonHSAIntrinsicError(DAG, DL, VT); 6336 6337 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6338 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6339 Align(4), false); 6340 case Intrinsic::r600_read_global_size_y: 6341 if (Subtarget->isAmdHsaOS()) 6342 return emitNonHSAIntrinsicError(DAG, DL, VT); 6343 6344 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6345 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6346 Align(4), false); 6347 case Intrinsic::r600_read_global_size_z: 6348 if (Subtarget->isAmdHsaOS()) 6349 return emitNonHSAIntrinsicError(DAG, DL, VT); 6350 6351 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6352 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6353 Align(4), false); 6354 case Intrinsic::r600_read_local_size_x: 6355 if (Subtarget->isAmdHsaOS()) 6356 return emitNonHSAIntrinsicError(DAG, DL, VT); 6357 6358 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6359 SI::KernelInputOffsets::LOCAL_SIZE_X); 6360 case Intrinsic::r600_read_local_size_y: 6361 if (Subtarget->isAmdHsaOS()) 6362 return emitNonHSAIntrinsicError(DAG, DL, VT); 6363 6364 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6365 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6366 case Intrinsic::r600_read_local_size_z: 6367 if (Subtarget->isAmdHsaOS()) 6368 return emitNonHSAIntrinsicError(DAG, DL, VT); 6369 6370 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6371 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6372 case Intrinsic::amdgcn_workgroup_id_x: 6373 return getPreloadedValue(DAG, *MFI, VT, 6374 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6375 case Intrinsic::amdgcn_workgroup_id_y: 6376 return getPreloadedValue(DAG, *MFI, VT, 6377 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6378 case Intrinsic::amdgcn_workgroup_id_z: 6379 return getPreloadedValue(DAG, *MFI, VT, 6380 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6381 case Intrinsic::amdgcn_workitem_id_x: 6382 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6383 SDLoc(DAG.getEntryNode()), 6384 MFI->getArgInfo().WorkItemIDX); 6385 case Intrinsic::amdgcn_workitem_id_y: 6386 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6387 SDLoc(DAG.getEntryNode()), 6388 MFI->getArgInfo().WorkItemIDY); 6389 case Intrinsic::amdgcn_workitem_id_z: 6390 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6391 SDLoc(DAG.getEntryNode()), 6392 MFI->getArgInfo().WorkItemIDZ); 6393 case Intrinsic::amdgcn_wavefrontsize: 6394 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6395 SDLoc(Op), MVT::i32); 6396 case Intrinsic::amdgcn_s_buffer_load: { 6397 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6398 SDValue GLC; 6399 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6400 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6401 IsGFX10 ? &DLC : nullptr)) 6402 return Op; 6403 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6404 DAG); 6405 } 6406 case Intrinsic::amdgcn_fdiv_fast: 6407 return lowerFDIV_FAST(Op, DAG); 6408 case Intrinsic::amdgcn_sin: 6409 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6410 6411 case Intrinsic::amdgcn_cos: 6412 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6413 6414 case Intrinsic::amdgcn_mul_u24: 6415 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6416 case Intrinsic::amdgcn_mul_i24: 6417 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6418 6419 case Intrinsic::amdgcn_log_clamp: { 6420 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6421 return SDValue(); 6422 6423 DiagnosticInfoUnsupported BadIntrin( 6424 MF.getFunction(), "intrinsic not supported on subtarget", 6425 DL.getDebugLoc()); 6426 DAG.getContext()->diagnose(BadIntrin); 6427 return DAG.getUNDEF(VT); 6428 } 6429 case Intrinsic::amdgcn_ldexp: 6430 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6431 Op.getOperand(1), Op.getOperand(2)); 6432 6433 case Intrinsic::amdgcn_fract: 6434 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6435 6436 case Intrinsic::amdgcn_class: 6437 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6438 Op.getOperand(1), Op.getOperand(2)); 6439 case Intrinsic::amdgcn_div_fmas: 6440 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6441 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6442 Op.getOperand(4)); 6443 6444 case Intrinsic::amdgcn_div_fixup: 6445 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6446 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6447 6448 case Intrinsic::amdgcn_div_scale: { 6449 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6450 6451 // Translate to the operands expected by the machine instruction. The 6452 // first parameter must be the same as the first instruction. 6453 SDValue Numerator = Op.getOperand(1); 6454 SDValue Denominator = Op.getOperand(2); 6455 6456 // Note this order is opposite of the machine instruction's operations, 6457 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6458 // intrinsic has the numerator as the first operand to match a normal 6459 // division operation. 6460 6461 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6462 6463 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6464 Denominator, Numerator); 6465 } 6466 case Intrinsic::amdgcn_icmp: { 6467 // There is a Pat that handles this variant, so return it as-is. 6468 if (Op.getOperand(1).getValueType() == MVT::i1 && 6469 Op.getConstantOperandVal(2) == 0 && 6470 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6471 return Op; 6472 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6473 } 6474 case Intrinsic::amdgcn_fcmp: { 6475 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6476 } 6477 case Intrinsic::amdgcn_ballot: 6478 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6479 case Intrinsic::amdgcn_fmed3: 6480 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6481 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6482 case Intrinsic::amdgcn_fdot2: 6483 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6484 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6485 Op.getOperand(4)); 6486 case Intrinsic::amdgcn_fmul_legacy: 6487 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6488 Op.getOperand(1), Op.getOperand(2)); 6489 case Intrinsic::amdgcn_sffbh: 6490 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6491 case Intrinsic::amdgcn_sbfe: 6492 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6493 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6494 case Intrinsic::amdgcn_ubfe: 6495 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6496 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6497 case Intrinsic::amdgcn_cvt_pkrtz: 6498 case Intrinsic::amdgcn_cvt_pknorm_i16: 6499 case Intrinsic::amdgcn_cvt_pknorm_u16: 6500 case Intrinsic::amdgcn_cvt_pk_i16: 6501 case Intrinsic::amdgcn_cvt_pk_u16: { 6502 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6503 EVT VT = Op.getValueType(); 6504 unsigned Opcode; 6505 6506 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6507 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6508 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6509 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6510 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6511 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6512 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6513 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6514 else 6515 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6516 6517 if (isTypeLegal(VT)) 6518 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6519 6520 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6521 Op.getOperand(1), Op.getOperand(2)); 6522 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6523 } 6524 case Intrinsic::amdgcn_fmad_ftz: 6525 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6526 Op.getOperand(2), Op.getOperand(3)); 6527 6528 case Intrinsic::amdgcn_if_break: 6529 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6530 Op->getOperand(1), Op->getOperand(2)), 0); 6531 6532 case Intrinsic::amdgcn_groupstaticsize: { 6533 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6534 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6535 return Op; 6536 6537 const Module *M = MF.getFunction().getParent(); 6538 const GlobalValue *GV = 6539 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6540 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6541 SIInstrInfo::MO_ABS32_LO); 6542 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6543 } 6544 case Intrinsic::amdgcn_is_shared: 6545 case Intrinsic::amdgcn_is_private: { 6546 SDLoc SL(Op); 6547 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6548 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6549 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6550 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6551 Op.getOperand(1)); 6552 6553 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6554 DAG.getConstant(1, SL, MVT::i32)); 6555 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6556 } 6557 case Intrinsic::amdgcn_alignbit: 6558 return DAG.getNode(ISD::FSHR, DL, VT, 6559 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6560 case Intrinsic::amdgcn_reloc_constant: { 6561 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6562 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6563 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6564 auto RelocSymbol = cast<GlobalVariable>( 6565 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6566 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6567 SIInstrInfo::MO_ABS32_LO); 6568 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6569 } 6570 default: 6571 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6572 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6573 return lowerImage(Op, ImageDimIntr, DAG); 6574 6575 return Op; 6576 } 6577 } 6578 6579 // This function computes an appropriate offset to pass to 6580 // MachineMemOperand::setOffset() based on the offset inputs to 6581 // an intrinsic. If any of the offsets are non-contstant or 6582 // if VIndex is non-zero then this function returns 0. Otherwise, 6583 // it returns the sum of VOffset, SOffset, and Offset. 6584 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6585 SDValue SOffset, 6586 SDValue Offset, 6587 SDValue VIndex = SDValue()) { 6588 6589 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6590 !isa<ConstantSDNode>(Offset)) 6591 return 0; 6592 6593 if (VIndex) { 6594 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6595 return 0; 6596 } 6597 6598 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6599 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6600 cast<ConstantSDNode>(Offset)->getSExtValue(); 6601 } 6602 6603 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6604 switch (MF.getFunction().getCallingConv()) { 6605 case CallingConv::AMDGPU_PS: 6606 return 1; 6607 case CallingConv::AMDGPU_VS: 6608 return 2; 6609 case CallingConv::AMDGPU_GS: 6610 return 3; 6611 case CallingConv::AMDGPU_HS: 6612 case CallingConv::AMDGPU_LS: 6613 case CallingConv::AMDGPU_ES: 6614 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6615 case CallingConv::AMDGPU_CS: 6616 case CallingConv::AMDGPU_KERNEL: 6617 case CallingConv::C: 6618 case CallingConv::Fast: 6619 default: 6620 // Assume other calling conventions are various compute callable functions 6621 return 0; 6622 } 6623 } 6624 6625 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6626 SelectionDAG &DAG) const { 6627 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6628 SDLoc DL(Op); 6629 6630 switch (IntrID) { 6631 case Intrinsic::amdgcn_ds_ordered_add: 6632 case Intrinsic::amdgcn_ds_ordered_swap: { 6633 MemSDNode *M = cast<MemSDNode>(Op); 6634 SDValue Chain = M->getOperand(0); 6635 SDValue M0 = M->getOperand(2); 6636 SDValue Value = M->getOperand(3); 6637 unsigned IndexOperand = M->getConstantOperandVal(7); 6638 unsigned WaveRelease = M->getConstantOperandVal(8); 6639 unsigned WaveDone = M->getConstantOperandVal(9); 6640 6641 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6642 IndexOperand &= ~0x3f; 6643 unsigned CountDw = 0; 6644 6645 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6646 CountDw = (IndexOperand >> 24) & 0xf; 6647 IndexOperand &= ~(0xf << 24); 6648 6649 if (CountDw < 1 || CountDw > 4) { 6650 report_fatal_error( 6651 "ds_ordered_count: dword count must be between 1 and 4"); 6652 } 6653 } 6654 6655 if (IndexOperand) 6656 report_fatal_error("ds_ordered_count: bad index operand"); 6657 6658 if (WaveDone && !WaveRelease) 6659 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6660 6661 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6662 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6663 unsigned Offset0 = OrderedCountIndex << 2; 6664 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6665 (Instruction << 4); 6666 6667 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6668 Offset1 |= (CountDw - 1) << 6; 6669 6670 unsigned Offset = Offset0 | (Offset1 << 8); 6671 6672 SDValue Ops[] = { 6673 Chain, 6674 Value, 6675 DAG.getTargetConstant(Offset, DL, MVT::i16), 6676 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6677 }; 6678 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6679 M->getVTList(), Ops, M->getMemoryVT(), 6680 M->getMemOperand()); 6681 } 6682 case Intrinsic::amdgcn_ds_fadd: { 6683 MemSDNode *M = cast<MemSDNode>(Op); 6684 unsigned Opc; 6685 switch (IntrID) { 6686 case Intrinsic::amdgcn_ds_fadd: 6687 Opc = ISD::ATOMIC_LOAD_FADD; 6688 break; 6689 } 6690 6691 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6692 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6693 M->getMemOperand()); 6694 } 6695 case Intrinsic::amdgcn_atomic_inc: 6696 case Intrinsic::amdgcn_atomic_dec: 6697 case Intrinsic::amdgcn_ds_fmin: 6698 case Intrinsic::amdgcn_ds_fmax: { 6699 MemSDNode *M = cast<MemSDNode>(Op); 6700 unsigned Opc; 6701 switch (IntrID) { 6702 case Intrinsic::amdgcn_atomic_inc: 6703 Opc = AMDGPUISD::ATOMIC_INC; 6704 break; 6705 case Intrinsic::amdgcn_atomic_dec: 6706 Opc = AMDGPUISD::ATOMIC_DEC; 6707 break; 6708 case Intrinsic::amdgcn_ds_fmin: 6709 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6710 break; 6711 case Intrinsic::amdgcn_ds_fmax: 6712 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6713 break; 6714 default: 6715 llvm_unreachable("Unknown intrinsic!"); 6716 } 6717 SDValue Ops[] = { 6718 M->getOperand(0), // Chain 6719 M->getOperand(2), // Ptr 6720 M->getOperand(3) // Value 6721 }; 6722 6723 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6724 M->getMemoryVT(), M->getMemOperand()); 6725 } 6726 case Intrinsic::amdgcn_buffer_load: 6727 case Intrinsic::amdgcn_buffer_load_format: { 6728 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6729 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6730 unsigned IdxEn = 1; 6731 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6732 IdxEn = Idx->getZExtValue() != 0; 6733 SDValue Ops[] = { 6734 Op.getOperand(0), // Chain 6735 Op.getOperand(2), // rsrc 6736 Op.getOperand(3), // vindex 6737 SDValue(), // voffset -- will be set by setBufferOffsets 6738 SDValue(), // soffset -- will be set by setBufferOffsets 6739 SDValue(), // offset -- will be set by setBufferOffsets 6740 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6741 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6742 }; 6743 6744 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6745 // We don't know the offset if vindex is non-zero, so clear it. 6746 if (IdxEn) 6747 Offset = 0; 6748 6749 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6750 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6751 6752 EVT VT = Op.getValueType(); 6753 EVT IntVT = VT.changeTypeToInteger(); 6754 auto *M = cast<MemSDNode>(Op); 6755 M->getMemOperand()->setOffset(Offset); 6756 EVT LoadVT = Op.getValueType(); 6757 6758 if (LoadVT.getScalarType() == MVT::f16) 6759 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6760 M, DAG, Ops); 6761 6762 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6763 if (LoadVT.getScalarType() == MVT::i8 || 6764 LoadVT.getScalarType() == MVT::i16) 6765 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6766 6767 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6768 M->getMemOperand(), DAG); 6769 } 6770 case Intrinsic::amdgcn_raw_buffer_load: 6771 case Intrinsic::amdgcn_raw_buffer_load_format: { 6772 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6773 6774 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6775 SDValue Ops[] = { 6776 Op.getOperand(0), // Chain 6777 Op.getOperand(2), // rsrc 6778 DAG.getConstant(0, DL, MVT::i32), // vindex 6779 Offsets.first, // voffset 6780 Op.getOperand(4), // soffset 6781 Offsets.second, // offset 6782 Op.getOperand(5), // cachepolicy, swizzled buffer 6783 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6784 }; 6785 6786 auto *M = cast<MemSDNode>(Op); 6787 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6788 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6789 } 6790 case Intrinsic::amdgcn_struct_buffer_load: 6791 case Intrinsic::amdgcn_struct_buffer_load_format: { 6792 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6793 6794 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6795 SDValue Ops[] = { 6796 Op.getOperand(0), // Chain 6797 Op.getOperand(2), // rsrc 6798 Op.getOperand(3), // vindex 6799 Offsets.first, // voffset 6800 Op.getOperand(5), // soffset 6801 Offsets.second, // offset 6802 Op.getOperand(6), // cachepolicy, swizzled buffer 6803 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6804 }; 6805 6806 auto *M = cast<MemSDNode>(Op); 6807 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6808 Ops[2])); 6809 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6810 } 6811 case Intrinsic::amdgcn_tbuffer_load: { 6812 MemSDNode *M = cast<MemSDNode>(Op); 6813 EVT LoadVT = Op.getValueType(); 6814 6815 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6816 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6817 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6818 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6819 unsigned IdxEn = 1; 6820 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6821 IdxEn = Idx->getZExtValue() != 0; 6822 SDValue Ops[] = { 6823 Op.getOperand(0), // Chain 6824 Op.getOperand(2), // rsrc 6825 Op.getOperand(3), // vindex 6826 Op.getOperand(4), // voffset 6827 Op.getOperand(5), // soffset 6828 Op.getOperand(6), // offset 6829 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6830 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6831 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6832 }; 6833 6834 if (LoadVT.getScalarType() == MVT::f16) 6835 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6836 M, DAG, Ops); 6837 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6838 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6839 DAG); 6840 } 6841 case Intrinsic::amdgcn_raw_tbuffer_load: { 6842 MemSDNode *M = cast<MemSDNode>(Op); 6843 EVT LoadVT = Op.getValueType(); 6844 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6845 6846 SDValue Ops[] = { 6847 Op.getOperand(0), // Chain 6848 Op.getOperand(2), // rsrc 6849 DAG.getConstant(0, DL, MVT::i32), // vindex 6850 Offsets.first, // voffset 6851 Op.getOperand(4), // soffset 6852 Offsets.second, // offset 6853 Op.getOperand(5), // format 6854 Op.getOperand(6), // cachepolicy, swizzled buffer 6855 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6856 }; 6857 6858 if (LoadVT.getScalarType() == MVT::f16) 6859 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6860 M, DAG, Ops); 6861 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6862 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6863 DAG); 6864 } 6865 case Intrinsic::amdgcn_struct_tbuffer_load: { 6866 MemSDNode *M = cast<MemSDNode>(Op); 6867 EVT LoadVT = Op.getValueType(); 6868 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6869 6870 SDValue Ops[] = { 6871 Op.getOperand(0), // Chain 6872 Op.getOperand(2), // rsrc 6873 Op.getOperand(3), // vindex 6874 Offsets.first, // voffset 6875 Op.getOperand(5), // soffset 6876 Offsets.second, // offset 6877 Op.getOperand(6), // format 6878 Op.getOperand(7), // cachepolicy, swizzled buffer 6879 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6880 }; 6881 6882 if (LoadVT.getScalarType() == MVT::f16) 6883 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6884 M, DAG, Ops); 6885 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6886 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6887 DAG); 6888 } 6889 case Intrinsic::amdgcn_buffer_atomic_swap: 6890 case Intrinsic::amdgcn_buffer_atomic_add: 6891 case Intrinsic::amdgcn_buffer_atomic_sub: 6892 case Intrinsic::amdgcn_buffer_atomic_csub: 6893 case Intrinsic::amdgcn_buffer_atomic_smin: 6894 case Intrinsic::amdgcn_buffer_atomic_umin: 6895 case Intrinsic::amdgcn_buffer_atomic_smax: 6896 case Intrinsic::amdgcn_buffer_atomic_umax: 6897 case Intrinsic::amdgcn_buffer_atomic_and: 6898 case Intrinsic::amdgcn_buffer_atomic_or: 6899 case Intrinsic::amdgcn_buffer_atomic_xor: { 6900 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6901 unsigned IdxEn = 1; 6902 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6903 IdxEn = Idx->getZExtValue() != 0; 6904 SDValue Ops[] = { 6905 Op.getOperand(0), // Chain 6906 Op.getOperand(2), // vdata 6907 Op.getOperand(3), // rsrc 6908 Op.getOperand(4), // vindex 6909 SDValue(), // voffset -- will be set by setBufferOffsets 6910 SDValue(), // soffset -- will be set by setBufferOffsets 6911 SDValue(), // offset -- will be set by setBufferOffsets 6912 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6913 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6914 }; 6915 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6916 // We don't know the offset if vindex is non-zero, so clear it. 6917 if (IdxEn) 6918 Offset = 0; 6919 EVT VT = Op.getValueType(); 6920 6921 auto *M = cast<MemSDNode>(Op); 6922 M->getMemOperand()->setOffset(Offset); 6923 unsigned Opcode = 0; 6924 6925 switch (IntrID) { 6926 case Intrinsic::amdgcn_buffer_atomic_swap: 6927 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6928 break; 6929 case Intrinsic::amdgcn_buffer_atomic_add: 6930 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6931 break; 6932 case Intrinsic::amdgcn_buffer_atomic_sub: 6933 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6934 break; 6935 case Intrinsic::amdgcn_buffer_atomic_csub: 6936 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 6937 break; 6938 case Intrinsic::amdgcn_buffer_atomic_smin: 6939 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6940 break; 6941 case Intrinsic::amdgcn_buffer_atomic_umin: 6942 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6943 break; 6944 case Intrinsic::amdgcn_buffer_atomic_smax: 6945 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6946 break; 6947 case Intrinsic::amdgcn_buffer_atomic_umax: 6948 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6949 break; 6950 case Intrinsic::amdgcn_buffer_atomic_and: 6951 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6952 break; 6953 case Intrinsic::amdgcn_buffer_atomic_or: 6954 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6955 break; 6956 case Intrinsic::amdgcn_buffer_atomic_xor: 6957 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6958 break; 6959 default: 6960 llvm_unreachable("unhandled atomic opcode"); 6961 } 6962 6963 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6964 M->getMemOperand()); 6965 } 6966 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6967 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6968 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6969 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6970 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6971 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6972 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6973 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6974 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6975 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6976 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6977 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6978 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6979 SDValue Ops[] = { 6980 Op.getOperand(0), // Chain 6981 Op.getOperand(2), // vdata 6982 Op.getOperand(3), // rsrc 6983 DAG.getConstant(0, DL, MVT::i32), // vindex 6984 Offsets.first, // voffset 6985 Op.getOperand(5), // soffset 6986 Offsets.second, // offset 6987 Op.getOperand(6), // cachepolicy 6988 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6989 }; 6990 EVT VT = Op.getValueType(); 6991 6992 auto *M = cast<MemSDNode>(Op); 6993 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6994 unsigned Opcode = 0; 6995 6996 switch (IntrID) { 6997 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6998 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6999 break; 7000 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7001 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7002 break; 7003 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7004 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7005 break; 7006 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7007 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7008 break; 7009 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7010 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7011 break; 7012 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7013 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7014 break; 7015 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7016 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7017 break; 7018 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7019 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7020 break; 7021 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7022 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7023 break; 7024 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7025 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7026 break; 7027 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7028 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7029 break; 7030 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7031 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7032 break; 7033 default: 7034 llvm_unreachable("unhandled atomic opcode"); 7035 } 7036 7037 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7038 M->getMemOperand()); 7039 } 7040 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7041 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7042 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7043 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7044 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7045 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7046 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7047 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7048 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7049 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7050 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7051 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 7052 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7053 SDValue Ops[] = { 7054 Op.getOperand(0), // Chain 7055 Op.getOperand(2), // vdata 7056 Op.getOperand(3), // rsrc 7057 Op.getOperand(4), // vindex 7058 Offsets.first, // voffset 7059 Op.getOperand(6), // soffset 7060 Offsets.second, // offset 7061 Op.getOperand(7), // cachepolicy 7062 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7063 }; 7064 EVT VT = Op.getValueType(); 7065 7066 auto *M = cast<MemSDNode>(Op); 7067 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7068 Ops[3])); 7069 unsigned Opcode = 0; 7070 7071 switch (IntrID) { 7072 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7073 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7074 break; 7075 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7076 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7077 break; 7078 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7079 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7080 break; 7081 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7082 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7083 break; 7084 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7085 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7086 break; 7087 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7088 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7089 break; 7090 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7091 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7092 break; 7093 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7094 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7095 break; 7096 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7097 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7098 break; 7099 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7100 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7101 break; 7102 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7103 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7104 break; 7105 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7106 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7107 break; 7108 default: 7109 llvm_unreachable("unhandled atomic opcode"); 7110 } 7111 7112 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7113 M->getMemOperand()); 7114 } 7115 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7116 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7117 unsigned IdxEn = 1; 7118 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7119 IdxEn = Idx->getZExtValue() != 0; 7120 SDValue Ops[] = { 7121 Op.getOperand(0), // Chain 7122 Op.getOperand(2), // src 7123 Op.getOperand(3), // cmp 7124 Op.getOperand(4), // rsrc 7125 Op.getOperand(5), // vindex 7126 SDValue(), // voffset -- will be set by setBufferOffsets 7127 SDValue(), // soffset -- will be set by setBufferOffsets 7128 SDValue(), // offset -- will be set by setBufferOffsets 7129 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7130 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7131 }; 7132 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7133 // We don't know the offset if vindex is non-zero, so clear it. 7134 if (IdxEn) 7135 Offset = 0; 7136 EVT VT = Op.getValueType(); 7137 auto *M = cast<MemSDNode>(Op); 7138 M->getMemOperand()->setOffset(Offset); 7139 7140 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7141 Op->getVTList(), Ops, VT, M->getMemOperand()); 7142 } 7143 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7144 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7145 SDValue Ops[] = { 7146 Op.getOperand(0), // Chain 7147 Op.getOperand(2), // src 7148 Op.getOperand(3), // cmp 7149 Op.getOperand(4), // rsrc 7150 DAG.getConstant(0, DL, MVT::i32), // vindex 7151 Offsets.first, // voffset 7152 Op.getOperand(6), // soffset 7153 Offsets.second, // offset 7154 Op.getOperand(7), // cachepolicy 7155 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7156 }; 7157 EVT VT = Op.getValueType(); 7158 auto *M = cast<MemSDNode>(Op); 7159 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7160 7161 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7162 Op->getVTList(), Ops, VT, M->getMemOperand()); 7163 } 7164 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7165 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7166 SDValue Ops[] = { 7167 Op.getOperand(0), // Chain 7168 Op.getOperand(2), // src 7169 Op.getOperand(3), // cmp 7170 Op.getOperand(4), // rsrc 7171 Op.getOperand(5), // vindex 7172 Offsets.first, // voffset 7173 Op.getOperand(7), // soffset 7174 Offsets.second, // offset 7175 Op.getOperand(8), // cachepolicy 7176 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7177 }; 7178 EVT VT = Op.getValueType(); 7179 auto *M = cast<MemSDNode>(Op); 7180 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7181 Ops[4])); 7182 7183 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7184 Op->getVTList(), Ops, VT, M->getMemOperand()); 7185 } 7186 case Intrinsic::amdgcn_global_atomic_csub: { 7187 MemSDNode *M = cast<MemSDNode>(Op); 7188 SDValue Ops[] = { 7189 M->getOperand(0), // Chain 7190 M->getOperand(2), // Ptr 7191 M->getOperand(3) // Value 7192 }; 7193 7194 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_LOAD_CSUB, SDLoc(Op), 7195 M->getVTList(), Ops, M->getMemoryVT(), 7196 M->getMemOperand()); 7197 } 7198 7199 default: 7200 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7201 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7202 return lowerImage(Op, ImageDimIntr, DAG); 7203 7204 return SDValue(); 7205 } 7206 } 7207 7208 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7209 // dwordx4 if on SI. 7210 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7211 SDVTList VTList, 7212 ArrayRef<SDValue> Ops, EVT MemVT, 7213 MachineMemOperand *MMO, 7214 SelectionDAG &DAG) const { 7215 EVT VT = VTList.VTs[0]; 7216 EVT WidenedVT = VT; 7217 EVT WidenedMemVT = MemVT; 7218 if (!Subtarget->hasDwordx3LoadStores() && 7219 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7220 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7221 WidenedVT.getVectorElementType(), 4); 7222 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7223 WidenedMemVT.getVectorElementType(), 4); 7224 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7225 } 7226 7227 assert(VTList.NumVTs == 2); 7228 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7229 7230 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7231 WidenedMemVT, MMO); 7232 if (WidenedVT != VT) { 7233 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7234 DAG.getVectorIdxConstant(0, DL)); 7235 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7236 } 7237 return NewOp; 7238 } 7239 7240 SDValue SITargetLowering::handleD16VData(SDValue VData, 7241 SelectionDAG &DAG) const { 7242 EVT StoreVT = VData.getValueType(); 7243 7244 // No change for f16 and legal vector D16 types. 7245 if (!StoreVT.isVector()) 7246 return VData; 7247 7248 SDLoc DL(VData); 7249 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7250 7251 if (Subtarget->hasUnpackedD16VMem()) { 7252 // We need to unpack the packed data to store. 7253 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7254 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7255 7256 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7257 StoreVT.getVectorNumElements()); 7258 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7259 return DAG.UnrollVectorOp(ZExt.getNode()); 7260 } 7261 7262 assert(isTypeLegal(StoreVT)); 7263 return VData; 7264 } 7265 7266 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7267 SelectionDAG &DAG) const { 7268 SDLoc DL(Op); 7269 SDValue Chain = Op.getOperand(0); 7270 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7271 MachineFunction &MF = DAG.getMachineFunction(); 7272 7273 switch (IntrinsicID) { 7274 case Intrinsic::amdgcn_exp_compr: { 7275 SDValue Src0 = Op.getOperand(4); 7276 SDValue Src1 = Op.getOperand(5); 7277 // Hack around illegal type on SI by directly selecting it. 7278 if (isTypeLegal(Src0.getValueType())) 7279 return SDValue(); 7280 7281 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7282 SDValue Undef = DAG.getUNDEF(MVT::f32); 7283 const SDValue Ops[] = { 7284 Op.getOperand(2), // tgt 7285 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7286 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7287 Undef, // src2 7288 Undef, // src3 7289 Op.getOperand(7), // vm 7290 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7291 Op.getOperand(3), // en 7292 Op.getOperand(0) // Chain 7293 }; 7294 7295 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7296 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7297 } 7298 case Intrinsic::amdgcn_s_barrier: { 7299 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7300 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7301 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7302 if (WGSize <= ST.getWavefrontSize()) 7303 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7304 Op.getOperand(0)), 0); 7305 } 7306 return SDValue(); 7307 }; 7308 case Intrinsic::amdgcn_tbuffer_store: { 7309 SDValue VData = Op.getOperand(2); 7310 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7311 if (IsD16) 7312 VData = handleD16VData(VData, DAG); 7313 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7314 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7315 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7316 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7317 unsigned IdxEn = 1; 7318 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7319 IdxEn = Idx->getZExtValue() != 0; 7320 SDValue Ops[] = { 7321 Chain, 7322 VData, // vdata 7323 Op.getOperand(3), // rsrc 7324 Op.getOperand(4), // vindex 7325 Op.getOperand(5), // voffset 7326 Op.getOperand(6), // soffset 7327 Op.getOperand(7), // offset 7328 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7329 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7330 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7331 }; 7332 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7333 AMDGPUISD::TBUFFER_STORE_FORMAT; 7334 MemSDNode *M = cast<MemSDNode>(Op); 7335 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7336 M->getMemoryVT(), M->getMemOperand()); 7337 } 7338 7339 case Intrinsic::amdgcn_struct_tbuffer_store: { 7340 SDValue VData = Op.getOperand(2); 7341 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7342 if (IsD16) 7343 VData = handleD16VData(VData, DAG); 7344 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7345 SDValue Ops[] = { 7346 Chain, 7347 VData, // vdata 7348 Op.getOperand(3), // rsrc 7349 Op.getOperand(4), // vindex 7350 Offsets.first, // voffset 7351 Op.getOperand(6), // soffset 7352 Offsets.second, // offset 7353 Op.getOperand(7), // format 7354 Op.getOperand(8), // cachepolicy, swizzled buffer 7355 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7356 }; 7357 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7358 AMDGPUISD::TBUFFER_STORE_FORMAT; 7359 MemSDNode *M = cast<MemSDNode>(Op); 7360 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7361 M->getMemoryVT(), M->getMemOperand()); 7362 } 7363 7364 case Intrinsic::amdgcn_raw_tbuffer_store: { 7365 SDValue VData = Op.getOperand(2); 7366 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7367 if (IsD16) 7368 VData = handleD16VData(VData, DAG); 7369 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7370 SDValue Ops[] = { 7371 Chain, 7372 VData, // vdata 7373 Op.getOperand(3), // rsrc 7374 DAG.getConstant(0, DL, MVT::i32), // vindex 7375 Offsets.first, // voffset 7376 Op.getOperand(5), // soffset 7377 Offsets.second, // offset 7378 Op.getOperand(6), // format 7379 Op.getOperand(7), // cachepolicy, swizzled buffer 7380 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7381 }; 7382 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7383 AMDGPUISD::TBUFFER_STORE_FORMAT; 7384 MemSDNode *M = cast<MemSDNode>(Op); 7385 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7386 M->getMemoryVT(), M->getMemOperand()); 7387 } 7388 7389 case Intrinsic::amdgcn_buffer_store: 7390 case Intrinsic::amdgcn_buffer_store_format: { 7391 SDValue VData = Op.getOperand(2); 7392 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7393 if (IsD16) 7394 VData = handleD16VData(VData, DAG); 7395 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7396 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7397 unsigned IdxEn = 1; 7398 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7399 IdxEn = Idx->getZExtValue() != 0; 7400 SDValue Ops[] = { 7401 Chain, 7402 VData, 7403 Op.getOperand(3), // rsrc 7404 Op.getOperand(4), // vindex 7405 SDValue(), // voffset -- will be set by setBufferOffsets 7406 SDValue(), // soffset -- will be set by setBufferOffsets 7407 SDValue(), // offset -- will be set by setBufferOffsets 7408 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7409 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7410 }; 7411 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7412 // We don't know the offset if vindex is non-zero, so clear it. 7413 if (IdxEn) 7414 Offset = 0; 7415 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7416 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7417 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7418 MemSDNode *M = cast<MemSDNode>(Op); 7419 M->getMemOperand()->setOffset(Offset); 7420 7421 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7422 EVT VDataType = VData.getValueType().getScalarType(); 7423 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7424 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7425 7426 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7427 M->getMemoryVT(), M->getMemOperand()); 7428 } 7429 7430 case Intrinsic::amdgcn_raw_buffer_store: 7431 case Intrinsic::amdgcn_raw_buffer_store_format: { 7432 const bool IsFormat = 7433 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7434 7435 SDValue VData = Op.getOperand(2); 7436 EVT VDataVT = VData.getValueType(); 7437 EVT EltType = VDataVT.getScalarType(); 7438 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7439 if (IsD16) 7440 VData = handleD16VData(VData, DAG); 7441 7442 if (!isTypeLegal(VDataVT)) { 7443 VData = 7444 DAG.getNode(ISD::BITCAST, DL, 7445 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7446 } 7447 7448 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7449 SDValue Ops[] = { 7450 Chain, 7451 VData, 7452 Op.getOperand(3), // rsrc 7453 DAG.getConstant(0, DL, MVT::i32), // vindex 7454 Offsets.first, // voffset 7455 Op.getOperand(5), // soffset 7456 Offsets.second, // offset 7457 Op.getOperand(6), // cachepolicy, swizzled buffer 7458 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7459 }; 7460 unsigned Opc = 7461 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7462 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7463 MemSDNode *M = cast<MemSDNode>(Op); 7464 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7465 7466 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7467 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7468 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7469 7470 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7471 M->getMemoryVT(), M->getMemOperand()); 7472 } 7473 7474 case Intrinsic::amdgcn_struct_buffer_store: 7475 case Intrinsic::amdgcn_struct_buffer_store_format: { 7476 const bool IsFormat = 7477 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7478 7479 SDValue VData = Op.getOperand(2); 7480 EVT VDataVT = VData.getValueType(); 7481 EVT EltType = VDataVT.getScalarType(); 7482 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7483 7484 if (IsD16) 7485 VData = handleD16VData(VData, DAG); 7486 7487 if (!isTypeLegal(VDataVT)) { 7488 VData = 7489 DAG.getNode(ISD::BITCAST, DL, 7490 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7491 } 7492 7493 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7494 SDValue Ops[] = { 7495 Chain, 7496 VData, 7497 Op.getOperand(3), // rsrc 7498 Op.getOperand(4), // vindex 7499 Offsets.first, // voffset 7500 Op.getOperand(6), // soffset 7501 Offsets.second, // offset 7502 Op.getOperand(7), // cachepolicy, swizzled buffer 7503 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7504 }; 7505 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7506 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7507 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7508 MemSDNode *M = cast<MemSDNode>(Op); 7509 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7510 Ops[3])); 7511 7512 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7513 EVT VDataType = VData.getValueType().getScalarType(); 7514 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7515 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7516 7517 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7518 M->getMemoryVT(), M->getMemOperand()); 7519 } 7520 7521 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7522 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7523 unsigned IdxEn = 1; 7524 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7525 IdxEn = Idx->getZExtValue() != 0; 7526 SDValue Ops[] = { 7527 Chain, 7528 Op.getOperand(2), // vdata 7529 Op.getOperand(3), // rsrc 7530 Op.getOperand(4), // vindex 7531 SDValue(), // voffset -- will be set by setBufferOffsets 7532 SDValue(), // soffset -- will be set by setBufferOffsets 7533 SDValue(), // offset -- will be set by setBufferOffsets 7534 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7535 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7536 }; 7537 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7538 // We don't know the offset if vindex is non-zero, so clear it. 7539 if (IdxEn) 7540 Offset = 0; 7541 EVT VT = Op.getOperand(2).getValueType(); 7542 7543 auto *M = cast<MemSDNode>(Op); 7544 M->getMemOperand()->setOffset(Offset); 7545 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7546 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7547 7548 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7549 M->getMemOperand()); 7550 } 7551 7552 case Intrinsic::amdgcn_global_atomic_fadd: { 7553 SDValue Ops[] = { 7554 Chain, 7555 Op.getOperand(2), // ptr 7556 Op.getOperand(3) // vdata 7557 }; 7558 EVT VT = Op.getOperand(3).getValueType(); 7559 7560 auto *M = cast<MemSDNode>(Op); 7561 if (VT.isVector()) { 7562 return DAG.getMemIntrinsicNode( 7563 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7564 M->getMemOperand()); 7565 } 7566 7567 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7568 DAG.getVTList(VT, MVT::Other), Ops, 7569 M->getMemOperand()).getValue(1); 7570 } 7571 case Intrinsic::amdgcn_end_cf: 7572 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7573 Op->getOperand(2), Chain), 0); 7574 7575 default: { 7576 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7577 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7578 return lowerImage(Op, ImageDimIntr, DAG); 7579 7580 return Op; 7581 } 7582 } 7583 } 7584 7585 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7586 // offset (the offset that is included in bounds checking and swizzling, to be 7587 // split between the instruction's voffset and immoffset fields) and soffset 7588 // (the offset that is excluded from bounds checking and swizzling, to go in 7589 // the instruction's soffset field). This function takes the first kind of 7590 // offset and figures out how to split it between voffset and immoffset. 7591 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7592 SDValue Offset, SelectionDAG &DAG) const { 7593 SDLoc DL(Offset); 7594 const unsigned MaxImm = 4095; 7595 SDValue N0 = Offset; 7596 ConstantSDNode *C1 = nullptr; 7597 7598 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7599 N0 = SDValue(); 7600 else if (DAG.isBaseWithConstantOffset(N0)) { 7601 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7602 N0 = N0.getOperand(0); 7603 } 7604 7605 if (C1) { 7606 unsigned ImmOffset = C1->getZExtValue(); 7607 // If the immediate value is too big for the immoffset field, put the value 7608 // and -4096 into the immoffset field so that the value that is copied/added 7609 // for the voffset field is a multiple of 4096, and it stands more chance 7610 // of being CSEd with the copy/add for another similar load/store. 7611 // However, do not do that rounding down to a multiple of 4096 if that is a 7612 // negative number, as it appears to be illegal to have a negative offset 7613 // in the vgpr, even if adding the immediate offset makes it positive. 7614 unsigned Overflow = ImmOffset & ~MaxImm; 7615 ImmOffset -= Overflow; 7616 if ((int32_t)Overflow < 0) { 7617 Overflow += ImmOffset; 7618 ImmOffset = 0; 7619 } 7620 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7621 if (Overflow) { 7622 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7623 if (!N0) 7624 N0 = OverflowVal; 7625 else { 7626 SDValue Ops[] = { N0, OverflowVal }; 7627 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7628 } 7629 } 7630 } 7631 if (!N0) 7632 N0 = DAG.getConstant(0, DL, MVT::i32); 7633 if (!C1) 7634 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7635 return {N0, SDValue(C1, 0)}; 7636 } 7637 7638 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7639 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7640 // pointed to by Offsets. 7641 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7642 SelectionDAG &DAG, SDValue *Offsets, 7643 Align Alignment) const { 7644 SDLoc DL(CombinedOffset); 7645 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7646 uint32_t Imm = C->getZExtValue(); 7647 uint32_t SOffset, ImmOffset; 7648 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7649 Alignment)) { 7650 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7651 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7652 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7653 return SOffset + ImmOffset; 7654 } 7655 } 7656 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7657 SDValue N0 = CombinedOffset.getOperand(0); 7658 SDValue N1 = CombinedOffset.getOperand(1); 7659 uint32_t SOffset, ImmOffset; 7660 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7661 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7662 Subtarget, Alignment)) { 7663 Offsets[0] = N0; 7664 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7665 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7666 return 0; 7667 } 7668 } 7669 Offsets[0] = CombinedOffset; 7670 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7671 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7672 return 0; 7673 } 7674 7675 // Handle 8 bit and 16 bit buffer loads 7676 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7677 EVT LoadVT, SDLoc DL, 7678 ArrayRef<SDValue> Ops, 7679 MemSDNode *M) const { 7680 EVT IntVT = LoadVT.changeTypeToInteger(); 7681 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7682 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7683 7684 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7685 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7686 Ops, IntVT, 7687 M->getMemOperand()); 7688 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7689 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7690 7691 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7692 } 7693 7694 // Handle 8 bit and 16 bit buffer stores 7695 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7696 EVT VDataType, SDLoc DL, 7697 SDValue Ops[], 7698 MemSDNode *M) const { 7699 if (VDataType == MVT::f16) 7700 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7701 7702 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7703 Ops[1] = BufferStoreExt; 7704 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7705 AMDGPUISD::BUFFER_STORE_SHORT; 7706 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7707 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7708 M->getMemOperand()); 7709 } 7710 7711 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7712 ISD::LoadExtType ExtType, SDValue Op, 7713 const SDLoc &SL, EVT VT) { 7714 if (VT.bitsLT(Op.getValueType())) 7715 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7716 7717 switch (ExtType) { 7718 case ISD::SEXTLOAD: 7719 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7720 case ISD::ZEXTLOAD: 7721 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7722 case ISD::EXTLOAD: 7723 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7724 case ISD::NON_EXTLOAD: 7725 return Op; 7726 } 7727 7728 llvm_unreachable("invalid ext type"); 7729 } 7730 7731 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7732 SelectionDAG &DAG = DCI.DAG; 7733 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7734 return SDValue(); 7735 7736 // FIXME: Constant loads should all be marked invariant. 7737 unsigned AS = Ld->getAddressSpace(); 7738 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7739 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7740 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7741 return SDValue(); 7742 7743 // Don't do this early, since it may interfere with adjacent load merging for 7744 // illegal types. We can avoid losing alignment information for exotic types 7745 // pre-legalize. 7746 EVT MemVT = Ld->getMemoryVT(); 7747 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7748 MemVT.getSizeInBits() >= 32) 7749 return SDValue(); 7750 7751 SDLoc SL(Ld); 7752 7753 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7754 "unexpected vector extload"); 7755 7756 // TODO: Drop only high part of range. 7757 SDValue Ptr = Ld->getBasePtr(); 7758 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7759 MVT::i32, SL, Ld->getChain(), Ptr, 7760 Ld->getOffset(), 7761 Ld->getPointerInfo(), MVT::i32, 7762 Ld->getAlignment(), 7763 Ld->getMemOperand()->getFlags(), 7764 Ld->getAAInfo(), 7765 nullptr); // Drop ranges 7766 7767 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7768 if (MemVT.isFloatingPoint()) { 7769 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7770 "unexpected fp extload"); 7771 TruncVT = MemVT.changeTypeToInteger(); 7772 } 7773 7774 SDValue Cvt = NewLoad; 7775 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7776 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7777 DAG.getValueType(TruncVT)); 7778 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7779 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7780 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7781 } else { 7782 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7783 } 7784 7785 EVT VT = Ld->getValueType(0); 7786 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7787 7788 DCI.AddToWorklist(Cvt.getNode()); 7789 7790 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7791 // the appropriate extension from the 32-bit load. 7792 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7793 DCI.AddToWorklist(Cvt.getNode()); 7794 7795 // Handle conversion back to floating point if necessary. 7796 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7797 7798 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7799 } 7800 7801 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7802 SDLoc DL(Op); 7803 LoadSDNode *Load = cast<LoadSDNode>(Op); 7804 ISD::LoadExtType ExtType = Load->getExtensionType(); 7805 EVT MemVT = Load->getMemoryVT(); 7806 7807 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7808 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7809 return SDValue(); 7810 7811 // FIXME: Copied from PPC 7812 // First, load into 32 bits, then truncate to 1 bit. 7813 7814 SDValue Chain = Load->getChain(); 7815 SDValue BasePtr = Load->getBasePtr(); 7816 MachineMemOperand *MMO = Load->getMemOperand(); 7817 7818 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7819 7820 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7821 BasePtr, RealMemVT, MMO); 7822 7823 if (!MemVT.isVector()) { 7824 SDValue Ops[] = { 7825 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7826 NewLD.getValue(1) 7827 }; 7828 7829 return DAG.getMergeValues(Ops, DL); 7830 } 7831 7832 SmallVector<SDValue, 3> Elts; 7833 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7834 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7835 DAG.getConstant(I, DL, MVT::i32)); 7836 7837 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7838 } 7839 7840 SDValue Ops[] = { 7841 DAG.getBuildVector(MemVT, DL, Elts), 7842 NewLD.getValue(1) 7843 }; 7844 7845 return DAG.getMergeValues(Ops, DL); 7846 } 7847 7848 if (!MemVT.isVector()) 7849 return SDValue(); 7850 7851 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7852 "Custom lowering for non-i32 vectors hasn't been implemented."); 7853 7854 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7855 MemVT, *Load->getMemOperand())) { 7856 SDValue Ops[2]; 7857 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7858 return DAG.getMergeValues(Ops, DL); 7859 } 7860 7861 unsigned Alignment = Load->getAlignment(); 7862 unsigned AS = Load->getAddressSpace(); 7863 if (Subtarget->hasLDSMisalignedBug() && 7864 AS == AMDGPUAS::FLAT_ADDRESS && 7865 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7866 return SplitVectorLoad(Op, DAG); 7867 } 7868 7869 MachineFunction &MF = DAG.getMachineFunction(); 7870 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7871 // If there is a possibilty that flat instruction access scratch memory 7872 // then we need to use the same legalization rules we use for private. 7873 if (AS == AMDGPUAS::FLAT_ADDRESS && 7874 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7875 AS = MFI->hasFlatScratchInit() ? 7876 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7877 7878 unsigned NumElements = MemVT.getVectorNumElements(); 7879 7880 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7881 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7882 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7883 if (MemVT.isPow2VectorType()) 7884 return SDValue(); 7885 if (NumElements == 3) 7886 return WidenVectorLoad(Op, DAG); 7887 return SplitVectorLoad(Op, DAG); 7888 } 7889 // Non-uniform loads will be selected to MUBUF instructions, so they 7890 // have the same legalization requirements as global and private 7891 // loads. 7892 // 7893 } 7894 7895 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7896 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7897 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7898 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7899 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7900 Alignment >= 4 && NumElements < 32) { 7901 if (MemVT.isPow2VectorType()) 7902 return SDValue(); 7903 if (NumElements == 3) 7904 return WidenVectorLoad(Op, DAG); 7905 return SplitVectorLoad(Op, DAG); 7906 } 7907 // Non-uniform loads will be selected to MUBUF instructions, so they 7908 // have the same legalization requirements as global and private 7909 // loads. 7910 // 7911 } 7912 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7913 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7914 AS == AMDGPUAS::GLOBAL_ADDRESS || 7915 AS == AMDGPUAS::FLAT_ADDRESS) { 7916 if (NumElements > 4) 7917 return SplitVectorLoad(Op, DAG); 7918 // v3 loads not supported on SI. 7919 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7920 return WidenVectorLoad(Op, DAG); 7921 // v3 and v4 loads are supported for private and global memory. 7922 return SDValue(); 7923 } 7924 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7925 // Depending on the setting of the private_element_size field in the 7926 // resource descriptor, we can only make private accesses up to a certain 7927 // size. 7928 switch (Subtarget->getMaxPrivateElementSize()) { 7929 case 4: { 7930 SDValue Ops[2]; 7931 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7932 return DAG.getMergeValues(Ops, DL); 7933 } 7934 case 8: 7935 if (NumElements > 2) 7936 return SplitVectorLoad(Op, DAG); 7937 return SDValue(); 7938 case 16: 7939 // Same as global/flat 7940 if (NumElements > 4) 7941 return SplitVectorLoad(Op, DAG); 7942 // v3 loads not supported on SI. 7943 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7944 return WidenVectorLoad(Op, DAG); 7945 return SDValue(); 7946 default: 7947 llvm_unreachable("unsupported private_element_size"); 7948 } 7949 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7950 // Use ds_read_b128 if possible. 7951 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7952 MemVT.getStoreSize() == 16) 7953 return SDValue(); 7954 7955 if (NumElements > 2) 7956 return SplitVectorLoad(Op, DAG); 7957 7958 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7959 // address is negative, then the instruction is incorrectly treated as 7960 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7961 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7962 // load later in the SILoadStoreOptimizer. 7963 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7964 NumElements == 2 && MemVT.getStoreSize() == 8 && 7965 Load->getAlignment() < 8) { 7966 return SplitVectorLoad(Op, DAG); 7967 } 7968 } 7969 return SDValue(); 7970 } 7971 7972 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7973 EVT VT = Op.getValueType(); 7974 assert(VT.getSizeInBits() == 64); 7975 7976 SDLoc DL(Op); 7977 SDValue Cond = Op.getOperand(0); 7978 7979 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7980 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7981 7982 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7983 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7984 7985 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7986 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7987 7988 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7989 7990 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7991 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7992 7993 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7994 7995 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7996 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7997 } 7998 7999 // Catch division cases where we can use shortcuts with rcp and rsq 8000 // instructions. 8001 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8002 SelectionDAG &DAG) const { 8003 SDLoc SL(Op); 8004 SDValue LHS = Op.getOperand(0); 8005 SDValue RHS = Op.getOperand(1); 8006 EVT VT = Op.getValueType(); 8007 const SDNodeFlags Flags = Op->getFlags(); 8008 8009 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8010 Flags.hasApproximateFuncs(); 8011 8012 // Without !fpmath accuracy information, we can't do more because we don't 8013 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8014 if (!AllowInaccurateRcp) 8015 return SDValue(); 8016 8017 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8018 if (CLHS->isExactlyValue(1.0)) { 8019 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8020 // the CI documentation has a worst case error of 1 ulp. 8021 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8022 // use it as long as we aren't trying to use denormals. 8023 // 8024 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8025 8026 // 1.0 / sqrt(x) -> rsq(x) 8027 8028 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8029 // error seems really high at 2^29 ULP. 8030 if (RHS.getOpcode() == ISD::FSQRT) 8031 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8032 8033 // 1.0 / x -> rcp(x) 8034 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8035 } 8036 8037 // Same as for 1.0, but expand the sign out of the constant. 8038 if (CLHS->isExactlyValue(-1.0)) { 8039 // -1.0 / x -> rcp (fneg x) 8040 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8041 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8042 } 8043 } 8044 8045 // Turn into multiply by the reciprocal. 8046 // x / y -> x * (1.0 / y) 8047 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8048 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8049 } 8050 8051 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8052 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8053 SDNodeFlags Flags) { 8054 if (GlueChain->getNumValues() <= 1) { 8055 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8056 } 8057 8058 assert(GlueChain->getNumValues() == 3); 8059 8060 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8061 switch (Opcode) { 8062 default: llvm_unreachable("no chain equivalent for opcode"); 8063 case ISD::FMUL: 8064 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8065 break; 8066 } 8067 8068 return DAG.getNode(Opcode, SL, VTList, 8069 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8070 Flags); 8071 } 8072 8073 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8074 EVT VT, SDValue A, SDValue B, SDValue C, 8075 SDValue GlueChain, SDNodeFlags Flags) { 8076 if (GlueChain->getNumValues() <= 1) { 8077 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8078 } 8079 8080 assert(GlueChain->getNumValues() == 3); 8081 8082 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8083 switch (Opcode) { 8084 default: llvm_unreachable("no chain equivalent for opcode"); 8085 case ISD::FMA: 8086 Opcode = AMDGPUISD::FMA_W_CHAIN; 8087 break; 8088 } 8089 8090 return DAG.getNode(Opcode, SL, VTList, 8091 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8092 Flags); 8093 } 8094 8095 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8096 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8097 return FastLowered; 8098 8099 SDLoc SL(Op); 8100 SDValue Src0 = Op.getOperand(0); 8101 SDValue Src1 = Op.getOperand(1); 8102 8103 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8104 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8105 8106 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8107 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8108 8109 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8110 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8111 8112 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8113 } 8114 8115 // Faster 2.5 ULP division that does not support denormals. 8116 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8117 SDLoc SL(Op); 8118 SDValue LHS = Op.getOperand(1); 8119 SDValue RHS = Op.getOperand(2); 8120 8121 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8122 8123 const APFloat K0Val(BitsToFloat(0x6f800000)); 8124 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8125 8126 const APFloat K1Val(BitsToFloat(0x2f800000)); 8127 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8128 8129 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8130 8131 EVT SetCCVT = 8132 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8133 8134 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8135 8136 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8137 8138 // TODO: Should this propagate fast-math-flags? 8139 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8140 8141 // rcp does not support denormals. 8142 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8143 8144 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8145 8146 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8147 } 8148 8149 // Returns immediate value for setting the F32 denorm mode when using the 8150 // S_DENORM_MODE instruction. 8151 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8152 const SDLoc &SL, const GCNSubtarget *ST) { 8153 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8154 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8155 ? FP_DENORM_FLUSH_NONE 8156 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8157 8158 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8159 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8160 } 8161 8162 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8163 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8164 return FastLowered; 8165 8166 // The selection matcher assumes anything with a chain selecting to a 8167 // mayRaiseFPException machine instruction. Since we're introducing a chain 8168 // here, we need to explicitly report nofpexcept for the regular fdiv 8169 // lowering. 8170 SDNodeFlags Flags = Op->getFlags(); 8171 Flags.setNoFPExcept(true); 8172 8173 SDLoc SL(Op); 8174 SDValue LHS = Op.getOperand(0); 8175 SDValue RHS = Op.getOperand(1); 8176 8177 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8178 8179 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8180 8181 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8182 {RHS, RHS, LHS}, Flags); 8183 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8184 {LHS, RHS, LHS}, Flags); 8185 8186 // Denominator is scaled to not be denormal, so using rcp is ok. 8187 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8188 DenominatorScaled, Flags); 8189 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8190 DenominatorScaled, Flags); 8191 8192 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8193 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8194 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8195 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8196 8197 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8198 8199 if (!HasFP32Denormals) { 8200 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8201 // lowering. The chain dependence is insufficient, and we need glue. We do 8202 // not need the glue variants in a strictfp function. 8203 8204 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8205 8206 SDNode *EnableDenorm; 8207 if (Subtarget->hasDenormModeInst()) { 8208 const SDValue EnableDenormValue = 8209 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8210 8211 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8212 DAG.getEntryNode(), EnableDenormValue).getNode(); 8213 } else { 8214 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8215 SL, MVT::i32); 8216 EnableDenorm = 8217 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8218 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8219 } 8220 8221 SDValue Ops[3] = { 8222 NegDivScale0, 8223 SDValue(EnableDenorm, 0), 8224 SDValue(EnableDenorm, 1) 8225 }; 8226 8227 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8228 } 8229 8230 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8231 ApproxRcp, One, NegDivScale0, Flags); 8232 8233 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8234 ApproxRcp, Fma0, Flags); 8235 8236 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8237 Fma1, Fma1, Flags); 8238 8239 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8240 NumeratorScaled, Mul, Flags); 8241 8242 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8243 Fma2, Fma1, Mul, Fma2, Flags); 8244 8245 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8246 NumeratorScaled, Fma3, Flags); 8247 8248 if (!HasFP32Denormals) { 8249 SDNode *DisableDenorm; 8250 if (Subtarget->hasDenormModeInst()) { 8251 const SDValue DisableDenormValue = 8252 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8253 8254 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8255 Fma4.getValue(1), DisableDenormValue, 8256 Fma4.getValue(2)).getNode(); 8257 } else { 8258 const SDValue DisableDenormValue = 8259 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8260 8261 DisableDenorm = DAG.getMachineNode( 8262 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8263 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8264 } 8265 8266 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8267 SDValue(DisableDenorm, 0), DAG.getRoot()); 8268 DAG.setRoot(OutputChain); 8269 } 8270 8271 SDValue Scale = NumeratorScaled.getValue(1); 8272 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8273 {Fma4, Fma1, Fma3, Scale}, Flags); 8274 8275 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8276 } 8277 8278 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8279 if (DAG.getTarget().Options.UnsafeFPMath) 8280 return lowerFastUnsafeFDIV(Op, DAG); 8281 8282 SDLoc SL(Op); 8283 SDValue X = Op.getOperand(0); 8284 SDValue Y = Op.getOperand(1); 8285 8286 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8287 8288 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8289 8290 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8291 8292 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8293 8294 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8295 8296 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8297 8298 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8299 8300 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8301 8302 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8303 8304 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8305 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8306 8307 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8308 NegDivScale0, Mul, DivScale1); 8309 8310 SDValue Scale; 8311 8312 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8313 // Workaround a hardware bug on SI where the condition output from div_scale 8314 // is not usable. 8315 8316 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8317 8318 // Figure out if the scale to use for div_fmas. 8319 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8320 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8321 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8322 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8323 8324 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8325 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8326 8327 SDValue Scale0Hi 8328 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8329 SDValue Scale1Hi 8330 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8331 8332 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8333 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8334 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8335 } else { 8336 Scale = DivScale1.getValue(1); 8337 } 8338 8339 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8340 Fma4, Fma3, Mul, Scale); 8341 8342 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8343 } 8344 8345 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8346 EVT VT = Op.getValueType(); 8347 8348 if (VT == MVT::f32) 8349 return LowerFDIV32(Op, DAG); 8350 8351 if (VT == MVT::f64) 8352 return LowerFDIV64(Op, DAG); 8353 8354 if (VT == MVT::f16) 8355 return LowerFDIV16(Op, DAG); 8356 8357 llvm_unreachable("Unexpected type for fdiv"); 8358 } 8359 8360 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8361 SDLoc DL(Op); 8362 StoreSDNode *Store = cast<StoreSDNode>(Op); 8363 EVT VT = Store->getMemoryVT(); 8364 8365 if (VT == MVT::i1) { 8366 return DAG.getTruncStore(Store->getChain(), DL, 8367 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8368 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8369 } 8370 8371 assert(VT.isVector() && 8372 Store->getValue().getValueType().getScalarType() == MVT::i32); 8373 8374 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8375 VT, *Store->getMemOperand())) { 8376 return expandUnalignedStore(Store, DAG); 8377 } 8378 8379 unsigned AS = Store->getAddressSpace(); 8380 if (Subtarget->hasLDSMisalignedBug() && 8381 AS == AMDGPUAS::FLAT_ADDRESS && 8382 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8383 return SplitVectorStore(Op, DAG); 8384 } 8385 8386 MachineFunction &MF = DAG.getMachineFunction(); 8387 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8388 // If there is a possibilty that flat instruction access scratch memory 8389 // then we need to use the same legalization rules we use for private. 8390 if (AS == AMDGPUAS::FLAT_ADDRESS && 8391 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8392 AS = MFI->hasFlatScratchInit() ? 8393 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8394 8395 unsigned NumElements = VT.getVectorNumElements(); 8396 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8397 AS == AMDGPUAS::FLAT_ADDRESS) { 8398 if (NumElements > 4) 8399 return SplitVectorStore(Op, DAG); 8400 // v3 stores not supported on SI. 8401 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8402 return SplitVectorStore(Op, DAG); 8403 return SDValue(); 8404 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8405 switch (Subtarget->getMaxPrivateElementSize()) { 8406 case 4: 8407 return scalarizeVectorStore(Store, DAG); 8408 case 8: 8409 if (NumElements > 2) 8410 return SplitVectorStore(Op, DAG); 8411 return SDValue(); 8412 case 16: 8413 if (NumElements > 4 || NumElements == 3) 8414 return SplitVectorStore(Op, DAG); 8415 return SDValue(); 8416 default: 8417 llvm_unreachable("unsupported private_element_size"); 8418 } 8419 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8420 // Use ds_write_b128 if possible. 8421 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8422 VT.getStoreSize() == 16 && NumElements != 3) 8423 return SDValue(); 8424 8425 if (NumElements > 2) 8426 return SplitVectorStore(Op, DAG); 8427 8428 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8429 // address is negative, then the instruction is incorrectly treated as 8430 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8431 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8432 // store later in the SILoadStoreOptimizer. 8433 if (!Subtarget->hasUsableDSOffset() && 8434 NumElements == 2 && VT.getStoreSize() == 8 && 8435 Store->getAlignment() < 8) { 8436 return SplitVectorStore(Op, DAG); 8437 } 8438 8439 return SDValue(); 8440 } else { 8441 llvm_unreachable("unhandled address space"); 8442 } 8443 } 8444 8445 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8446 SDLoc DL(Op); 8447 EVT VT = Op.getValueType(); 8448 SDValue Arg = Op.getOperand(0); 8449 SDValue TrigVal; 8450 8451 // Propagate fast-math flags so that the multiply we introduce can be folded 8452 // if Arg is already the result of a multiply by constant. 8453 auto Flags = Op->getFlags(); 8454 8455 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8456 8457 if (Subtarget->hasTrigReducedRange()) { 8458 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8459 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8460 } else { 8461 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8462 } 8463 8464 switch (Op.getOpcode()) { 8465 case ISD::FCOS: 8466 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8467 case ISD::FSIN: 8468 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8469 default: 8470 llvm_unreachable("Wrong trig opcode"); 8471 } 8472 } 8473 8474 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8475 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8476 assert(AtomicNode->isCompareAndSwap()); 8477 unsigned AS = AtomicNode->getAddressSpace(); 8478 8479 // No custom lowering required for local address space 8480 if (!isFlatGlobalAddrSpace(AS)) 8481 return Op; 8482 8483 // Non-local address space requires custom lowering for atomic compare 8484 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8485 SDLoc DL(Op); 8486 SDValue ChainIn = Op.getOperand(0); 8487 SDValue Addr = Op.getOperand(1); 8488 SDValue Old = Op.getOperand(2); 8489 SDValue New = Op.getOperand(3); 8490 EVT VT = Op.getValueType(); 8491 MVT SimpleVT = VT.getSimpleVT(); 8492 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8493 8494 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8495 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8496 8497 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8498 Ops, VT, AtomicNode->getMemOperand()); 8499 } 8500 8501 //===----------------------------------------------------------------------===// 8502 // Custom DAG optimizations 8503 //===----------------------------------------------------------------------===// 8504 8505 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8506 DAGCombinerInfo &DCI) const { 8507 EVT VT = N->getValueType(0); 8508 EVT ScalarVT = VT.getScalarType(); 8509 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8510 return SDValue(); 8511 8512 SelectionDAG &DAG = DCI.DAG; 8513 SDLoc DL(N); 8514 8515 SDValue Src = N->getOperand(0); 8516 EVT SrcVT = Src.getValueType(); 8517 8518 // TODO: We could try to match extracting the higher bytes, which would be 8519 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8520 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8521 // about in practice. 8522 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8523 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8524 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8525 DCI.AddToWorklist(Cvt.getNode()); 8526 8527 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8528 if (ScalarVT != MVT::f32) { 8529 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8530 DAG.getTargetConstant(0, DL, MVT::i32)); 8531 } 8532 return Cvt; 8533 } 8534 } 8535 8536 return SDValue(); 8537 } 8538 8539 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8540 8541 // This is a variant of 8542 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8543 // 8544 // The normal DAG combiner will do this, but only if the add has one use since 8545 // that would increase the number of instructions. 8546 // 8547 // This prevents us from seeing a constant offset that can be folded into a 8548 // memory instruction's addressing mode. If we know the resulting add offset of 8549 // a pointer can be folded into an addressing offset, we can replace the pointer 8550 // operand with the add of new constant offset. This eliminates one of the uses, 8551 // and may allow the remaining use to also be simplified. 8552 // 8553 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8554 unsigned AddrSpace, 8555 EVT MemVT, 8556 DAGCombinerInfo &DCI) const { 8557 SDValue N0 = N->getOperand(0); 8558 SDValue N1 = N->getOperand(1); 8559 8560 // We only do this to handle cases where it's profitable when there are 8561 // multiple uses of the add, so defer to the standard combine. 8562 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8563 N0->hasOneUse()) 8564 return SDValue(); 8565 8566 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8567 if (!CN1) 8568 return SDValue(); 8569 8570 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8571 if (!CAdd) 8572 return SDValue(); 8573 8574 // If the resulting offset is too large, we can't fold it into the addressing 8575 // mode offset. 8576 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8577 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8578 8579 AddrMode AM; 8580 AM.HasBaseReg = true; 8581 AM.BaseOffs = Offset.getSExtValue(); 8582 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8583 return SDValue(); 8584 8585 SelectionDAG &DAG = DCI.DAG; 8586 SDLoc SL(N); 8587 EVT VT = N->getValueType(0); 8588 8589 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8590 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8591 8592 SDNodeFlags Flags; 8593 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8594 (N0.getOpcode() == ISD::OR || 8595 N0->getFlags().hasNoUnsignedWrap())); 8596 8597 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8598 } 8599 8600 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8601 DAGCombinerInfo &DCI) const { 8602 SDValue Ptr = N->getBasePtr(); 8603 SelectionDAG &DAG = DCI.DAG; 8604 SDLoc SL(N); 8605 8606 // TODO: We could also do this for multiplies. 8607 if (Ptr.getOpcode() == ISD::SHL) { 8608 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8609 N->getMemoryVT(), DCI); 8610 if (NewPtr) { 8611 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8612 8613 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8614 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8615 } 8616 } 8617 8618 return SDValue(); 8619 } 8620 8621 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8622 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8623 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8624 (Opc == ISD::XOR && Val == 0); 8625 } 8626 8627 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8628 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8629 // integer combine opportunities since most 64-bit operations are decomposed 8630 // this way. TODO: We won't want this for SALU especially if it is an inline 8631 // immediate. 8632 SDValue SITargetLowering::splitBinaryBitConstantOp( 8633 DAGCombinerInfo &DCI, 8634 const SDLoc &SL, 8635 unsigned Opc, SDValue LHS, 8636 const ConstantSDNode *CRHS) const { 8637 uint64_t Val = CRHS->getZExtValue(); 8638 uint32_t ValLo = Lo_32(Val); 8639 uint32_t ValHi = Hi_32(Val); 8640 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8641 8642 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8643 bitOpWithConstantIsReducible(Opc, ValHi)) || 8644 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8645 // If we need to materialize a 64-bit immediate, it will be split up later 8646 // anyway. Avoid creating the harder to understand 64-bit immediate 8647 // materialization. 8648 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8649 } 8650 8651 return SDValue(); 8652 } 8653 8654 // Returns true if argument is a boolean value which is not serialized into 8655 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8656 static bool isBoolSGPR(SDValue V) { 8657 if (V.getValueType() != MVT::i1) 8658 return false; 8659 switch (V.getOpcode()) { 8660 default: break; 8661 case ISD::SETCC: 8662 case ISD::AND: 8663 case ISD::OR: 8664 case ISD::XOR: 8665 case AMDGPUISD::FP_CLASS: 8666 return true; 8667 } 8668 return false; 8669 } 8670 8671 // If a constant has all zeroes or all ones within each byte return it. 8672 // Otherwise return 0. 8673 static uint32_t getConstantPermuteMask(uint32_t C) { 8674 // 0xff for any zero byte in the mask 8675 uint32_t ZeroByteMask = 0; 8676 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8677 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8678 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8679 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8680 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8681 if ((NonZeroByteMask & C) != NonZeroByteMask) 8682 return 0; // Partial bytes selected. 8683 return C; 8684 } 8685 8686 // Check if a node selects whole bytes from its operand 0 starting at a byte 8687 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8688 // or -1 if not succeeded. 8689 // Note byte select encoding: 8690 // value 0-3 selects corresponding source byte; 8691 // value 0xc selects zero; 8692 // value 0xff selects 0xff. 8693 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8694 assert(V.getValueSizeInBits() == 32); 8695 8696 if (V.getNumOperands() != 2) 8697 return ~0; 8698 8699 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8700 if (!N1) 8701 return ~0; 8702 8703 uint32_t C = N1->getZExtValue(); 8704 8705 switch (V.getOpcode()) { 8706 default: 8707 break; 8708 case ISD::AND: 8709 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8710 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8711 } 8712 break; 8713 8714 case ISD::OR: 8715 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8716 return (0x03020100 & ~ConstMask) | ConstMask; 8717 } 8718 break; 8719 8720 case ISD::SHL: 8721 if (C % 8) 8722 return ~0; 8723 8724 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8725 8726 case ISD::SRL: 8727 if (C % 8) 8728 return ~0; 8729 8730 return uint32_t(0x0c0c0c0c03020100ull >> C); 8731 } 8732 8733 return ~0; 8734 } 8735 8736 SDValue SITargetLowering::performAndCombine(SDNode *N, 8737 DAGCombinerInfo &DCI) const { 8738 if (DCI.isBeforeLegalize()) 8739 return SDValue(); 8740 8741 SelectionDAG &DAG = DCI.DAG; 8742 EVT VT = N->getValueType(0); 8743 SDValue LHS = N->getOperand(0); 8744 SDValue RHS = N->getOperand(1); 8745 8746 8747 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8748 if (VT == MVT::i64 && CRHS) { 8749 if (SDValue Split 8750 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8751 return Split; 8752 } 8753 8754 if (CRHS && VT == MVT::i32) { 8755 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8756 // nb = number of trailing zeroes in mask 8757 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8758 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8759 uint64_t Mask = CRHS->getZExtValue(); 8760 unsigned Bits = countPopulation(Mask); 8761 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8762 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8763 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8764 unsigned Shift = CShift->getZExtValue(); 8765 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8766 unsigned Offset = NB + Shift; 8767 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8768 SDLoc SL(N); 8769 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8770 LHS->getOperand(0), 8771 DAG.getConstant(Offset, SL, MVT::i32), 8772 DAG.getConstant(Bits, SL, MVT::i32)); 8773 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8774 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8775 DAG.getValueType(NarrowVT)); 8776 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8777 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8778 return Shl; 8779 } 8780 } 8781 } 8782 8783 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8784 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8785 isa<ConstantSDNode>(LHS.getOperand(2))) { 8786 uint32_t Sel = getConstantPermuteMask(Mask); 8787 if (!Sel) 8788 return SDValue(); 8789 8790 // Select 0xc for all zero bytes 8791 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8792 SDLoc DL(N); 8793 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8794 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8795 } 8796 } 8797 8798 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8799 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8800 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8801 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8802 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8803 8804 SDValue X = LHS.getOperand(0); 8805 SDValue Y = RHS.getOperand(0); 8806 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8807 return SDValue(); 8808 8809 if (LCC == ISD::SETO) { 8810 if (X != LHS.getOperand(1)) 8811 return SDValue(); 8812 8813 if (RCC == ISD::SETUNE) { 8814 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8815 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8816 return SDValue(); 8817 8818 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8819 SIInstrFlags::N_SUBNORMAL | 8820 SIInstrFlags::N_ZERO | 8821 SIInstrFlags::P_ZERO | 8822 SIInstrFlags::P_SUBNORMAL | 8823 SIInstrFlags::P_NORMAL; 8824 8825 static_assert(((~(SIInstrFlags::S_NAN | 8826 SIInstrFlags::Q_NAN | 8827 SIInstrFlags::N_INFINITY | 8828 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8829 "mask not equal"); 8830 8831 SDLoc DL(N); 8832 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8833 X, DAG.getConstant(Mask, DL, MVT::i32)); 8834 } 8835 } 8836 } 8837 8838 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8839 std::swap(LHS, RHS); 8840 8841 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8842 RHS.hasOneUse()) { 8843 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8844 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8845 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8846 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8847 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8848 (RHS.getOperand(0) == LHS.getOperand(0) && 8849 LHS.getOperand(0) == LHS.getOperand(1))) { 8850 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8851 unsigned NewMask = LCC == ISD::SETO ? 8852 Mask->getZExtValue() & ~OrdMask : 8853 Mask->getZExtValue() & OrdMask; 8854 8855 SDLoc DL(N); 8856 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8857 DAG.getConstant(NewMask, DL, MVT::i32)); 8858 } 8859 } 8860 8861 if (VT == MVT::i32 && 8862 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8863 // and x, (sext cc from i1) => select cc, x, 0 8864 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8865 std::swap(LHS, RHS); 8866 if (isBoolSGPR(RHS.getOperand(0))) 8867 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8868 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8869 } 8870 8871 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8872 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8873 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8874 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8875 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8876 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8877 if (LHSMask != ~0u && RHSMask != ~0u) { 8878 // Canonicalize the expression in an attempt to have fewer unique masks 8879 // and therefore fewer registers used to hold the masks. 8880 if (LHSMask > RHSMask) { 8881 std::swap(LHSMask, RHSMask); 8882 std::swap(LHS, RHS); 8883 } 8884 8885 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8886 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8887 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8888 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8889 8890 // Check of we need to combine values from two sources within a byte. 8891 if (!(LHSUsedLanes & RHSUsedLanes) && 8892 // If we select high and lower word keep it for SDWA. 8893 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8894 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8895 // Each byte in each mask is either selector mask 0-3, or has higher 8896 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8897 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8898 // mask which is not 0xff wins. By anding both masks we have a correct 8899 // result except that 0x0c shall be corrected to give 0x0c only. 8900 uint32_t Mask = LHSMask & RHSMask; 8901 for (unsigned I = 0; I < 32; I += 8) { 8902 uint32_t ByteSel = 0xff << I; 8903 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8904 Mask &= (0x0c << I) & 0xffffffff; 8905 } 8906 8907 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8908 // or 0x0c. 8909 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8910 SDLoc DL(N); 8911 8912 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8913 LHS.getOperand(0), RHS.getOperand(0), 8914 DAG.getConstant(Sel, DL, MVT::i32)); 8915 } 8916 } 8917 } 8918 8919 return SDValue(); 8920 } 8921 8922 SDValue SITargetLowering::performOrCombine(SDNode *N, 8923 DAGCombinerInfo &DCI) const { 8924 SelectionDAG &DAG = DCI.DAG; 8925 SDValue LHS = N->getOperand(0); 8926 SDValue RHS = N->getOperand(1); 8927 8928 EVT VT = N->getValueType(0); 8929 if (VT == MVT::i1) { 8930 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8931 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8932 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8933 SDValue Src = LHS.getOperand(0); 8934 if (Src != RHS.getOperand(0)) 8935 return SDValue(); 8936 8937 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8938 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8939 if (!CLHS || !CRHS) 8940 return SDValue(); 8941 8942 // Only 10 bits are used. 8943 static const uint32_t MaxMask = 0x3ff; 8944 8945 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8946 SDLoc DL(N); 8947 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8948 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8949 } 8950 8951 return SDValue(); 8952 } 8953 8954 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8955 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8956 LHS.getOpcode() == AMDGPUISD::PERM && 8957 isa<ConstantSDNode>(LHS.getOperand(2))) { 8958 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8959 if (!Sel) 8960 return SDValue(); 8961 8962 Sel |= LHS.getConstantOperandVal(2); 8963 SDLoc DL(N); 8964 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8965 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8966 } 8967 8968 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8969 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8970 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8971 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8972 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8973 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8974 if (LHSMask != ~0u && RHSMask != ~0u) { 8975 // Canonicalize the expression in an attempt to have fewer unique masks 8976 // and therefore fewer registers used to hold the masks. 8977 if (LHSMask > RHSMask) { 8978 std::swap(LHSMask, RHSMask); 8979 std::swap(LHS, RHS); 8980 } 8981 8982 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8983 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8984 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8985 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8986 8987 // Check of we need to combine values from two sources within a byte. 8988 if (!(LHSUsedLanes & RHSUsedLanes) && 8989 // If we select high and lower word keep it for SDWA. 8990 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8991 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8992 // Kill zero bytes selected by other mask. Zero value is 0xc. 8993 LHSMask &= ~RHSUsedLanes; 8994 RHSMask &= ~LHSUsedLanes; 8995 // Add 4 to each active LHS lane 8996 LHSMask |= LHSUsedLanes & 0x04040404; 8997 // Combine masks 8998 uint32_t Sel = LHSMask | RHSMask; 8999 SDLoc DL(N); 9000 9001 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9002 LHS.getOperand(0), RHS.getOperand(0), 9003 DAG.getConstant(Sel, DL, MVT::i32)); 9004 } 9005 } 9006 } 9007 9008 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9009 return SDValue(); 9010 9011 // TODO: This could be a generic combine with a predicate for extracting the 9012 // high half of an integer being free. 9013 9014 // (or i64:x, (zero_extend i32:y)) -> 9015 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9016 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9017 RHS.getOpcode() != ISD::ZERO_EXTEND) 9018 std::swap(LHS, RHS); 9019 9020 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9021 SDValue ExtSrc = RHS.getOperand(0); 9022 EVT SrcVT = ExtSrc.getValueType(); 9023 if (SrcVT == MVT::i32) { 9024 SDLoc SL(N); 9025 SDValue LowLHS, HiBits; 9026 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9027 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9028 9029 DCI.AddToWorklist(LowOr.getNode()); 9030 DCI.AddToWorklist(HiBits.getNode()); 9031 9032 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9033 LowOr, HiBits); 9034 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9035 } 9036 } 9037 9038 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9039 if (CRHS) { 9040 if (SDValue Split 9041 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9042 return Split; 9043 } 9044 9045 return SDValue(); 9046 } 9047 9048 SDValue SITargetLowering::performXorCombine(SDNode *N, 9049 DAGCombinerInfo &DCI) const { 9050 EVT VT = N->getValueType(0); 9051 if (VT != MVT::i64) 9052 return SDValue(); 9053 9054 SDValue LHS = N->getOperand(0); 9055 SDValue RHS = N->getOperand(1); 9056 9057 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9058 if (CRHS) { 9059 if (SDValue Split 9060 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9061 return Split; 9062 } 9063 9064 return SDValue(); 9065 } 9066 9067 // Instructions that will be lowered with a final instruction that zeros the 9068 // high result bits. 9069 // XXX - probably only need to list legal operations. 9070 static bool fp16SrcZerosHighBits(unsigned Opc) { 9071 switch (Opc) { 9072 case ISD::FADD: 9073 case ISD::FSUB: 9074 case ISD::FMUL: 9075 case ISD::FDIV: 9076 case ISD::FREM: 9077 case ISD::FMA: 9078 case ISD::FMAD: 9079 case ISD::FCANONICALIZE: 9080 case ISD::FP_ROUND: 9081 case ISD::UINT_TO_FP: 9082 case ISD::SINT_TO_FP: 9083 case ISD::FABS: 9084 // Fabs is lowered to a bit operation, but it's an and which will clear the 9085 // high bits anyway. 9086 case ISD::FSQRT: 9087 case ISD::FSIN: 9088 case ISD::FCOS: 9089 case ISD::FPOWI: 9090 case ISD::FPOW: 9091 case ISD::FLOG: 9092 case ISD::FLOG2: 9093 case ISD::FLOG10: 9094 case ISD::FEXP: 9095 case ISD::FEXP2: 9096 case ISD::FCEIL: 9097 case ISD::FTRUNC: 9098 case ISD::FRINT: 9099 case ISD::FNEARBYINT: 9100 case ISD::FROUND: 9101 case ISD::FFLOOR: 9102 case ISD::FMINNUM: 9103 case ISD::FMAXNUM: 9104 case AMDGPUISD::FRACT: 9105 case AMDGPUISD::CLAMP: 9106 case AMDGPUISD::COS_HW: 9107 case AMDGPUISD::SIN_HW: 9108 case AMDGPUISD::FMIN3: 9109 case AMDGPUISD::FMAX3: 9110 case AMDGPUISD::FMED3: 9111 case AMDGPUISD::FMAD_FTZ: 9112 case AMDGPUISD::RCP: 9113 case AMDGPUISD::RSQ: 9114 case AMDGPUISD::RCP_IFLAG: 9115 case AMDGPUISD::LDEXP: 9116 return true; 9117 default: 9118 // fcopysign, select and others may be lowered to 32-bit bit operations 9119 // which don't zero the high bits. 9120 return false; 9121 } 9122 } 9123 9124 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9125 DAGCombinerInfo &DCI) const { 9126 if (!Subtarget->has16BitInsts() || 9127 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9128 return SDValue(); 9129 9130 EVT VT = N->getValueType(0); 9131 if (VT != MVT::i32) 9132 return SDValue(); 9133 9134 SDValue Src = N->getOperand(0); 9135 if (Src.getValueType() != MVT::i16) 9136 return SDValue(); 9137 9138 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9139 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9140 if (Src.getOpcode() == ISD::BITCAST) { 9141 SDValue BCSrc = Src.getOperand(0); 9142 if (BCSrc.getValueType() == MVT::f16 && 9143 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9144 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9145 } 9146 9147 return SDValue(); 9148 } 9149 9150 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9151 DAGCombinerInfo &DCI) 9152 const { 9153 SDValue Src = N->getOperand(0); 9154 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9155 9156 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9157 VTSign->getVT() == MVT::i8) || 9158 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9159 VTSign->getVT() == MVT::i16)) && 9160 Src.hasOneUse()) { 9161 auto *M = cast<MemSDNode>(Src); 9162 SDValue Ops[] = { 9163 Src.getOperand(0), // Chain 9164 Src.getOperand(1), // rsrc 9165 Src.getOperand(2), // vindex 9166 Src.getOperand(3), // voffset 9167 Src.getOperand(4), // soffset 9168 Src.getOperand(5), // offset 9169 Src.getOperand(6), 9170 Src.getOperand(7) 9171 }; 9172 // replace with BUFFER_LOAD_BYTE/SHORT 9173 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9174 Src.getOperand(0).getValueType()); 9175 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9176 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9177 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9178 ResList, 9179 Ops, M->getMemoryVT(), 9180 M->getMemOperand()); 9181 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9182 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9183 } 9184 return SDValue(); 9185 } 9186 9187 SDValue SITargetLowering::performClassCombine(SDNode *N, 9188 DAGCombinerInfo &DCI) const { 9189 SelectionDAG &DAG = DCI.DAG; 9190 SDValue Mask = N->getOperand(1); 9191 9192 // fp_class x, 0 -> false 9193 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9194 if (CMask->isNullValue()) 9195 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9196 } 9197 9198 if (N->getOperand(0).isUndef()) 9199 return DAG.getUNDEF(MVT::i1); 9200 9201 return SDValue(); 9202 } 9203 9204 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9205 DAGCombinerInfo &DCI) const { 9206 EVT VT = N->getValueType(0); 9207 SDValue N0 = N->getOperand(0); 9208 9209 if (N0.isUndef()) 9210 return N0; 9211 9212 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9213 N0.getOpcode() == ISD::SINT_TO_FP)) { 9214 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9215 N->getFlags()); 9216 } 9217 9218 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9219 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9220 N0.getOperand(0), N->getFlags()); 9221 } 9222 9223 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9224 } 9225 9226 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9227 unsigned MaxDepth) const { 9228 unsigned Opcode = Op.getOpcode(); 9229 if (Opcode == ISD::FCANONICALIZE) 9230 return true; 9231 9232 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9233 auto F = CFP->getValueAPF(); 9234 if (F.isNaN() && F.isSignaling()) 9235 return false; 9236 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9237 } 9238 9239 // If source is a result of another standard FP operation it is already in 9240 // canonical form. 9241 if (MaxDepth == 0) 9242 return false; 9243 9244 switch (Opcode) { 9245 // These will flush denorms if required. 9246 case ISD::FADD: 9247 case ISD::FSUB: 9248 case ISD::FMUL: 9249 case ISD::FCEIL: 9250 case ISD::FFLOOR: 9251 case ISD::FMA: 9252 case ISD::FMAD: 9253 case ISD::FSQRT: 9254 case ISD::FDIV: 9255 case ISD::FREM: 9256 case ISD::FP_ROUND: 9257 case ISD::FP_EXTEND: 9258 case AMDGPUISD::FMUL_LEGACY: 9259 case AMDGPUISD::FMAD_FTZ: 9260 case AMDGPUISD::RCP: 9261 case AMDGPUISD::RSQ: 9262 case AMDGPUISD::RSQ_CLAMP: 9263 case AMDGPUISD::RCP_LEGACY: 9264 case AMDGPUISD::RCP_IFLAG: 9265 case AMDGPUISD::DIV_SCALE: 9266 case AMDGPUISD::DIV_FMAS: 9267 case AMDGPUISD::DIV_FIXUP: 9268 case AMDGPUISD::FRACT: 9269 case AMDGPUISD::LDEXP: 9270 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9271 case AMDGPUISD::CVT_F32_UBYTE0: 9272 case AMDGPUISD::CVT_F32_UBYTE1: 9273 case AMDGPUISD::CVT_F32_UBYTE2: 9274 case AMDGPUISD::CVT_F32_UBYTE3: 9275 return true; 9276 9277 // It can/will be lowered or combined as a bit operation. 9278 // Need to check their input recursively to handle. 9279 case ISD::FNEG: 9280 case ISD::FABS: 9281 case ISD::FCOPYSIGN: 9282 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9283 9284 case ISD::FSIN: 9285 case ISD::FCOS: 9286 case ISD::FSINCOS: 9287 return Op.getValueType().getScalarType() != MVT::f16; 9288 9289 case ISD::FMINNUM: 9290 case ISD::FMAXNUM: 9291 case ISD::FMINNUM_IEEE: 9292 case ISD::FMAXNUM_IEEE: 9293 case AMDGPUISD::CLAMP: 9294 case AMDGPUISD::FMED3: 9295 case AMDGPUISD::FMAX3: 9296 case AMDGPUISD::FMIN3: { 9297 // FIXME: Shouldn't treat the generic operations different based these. 9298 // However, we aren't really required to flush the result from 9299 // minnum/maxnum.. 9300 9301 // snans will be quieted, so we only need to worry about denormals. 9302 if (Subtarget->supportsMinMaxDenormModes() || 9303 denormalsEnabledForType(DAG, Op.getValueType())) 9304 return true; 9305 9306 // Flushing may be required. 9307 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9308 // targets need to check their input recursively. 9309 9310 // FIXME: Does this apply with clamp? It's implemented with max. 9311 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9312 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9313 return false; 9314 } 9315 9316 return true; 9317 } 9318 case ISD::SELECT: { 9319 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9320 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9321 } 9322 case ISD::BUILD_VECTOR: { 9323 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9324 SDValue SrcOp = Op.getOperand(i); 9325 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9326 return false; 9327 } 9328 9329 return true; 9330 } 9331 case ISD::EXTRACT_VECTOR_ELT: 9332 case ISD::EXTRACT_SUBVECTOR: { 9333 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9334 } 9335 case ISD::INSERT_VECTOR_ELT: { 9336 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9337 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9338 } 9339 case ISD::UNDEF: 9340 // Could be anything. 9341 return false; 9342 9343 case ISD::BITCAST: { 9344 // Hack round the mess we make when legalizing extract_vector_elt 9345 SDValue Src = Op.getOperand(0); 9346 if (Src.getValueType() == MVT::i16 && 9347 Src.getOpcode() == ISD::TRUNCATE) { 9348 SDValue TruncSrc = Src.getOperand(0); 9349 if (TruncSrc.getValueType() == MVT::i32 && 9350 TruncSrc.getOpcode() == ISD::BITCAST && 9351 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9352 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9353 } 9354 } 9355 9356 return false; 9357 } 9358 case ISD::INTRINSIC_WO_CHAIN: { 9359 unsigned IntrinsicID 9360 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9361 // TODO: Handle more intrinsics 9362 switch (IntrinsicID) { 9363 case Intrinsic::amdgcn_cvt_pkrtz: 9364 case Intrinsic::amdgcn_cubeid: 9365 case Intrinsic::amdgcn_frexp_mant: 9366 case Intrinsic::amdgcn_fdot2: 9367 case Intrinsic::amdgcn_rcp: 9368 case Intrinsic::amdgcn_rsq: 9369 case Intrinsic::amdgcn_rsq_clamp: 9370 case Intrinsic::amdgcn_rcp_legacy: 9371 case Intrinsic::amdgcn_rsq_legacy: 9372 case Intrinsic::amdgcn_trig_preop: 9373 return true; 9374 default: 9375 break; 9376 } 9377 9378 LLVM_FALLTHROUGH; 9379 } 9380 default: 9381 return denormalsEnabledForType(DAG, Op.getValueType()) && 9382 DAG.isKnownNeverSNaN(Op); 9383 } 9384 9385 llvm_unreachable("invalid operation"); 9386 } 9387 9388 // Constant fold canonicalize. 9389 SDValue SITargetLowering::getCanonicalConstantFP( 9390 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9391 // Flush denormals to 0 if not enabled. 9392 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9393 return DAG.getConstantFP(0.0, SL, VT); 9394 9395 if (C.isNaN()) { 9396 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9397 if (C.isSignaling()) { 9398 // Quiet a signaling NaN. 9399 // FIXME: Is this supposed to preserve payload bits? 9400 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9401 } 9402 9403 // Make sure it is the canonical NaN bitpattern. 9404 // 9405 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9406 // immediate? 9407 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9408 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9409 } 9410 9411 // Already canonical. 9412 return DAG.getConstantFP(C, SL, VT); 9413 } 9414 9415 static bool vectorEltWillFoldAway(SDValue Op) { 9416 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9417 } 9418 9419 SDValue SITargetLowering::performFCanonicalizeCombine( 9420 SDNode *N, 9421 DAGCombinerInfo &DCI) const { 9422 SelectionDAG &DAG = DCI.DAG; 9423 SDValue N0 = N->getOperand(0); 9424 EVT VT = N->getValueType(0); 9425 9426 // fcanonicalize undef -> qnan 9427 if (N0.isUndef()) { 9428 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9429 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9430 } 9431 9432 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9433 EVT VT = N->getValueType(0); 9434 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9435 } 9436 9437 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9438 // (fcanonicalize k) 9439 // 9440 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9441 9442 // TODO: This could be better with wider vectors that will be split to v2f16, 9443 // and to consider uses since there aren't that many packed operations. 9444 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9445 isTypeLegal(MVT::v2f16)) { 9446 SDLoc SL(N); 9447 SDValue NewElts[2]; 9448 SDValue Lo = N0.getOperand(0); 9449 SDValue Hi = N0.getOperand(1); 9450 EVT EltVT = Lo.getValueType(); 9451 9452 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9453 for (unsigned I = 0; I != 2; ++I) { 9454 SDValue Op = N0.getOperand(I); 9455 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9456 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9457 CFP->getValueAPF()); 9458 } else if (Op.isUndef()) { 9459 // Handled below based on what the other operand is. 9460 NewElts[I] = Op; 9461 } else { 9462 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9463 } 9464 } 9465 9466 // If one half is undef, and one is constant, perfer a splat vector rather 9467 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9468 // cheaper to use and may be free with a packed operation. 9469 if (NewElts[0].isUndef()) { 9470 if (isa<ConstantFPSDNode>(NewElts[1])) 9471 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9472 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9473 } 9474 9475 if (NewElts[1].isUndef()) { 9476 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9477 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9478 } 9479 9480 return DAG.getBuildVector(VT, SL, NewElts); 9481 } 9482 } 9483 9484 unsigned SrcOpc = N0.getOpcode(); 9485 9486 // If it's free to do so, push canonicalizes further up the source, which may 9487 // find a canonical source. 9488 // 9489 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9490 // sNaNs. 9491 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9492 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9493 if (CRHS && N0.hasOneUse()) { 9494 SDLoc SL(N); 9495 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9496 N0.getOperand(0)); 9497 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9498 DCI.AddToWorklist(Canon0.getNode()); 9499 9500 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9501 } 9502 } 9503 9504 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9505 } 9506 9507 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9508 switch (Opc) { 9509 case ISD::FMAXNUM: 9510 case ISD::FMAXNUM_IEEE: 9511 return AMDGPUISD::FMAX3; 9512 case ISD::SMAX: 9513 return AMDGPUISD::SMAX3; 9514 case ISD::UMAX: 9515 return AMDGPUISD::UMAX3; 9516 case ISD::FMINNUM: 9517 case ISD::FMINNUM_IEEE: 9518 return AMDGPUISD::FMIN3; 9519 case ISD::SMIN: 9520 return AMDGPUISD::SMIN3; 9521 case ISD::UMIN: 9522 return AMDGPUISD::UMIN3; 9523 default: 9524 llvm_unreachable("Not a min/max opcode"); 9525 } 9526 } 9527 9528 SDValue SITargetLowering::performIntMed3ImmCombine( 9529 SelectionDAG &DAG, const SDLoc &SL, 9530 SDValue Op0, SDValue Op1, bool Signed) const { 9531 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9532 if (!K1) 9533 return SDValue(); 9534 9535 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9536 if (!K0) 9537 return SDValue(); 9538 9539 if (Signed) { 9540 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9541 return SDValue(); 9542 } else { 9543 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9544 return SDValue(); 9545 } 9546 9547 EVT VT = K0->getValueType(0); 9548 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9549 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9550 return DAG.getNode(Med3Opc, SL, VT, 9551 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9552 } 9553 9554 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9555 MVT NVT = MVT::i32; 9556 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9557 9558 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9559 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9560 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9561 9562 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9563 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9564 } 9565 9566 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9567 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9568 return C; 9569 9570 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9571 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9572 return C; 9573 } 9574 9575 return nullptr; 9576 } 9577 9578 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9579 const SDLoc &SL, 9580 SDValue Op0, 9581 SDValue Op1) const { 9582 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9583 if (!K1) 9584 return SDValue(); 9585 9586 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9587 if (!K0) 9588 return SDValue(); 9589 9590 // Ordered >= (although NaN inputs should have folded away by now). 9591 if (K0->getValueAPF() > K1->getValueAPF()) 9592 return SDValue(); 9593 9594 const MachineFunction &MF = DAG.getMachineFunction(); 9595 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9596 9597 // TODO: Check IEEE bit enabled? 9598 EVT VT = Op0.getValueType(); 9599 if (Info->getMode().DX10Clamp) { 9600 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9601 // hardware fmed3 behavior converting to a min. 9602 // FIXME: Should this be allowing -0.0? 9603 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9604 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9605 } 9606 9607 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9608 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9609 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9610 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9611 // then give the other result, which is different from med3 with a NaN 9612 // input. 9613 SDValue Var = Op0.getOperand(0); 9614 if (!DAG.isKnownNeverSNaN(Var)) 9615 return SDValue(); 9616 9617 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9618 9619 if ((!K0->hasOneUse() || 9620 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9621 (!K1->hasOneUse() || 9622 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9623 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9624 Var, SDValue(K0, 0), SDValue(K1, 0)); 9625 } 9626 } 9627 9628 return SDValue(); 9629 } 9630 9631 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9632 DAGCombinerInfo &DCI) const { 9633 SelectionDAG &DAG = DCI.DAG; 9634 9635 EVT VT = N->getValueType(0); 9636 unsigned Opc = N->getOpcode(); 9637 SDValue Op0 = N->getOperand(0); 9638 SDValue Op1 = N->getOperand(1); 9639 9640 // Only do this if the inner op has one use since this will just increases 9641 // register pressure for no benefit. 9642 9643 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9644 !VT.isVector() && 9645 (VT == MVT::i32 || VT == MVT::f32 || 9646 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9647 // max(max(a, b), c) -> max3(a, b, c) 9648 // min(min(a, b), c) -> min3(a, b, c) 9649 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9650 SDLoc DL(N); 9651 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9652 DL, 9653 N->getValueType(0), 9654 Op0.getOperand(0), 9655 Op0.getOperand(1), 9656 Op1); 9657 } 9658 9659 // Try commuted. 9660 // max(a, max(b, c)) -> max3(a, b, c) 9661 // min(a, min(b, c)) -> min3(a, b, c) 9662 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9663 SDLoc DL(N); 9664 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9665 DL, 9666 N->getValueType(0), 9667 Op0, 9668 Op1.getOperand(0), 9669 Op1.getOperand(1)); 9670 } 9671 } 9672 9673 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9674 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9675 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9676 return Med3; 9677 } 9678 9679 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9680 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9681 return Med3; 9682 } 9683 9684 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9685 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9686 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9687 (Opc == AMDGPUISD::FMIN_LEGACY && 9688 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9689 (VT == MVT::f32 || VT == MVT::f64 || 9690 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9691 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9692 Op0.hasOneUse()) { 9693 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9694 return Res; 9695 } 9696 9697 return SDValue(); 9698 } 9699 9700 static bool isClampZeroToOne(SDValue A, SDValue B) { 9701 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9702 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9703 // FIXME: Should this be allowing -0.0? 9704 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9705 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9706 } 9707 } 9708 9709 return false; 9710 } 9711 9712 // FIXME: Should only worry about snans for version with chain. 9713 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9714 DAGCombinerInfo &DCI) const { 9715 EVT VT = N->getValueType(0); 9716 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9717 // NaNs. With a NaN input, the order of the operands may change the result. 9718 9719 SelectionDAG &DAG = DCI.DAG; 9720 SDLoc SL(N); 9721 9722 SDValue Src0 = N->getOperand(0); 9723 SDValue Src1 = N->getOperand(1); 9724 SDValue Src2 = N->getOperand(2); 9725 9726 if (isClampZeroToOne(Src0, Src1)) { 9727 // const_a, const_b, x -> clamp is safe in all cases including signaling 9728 // nans. 9729 // FIXME: Should this be allowing -0.0? 9730 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9731 } 9732 9733 const MachineFunction &MF = DAG.getMachineFunction(); 9734 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9735 9736 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9737 // handling no dx10-clamp? 9738 if (Info->getMode().DX10Clamp) { 9739 // If NaNs is clamped to 0, we are free to reorder the inputs. 9740 9741 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9742 std::swap(Src0, Src1); 9743 9744 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9745 std::swap(Src1, Src2); 9746 9747 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9748 std::swap(Src0, Src1); 9749 9750 if (isClampZeroToOne(Src1, Src2)) 9751 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9752 } 9753 9754 return SDValue(); 9755 } 9756 9757 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9758 DAGCombinerInfo &DCI) const { 9759 SDValue Src0 = N->getOperand(0); 9760 SDValue Src1 = N->getOperand(1); 9761 if (Src0.isUndef() && Src1.isUndef()) 9762 return DCI.DAG.getUNDEF(N->getValueType(0)); 9763 return SDValue(); 9764 } 9765 9766 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9767 // expanded into a set of cmp/select instructions. 9768 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9769 unsigned NumElem, 9770 bool IsDivergentIdx) { 9771 if (UseDivergentRegisterIndexing) 9772 return false; 9773 9774 unsigned VecSize = EltSize * NumElem; 9775 9776 // Sub-dword vectors of size 2 dword or less have better implementation. 9777 if (VecSize <= 64 && EltSize < 32) 9778 return false; 9779 9780 // Always expand the rest of sub-dword instructions, otherwise it will be 9781 // lowered via memory. 9782 if (EltSize < 32) 9783 return true; 9784 9785 // Always do this if var-idx is divergent, otherwise it will become a loop. 9786 if (IsDivergentIdx) 9787 return true; 9788 9789 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9790 unsigned NumInsts = NumElem /* Number of compares */ + 9791 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9792 return NumInsts <= 16; 9793 } 9794 9795 static bool shouldExpandVectorDynExt(SDNode *N) { 9796 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9797 if (isa<ConstantSDNode>(Idx)) 9798 return false; 9799 9800 SDValue Vec = N->getOperand(0); 9801 EVT VecVT = Vec.getValueType(); 9802 EVT EltVT = VecVT.getVectorElementType(); 9803 unsigned EltSize = EltVT.getSizeInBits(); 9804 unsigned NumElem = VecVT.getVectorNumElements(); 9805 9806 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9807 Idx->isDivergent()); 9808 } 9809 9810 SDValue SITargetLowering::performExtractVectorEltCombine( 9811 SDNode *N, DAGCombinerInfo &DCI) const { 9812 SDValue Vec = N->getOperand(0); 9813 SelectionDAG &DAG = DCI.DAG; 9814 9815 EVT VecVT = Vec.getValueType(); 9816 EVT EltVT = VecVT.getVectorElementType(); 9817 9818 if ((Vec.getOpcode() == ISD::FNEG || 9819 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9820 SDLoc SL(N); 9821 EVT EltVT = N->getValueType(0); 9822 SDValue Idx = N->getOperand(1); 9823 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9824 Vec.getOperand(0), Idx); 9825 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9826 } 9827 9828 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9829 // => 9830 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9831 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9832 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9833 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9834 SDLoc SL(N); 9835 EVT EltVT = N->getValueType(0); 9836 SDValue Idx = N->getOperand(1); 9837 unsigned Opc = Vec.getOpcode(); 9838 9839 switch(Opc) { 9840 default: 9841 break; 9842 // TODO: Support other binary operations. 9843 case ISD::FADD: 9844 case ISD::FSUB: 9845 case ISD::FMUL: 9846 case ISD::ADD: 9847 case ISD::UMIN: 9848 case ISD::UMAX: 9849 case ISD::SMIN: 9850 case ISD::SMAX: 9851 case ISD::FMAXNUM: 9852 case ISD::FMINNUM: 9853 case ISD::FMAXNUM_IEEE: 9854 case ISD::FMINNUM_IEEE: { 9855 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9856 Vec.getOperand(0), Idx); 9857 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9858 Vec.getOperand(1), Idx); 9859 9860 DCI.AddToWorklist(Elt0.getNode()); 9861 DCI.AddToWorklist(Elt1.getNode()); 9862 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9863 } 9864 } 9865 } 9866 9867 unsigned VecSize = VecVT.getSizeInBits(); 9868 unsigned EltSize = EltVT.getSizeInBits(); 9869 9870 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9871 if (::shouldExpandVectorDynExt(N)) { 9872 SDLoc SL(N); 9873 SDValue Idx = N->getOperand(1); 9874 SDValue V; 9875 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9876 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9877 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9878 if (I == 0) 9879 V = Elt; 9880 else 9881 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9882 } 9883 return V; 9884 } 9885 9886 if (!DCI.isBeforeLegalize()) 9887 return SDValue(); 9888 9889 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9890 // elements. This exposes more load reduction opportunities by replacing 9891 // multiple small extract_vector_elements with a single 32-bit extract. 9892 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9893 if (isa<MemSDNode>(Vec) && 9894 EltSize <= 16 && 9895 EltVT.isByteSized() && 9896 VecSize > 32 && 9897 VecSize % 32 == 0 && 9898 Idx) { 9899 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9900 9901 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9902 unsigned EltIdx = BitIndex / 32; 9903 unsigned LeftoverBitIdx = BitIndex % 32; 9904 SDLoc SL(N); 9905 9906 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9907 DCI.AddToWorklist(Cast.getNode()); 9908 9909 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9910 DAG.getConstant(EltIdx, SL, MVT::i32)); 9911 DCI.AddToWorklist(Elt.getNode()); 9912 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9913 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9914 DCI.AddToWorklist(Srl.getNode()); 9915 9916 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9917 DCI.AddToWorklist(Trunc.getNode()); 9918 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9919 } 9920 9921 return SDValue(); 9922 } 9923 9924 SDValue 9925 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9926 DAGCombinerInfo &DCI) const { 9927 SDValue Vec = N->getOperand(0); 9928 SDValue Idx = N->getOperand(2); 9929 EVT VecVT = Vec.getValueType(); 9930 EVT EltVT = VecVT.getVectorElementType(); 9931 9932 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9933 // => BUILD_VECTOR n x select (e, const-idx) 9934 if (!::shouldExpandVectorDynExt(N)) 9935 return SDValue(); 9936 9937 SelectionDAG &DAG = DCI.DAG; 9938 SDLoc SL(N); 9939 SDValue Ins = N->getOperand(1); 9940 EVT IdxVT = Idx.getValueType(); 9941 9942 SmallVector<SDValue, 16> Ops; 9943 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9944 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9945 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9946 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9947 Ops.push_back(V); 9948 } 9949 9950 return DAG.getBuildVector(VecVT, SL, Ops); 9951 } 9952 9953 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9954 const SDNode *N0, 9955 const SDNode *N1) const { 9956 EVT VT = N0->getValueType(0); 9957 9958 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9959 // support denormals ever. 9960 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9961 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9962 getSubtarget()->hasMadF16())) && 9963 isOperationLegal(ISD::FMAD, VT)) 9964 return ISD::FMAD; 9965 9966 const TargetOptions &Options = DAG.getTarget().Options; 9967 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9968 (N0->getFlags().hasAllowContract() && 9969 N1->getFlags().hasAllowContract())) && 9970 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9971 return ISD::FMA; 9972 } 9973 9974 return 0; 9975 } 9976 9977 // For a reassociatable opcode perform: 9978 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9979 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9980 SelectionDAG &DAG) const { 9981 EVT VT = N->getValueType(0); 9982 if (VT != MVT::i32 && VT != MVT::i64) 9983 return SDValue(); 9984 9985 unsigned Opc = N->getOpcode(); 9986 SDValue Op0 = N->getOperand(0); 9987 SDValue Op1 = N->getOperand(1); 9988 9989 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9990 return SDValue(); 9991 9992 if (Op0->isDivergent()) 9993 std::swap(Op0, Op1); 9994 9995 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9996 return SDValue(); 9997 9998 SDValue Op2 = Op1.getOperand(1); 9999 Op1 = Op1.getOperand(0); 10000 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10001 return SDValue(); 10002 10003 if (Op1->isDivergent()) 10004 std::swap(Op1, Op2); 10005 10006 // If either operand is constant this will conflict with 10007 // DAGCombiner::ReassociateOps(). 10008 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10009 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10010 return SDValue(); 10011 10012 SDLoc SL(N); 10013 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10014 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10015 } 10016 10017 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10018 EVT VT, 10019 SDValue N0, SDValue N1, SDValue N2, 10020 bool Signed) { 10021 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10022 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10023 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10024 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10025 } 10026 10027 SDValue SITargetLowering::performAddCombine(SDNode *N, 10028 DAGCombinerInfo &DCI) const { 10029 SelectionDAG &DAG = DCI.DAG; 10030 EVT VT = N->getValueType(0); 10031 SDLoc SL(N); 10032 SDValue LHS = N->getOperand(0); 10033 SDValue RHS = N->getOperand(1); 10034 10035 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10036 && Subtarget->hasMad64_32() && 10037 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10038 VT.getScalarSizeInBits() <= 64) { 10039 if (LHS.getOpcode() != ISD::MUL) 10040 std::swap(LHS, RHS); 10041 10042 SDValue MulLHS = LHS.getOperand(0); 10043 SDValue MulRHS = LHS.getOperand(1); 10044 SDValue AddRHS = RHS; 10045 10046 // TODO: Maybe restrict if SGPR inputs. 10047 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10048 numBitsUnsigned(MulRHS, DAG) <= 32) { 10049 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10050 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10051 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10052 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10053 } 10054 10055 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10056 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10057 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10058 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10059 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10060 } 10061 10062 return SDValue(); 10063 } 10064 10065 if (SDValue V = reassociateScalarOps(N, DAG)) { 10066 return V; 10067 } 10068 10069 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10070 return SDValue(); 10071 10072 // add x, zext (setcc) => addcarry x, 0, setcc 10073 // add x, sext (setcc) => subcarry x, 0, setcc 10074 unsigned Opc = LHS.getOpcode(); 10075 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10076 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10077 std::swap(RHS, LHS); 10078 10079 Opc = RHS.getOpcode(); 10080 switch (Opc) { 10081 default: break; 10082 case ISD::ZERO_EXTEND: 10083 case ISD::SIGN_EXTEND: 10084 case ISD::ANY_EXTEND: { 10085 auto Cond = RHS.getOperand(0); 10086 // If this won't be a real VOPC output, we would still need to insert an 10087 // extra instruction anyway. 10088 if (!isBoolSGPR(Cond)) 10089 break; 10090 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10091 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10092 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10093 return DAG.getNode(Opc, SL, VTList, Args); 10094 } 10095 case ISD::ADDCARRY: { 10096 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10097 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10098 if (!C || C->getZExtValue() != 0) break; 10099 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10100 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10101 } 10102 } 10103 return SDValue(); 10104 } 10105 10106 SDValue SITargetLowering::performSubCombine(SDNode *N, 10107 DAGCombinerInfo &DCI) const { 10108 SelectionDAG &DAG = DCI.DAG; 10109 EVT VT = N->getValueType(0); 10110 10111 if (VT != MVT::i32) 10112 return SDValue(); 10113 10114 SDLoc SL(N); 10115 SDValue LHS = N->getOperand(0); 10116 SDValue RHS = N->getOperand(1); 10117 10118 // sub x, zext (setcc) => subcarry x, 0, setcc 10119 // sub x, sext (setcc) => addcarry x, 0, setcc 10120 unsigned Opc = RHS.getOpcode(); 10121 switch (Opc) { 10122 default: break; 10123 case ISD::ZERO_EXTEND: 10124 case ISD::SIGN_EXTEND: 10125 case ISD::ANY_EXTEND: { 10126 auto Cond = RHS.getOperand(0); 10127 // If this won't be a real VOPC output, we would still need to insert an 10128 // extra instruction anyway. 10129 if (!isBoolSGPR(Cond)) 10130 break; 10131 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10132 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10133 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10134 return DAG.getNode(Opc, SL, VTList, Args); 10135 } 10136 } 10137 10138 if (LHS.getOpcode() == ISD::SUBCARRY) { 10139 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10140 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10141 if (!C || !C->isNullValue()) 10142 return SDValue(); 10143 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10144 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10145 } 10146 return SDValue(); 10147 } 10148 10149 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10150 DAGCombinerInfo &DCI) const { 10151 10152 if (N->getValueType(0) != MVT::i32) 10153 return SDValue(); 10154 10155 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10156 if (!C || C->getZExtValue() != 0) 10157 return SDValue(); 10158 10159 SelectionDAG &DAG = DCI.DAG; 10160 SDValue LHS = N->getOperand(0); 10161 10162 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10163 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10164 unsigned LHSOpc = LHS.getOpcode(); 10165 unsigned Opc = N->getOpcode(); 10166 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10167 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10168 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10169 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10170 } 10171 return SDValue(); 10172 } 10173 10174 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10175 DAGCombinerInfo &DCI) const { 10176 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10177 return SDValue(); 10178 10179 SelectionDAG &DAG = DCI.DAG; 10180 EVT VT = N->getValueType(0); 10181 10182 SDLoc SL(N); 10183 SDValue LHS = N->getOperand(0); 10184 SDValue RHS = N->getOperand(1); 10185 10186 // These should really be instruction patterns, but writing patterns with 10187 // source modiifiers is a pain. 10188 10189 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10190 if (LHS.getOpcode() == ISD::FADD) { 10191 SDValue A = LHS.getOperand(0); 10192 if (A == LHS.getOperand(1)) { 10193 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10194 if (FusedOp != 0) { 10195 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10196 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10197 } 10198 } 10199 } 10200 10201 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10202 if (RHS.getOpcode() == ISD::FADD) { 10203 SDValue A = RHS.getOperand(0); 10204 if (A == RHS.getOperand(1)) { 10205 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10206 if (FusedOp != 0) { 10207 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10208 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10209 } 10210 } 10211 } 10212 10213 return SDValue(); 10214 } 10215 10216 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10217 DAGCombinerInfo &DCI) const { 10218 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10219 return SDValue(); 10220 10221 SelectionDAG &DAG = DCI.DAG; 10222 SDLoc SL(N); 10223 EVT VT = N->getValueType(0); 10224 assert(!VT.isVector()); 10225 10226 // Try to get the fneg to fold into the source modifier. This undoes generic 10227 // DAG combines and folds them into the mad. 10228 // 10229 // Only do this if we are not trying to support denormals. v_mad_f32 does 10230 // not support denormals ever. 10231 SDValue LHS = N->getOperand(0); 10232 SDValue RHS = N->getOperand(1); 10233 if (LHS.getOpcode() == ISD::FADD) { 10234 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10235 SDValue A = LHS.getOperand(0); 10236 if (A == LHS.getOperand(1)) { 10237 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10238 if (FusedOp != 0){ 10239 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10240 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10241 10242 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10243 } 10244 } 10245 } 10246 10247 if (RHS.getOpcode() == ISD::FADD) { 10248 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10249 10250 SDValue A = RHS.getOperand(0); 10251 if (A == RHS.getOperand(1)) { 10252 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10253 if (FusedOp != 0){ 10254 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10255 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10256 } 10257 } 10258 } 10259 10260 return SDValue(); 10261 } 10262 10263 SDValue SITargetLowering::performFMACombine(SDNode *N, 10264 DAGCombinerInfo &DCI) const { 10265 SelectionDAG &DAG = DCI.DAG; 10266 EVT VT = N->getValueType(0); 10267 SDLoc SL(N); 10268 10269 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10270 return SDValue(); 10271 10272 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10273 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10274 SDValue Op1 = N->getOperand(0); 10275 SDValue Op2 = N->getOperand(1); 10276 SDValue FMA = N->getOperand(2); 10277 10278 if (FMA.getOpcode() != ISD::FMA || 10279 Op1.getOpcode() != ISD::FP_EXTEND || 10280 Op2.getOpcode() != ISD::FP_EXTEND) 10281 return SDValue(); 10282 10283 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10284 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10285 // is sufficient to allow generaing fdot2. 10286 const TargetOptions &Options = DAG.getTarget().Options; 10287 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10288 (N->getFlags().hasAllowContract() && 10289 FMA->getFlags().hasAllowContract())) { 10290 Op1 = Op1.getOperand(0); 10291 Op2 = Op2.getOperand(0); 10292 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10293 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10294 return SDValue(); 10295 10296 SDValue Vec1 = Op1.getOperand(0); 10297 SDValue Idx1 = Op1.getOperand(1); 10298 SDValue Vec2 = Op2.getOperand(0); 10299 10300 SDValue FMAOp1 = FMA.getOperand(0); 10301 SDValue FMAOp2 = FMA.getOperand(1); 10302 SDValue FMAAcc = FMA.getOperand(2); 10303 10304 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10305 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10306 return SDValue(); 10307 10308 FMAOp1 = FMAOp1.getOperand(0); 10309 FMAOp2 = FMAOp2.getOperand(0); 10310 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10311 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10312 return SDValue(); 10313 10314 SDValue Vec3 = FMAOp1.getOperand(0); 10315 SDValue Vec4 = FMAOp2.getOperand(0); 10316 SDValue Idx2 = FMAOp1.getOperand(1); 10317 10318 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10319 // Idx1 and Idx2 cannot be the same. 10320 Idx1 == Idx2) 10321 return SDValue(); 10322 10323 if (Vec1 == Vec2 || Vec3 == Vec4) 10324 return SDValue(); 10325 10326 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10327 return SDValue(); 10328 10329 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10330 (Vec1 == Vec4 && Vec2 == Vec3)) { 10331 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10332 DAG.getTargetConstant(0, SL, MVT::i1)); 10333 } 10334 } 10335 return SDValue(); 10336 } 10337 10338 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10339 DAGCombinerInfo &DCI) const { 10340 SelectionDAG &DAG = DCI.DAG; 10341 SDLoc SL(N); 10342 10343 SDValue LHS = N->getOperand(0); 10344 SDValue RHS = N->getOperand(1); 10345 EVT VT = LHS.getValueType(); 10346 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10347 10348 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10349 if (!CRHS) { 10350 CRHS = dyn_cast<ConstantSDNode>(LHS); 10351 if (CRHS) { 10352 std::swap(LHS, RHS); 10353 CC = getSetCCSwappedOperands(CC); 10354 } 10355 } 10356 10357 if (CRHS) { 10358 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10359 isBoolSGPR(LHS.getOperand(0))) { 10360 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10361 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10362 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10363 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10364 if ((CRHS->isAllOnesValue() && 10365 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10366 (CRHS->isNullValue() && 10367 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10368 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10369 DAG.getConstant(-1, SL, MVT::i1)); 10370 if ((CRHS->isAllOnesValue() && 10371 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10372 (CRHS->isNullValue() && 10373 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10374 return LHS.getOperand(0); 10375 } 10376 10377 uint64_t CRHSVal = CRHS->getZExtValue(); 10378 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10379 LHS.getOpcode() == ISD::SELECT && 10380 isa<ConstantSDNode>(LHS.getOperand(1)) && 10381 isa<ConstantSDNode>(LHS.getOperand(2)) && 10382 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10383 isBoolSGPR(LHS.getOperand(0))) { 10384 // Given CT != FT: 10385 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10386 // setcc (select cc, CT, CF), CF, ne => cc 10387 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10388 // setcc (select cc, CT, CF), CT, eq => cc 10389 uint64_t CT = LHS.getConstantOperandVal(1); 10390 uint64_t CF = LHS.getConstantOperandVal(2); 10391 10392 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10393 (CT == CRHSVal && CC == ISD::SETNE)) 10394 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10395 DAG.getConstant(-1, SL, MVT::i1)); 10396 if ((CF == CRHSVal && CC == ISD::SETNE) || 10397 (CT == CRHSVal && CC == ISD::SETEQ)) 10398 return LHS.getOperand(0); 10399 } 10400 } 10401 10402 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10403 VT != MVT::f16)) 10404 return SDValue(); 10405 10406 // Match isinf/isfinite pattern 10407 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10408 // (fcmp one (fabs x), inf) -> (fp_class x, 10409 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10410 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10411 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10412 if (!CRHS) 10413 return SDValue(); 10414 10415 const APFloat &APF = CRHS->getValueAPF(); 10416 if (APF.isInfinity() && !APF.isNegative()) { 10417 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10418 SIInstrFlags::N_INFINITY; 10419 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10420 SIInstrFlags::P_ZERO | 10421 SIInstrFlags::N_NORMAL | 10422 SIInstrFlags::P_NORMAL | 10423 SIInstrFlags::N_SUBNORMAL | 10424 SIInstrFlags::P_SUBNORMAL; 10425 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10426 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10427 DAG.getConstant(Mask, SL, MVT::i32)); 10428 } 10429 } 10430 10431 return SDValue(); 10432 } 10433 10434 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10435 DAGCombinerInfo &DCI) const { 10436 SelectionDAG &DAG = DCI.DAG; 10437 SDLoc SL(N); 10438 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10439 10440 SDValue Src = N->getOperand(0); 10441 SDValue Shift = N->getOperand(0); 10442 10443 // TODO: Extend type shouldn't matter (assuming legal types). 10444 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10445 Shift = Shift.getOperand(0); 10446 10447 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10448 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10449 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10450 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10451 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10452 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10453 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10454 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10455 SDLoc(Shift.getOperand(0)), MVT::i32); 10456 10457 unsigned ShiftOffset = 8 * Offset; 10458 if (Shift.getOpcode() == ISD::SHL) 10459 ShiftOffset -= C->getZExtValue(); 10460 else 10461 ShiftOffset += C->getZExtValue(); 10462 10463 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10464 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10465 MVT::f32, Shift); 10466 } 10467 } 10468 } 10469 10470 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10471 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10472 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10473 // We simplified Src. If this node is not dead, visit it again so it is 10474 // folded properly. 10475 if (N->getOpcode() != ISD::DELETED_NODE) 10476 DCI.AddToWorklist(N); 10477 return SDValue(N, 0); 10478 } 10479 10480 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10481 if (SDValue DemandedSrc = 10482 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10483 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10484 10485 return SDValue(); 10486 } 10487 10488 SDValue SITargetLowering::performClampCombine(SDNode *N, 10489 DAGCombinerInfo &DCI) const { 10490 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10491 if (!CSrc) 10492 return SDValue(); 10493 10494 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10495 const APFloat &F = CSrc->getValueAPF(); 10496 APFloat Zero = APFloat::getZero(F.getSemantics()); 10497 if (F < Zero || 10498 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10499 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10500 } 10501 10502 APFloat One(F.getSemantics(), "1.0"); 10503 if (F > One) 10504 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10505 10506 return SDValue(CSrc, 0); 10507 } 10508 10509 10510 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10511 DAGCombinerInfo &DCI) const { 10512 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10513 return SDValue(); 10514 switch (N->getOpcode()) { 10515 default: 10516 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10517 case ISD::ADD: 10518 return performAddCombine(N, DCI); 10519 case ISD::SUB: 10520 return performSubCombine(N, DCI); 10521 case ISD::ADDCARRY: 10522 case ISD::SUBCARRY: 10523 return performAddCarrySubCarryCombine(N, DCI); 10524 case ISD::FADD: 10525 return performFAddCombine(N, DCI); 10526 case ISD::FSUB: 10527 return performFSubCombine(N, DCI); 10528 case ISD::SETCC: 10529 return performSetCCCombine(N, DCI); 10530 case ISD::FMAXNUM: 10531 case ISD::FMINNUM: 10532 case ISD::FMAXNUM_IEEE: 10533 case ISD::FMINNUM_IEEE: 10534 case ISD::SMAX: 10535 case ISD::SMIN: 10536 case ISD::UMAX: 10537 case ISD::UMIN: 10538 case AMDGPUISD::FMIN_LEGACY: 10539 case AMDGPUISD::FMAX_LEGACY: 10540 return performMinMaxCombine(N, DCI); 10541 case ISD::FMA: 10542 return performFMACombine(N, DCI); 10543 case ISD::LOAD: { 10544 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10545 return Widended; 10546 LLVM_FALLTHROUGH; 10547 } 10548 case ISD::STORE: 10549 case ISD::ATOMIC_LOAD: 10550 case ISD::ATOMIC_STORE: 10551 case ISD::ATOMIC_CMP_SWAP: 10552 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10553 case ISD::ATOMIC_SWAP: 10554 case ISD::ATOMIC_LOAD_ADD: 10555 case ISD::ATOMIC_LOAD_SUB: 10556 case ISD::ATOMIC_LOAD_AND: 10557 case ISD::ATOMIC_LOAD_OR: 10558 case ISD::ATOMIC_LOAD_XOR: 10559 case ISD::ATOMIC_LOAD_NAND: 10560 case ISD::ATOMIC_LOAD_MIN: 10561 case ISD::ATOMIC_LOAD_MAX: 10562 case ISD::ATOMIC_LOAD_UMIN: 10563 case ISD::ATOMIC_LOAD_UMAX: 10564 case ISD::ATOMIC_LOAD_FADD: 10565 case AMDGPUISD::ATOMIC_INC: 10566 case AMDGPUISD::ATOMIC_DEC: 10567 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10568 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10569 if (DCI.isBeforeLegalize()) 10570 break; 10571 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10572 case ISD::AND: 10573 return performAndCombine(N, DCI); 10574 case ISD::OR: 10575 return performOrCombine(N, DCI); 10576 case ISD::XOR: 10577 return performXorCombine(N, DCI); 10578 case ISD::ZERO_EXTEND: 10579 return performZeroExtendCombine(N, DCI); 10580 case ISD::SIGN_EXTEND_INREG: 10581 return performSignExtendInRegCombine(N , DCI); 10582 case AMDGPUISD::FP_CLASS: 10583 return performClassCombine(N, DCI); 10584 case ISD::FCANONICALIZE: 10585 return performFCanonicalizeCombine(N, DCI); 10586 case AMDGPUISD::RCP: 10587 return performRcpCombine(N, DCI); 10588 case AMDGPUISD::FRACT: 10589 case AMDGPUISD::RSQ: 10590 case AMDGPUISD::RCP_LEGACY: 10591 case AMDGPUISD::RCP_IFLAG: 10592 case AMDGPUISD::RSQ_CLAMP: 10593 case AMDGPUISD::LDEXP: { 10594 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10595 SDValue Src = N->getOperand(0); 10596 if (Src.isUndef()) 10597 return Src; 10598 break; 10599 } 10600 case ISD::SINT_TO_FP: 10601 case ISD::UINT_TO_FP: 10602 return performUCharToFloatCombine(N, DCI); 10603 case AMDGPUISD::CVT_F32_UBYTE0: 10604 case AMDGPUISD::CVT_F32_UBYTE1: 10605 case AMDGPUISD::CVT_F32_UBYTE2: 10606 case AMDGPUISD::CVT_F32_UBYTE3: 10607 return performCvtF32UByteNCombine(N, DCI); 10608 case AMDGPUISD::FMED3: 10609 return performFMed3Combine(N, DCI); 10610 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10611 return performCvtPkRTZCombine(N, DCI); 10612 case AMDGPUISD::CLAMP: 10613 return performClampCombine(N, DCI); 10614 case ISD::SCALAR_TO_VECTOR: { 10615 SelectionDAG &DAG = DCI.DAG; 10616 EVT VT = N->getValueType(0); 10617 10618 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10619 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10620 SDLoc SL(N); 10621 SDValue Src = N->getOperand(0); 10622 EVT EltVT = Src.getValueType(); 10623 if (EltVT == MVT::f16) 10624 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10625 10626 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10627 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10628 } 10629 10630 break; 10631 } 10632 case ISD::EXTRACT_VECTOR_ELT: 10633 return performExtractVectorEltCombine(N, DCI); 10634 case ISD::INSERT_VECTOR_ELT: 10635 return performInsertVectorEltCombine(N, DCI); 10636 } 10637 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10638 } 10639 10640 /// Helper function for adjustWritemask 10641 static unsigned SubIdx2Lane(unsigned Idx) { 10642 switch (Idx) { 10643 default: return 0; 10644 case AMDGPU::sub0: return 0; 10645 case AMDGPU::sub1: return 1; 10646 case AMDGPU::sub2: return 2; 10647 case AMDGPU::sub3: return 3; 10648 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10649 } 10650 } 10651 10652 /// Adjust the writemask of MIMG instructions 10653 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10654 SelectionDAG &DAG) const { 10655 unsigned Opcode = Node->getMachineOpcode(); 10656 10657 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10658 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10659 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10660 return Node; // not implemented for D16 10661 10662 SDNode *Users[5] = { nullptr }; 10663 unsigned Lane = 0; 10664 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10665 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10666 unsigned NewDmask = 0; 10667 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10668 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10669 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10670 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10671 unsigned TFCLane = 0; 10672 bool HasChain = Node->getNumValues() > 1; 10673 10674 if (OldDmask == 0) { 10675 // These are folded out, but on the chance it happens don't assert. 10676 return Node; 10677 } 10678 10679 unsigned OldBitsSet = countPopulation(OldDmask); 10680 // Work out which is the TFE/LWE lane if that is enabled. 10681 if (UsesTFC) { 10682 TFCLane = OldBitsSet; 10683 } 10684 10685 // Try to figure out the used register components 10686 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10687 I != E; ++I) { 10688 10689 // Don't look at users of the chain. 10690 if (I.getUse().getResNo() != 0) 10691 continue; 10692 10693 // Abort if we can't understand the usage 10694 if (!I->isMachineOpcode() || 10695 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10696 return Node; 10697 10698 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10699 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10700 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10701 // set, etc. 10702 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10703 10704 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10705 if (UsesTFC && Lane == TFCLane) { 10706 Users[Lane] = *I; 10707 } else { 10708 // Set which texture component corresponds to the lane. 10709 unsigned Comp; 10710 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10711 Comp = countTrailingZeros(Dmask); 10712 Dmask &= ~(1 << Comp); 10713 } 10714 10715 // Abort if we have more than one user per component. 10716 if (Users[Lane]) 10717 return Node; 10718 10719 Users[Lane] = *I; 10720 NewDmask |= 1 << Comp; 10721 } 10722 } 10723 10724 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10725 bool NoChannels = !NewDmask; 10726 if (NoChannels) { 10727 if (!UsesTFC) { 10728 // No uses of the result and not using TFC. Then do nothing. 10729 return Node; 10730 } 10731 // If the original dmask has one channel - then nothing to do 10732 if (OldBitsSet == 1) 10733 return Node; 10734 // Use an arbitrary dmask - required for the instruction to work 10735 NewDmask = 1; 10736 } 10737 // Abort if there's no change 10738 if (NewDmask == OldDmask) 10739 return Node; 10740 10741 unsigned BitsSet = countPopulation(NewDmask); 10742 10743 // Check for TFE or LWE - increase the number of channels by one to account 10744 // for the extra return value 10745 // This will need adjustment for D16 if this is also included in 10746 // adjustWriteMask (this function) but at present D16 are excluded. 10747 unsigned NewChannels = BitsSet + UsesTFC; 10748 10749 int NewOpcode = 10750 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10751 assert(NewOpcode != -1 && 10752 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10753 "failed to find equivalent MIMG op"); 10754 10755 // Adjust the writemask in the node 10756 SmallVector<SDValue, 12> Ops; 10757 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10758 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10759 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10760 10761 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10762 10763 MVT ResultVT = NewChannels == 1 ? 10764 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10765 NewChannels == 5 ? 8 : NewChannels); 10766 SDVTList NewVTList = HasChain ? 10767 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10768 10769 10770 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10771 NewVTList, Ops); 10772 10773 if (HasChain) { 10774 // Update chain. 10775 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10776 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10777 } 10778 10779 if (NewChannels == 1) { 10780 assert(Node->hasNUsesOfValue(1, 0)); 10781 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10782 SDLoc(Node), Users[Lane]->getValueType(0), 10783 SDValue(NewNode, 0)); 10784 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10785 return nullptr; 10786 } 10787 10788 // Update the users of the node with the new indices 10789 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10790 SDNode *User = Users[i]; 10791 if (!User) { 10792 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10793 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10794 if (i || !NoChannels) 10795 continue; 10796 } else { 10797 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10798 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10799 } 10800 10801 switch (Idx) { 10802 default: break; 10803 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10804 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10805 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10806 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10807 } 10808 } 10809 10810 DAG.RemoveDeadNode(Node); 10811 return nullptr; 10812 } 10813 10814 static bool isFrameIndexOp(SDValue Op) { 10815 if (Op.getOpcode() == ISD::AssertZext) 10816 Op = Op.getOperand(0); 10817 10818 return isa<FrameIndexSDNode>(Op); 10819 } 10820 10821 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10822 /// with frame index operands. 10823 /// LLVM assumes that inputs are to these instructions are registers. 10824 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10825 SelectionDAG &DAG) const { 10826 if (Node->getOpcode() == ISD::CopyToReg) { 10827 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10828 SDValue SrcVal = Node->getOperand(2); 10829 10830 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10831 // to try understanding copies to physical registers. 10832 if (SrcVal.getValueType() == MVT::i1 && 10833 Register::isPhysicalRegister(DestReg->getReg())) { 10834 SDLoc SL(Node); 10835 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10836 SDValue VReg = DAG.getRegister( 10837 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10838 10839 SDNode *Glued = Node->getGluedNode(); 10840 SDValue ToVReg 10841 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10842 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10843 SDValue ToResultReg 10844 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10845 VReg, ToVReg.getValue(1)); 10846 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10847 DAG.RemoveDeadNode(Node); 10848 return ToResultReg.getNode(); 10849 } 10850 } 10851 10852 SmallVector<SDValue, 8> Ops; 10853 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10854 if (!isFrameIndexOp(Node->getOperand(i))) { 10855 Ops.push_back(Node->getOperand(i)); 10856 continue; 10857 } 10858 10859 SDLoc DL(Node); 10860 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10861 Node->getOperand(i).getValueType(), 10862 Node->getOperand(i)), 0)); 10863 } 10864 10865 return DAG.UpdateNodeOperands(Node, Ops); 10866 } 10867 10868 /// Fold the instructions after selecting them. 10869 /// Returns null if users were already updated. 10870 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10871 SelectionDAG &DAG) const { 10872 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10873 unsigned Opcode = Node->getMachineOpcode(); 10874 10875 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10876 !TII->isGather4(Opcode)) { 10877 return adjustWritemask(Node, DAG); 10878 } 10879 10880 if (Opcode == AMDGPU::INSERT_SUBREG || 10881 Opcode == AMDGPU::REG_SEQUENCE) { 10882 legalizeTargetIndependentNode(Node, DAG); 10883 return Node; 10884 } 10885 10886 switch (Opcode) { 10887 case AMDGPU::V_DIV_SCALE_F32: 10888 case AMDGPU::V_DIV_SCALE_F64: { 10889 // Satisfy the operand register constraint when one of the inputs is 10890 // undefined. Ordinarily each undef value will have its own implicit_def of 10891 // a vreg, so force these to use a single register. 10892 SDValue Src0 = Node->getOperand(0); 10893 SDValue Src1 = Node->getOperand(1); 10894 SDValue Src2 = Node->getOperand(2); 10895 10896 if ((Src0.isMachineOpcode() && 10897 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10898 (Src0 == Src1 || Src0 == Src2)) 10899 break; 10900 10901 MVT VT = Src0.getValueType().getSimpleVT(); 10902 const TargetRegisterClass *RC = 10903 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10904 10905 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10906 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10907 10908 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10909 UndefReg, Src0, SDValue()); 10910 10911 // src0 must be the same register as src1 or src2, even if the value is 10912 // undefined, so make sure we don't violate this constraint. 10913 if (Src0.isMachineOpcode() && 10914 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10915 if (Src1.isMachineOpcode() && 10916 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10917 Src0 = Src1; 10918 else if (Src2.isMachineOpcode() && 10919 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10920 Src0 = Src2; 10921 else { 10922 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10923 Src0 = UndefReg; 10924 Src1 = UndefReg; 10925 } 10926 } else 10927 break; 10928 10929 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10930 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10931 Ops.push_back(Node->getOperand(I)); 10932 10933 Ops.push_back(ImpDef.getValue(1)); 10934 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10935 } 10936 default: 10937 break; 10938 } 10939 10940 return Node; 10941 } 10942 10943 /// Assign the register class depending on the number of 10944 /// bits set in the writemask 10945 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10946 SDNode *Node) const { 10947 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10948 10949 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10950 10951 if (TII->isVOP3(MI.getOpcode())) { 10952 // Make sure constant bus requirements are respected. 10953 TII->legalizeOperandsVOP3(MRI, MI); 10954 10955 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10956 // This saves a chain-copy of registers and better ballance register 10957 // use between vgpr and agpr as agpr tuples tend to be big. 10958 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10959 unsigned Opc = MI.getOpcode(); 10960 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10961 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10962 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10963 if (I == -1) 10964 break; 10965 MachineOperand &Op = MI.getOperand(I); 10966 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10967 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10968 !Register::isVirtualRegister(Op.getReg()) || 10969 !TRI->isAGPR(MRI, Op.getReg())) 10970 continue; 10971 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10972 if (!Src || !Src->isCopy() || 10973 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10974 continue; 10975 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10976 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10977 // All uses of agpr64 and agpr32 can also accept vgpr except for 10978 // v_accvgpr_read, but we do not produce agpr reads during selection, 10979 // so no use checks are needed. 10980 MRI.setRegClass(Op.getReg(), NewRC); 10981 } 10982 } 10983 10984 return; 10985 } 10986 10987 // Replace unused atomics with the no return version. 10988 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10989 if (NoRetAtomicOp != -1) { 10990 if (!Node->hasAnyUseOfValue(0)) { 10991 MI.setDesc(TII->get(NoRetAtomicOp)); 10992 MI.RemoveOperand(0); 10993 return; 10994 } 10995 10996 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10997 // instruction, because the return type of these instructions is a vec2 of 10998 // the memory type, so it can be tied to the input operand. 10999 // This means these instructions always have a use, so we need to add a 11000 // special case to check if the atomic has only one extract_subreg use, 11001 // which itself has no uses. 11002 if ((Node->hasNUsesOfValue(1, 0) && 11003 Node->use_begin()->isMachineOpcode() && 11004 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11005 !Node->use_begin()->hasAnyUseOfValue(0))) { 11006 Register Def = MI.getOperand(0).getReg(); 11007 11008 // Change this into a noret atomic. 11009 MI.setDesc(TII->get(NoRetAtomicOp)); 11010 MI.RemoveOperand(0); 11011 11012 // If we only remove the def operand from the atomic instruction, the 11013 // extract_subreg will be left with a use of a vreg without a def. 11014 // So we need to insert an implicit_def to avoid machine verifier 11015 // errors. 11016 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11017 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11018 } 11019 return; 11020 } 11021 } 11022 11023 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11024 uint64_t Val) { 11025 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11026 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11027 } 11028 11029 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11030 const SDLoc &DL, 11031 SDValue Ptr) const { 11032 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11033 11034 // Build the half of the subregister with the constants before building the 11035 // full 128-bit register. If we are building multiple resource descriptors, 11036 // this will allow CSEing of the 2-component register. 11037 const SDValue Ops0[] = { 11038 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11039 buildSMovImm32(DAG, DL, 0), 11040 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11041 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11042 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11043 }; 11044 11045 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11046 MVT::v2i32, Ops0), 0); 11047 11048 // Combine the constants and the pointer. 11049 const SDValue Ops1[] = { 11050 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11051 Ptr, 11052 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11053 SubRegHi, 11054 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11055 }; 11056 11057 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11058 } 11059 11060 /// Return a resource descriptor with the 'Add TID' bit enabled 11061 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11062 /// of the resource descriptor) to create an offset, which is added to 11063 /// the resource pointer. 11064 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11065 SDValue Ptr, uint32_t RsrcDword1, 11066 uint64_t RsrcDword2And3) const { 11067 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11068 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11069 if (RsrcDword1) { 11070 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11071 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11072 0); 11073 } 11074 11075 SDValue DataLo = buildSMovImm32(DAG, DL, 11076 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11077 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11078 11079 const SDValue Ops[] = { 11080 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11081 PtrLo, 11082 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11083 PtrHi, 11084 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11085 DataLo, 11086 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11087 DataHi, 11088 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11089 }; 11090 11091 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11092 } 11093 11094 //===----------------------------------------------------------------------===// 11095 // SI Inline Assembly Support 11096 //===----------------------------------------------------------------------===// 11097 11098 std::pair<unsigned, const TargetRegisterClass *> 11099 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11100 StringRef Constraint, 11101 MVT VT) const { 11102 const TargetRegisterClass *RC = nullptr; 11103 if (Constraint.size() == 1) { 11104 const unsigned BitWidth = VT.getSizeInBits(); 11105 switch (Constraint[0]) { 11106 default: 11107 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11108 case 's': 11109 case 'r': 11110 switch (BitWidth) { 11111 case 16: 11112 RC = &AMDGPU::SReg_32RegClass; 11113 break; 11114 case 64: 11115 RC = &AMDGPU::SGPR_64RegClass; 11116 break; 11117 default: 11118 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11119 if (!RC) 11120 return std::make_pair(0U, nullptr); 11121 break; 11122 } 11123 break; 11124 case 'v': 11125 switch (BitWidth) { 11126 case 16: 11127 RC = &AMDGPU::VGPR_32RegClass; 11128 break; 11129 default: 11130 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11131 if (!RC) 11132 return std::make_pair(0U, nullptr); 11133 break; 11134 } 11135 break; 11136 case 'a': 11137 if (!Subtarget->hasMAIInsts()) 11138 break; 11139 switch (BitWidth) { 11140 case 16: 11141 RC = &AMDGPU::AGPR_32RegClass; 11142 break; 11143 default: 11144 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11145 if (!RC) 11146 return std::make_pair(0U, nullptr); 11147 break; 11148 } 11149 break; 11150 } 11151 // We actually support i128, i16 and f16 as inline parameters 11152 // even if they are not reported as legal 11153 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11154 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11155 return std::make_pair(0U, RC); 11156 } 11157 11158 if (Constraint.size() > 1) { 11159 if (Constraint[1] == 'v') { 11160 RC = &AMDGPU::VGPR_32RegClass; 11161 } else if (Constraint[1] == 's') { 11162 RC = &AMDGPU::SGPR_32RegClass; 11163 } else if (Constraint[1] == 'a') { 11164 RC = &AMDGPU::AGPR_32RegClass; 11165 } 11166 11167 if (RC) { 11168 uint32_t Idx; 11169 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11170 if (!Failed && Idx < RC->getNumRegs()) 11171 return std::make_pair(RC->getRegister(Idx), RC); 11172 } 11173 } 11174 11175 // FIXME: Returns VS_32 for physical SGPR constraints 11176 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11177 } 11178 11179 static bool isImmConstraint(StringRef Constraint) { 11180 if (Constraint.size() == 1) { 11181 switch (Constraint[0]) { 11182 default: break; 11183 case 'I': 11184 case 'J': 11185 case 'A': 11186 case 'B': 11187 case 'C': 11188 return true; 11189 } 11190 } else if (Constraint == "DA" || 11191 Constraint == "DB") { 11192 return true; 11193 } 11194 return false; 11195 } 11196 11197 SITargetLowering::ConstraintType 11198 SITargetLowering::getConstraintType(StringRef Constraint) const { 11199 if (Constraint.size() == 1) { 11200 switch (Constraint[0]) { 11201 default: break; 11202 case 's': 11203 case 'v': 11204 case 'a': 11205 return C_RegisterClass; 11206 } 11207 } 11208 if (isImmConstraint(Constraint)) { 11209 return C_Other; 11210 } 11211 return TargetLowering::getConstraintType(Constraint); 11212 } 11213 11214 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11215 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11216 Val = Val & maskTrailingOnes<uint64_t>(Size); 11217 } 11218 return Val; 11219 } 11220 11221 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11222 std::string &Constraint, 11223 std::vector<SDValue> &Ops, 11224 SelectionDAG &DAG) const { 11225 if (isImmConstraint(Constraint)) { 11226 uint64_t Val; 11227 if (getAsmOperandConstVal(Op, Val) && 11228 checkAsmConstraintVal(Op, Constraint, Val)) { 11229 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11230 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11231 } 11232 } else { 11233 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11234 } 11235 } 11236 11237 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11238 unsigned Size = Op.getScalarValueSizeInBits(); 11239 if (Size > 64) 11240 return false; 11241 11242 if (Size == 16 && !Subtarget->has16BitInsts()) 11243 return false; 11244 11245 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11246 Val = C->getSExtValue(); 11247 return true; 11248 } 11249 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11250 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11251 return true; 11252 } 11253 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11254 if (Size != 16 || Op.getNumOperands() != 2) 11255 return false; 11256 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11257 return false; 11258 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11259 Val = C->getSExtValue(); 11260 return true; 11261 } 11262 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11263 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11264 return true; 11265 } 11266 } 11267 11268 return false; 11269 } 11270 11271 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11272 const std::string &Constraint, 11273 uint64_t Val) const { 11274 if (Constraint.size() == 1) { 11275 switch (Constraint[0]) { 11276 case 'I': 11277 return AMDGPU::isInlinableIntLiteral(Val); 11278 case 'J': 11279 return isInt<16>(Val); 11280 case 'A': 11281 return checkAsmConstraintValA(Op, Val); 11282 case 'B': 11283 return isInt<32>(Val); 11284 case 'C': 11285 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11286 AMDGPU::isInlinableIntLiteral(Val); 11287 default: 11288 break; 11289 } 11290 } else if (Constraint.size() == 2) { 11291 if (Constraint == "DA") { 11292 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11293 int64_t LoBits = static_cast<int32_t>(Val); 11294 return checkAsmConstraintValA(Op, HiBits, 32) && 11295 checkAsmConstraintValA(Op, LoBits, 32); 11296 } 11297 if (Constraint == "DB") { 11298 return true; 11299 } 11300 } 11301 llvm_unreachable("Invalid asm constraint"); 11302 } 11303 11304 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11305 uint64_t Val, 11306 unsigned MaxSize) const { 11307 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11308 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11309 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11310 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11311 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11312 return true; 11313 } 11314 return false; 11315 } 11316 11317 // Figure out which registers should be reserved for stack access. Only after 11318 // the function is legalized do we know all of the non-spill stack objects or if 11319 // calls are present. 11320 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11321 MachineRegisterInfo &MRI = MF.getRegInfo(); 11322 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11323 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11324 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11325 11326 if (Info->isEntryFunction()) { 11327 // Callable functions have fixed registers used for stack access. 11328 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11329 } 11330 11331 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11332 Info->getStackPtrOffsetReg())); 11333 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11334 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11335 11336 // We need to worry about replacing the default register with itself in case 11337 // of MIR testcases missing the MFI. 11338 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11339 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11340 11341 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11342 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11343 11344 Info->limitOccupancy(MF); 11345 11346 if (ST.isWave32() && !MF.empty()) { 11347 // Add VCC_HI def because many instructions marked as imp-use VCC where 11348 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11349 // having a use of undef. 11350 11351 const SIInstrInfo *TII = ST.getInstrInfo(); 11352 DebugLoc DL; 11353 11354 MachineBasicBlock &MBB = MF.front(); 11355 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11356 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11357 11358 for (auto &MBB : MF) { 11359 for (auto &MI : MBB) { 11360 TII->fixImplicitOperands(MI); 11361 } 11362 } 11363 } 11364 11365 TargetLoweringBase::finalizeLowering(MF); 11366 11367 // Allocate a VGPR for future SGPR Spill if 11368 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11369 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11370 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11371 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11372 Info->reserveVGPRforSGPRSpills(MF); 11373 } 11374 11375 void SITargetLowering::computeKnownBitsForFrameIndex( 11376 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11377 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11378 11379 // Set the high bits to zero based on the maximum allowed scratch size per 11380 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11381 // calculation won't overflow, so assume the sign bit is never set. 11382 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11383 } 11384 11385 Align SITargetLowering::computeKnownAlignForTargetInstr( 11386 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11387 unsigned Depth) const { 11388 const MachineInstr *MI = MRI.getVRegDef(R); 11389 switch (MI->getOpcode()) { 11390 case AMDGPU::G_INTRINSIC: 11391 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11392 // FIXME: Can this move to generic code? What about the case where the call 11393 // site specifies a lower alignment? 11394 Intrinsic::ID IID = MI->getIntrinsicID(); 11395 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11396 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11397 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11398 return *RetAlign; 11399 return Align(1); 11400 } 11401 default: 11402 return Align(1); 11403 } 11404 } 11405 11406 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11407 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11408 const Align CacheLineAlign = Align(64); 11409 11410 // Pre-GFX10 target did not benefit from loop alignment 11411 if (!ML || DisableLoopAlignment || 11412 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11413 getSubtarget()->hasInstFwdPrefetchBug()) 11414 return PrefAlign; 11415 11416 // On GFX10 I$ is 4 x 64 bytes cache lines. 11417 // By default prefetcher keeps one cache line behind and reads two ahead. 11418 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11419 // behind and one ahead. 11420 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11421 // If loop fits 64 bytes it always spans no more than two cache lines and 11422 // does not need an alignment. 11423 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11424 // Else if loop is less or equal 192 bytes we need two lines behind. 11425 11426 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11427 const MachineBasicBlock *Header = ML->getHeader(); 11428 if (Header->getAlignment() != PrefAlign) 11429 return Header->getAlignment(); // Already processed. 11430 11431 unsigned LoopSize = 0; 11432 for (const MachineBasicBlock *MBB : ML->blocks()) { 11433 // If inner loop block is aligned assume in average half of the alignment 11434 // size to be added as nops. 11435 if (MBB != Header) 11436 LoopSize += MBB->getAlignment().value() / 2; 11437 11438 for (const MachineInstr &MI : *MBB) { 11439 LoopSize += TII->getInstSizeInBytes(MI); 11440 if (LoopSize > 192) 11441 return PrefAlign; 11442 } 11443 } 11444 11445 if (LoopSize <= 64) 11446 return PrefAlign; 11447 11448 if (LoopSize <= 128) 11449 return CacheLineAlign; 11450 11451 // If any of parent loops is surrounded by prefetch instructions do not 11452 // insert new for inner loop, which would reset parent's settings. 11453 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11454 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11455 auto I = Exit->getFirstNonDebugInstr(); 11456 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11457 return CacheLineAlign; 11458 } 11459 } 11460 11461 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11462 MachineBasicBlock *Exit = ML->getExitBlock(); 11463 11464 if (Pre && Exit) { 11465 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11466 TII->get(AMDGPU::S_INST_PREFETCH)) 11467 .addImm(1); // prefetch 2 lines behind PC 11468 11469 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11470 TII->get(AMDGPU::S_INST_PREFETCH)) 11471 .addImm(2); // prefetch 1 line behind PC 11472 } 11473 11474 return CacheLineAlign; 11475 } 11476 11477 LLVM_ATTRIBUTE_UNUSED 11478 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11479 assert(N->getOpcode() == ISD::CopyFromReg); 11480 do { 11481 // Follow the chain until we find an INLINEASM node. 11482 N = N->getOperand(0).getNode(); 11483 if (N->getOpcode() == ISD::INLINEASM || 11484 N->getOpcode() == ISD::INLINEASM_BR) 11485 return true; 11486 } while (N->getOpcode() == ISD::CopyFromReg); 11487 return false; 11488 } 11489 11490 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11491 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11492 { 11493 switch (N->getOpcode()) { 11494 case ISD::CopyFromReg: 11495 { 11496 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11497 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11498 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11499 Register Reg = R->getReg(); 11500 11501 // FIXME: Why does this need to consider isLiveIn? 11502 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11503 return !TRI->isSGPRReg(MRI, Reg); 11504 11505 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11506 return KDA->isDivergent(V); 11507 11508 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11509 return !TRI->isSGPRReg(MRI, Reg); 11510 } 11511 break; 11512 case ISD::LOAD: { 11513 const LoadSDNode *L = cast<LoadSDNode>(N); 11514 unsigned AS = L->getAddressSpace(); 11515 // A flat load may access private memory. 11516 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11517 } break; 11518 case ISD::CALLSEQ_END: 11519 return true; 11520 break; 11521 case ISD::INTRINSIC_WO_CHAIN: 11522 { 11523 11524 } 11525 return AMDGPU::isIntrinsicSourceOfDivergence( 11526 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11527 case ISD::INTRINSIC_W_CHAIN: 11528 return AMDGPU::isIntrinsicSourceOfDivergence( 11529 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11530 } 11531 return false; 11532 } 11533 11534 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11535 EVT VT) const { 11536 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11537 case MVT::f32: 11538 return hasFP32Denormals(DAG.getMachineFunction()); 11539 case MVT::f64: 11540 case MVT::f16: 11541 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11542 default: 11543 return false; 11544 } 11545 } 11546 11547 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11548 const SelectionDAG &DAG, 11549 bool SNaN, 11550 unsigned Depth) const { 11551 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11552 const MachineFunction &MF = DAG.getMachineFunction(); 11553 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11554 11555 if (Info->getMode().DX10Clamp) 11556 return true; // Clamped to 0. 11557 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11558 } 11559 11560 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11561 SNaN, Depth); 11562 } 11563 11564 TargetLowering::AtomicExpansionKind 11565 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11566 switch (RMW->getOperation()) { 11567 case AtomicRMWInst::FAdd: { 11568 Type *Ty = RMW->getType(); 11569 11570 // We don't have a way to support 16-bit atomics now, so just leave them 11571 // as-is. 11572 if (Ty->isHalfTy()) 11573 return AtomicExpansionKind::None; 11574 11575 if (!Ty->isFloatTy()) 11576 return AtomicExpansionKind::CmpXChg; 11577 11578 // TODO: Do have these for flat. Older targets also had them for buffers. 11579 unsigned AS = RMW->getPointerAddressSpace(); 11580 11581 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11582 return RMW->use_empty() ? AtomicExpansionKind::None : 11583 AtomicExpansionKind::CmpXChg; 11584 } 11585 11586 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11587 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11588 } 11589 default: 11590 break; 11591 } 11592 11593 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11594 } 11595 11596 const TargetRegisterClass * 11597 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11598 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11599 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11600 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11601 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11602 : &AMDGPU::SReg_32RegClass; 11603 if (!TRI->isSGPRClass(RC) && !isDivergent) 11604 return TRI->getEquivalentSGPRClass(RC); 11605 else if (TRI->isSGPRClass(RC) && isDivergent) 11606 return TRI->getEquivalentVGPRClass(RC); 11607 11608 return RC; 11609 } 11610 11611 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11612 // uniform values (as produced by the mask results of control flow intrinsics) 11613 // used outside of divergent blocks. The phi users need to also be treated as 11614 // always uniform. 11615 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11616 unsigned WaveSize) { 11617 // FIXME: We asssume we never cast the mask results of a control flow 11618 // intrinsic. 11619 // Early exit if the type won't be consistent as a compile time hack. 11620 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11621 if (!IT || IT->getBitWidth() != WaveSize) 11622 return false; 11623 11624 if (!isa<Instruction>(V)) 11625 return false; 11626 if (!Visited.insert(V).second) 11627 return false; 11628 bool Result = false; 11629 for (auto U : V->users()) { 11630 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11631 if (V == U->getOperand(1)) { 11632 switch (Intrinsic->getIntrinsicID()) { 11633 default: 11634 Result = false; 11635 break; 11636 case Intrinsic::amdgcn_if_break: 11637 case Intrinsic::amdgcn_if: 11638 case Intrinsic::amdgcn_else: 11639 Result = true; 11640 break; 11641 } 11642 } 11643 if (V == U->getOperand(0)) { 11644 switch (Intrinsic->getIntrinsicID()) { 11645 default: 11646 Result = false; 11647 break; 11648 case Intrinsic::amdgcn_end_cf: 11649 case Intrinsic::amdgcn_loop: 11650 Result = true; 11651 break; 11652 } 11653 } 11654 } else { 11655 Result = hasCFUser(U, Visited, WaveSize); 11656 } 11657 if (Result) 11658 break; 11659 } 11660 return Result; 11661 } 11662 11663 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11664 const Value *V) const { 11665 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11666 if (CI->isInlineAsm()) { 11667 // FIXME: This cannot give a correct answer. This should only trigger in 11668 // the case where inline asm returns mixed SGPR and VGPR results, used 11669 // outside the defining block. We don't have a specific result to 11670 // consider, so this assumes if any value is SGPR, the overall register 11671 // also needs to be SGPR. 11672 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11673 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11674 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11675 for (auto &TC : TargetConstraints) { 11676 if (TC.Type == InlineAsm::isOutput) { 11677 ComputeConstraintToUse(TC, SDValue()); 11678 unsigned AssignedReg; 11679 const TargetRegisterClass *RC; 11680 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11681 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11682 if (RC) { 11683 MachineRegisterInfo &MRI = MF.getRegInfo(); 11684 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11685 return true; 11686 else if (SIRI->isSGPRClass(RC)) 11687 return true; 11688 } 11689 } 11690 } 11691 } 11692 } 11693 SmallPtrSet<const Value *, 16> Visited; 11694 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11695 } 11696 11697 std::pair<int, MVT> 11698 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11699 Type *Ty) const { 11700 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11701 auto Size = DL.getTypeSizeInBits(Ty); 11702 // Maximum load or store can handle 8 dwords for scalar and 4 for 11703 // vector ALU. Let's assume anything above 8 dwords is expensive 11704 // even if legal. 11705 if (Size <= 256) 11706 return Cost; 11707 11708 Cost.first = (Size + 255) / 256; 11709 return Cost; 11710 } 11711