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::FPOWI, MVT::f16, Promote); 453 setOperationAction(ISD::FLOG, MVT::f16, Custom); 454 setOperationAction(ISD::FEXP, MVT::f16, Custom); 455 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 456 } 457 458 if (Subtarget->hasMadMacF32Insts()) 459 setOperationAction(ISD::FMAD, MVT::f32, Legal); 460 461 if (!Subtarget->hasBFI()) { 462 // fcopysign can be done in a single instruction with BFI. 463 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 464 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 465 } 466 467 if (!Subtarget->hasBCNT(32)) 468 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 469 470 if (!Subtarget->hasBCNT(64)) 471 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 472 473 if (Subtarget->hasFFBH()) 474 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 475 476 if (Subtarget->hasFFBL()) 477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 478 479 // We only really have 32-bit BFE instructions (and 16-bit on VI). 480 // 481 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 482 // effort to match them now. We want this to be false for i64 cases when the 483 // extraction isn't restricted to the upper or lower half. Ideally we would 484 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 485 // span the midpoint are probably relatively rare, so don't worry about them 486 // for now. 487 if (Subtarget->hasBFE()) 488 setHasExtractBitsInsn(true); 489 490 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 491 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 492 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 493 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 494 495 496 // These are really only legal for ieee_mode functions. We should be avoiding 497 // them for functions that don't have ieee_mode enabled, so just say they are 498 // legal. 499 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 500 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 501 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 502 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 503 504 505 if (Subtarget->haveRoundOpsF64()) { 506 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 507 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 508 setOperationAction(ISD::FRINT, MVT::f64, Legal); 509 } else { 510 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 511 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 512 setOperationAction(ISD::FRINT, MVT::f64, Custom); 513 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 514 } 515 516 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 517 518 setOperationAction(ISD::FSIN, MVT::f32, Custom); 519 setOperationAction(ISD::FCOS, MVT::f32, Custom); 520 setOperationAction(ISD::FDIV, MVT::f32, Custom); 521 setOperationAction(ISD::FDIV, MVT::f64, Custom); 522 523 if (Subtarget->has16BitInsts()) { 524 setOperationAction(ISD::Constant, MVT::i16, Legal); 525 526 setOperationAction(ISD::SMIN, MVT::i16, Legal); 527 setOperationAction(ISD::SMAX, MVT::i16, Legal); 528 529 setOperationAction(ISD::UMIN, MVT::i16, Legal); 530 setOperationAction(ISD::UMAX, MVT::i16, Legal); 531 532 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 533 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 534 535 setOperationAction(ISD::ROTR, MVT::i16, Promote); 536 setOperationAction(ISD::ROTL, MVT::i16, Promote); 537 538 setOperationAction(ISD::SDIV, MVT::i16, Promote); 539 setOperationAction(ISD::UDIV, MVT::i16, Promote); 540 setOperationAction(ISD::SREM, MVT::i16, Promote); 541 setOperationAction(ISD::UREM, MVT::i16, Promote); 542 543 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 544 545 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 546 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 547 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 548 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 549 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 550 551 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 552 553 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 554 555 setOperationAction(ISD::LOAD, MVT::i16, Custom); 556 557 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 558 559 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 560 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 561 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 562 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 563 564 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 565 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 566 567 // F16 - Constant Actions. 568 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 569 570 // F16 - Load/Store Actions. 571 setOperationAction(ISD::LOAD, MVT::f16, Promote); 572 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 573 setOperationAction(ISD::STORE, MVT::f16, Promote); 574 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 575 576 // F16 - VOP1 Actions. 577 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 578 setOperationAction(ISD::FCOS, MVT::f16, Custom); 579 setOperationAction(ISD::FSIN, MVT::f16, Custom); 580 581 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 582 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 583 584 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 585 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 586 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 587 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 588 setOperationAction(ISD::FROUND, MVT::f16, Custom); 589 590 // F16 - VOP2 Actions. 591 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 592 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 593 594 setOperationAction(ISD::FDIV, MVT::f16, Custom); 595 596 // F16 - VOP3 Actions. 597 setOperationAction(ISD::FMA, MVT::f16, Legal); 598 if (STI.hasMadF16()) 599 setOperationAction(ISD::FMAD, MVT::f16, Legal); 600 601 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 602 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 603 switch (Op) { 604 case ISD::LOAD: 605 case ISD::STORE: 606 case ISD::BUILD_VECTOR: 607 case ISD::BITCAST: 608 case ISD::EXTRACT_VECTOR_ELT: 609 case ISD::INSERT_VECTOR_ELT: 610 case ISD::INSERT_SUBVECTOR: 611 case ISD::EXTRACT_SUBVECTOR: 612 case ISD::SCALAR_TO_VECTOR: 613 break; 614 case ISD::CONCAT_VECTORS: 615 setOperationAction(Op, VT, Custom); 616 break; 617 default: 618 setOperationAction(Op, VT, Expand); 619 break; 620 } 621 } 622 } 623 624 // v_perm_b32 can handle either of these. 625 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 626 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 627 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 628 629 // XXX - Do these do anything? Vector constants turn into build_vector. 630 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 631 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 632 633 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 634 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 635 636 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 637 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 638 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 639 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 640 641 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 642 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 643 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 644 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 645 646 setOperationAction(ISD::AND, MVT::v2i16, Promote); 647 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 648 setOperationAction(ISD::OR, MVT::v2i16, Promote); 649 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 650 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 651 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 652 653 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 654 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 655 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 656 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 657 658 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 659 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 660 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 661 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 662 663 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 664 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 665 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 666 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 667 668 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 669 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 670 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 671 672 if (!Subtarget->hasVOP3PInsts()) { 673 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 674 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 675 } 676 677 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 678 // This isn't really legal, but this avoids the legalizer unrolling it (and 679 // allows matching fneg (fabs x) patterns) 680 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 681 682 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 683 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 684 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 685 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 686 687 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 688 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 689 690 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 691 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 692 } 693 694 if (Subtarget->hasVOP3PInsts()) { 695 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 696 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 697 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 698 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 699 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 700 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 701 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 702 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 703 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 704 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 705 706 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 707 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 708 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 709 710 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 711 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 712 713 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 714 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 716 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 717 718 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 719 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 720 721 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 722 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 723 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 724 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 725 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 726 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 727 728 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 729 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 730 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 731 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 732 733 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 734 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 735 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 736 737 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 738 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 739 740 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 741 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 742 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 743 744 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 745 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 746 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 747 } 748 749 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 750 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 751 752 if (Subtarget->has16BitInsts()) { 753 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 754 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 755 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 756 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 757 } else { 758 // Legalization hack. 759 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 760 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 761 762 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 763 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 764 } 765 766 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 767 setOperationAction(ISD::SELECT, VT, Custom); 768 } 769 770 setOperationAction(ISD::SMULO, MVT::i64, Custom); 771 setOperationAction(ISD::UMULO, MVT::i64, Custom); 772 773 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 774 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 775 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 776 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 777 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 778 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 779 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 780 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 785 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 786 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 787 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 788 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 789 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 790 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 795 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 796 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 797 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 798 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 799 800 setTargetDAGCombine(ISD::ADD); 801 setTargetDAGCombine(ISD::ADDCARRY); 802 setTargetDAGCombine(ISD::SUB); 803 setTargetDAGCombine(ISD::SUBCARRY); 804 setTargetDAGCombine(ISD::FADD); 805 setTargetDAGCombine(ISD::FSUB); 806 setTargetDAGCombine(ISD::FMINNUM); 807 setTargetDAGCombine(ISD::FMAXNUM); 808 setTargetDAGCombine(ISD::FMINNUM_IEEE); 809 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 810 setTargetDAGCombine(ISD::FMA); 811 setTargetDAGCombine(ISD::SMIN); 812 setTargetDAGCombine(ISD::SMAX); 813 setTargetDAGCombine(ISD::UMIN); 814 setTargetDAGCombine(ISD::UMAX); 815 setTargetDAGCombine(ISD::SETCC); 816 setTargetDAGCombine(ISD::AND); 817 setTargetDAGCombine(ISD::OR); 818 setTargetDAGCombine(ISD::XOR); 819 setTargetDAGCombine(ISD::SINT_TO_FP); 820 setTargetDAGCombine(ISD::UINT_TO_FP); 821 setTargetDAGCombine(ISD::FCANONICALIZE); 822 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 823 setTargetDAGCombine(ISD::ZERO_EXTEND); 824 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 825 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 826 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 827 828 // All memory operations. Some folding on the pointer operand is done to help 829 // matching the constant offsets in the addressing modes. 830 setTargetDAGCombine(ISD::LOAD); 831 setTargetDAGCombine(ISD::STORE); 832 setTargetDAGCombine(ISD::ATOMIC_LOAD); 833 setTargetDAGCombine(ISD::ATOMIC_STORE); 834 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 835 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 836 setTargetDAGCombine(ISD::ATOMIC_SWAP); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 844 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 845 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 846 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 847 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 848 849 // FIXME: In other contexts we pretend this is a per-function property. 850 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 851 852 setSchedulingPreference(Sched::RegPressure); 853 } 854 855 const GCNSubtarget *SITargetLowering::getSubtarget() const { 856 return Subtarget; 857 } 858 859 //===----------------------------------------------------------------------===// 860 // TargetLowering queries 861 //===----------------------------------------------------------------------===// 862 863 // v_mad_mix* support a conversion from f16 to f32. 864 // 865 // There is only one special case when denormals are enabled we don't currently, 866 // where this is OK to use. 867 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 868 EVT DestVT, EVT SrcVT) const { 869 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 870 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 871 DestVT.getScalarType() == MVT::f32 && 872 SrcVT.getScalarType() == MVT::f16 && 873 // TODO: This probably only requires no input flushing? 874 !hasFP32Denormals(DAG.getMachineFunction()); 875 } 876 877 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 878 // SI has some legal vector types, but no legal vector operations. Say no 879 // shuffles are legal in order to prefer scalarizing some vector operations. 880 return false; 881 } 882 883 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 884 CallingConv::ID CC, 885 EVT VT) const { 886 if (CC == CallingConv::AMDGPU_KERNEL) 887 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 888 889 if (VT.isVector()) { 890 EVT ScalarVT = VT.getScalarType(); 891 unsigned Size = ScalarVT.getSizeInBits(); 892 if (Size == 32) 893 return ScalarVT.getSimpleVT(); 894 895 if (Size > 32) 896 return MVT::i32; 897 898 if (Size == 16 && Subtarget->has16BitInsts()) 899 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 900 } else if (VT.getSizeInBits() > 32) 901 return MVT::i32; 902 903 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 904 } 905 906 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 907 CallingConv::ID CC, 908 EVT VT) const { 909 if (CC == CallingConv::AMDGPU_KERNEL) 910 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 911 912 if (VT.isVector()) { 913 unsigned NumElts = VT.getVectorNumElements(); 914 EVT ScalarVT = VT.getScalarType(); 915 unsigned Size = ScalarVT.getSizeInBits(); 916 917 if (Size == 32) 918 return NumElts; 919 920 if (Size > 32) 921 return NumElts * ((Size + 31) / 32); 922 923 if (Size == 16 && Subtarget->has16BitInsts()) 924 return (NumElts + 1) / 2; 925 } else if (VT.getSizeInBits() > 32) 926 return (VT.getSizeInBits() + 31) / 32; 927 928 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 929 } 930 931 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 932 LLVMContext &Context, CallingConv::ID CC, 933 EVT VT, EVT &IntermediateVT, 934 unsigned &NumIntermediates, MVT &RegisterVT) const { 935 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 936 unsigned NumElts = VT.getVectorNumElements(); 937 EVT ScalarVT = VT.getScalarType(); 938 unsigned Size = ScalarVT.getSizeInBits(); 939 if (Size == 32) { 940 RegisterVT = ScalarVT.getSimpleVT(); 941 IntermediateVT = RegisterVT; 942 NumIntermediates = NumElts; 943 return NumIntermediates; 944 } 945 946 if (Size > 32) { 947 RegisterVT = MVT::i32; 948 IntermediateVT = RegisterVT; 949 NumIntermediates = NumElts * ((Size + 31) / 32); 950 return NumIntermediates; 951 } 952 953 // FIXME: We should fix the ABI to be the same on targets without 16-bit 954 // support, but unless we can properly handle 3-vectors, it will be still be 955 // inconsistent. 956 if (Size == 16 && Subtarget->has16BitInsts()) { 957 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 958 IntermediateVT = RegisterVT; 959 NumIntermediates = (NumElts + 1) / 2; 960 return NumIntermediates; 961 } 962 } 963 964 return TargetLowering::getVectorTypeBreakdownForCallingConv( 965 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 966 } 967 968 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 969 assert(DMaskLanes != 0); 970 971 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 972 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 973 return EVT::getVectorVT(Ty->getContext(), 974 EVT::getEVT(VT->getElementType()), 975 NumElts); 976 } 977 978 return EVT::getEVT(Ty); 979 } 980 981 // Peek through TFE struct returns to only use the data size. 982 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 983 auto *ST = dyn_cast<StructType>(Ty); 984 if (!ST) 985 return memVTFromImageData(Ty, DMaskLanes); 986 987 // Some intrinsics return an aggregate type - special case to work out the 988 // correct memVT. 989 // 990 // Only limited forms of aggregate type currently expected. 991 if (ST->getNumContainedTypes() != 2 || 992 !ST->getContainedType(1)->isIntegerTy(32)) 993 return EVT(); 994 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 995 } 996 997 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 998 const CallInst &CI, 999 MachineFunction &MF, 1000 unsigned IntrID) const { 1001 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1002 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1003 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1004 (Intrinsic::ID)IntrID); 1005 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1006 return false; 1007 1008 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1009 1010 if (RsrcIntr->IsImage) { 1011 Info.ptrVal = MFI->getImagePSV( 1012 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1013 CI.getArgOperand(RsrcIntr->RsrcArg)); 1014 Info.align.reset(); 1015 } else { 1016 Info.ptrVal = MFI->getBufferPSV( 1017 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1018 CI.getArgOperand(RsrcIntr->RsrcArg)); 1019 } 1020 1021 Info.flags = MachineMemOperand::MODereferenceable; 1022 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1023 unsigned DMaskLanes = 4; 1024 1025 if (RsrcIntr->IsImage) { 1026 const AMDGPU::ImageDimIntrinsicInfo *Intr 1027 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1028 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1029 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1030 1031 if (!BaseOpcode->Gather4) { 1032 // If this isn't a gather, we may have excess loaded elements in the 1033 // IR type. Check the dmask for the real number of elements loaded. 1034 unsigned DMask 1035 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1036 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1037 } 1038 1039 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1040 } else 1041 Info.memVT = EVT::getEVT(CI.getType()); 1042 1043 // FIXME: What does alignment mean for an image? 1044 Info.opc = ISD::INTRINSIC_W_CHAIN; 1045 Info.flags |= MachineMemOperand::MOLoad; 1046 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1047 Info.opc = ISD::INTRINSIC_VOID; 1048 1049 Type *DataTy = CI.getArgOperand(0)->getType(); 1050 if (RsrcIntr->IsImage) { 1051 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1052 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1053 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1054 } else 1055 Info.memVT = EVT::getEVT(DataTy); 1056 1057 Info.flags |= MachineMemOperand::MOStore; 1058 } else { 1059 // Atomic 1060 Info.opc = ISD::INTRINSIC_W_CHAIN; 1061 Info.memVT = MVT::getVT(CI.getType()); 1062 Info.flags = MachineMemOperand::MOLoad | 1063 MachineMemOperand::MOStore | 1064 MachineMemOperand::MODereferenceable; 1065 1066 // XXX - Should this be volatile without known ordering? 1067 Info.flags |= MachineMemOperand::MOVolatile; 1068 } 1069 return true; 1070 } 1071 1072 switch (IntrID) { 1073 case Intrinsic::amdgcn_atomic_inc: 1074 case Intrinsic::amdgcn_atomic_dec: 1075 case Intrinsic::amdgcn_ds_ordered_add: 1076 case Intrinsic::amdgcn_ds_ordered_swap: 1077 case Intrinsic::amdgcn_ds_fadd: 1078 case Intrinsic::amdgcn_ds_fmin: 1079 case Intrinsic::amdgcn_ds_fmax: { 1080 Info.opc = ISD::INTRINSIC_W_CHAIN; 1081 Info.memVT = MVT::getVT(CI.getType()); 1082 Info.ptrVal = CI.getOperand(0); 1083 Info.align.reset(); 1084 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1085 1086 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1087 if (!Vol->isZero()) 1088 Info.flags |= MachineMemOperand::MOVolatile; 1089 1090 return true; 1091 } 1092 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1093 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1094 1095 Info.opc = ISD::INTRINSIC_VOID; 1096 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1097 Info.ptrVal = MFI->getBufferPSV( 1098 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1099 CI.getArgOperand(1)); 1100 Info.align.reset(); 1101 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1102 1103 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1104 if (!Vol || !Vol->isZero()) 1105 Info.flags |= MachineMemOperand::MOVolatile; 1106 1107 return true; 1108 } 1109 case Intrinsic::amdgcn_global_atomic_fadd: { 1110 Info.opc = ISD::INTRINSIC_VOID; 1111 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1112 ->getPointerElementType()); 1113 Info.ptrVal = CI.getOperand(0); 1114 Info.align.reset(); 1115 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1116 1117 return true; 1118 } 1119 case Intrinsic::amdgcn_ds_append: 1120 case Intrinsic::amdgcn_ds_consume: { 1121 Info.opc = ISD::INTRINSIC_W_CHAIN; 1122 Info.memVT = MVT::getVT(CI.getType()); 1123 Info.ptrVal = CI.getOperand(0); 1124 Info.align.reset(); 1125 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1126 1127 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1128 if (!Vol->isZero()) 1129 Info.flags |= MachineMemOperand::MOVolatile; 1130 1131 return true; 1132 } 1133 case Intrinsic::amdgcn_global_atomic_csub: { 1134 Info.opc = ISD::INTRINSIC_W_CHAIN; 1135 Info.memVT = MVT::getVT(CI.getType()); 1136 Info.ptrVal = CI.getOperand(0); 1137 Info.align.reset(); 1138 Info.flags = MachineMemOperand::MOLoad | 1139 MachineMemOperand::MOStore | 1140 MachineMemOperand::MODereferenceable | 1141 MachineMemOperand::MOVolatile; 1142 return true; 1143 } 1144 case Intrinsic::amdgcn_ds_gws_init: 1145 case Intrinsic::amdgcn_ds_gws_barrier: 1146 case Intrinsic::amdgcn_ds_gws_sema_v: 1147 case Intrinsic::amdgcn_ds_gws_sema_br: 1148 case Intrinsic::amdgcn_ds_gws_sema_p: 1149 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1150 Info.opc = ISD::INTRINSIC_VOID; 1151 1152 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1153 Info.ptrVal = 1154 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1155 1156 // This is an abstract access, but we need to specify a type and size. 1157 Info.memVT = MVT::i32; 1158 Info.size = 4; 1159 Info.align = Align(4); 1160 1161 Info.flags = MachineMemOperand::MOStore; 1162 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1163 Info.flags = MachineMemOperand::MOLoad; 1164 return true; 1165 } 1166 default: 1167 return false; 1168 } 1169 } 1170 1171 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1172 SmallVectorImpl<Value*> &Ops, 1173 Type *&AccessTy) const { 1174 switch (II->getIntrinsicID()) { 1175 case Intrinsic::amdgcn_atomic_inc: 1176 case Intrinsic::amdgcn_atomic_dec: 1177 case Intrinsic::amdgcn_ds_ordered_add: 1178 case Intrinsic::amdgcn_ds_ordered_swap: 1179 case Intrinsic::amdgcn_ds_fadd: 1180 case Intrinsic::amdgcn_ds_fmin: 1181 case Intrinsic::amdgcn_ds_fmax: { 1182 Value *Ptr = II->getArgOperand(0); 1183 AccessTy = II->getType(); 1184 Ops.push_back(Ptr); 1185 return true; 1186 } 1187 default: 1188 return false; 1189 } 1190 } 1191 1192 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1193 if (!Subtarget->hasFlatInstOffsets()) { 1194 // Flat instructions do not have offsets, and only have the register 1195 // address. 1196 return AM.BaseOffs == 0 && AM.Scale == 0; 1197 } 1198 1199 return AM.Scale == 0 && 1200 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1201 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1202 /*Signed=*/false)); 1203 } 1204 1205 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1206 if (Subtarget->hasFlatGlobalInsts()) 1207 return AM.Scale == 0 && 1208 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1209 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1210 /*Signed=*/true)); 1211 1212 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1213 // Assume the we will use FLAT for all global memory accesses 1214 // on VI. 1215 // FIXME: This assumption is currently wrong. On VI we still use 1216 // MUBUF instructions for the r + i addressing mode. As currently 1217 // implemented, the MUBUF instructions only work on buffer < 4GB. 1218 // It may be possible to support > 4GB buffers with MUBUF instructions, 1219 // by setting the stride value in the resource descriptor which would 1220 // increase the size limit to (stride * 4GB). However, this is risky, 1221 // because it has never been validated. 1222 return isLegalFlatAddressingMode(AM); 1223 } 1224 1225 return isLegalMUBUFAddressingMode(AM); 1226 } 1227 1228 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1229 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1230 // additionally can do r + r + i with addr64. 32-bit has more addressing 1231 // mode options. Depending on the resource constant, it can also do 1232 // (i64 r0) + (i32 r1) * (i14 i). 1233 // 1234 // Private arrays end up using a scratch buffer most of the time, so also 1235 // assume those use MUBUF instructions. Scratch loads / stores are currently 1236 // implemented as mubuf instructions with offen bit set, so slightly 1237 // different than the normal addr64. 1238 if (!isUInt<12>(AM.BaseOffs)) 1239 return false; 1240 1241 // FIXME: Since we can split immediate into soffset and immediate offset, 1242 // would it make sense to allow any immediate? 1243 1244 switch (AM.Scale) { 1245 case 0: // r + i or just i, depending on HasBaseReg. 1246 return true; 1247 case 1: 1248 return true; // We have r + r or r + i. 1249 case 2: 1250 if (AM.HasBaseReg) { 1251 // Reject 2 * r + r. 1252 return false; 1253 } 1254 1255 // Allow 2 * r as r + r 1256 // Or 2 * r + i is allowed as r + r + i. 1257 return true; 1258 default: // Don't allow n * r 1259 return false; 1260 } 1261 } 1262 1263 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1264 const AddrMode &AM, Type *Ty, 1265 unsigned AS, Instruction *I) const { 1266 // No global is ever allowed as a base. 1267 if (AM.BaseGV) 1268 return false; 1269 1270 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1271 return isLegalGlobalAddressingMode(AM); 1272 1273 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1274 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1275 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1276 // If the offset isn't a multiple of 4, it probably isn't going to be 1277 // correctly aligned. 1278 // FIXME: Can we get the real alignment here? 1279 if (AM.BaseOffs % 4 != 0) 1280 return isLegalMUBUFAddressingMode(AM); 1281 1282 // There are no SMRD extloads, so if we have to do a small type access we 1283 // will use a MUBUF load. 1284 // FIXME?: We also need to do this if unaligned, but we don't know the 1285 // alignment here. 1286 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1287 return isLegalGlobalAddressingMode(AM); 1288 1289 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1290 // SMRD instructions have an 8-bit, dword offset on SI. 1291 if (!isUInt<8>(AM.BaseOffs / 4)) 1292 return false; 1293 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1294 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1295 // in 8-bits, it can use a smaller encoding. 1296 if (!isUInt<32>(AM.BaseOffs / 4)) 1297 return false; 1298 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1299 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1300 if (!isUInt<20>(AM.BaseOffs)) 1301 return false; 1302 } else 1303 llvm_unreachable("unhandled generation"); 1304 1305 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1306 return true; 1307 1308 if (AM.Scale == 1 && AM.HasBaseReg) 1309 return true; 1310 1311 return false; 1312 1313 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1314 return isLegalMUBUFAddressingMode(AM); 1315 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1316 AS == AMDGPUAS::REGION_ADDRESS) { 1317 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1318 // field. 1319 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1320 // an 8-bit dword offset but we don't know the alignment here. 1321 if (!isUInt<16>(AM.BaseOffs)) 1322 return false; 1323 1324 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1325 return true; 1326 1327 if (AM.Scale == 1 && AM.HasBaseReg) 1328 return true; 1329 1330 return false; 1331 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1332 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1333 // For an unknown address space, this usually means that this is for some 1334 // reason being used for pure arithmetic, and not based on some addressing 1335 // computation. We don't have instructions that compute pointers with any 1336 // addressing modes, so treat them as having no offset like flat 1337 // instructions. 1338 return isLegalFlatAddressingMode(AM); 1339 } 1340 1341 // Assume a user alias of global for unknown address spaces. 1342 return isLegalGlobalAddressingMode(AM); 1343 } 1344 1345 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1346 const SelectionDAG &DAG) const { 1347 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1348 return (MemVT.getSizeInBits() <= 4 * 32); 1349 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1350 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1351 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1352 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1353 return (MemVT.getSizeInBits() <= 2 * 32); 1354 } 1355 return true; 1356 } 1357 1358 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1359 unsigned Size, unsigned AddrSpace, unsigned Align, 1360 MachineMemOperand::Flags Flags, bool *IsFast) const { 1361 if (IsFast) 1362 *IsFast = false; 1363 1364 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1365 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1366 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1367 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1368 // with adjacent offsets. 1369 bool AlignedBy4 = (Align % 4 == 0); 1370 if (IsFast) 1371 *IsFast = AlignedBy4; 1372 1373 return AlignedBy4; 1374 } 1375 1376 // FIXME: We have to be conservative here and assume that flat operations 1377 // will access scratch. If we had access to the IR function, then we 1378 // could determine if any private memory was used in the function. 1379 if (!Subtarget->hasUnalignedScratchAccess() && 1380 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1381 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1382 bool AlignedBy4 = Align >= 4; 1383 if (IsFast) 1384 *IsFast = AlignedBy4; 1385 1386 return AlignedBy4; 1387 } 1388 1389 if (Subtarget->hasUnalignedBufferAccess()) { 1390 // If we have an uniform constant load, it still requires using a slow 1391 // buffer instruction if unaligned. 1392 if (IsFast) { 1393 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1394 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1395 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1396 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1397 Align >= 4 : Align != 2; 1398 } 1399 1400 return true; 1401 } 1402 1403 // Smaller than dword value must be aligned. 1404 if (Size < 32) 1405 return false; 1406 1407 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1408 // byte-address are ignored, thus forcing Dword alignment. 1409 // This applies to private, global, and constant memory. 1410 if (IsFast) 1411 *IsFast = true; 1412 1413 return Size >= 32 && Align >= 4; 1414 } 1415 1416 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1417 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1418 bool *IsFast) const { 1419 if (IsFast) 1420 *IsFast = false; 1421 1422 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1423 // which isn't a simple VT. 1424 // Until MVT is extended to handle this, simply check for the size and 1425 // rely on the condition below: allow accesses if the size is a multiple of 4. 1426 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1427 VT.getStoreSize() > 16)) { 1428 return false; 1429 } 1430 1431 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1432 Align, Flags, IsFast); 1433 } 1434 1435 EVT SITargetLowering::getOptimalMemOpType( 1436 const MemOp &Op, const AttributeList &FuncAttributes) const { 1437 // FIXME: Should account for address space here. 1438 1439 // The default fallback uses the private pointer size as a guess for a type to 1440 // use. Make sure we switch these to 64-bit accesses. 1441 1442 if (Op.size() >= 16 && 1443 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1444 return MVT::v4i32; 1445 1446 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1447 return MVT::v2i32; 1448 1449 // Use the default. 1450 return MVT::Other; 1451 } 1452 1453 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1454 unsigned DestAS) const { 1455 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1456 } 1457 1458 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1459 const MemSDNode *MemNode = cast<MemSDNode>(N); 1460 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1461 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1462 return I && I->getMetadata("amdgpu.noclobber"); 1463 } 1464 1465 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1466 unsigned DestAS) const { 1467 // Flat -> private/local is a simple truncate. 1468 // Flat -> global is no-op 1469 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1470 return true; 1471 1472 return isNoopAddrSpaceCast(SrcAS, DestAS); 1473 } 1474 1475 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1476 const MemSDNode *MemNode = cast<MemSDNode>(N); 1477 1478 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1479 } 1480 1481 TargetLoweringBase::LegalizeTypeAction 1482 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1483 int NumElts = VT.getVectorNumElements(); 1484 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1485 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1486 return TargetLoweringBase::getPreferredVectorAction(VT); 1487 } 1488 1489 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1490 Type *Ty) const { 1491 // FIXME: Could be smarter if called for vector constants. 1492 return true; 1493 } 1494 1495 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1496 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1497 switch (Op) { 1498 case ISD::LOAD: 1499 case ISD::STORE: 1500 1501 // These operations are done with 32-bit instructions anyway. 1502 case ISD::AND: 1503 case ISD::OR: 1504 case ISD::XOR: 1505 case ISD::SELECT: 1506 // TODO: Extensions? 1507 return true; 1508 default: 1509 return false; 1510 } 1511 } 1512 1513 // SimplifySetCC uses this function to determine whether or not it should 1514 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1515 if (VT == MVT::i1 && Op == ISD::SETCC) 1516 return false; 1517 1518 return TargetLowering::isTypeDesirableForOp(Op, VT); 1519 } 1520 1521 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1522 const SDLoc &SL, 1523 SDValue Chain, 1524 uint64_t Offset) const { 1525 const DataLayout &DL = DAG.getDataLayout(); 1526 MachineFunction &MF = DAG.getMachineFunction(); 1527 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1528 1529 const ArgDescriptor *InputPtrReg; 1530 const TargetRegisterClass *RC; 1531 LLT ArgTy; 1532 1533 std::tie(InputPtrReg, RC, ArgTy) = 1534 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1535 1536 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1537 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1538 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1539 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1540 1541 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1542 } 1543 1544 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1545 const SDLoc &SL) const { 1546 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1547 FIRST_IMPLICIT); 1548 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1549 } 1550 1551 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1552 const SDLoc &SL, SDValue Val, 1553 bool Signed, 1554 const ISD::InputArg *Arg) const { 1555 // First, if it is a widened vector, narrow it. 1556 if (VT.isVector() && 1557 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1558 EVT NarrowedVT = 1559 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1560 VT.getVectorNumElements()); 1561 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1562 DAG.getConstant(0, SL, MVT::i32)); 1563 } 1564 1565 // Then convert the vector elements or scalar value. 1566 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1567 VT.bitsLT(MemVT)) { 1568 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1569 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1570 } 1571 1572 if (MemVT.isFloatingPoint()) 1573 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1574 else if (Signed) 1575 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1576 else 1577 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1578 1579 return Val; 1580 } 1581 1582 SDValue SITargetLowering::lowerKernargMemParameter( 1583 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1584 uint64_t Offset, Align Alignment, bool Signed, 1585 const ISD::InputArg *Arg) const { 1586 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1587 1588 // Try to avoid using an extload by loading earlier than the argument address, 1589 // and extracting the relevant bits. The load should hopefully be merged with 1590 // the previous argument. 1591 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1592 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1593 int64_t AlignDownOffset = alignDown(Offset, 4); 1594 int64_t OffsetDiff = Offset - AlignDownOffset; 1595 1596 EVT IntVT = MemVT.changeTypeToInteger(); 1597 1598 // TODO: If we passed in the base kernel offset we could have a better 1599 // alignment than 4, but we don't really need it. 1600 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1601 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1602 MachineMemOperand::MODereferenceable | 1603 MachineMemOperand::MOInvariant); 1604 1605 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1606 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1607 1608 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1609 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1610 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1611 1612 1613 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1614 } 1615 1616 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1617 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1618 MachineMemOperand::MODereferenceable | 1619 MachineMemOperand::MOInvariant); 1620 1621 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1622 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1623 } 1624 1625 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1626 const SDLoc &SL, SDValue Chain, 1627 const ISD::InputArg &Arg) const { 1628 MachineFunction &MF = DAG.getMachineFunction(); 1629 MachineFrameInfo &MFI = MF.getFrameInfo(); 1630 1631 if (Arg.Flags.isByVal()) { 1632 unsigned Size = Arg.Flags.getByValSize(); 1633 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1634 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1635 } 1636 1637 unsigned ArgOffset = VA.getLocMemOffset(); 1638 unsigned ArgSize = VA.getValVT().getStoreSize(); 1639 1640 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1641 1642 // Create load nodes to retrieve arguments from the stack. 1643 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1644 SDValue ArgValue; 1645 1646 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1647 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1648 MVT MemVT = VA.getValVT(); 1649 1650 switch (VA.getLocInfo()) { 1651 default: 1652 break; 1653 case CCValAssign::BCvt: 1654 MemVT = VA.getLocVT(); 1655 break; 1656 case CCValAssign::SExt: 1657 ExtType = ISD::SEXTLOAD; 1658 break; 1659 case CCValAssign::ZExt: 1660 ExtType = ISD::ZEXTLOAD; 1661 break; 1662 case CCValAssign::AExt: 1663 ExtType = ISD::EXTLOAD; 1664 break; 1665 } 1666 1667 ArgValue = DAG.getExtLoad( 1668 ExtType, SL, VA.getLocVT(), Chain, FIN, 1669 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1670 MemVT); 1671 return ArgValue; 1672 } 1673 1674 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1675 const SIMachineFunctionInfo &MFI, 1676 EVT VT, 1677 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1678 const ArgDescriptor *Reg; 1679 const TargetRegisterClass *RC; 1680 LLT Ty; 1681 1682 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1683 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1684 } 1685 1686 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1687 CallingConv::ID CallConv, 1688 ArrayRef<ISD::InputArg> Ins, 1689 BitVector &Skipped, 1690 FunctionType *FType, 1691 SIMachineFunctionInfo *Info) { 1692 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1693 const ISD::InputArg *Arg = &Ins[I]; 1694 1695 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1696 "vector type argument should have been split"); 1697 1698 // First check if it's a PS input addr. 1699 if (CallConv == CallingConv::AMDGPU_PS && 1700 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1701 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1702 1703 // Inconveniently only the first part of the split is marked as isSplit, 1704 // so skip to the end. We only want to increment PSInputNum once for the 1705 // entire split argument. 1706 if (Arg->Flags.isSplit()) { 1707 while (!Arg->Flags.isSplitEnd()) { 1708 assert((!Arg->VT.isVector() || 1709 Arg->VT.getScalarSizeInBits() == 16) && 1710 "unexpected vector split in ps argument type"); 1711 if (!SkipArg) 1712 Splits.push_back(*Arg); 1713 Arg = &Ins[++I]; 1714 } 1715 } 1716 1717 if (SkipArg) { 1718 // We can safely skip PS inputs. 1719 Skipped.set(Arg->getOrigArgIndex()); 1720 ++PSInputNum; 1721 continue; 1722 } 1723 1724 Info->markPSInputAllocated(PSInputNum); 1725 if (Arg->Used) 1726 Info->markPSInputEnabled(PSInputNum); 1727 1728 ++PSInputNum; 1729 } 1730 1731 Splits.push_back(*Arg); 1732 } 1733 } 1734 1735 // Allocate special inputs passed in VGPRs. 1736 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1737 MachineFunction &MF, 1738 const SIRegisterInfo &TRI, 1739 SIMachineFunctionInfo &Info) const { 1740 const LLT S32 = LLT::scalar(32); 1741 MachineRegisterInfo &MRI = MF.getRegInfo(); 1742 1743 if (Info.hasWorkItemIDX()) { 1744 Register Reg = AMDGPU::VGPR0; 1745 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1746 1747 CCInfo.AllocateReg(Reg); 1748 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1749 } 1750 1751 if (Info.hasWorkItemIDY()) { 1752 Register Reg = AMDGPU::VGPR1; 1753 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1754 1755 CCInfo.AllocateReg(Reg); 1756 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1757 } 1758 1759 if (Info.hasWorkItemIDZ()) { 1760 Register Reg = AMDGPU::VGPR2; 1761 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1762 1763 CCInfo.AllocateReg(Reg); 1764 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1765 } 1766 } 1767 1768 // Try to allocate a VGPR at the end of the argument list, or if no argument 1769 // VGPRs are left allocating a stack slot. 1770 // If \p Mask is is given it indicates bitfield position in the register. 1771 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1772 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1773 ArgDescriptor Arg = ArgDescriptor()) { 1774 if (Arg.isSet()) 1775 return ArgDescriptor::createArg(Arg, Mask); 1776 1777 ArrayRef<MCPhysReg> ArgVGPRs 1778 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1779 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1780 if (RegIdx == ArgVGPRs.size()) { 1781 // Spill to stack required. 1782 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1783 1784 return ArgDescriptor::createStack(Offset, Mask); 1785 } 1786 1787 unsigned Reg = ArgVGPRs[RegIdx]; 1788 Reg = CCInfo.AllocateReg(Reg); 1789 assert(Reg != AMDGPU::NoRegister); 1790 1791 MachineFunction &MF = CCInfo.getMachineFunction(); 1792 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1793 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1794 return ArgDescriptor::createRegister(Reg, Mask); 1795 } 1796 1797 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1798 const TargetRegisterClass *RC, 1799 unsigned NumArgRegs) { 1800 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1801 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1802 if (RegIdx == ArgSGPRs.size()) 1803 report_fatal_error("ran out of SGPRs for arguments"); 1804 1805 unsigned Reg = ArgSGPRs[RegIdx]; 1806 Reg = CCInfo.AllocateReg(Reg); 1807 assert(Reg != AMDGPU::NoRegister); 1808 1809 MachineFunction &MF = CCInfo.getMachineFunction(); 1810 MF.addLiveIn(Reg, RC); 1811 return ArgDescriptor::createRegister(Reg); 1812 } 1813 1814 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1815 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1816 } 1817 1818 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1819 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1820 } 1821 1822 /// Allocate implicit function VGPR arguments at the end of allocated user 1823 /// arguments. 1824 void SITargetLowering::allocateSpecialInputVGPRs( 1825 CCState &CCInfo, MachineFunction &MF, 1826 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1827 const unsigned Mask = 0x3ff; 1828 ArgDescriptor Arg; 1829 1830 if (Info.hasWorkItemIDX()) { 1831 Arg = allocateVGPR32Input(CCInfo, Mask); 1832 Info.setWorkItemIDX(Arg); 1833 } 1834 1835 if (Info.hasWorkItemIDY()) { 1836 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1837 Info.setWorkItemIDY(Arg); 1838 } 1839 1840 if (Info.hasWorkItemIDZ()) 1841 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1842 } 1843 1844 /// Allocate implicit function VGPR arguments in fixed registers. 1845 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1846 CCState &CCInfo, MachineFunction &MF, 1847 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1848 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1849 if (!Reg) 1850 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1851 1852 const unsigned Mask = 0x3ff; 1853 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1854 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1855 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1856 } 1857 1858 void SITargetLowering::allocateSpecialInputSGPRs( 1859 CCState &CCInfo, 1860 MachineFunction &MF, 1861 const SIRegisterInfo &TRI, 1862 SIMachineFunctionInfo &Info) const { 1863 auto &ArgInfo = Info.getArgInfo(); 1864 1865 // TODO: Unify handling with private memory pointers. 1866 1867 if (Info.hasDispatchPtr()) 1868 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1869 1870 if (Info.hasQueuePtr()) 1871 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1872 1873 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1874 // constant offset from the kernarg segment. 1875 if (Info.hasImplicitArgPtr()) 1876 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1877 1878 if (Info.hasDispatchID()) 1879 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1880 1881 // flat_scratch_init is not applicable for non-kernel functions. 1882 1883 if (Info.hasWorkGroupIDX()) 1884 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1885 1886 if (Info.hasWorkGroupIDY()) 1887 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1888 1889 if (Info.hasWorkGroupIDZ()) 1890 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1891 } 1892 1893 // Allocate special inputs passed in user SGPRs. 1894 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1895 MachineFunction &MF, 1896 const SIRegisterInfo &TRI, 1897 SIMachineFunctionInfo &Info) const { 1898 if (Info.hasImplicitBufferPtr()) { 1899 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1900 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1901 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1902 } 1903 1904 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1905 if (Info.hasPrivateSegmentBuffer()) { 1906 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1907 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1908 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1909 } 1910 1911 if (Info.hasDispatchPtr()) { 1912 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1913 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1914 CCInfo.AllocateReg(DispatchPtrReg); 1915 } 1916 1917 if (Info.hasQueuePtr()) { 1918 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1919 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1920 CCInfo.AllocateReg(QueuePtrReg); 1921 } 1922 1923 if (Info.hasKernargSegmentPtr()) { 1924 MachineRegisterInfo &MRI = MF.getRegInfo(); 1925 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1926 CCInfo.AllocateReg(InputPtrReg); 1927 1928 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1929 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1930 } 1931 1932 if (Info.hasDispatchID()) { 1933 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1934 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1935 CCInfo.AllocateReg(DispatchIDReg); 1936 } 1937 1938 if (Info.hasFlatScratchInit()) { 1939 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1940 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1941 CCInfo.AllocateReg(FlatScratchInitReg); 1942 } 1943 1944 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1945 // these from the dispatch pointer. 1946 } 1947 1948 // Allocate special input registers that are initialized per-wave. 1949 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1950 MachineFunction &MF, 1951 SIMachineFunctionInfo &Info, 1952 CallingConv::ID CallConv, 1953 bool IsShader) const { 1954 if (Info.hasWorkGroupIDX()) { 1955 unsigned Reg = Info.addWorkGroupIDX(); 1956 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1957 CCInfo.AllocateReg(Reg); 1958 } 1959 1960 if (Info.hasWorkGroupIDY()) { 1961 unsigned Reg = Info.addWorkGroupIDY(); 1962 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1963 CCInfo.AllocateReg(Reg); 1964 } 1965 1966 if (Info.hasWorkGroupIDZ()) { 1967 unsigned Reg = Info.addWorkGroupIDZ(); 1968 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1969 CCInfo.AllocateReg(Reg); 1970 } 1971 1972 if (Info.hasWorkGroupInfo()) { 1973 unsigned Reg = Info.addWorkGroupInfo(); 1974 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1975 CCInfo.AllocateReg(Reg); 1976 } 1977 1978 if (Info.hasPrivateSegmentWaveByteOffset()) { 1979 // Scratch wave offset passed in system SGPR. 1980 unsigned PrivateSegmentWaveByteOffsetReg; 1981 1982 if (IsShader) { 1983 PrivateSegmentWaveByteOffsetReg = 1984 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1985 1986 // This is true if the scratch wave byte offset doesn't have a fixed 1987 // location. 1988 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1989 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1990 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1991 } 1992 } else 1993 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1994 1995 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1996 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1997 } 1998 } 1999 2000 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2001 MachineFunction &MF, 2002 const SIRegisterInfo &TRI, 2003 SIMachineFunctionInfo &Info) { 2004 // Now that we've figured out where the scratch register inputs are, see if 2005 // should reserve the arguments and use them directly. 2006 MachineFrameInfo &MFI = MF.getFrameInfo(); 2007 bool HasStackObjects = MFI.hasStackObjects(); 2008 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2009 2010 // Record that we know we have non-spill stack objects so we don't need to 2011 // check all stack objects later. 2012 if (HasStackObjects) 2013 Info.setHasNonSpillStackObjects(true); 2014 2015 // Everything live out of a block is spilled with fast regalloc, so it's 2016 // almost certain that spilling will be required. 2017 if (TM.getOptLevel() == CodeGenOpt::None) 2018 HasStackObjects = true; 2019 2020 // For now assume stack access is needed in any callee functions, so we need 2021 // the scratch registers to pass in. 2022 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2023 2024 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2025 // If we have stack objects, we unquestionably need the private buffer 2026 // resource. For the Code Object V2 ABI, this will be the first 4 user 2027 // SGPR inputs. We can reserve those and use them directly. 2028 2029 Register PrivateSegmentBufferReg = 2030 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2031 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2032 } else { 2033 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2034 // We tentatively reserve the last registers (skipping the last registers 2035 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2036 // we'll replace these with the ones immediately after those which were 2037 // really allocated. In the prologue copies will be inserted from the 2038 // argument to these reserved registers. 2039 2040 // Without HSA, relocations are used for the scratch pointer and the 2041 // buffer resource setup is always inserted in the prologue. Scratch wave 2042 // offset is still in an input SGPR. 2043 Info.setScratchRSrcReg(ReservedBufferReg); 2044 } 2045 2046 MachineRegisterInfo &MRI = MF.getRegInfo(); 2047 2048 // For entry functions we have to set up the stack pointer if we use it, 2049 // whereas non-entry functions get this "for free". This means there is no 2050 // intrinsic advantage to using S32 over S34 in cases where we do not have 2051 // calls but do need a frame pointer (i.e. if we are requested to have one 2052 // because frame pointer elimination is disabled). To keep things simple we 2053 // only ever use S32 as the call ABI stack pointer, and so using it does not 2054 // imply we need a separate frame pointer. 2055 // 2056 // Try to use s32 as the SP, but move it if it would interfere with input 2057 // arguments. This won't work with calls though. 2058 // 2059 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2060 // registers. 2061 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2062 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2063 } else { 2064 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2065 2066 if (MFI.hasCalls()) 2067 report_fatal_error("call in graphics shader with too many input SGPRs"); 2068 2069 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2070 if (!MRI.isLiveIn(Reg)) { 2071 Info.setStackPtrOffsetReg(Reg); 2072 break; 2073 } 2074 } 2075 2076 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2077 report_fatal_error("failed to find register for SP"); 2078 } 2079 2080 // hasFP should be accurate for entry functions even before the frame is 2081 // finalized, because it does not rely on the known stack size, only 2082 // properties like whether variable sized objects are present. 2083 if (ST.getFrameLowering()->hasFP(MF)) { 2084 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2085 } 2086 } 2087 2088 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2089 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2090 return !Info->isEntryFunction(); 2091 } 2092 2093 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2094 2095 } 2096 2097 void SITargetLowering::insertCopiesSplitCSR( 2098 MachineBasicBlock *Entry, 2099 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2100 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2101 2102 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2103 if (!IStart) 2104 return; 2105 2106 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2107 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2108 MachineBasicBlock::iterator MBBI = Entry->begin(); 2109 for (const MCPhysReg *I = IStart; *I; ++I) { 2110 const TargetRegisterClass *RC = nullptr; 2111 if (AMDGPU::SReg_64RegClass.contains(*I)) 2112 RC = &AMDGPU::SGPR_64RegClass; 2113 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2114 RC = &AMDGPU::SGPR_32RegClass; 2115 else 2116 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2117 2118 Register NewVR = MRI->createVirtualRegister(RC); 2119 // Create copy from CSR to a virtual register. 2120 Entry->addLiveIn(*I); 2121 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2122 .addReg(*I); 2123 2124 // Insert the copy-back instructions right before the terminator. 2125 for (auto *Exit : Exits) 2126 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2127 TII->get(TargetOpcode::COPY), *I) 2128 .addReg(NewVR); 2129 } 2130 } 2131 2132 SDValue SITargetLowering::LowerFormalArguments( 2133 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2134 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2135 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2136 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2137 2138 MachineFunction &MF = DAG.getMachineFunction(); 2139 const Function &Fn = MF.getFunction(); 2140 FunctionType *FType = MF.getFunction().getFunctionType(); 2141 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2142 2143 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2144 DiagnosticInfoUnsupported NoGraphicsHSA( 2145 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2146 DAG.getContext()->diagnose(NoGraphicsHSA); 2147 return DAG.getEntryNode(); 2148 } 2149 2150 SmallVector<ISD::InputArg, 16> Splits; 2151 SmallVector<CCValAssign, 16> ArgLocs; 2152 BitVector Skipped(Ins.size()); 2153 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2154 *DAG.getContext()); 2155 2156 bool IsShader = AMDGPU::isShader(CallConv); 2157 bool IsKernel = AMDGPU::isKernel(CallConv); 2158 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2159 2160 if (IsShader) { 2161 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2162 2163 // At least one interpolation mode must be enabled or else the GPU will 2164 // hang. 2165 // 2166 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2167 // set PSInputAddr, the user wants to enable some bits after the compilation 2168 // based on run-time states. Since we can't know what the final PSInputEna 2169 // will look like, so we shouldn't do anything here and the user should take 2170 // responsibility for the correct programming. 2171 // 2172 // Otherwise, the following restrictions apply: 2173 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2174 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2175 // enabled too. 2176 if (CallConv == CallingConv::AMDGPU_PS) { 2177 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2178 ((Info->getPSInputAddr() & 0xF) == 0 && 2179 Info->isPSInputAllocated(11))) { 2180 CCInfo.AllocateReg(AMDGPU::VGPR0); 2181 CCInfo.AllocateReg(AMDGPU::VGPR1); 2182 Info->markPSInputAllocated(0); 2183 Info->markPSInputEnabled(0); 2184 } 2185 if (Subtarget->isAmdPalOS()) { 2186 // For isAmdPalOS, the user does not enable some bits after compilation 2187 // based on run-time states; the register values being generated here are 2188 // the final ones set in hardware. Therefore we need to apply the 2189 // workaround to PSInputAddr and PSInputEnable together. (The case where 2190 // a bit is set in PSInputAddr but not PSInputEnable is where the 2191 // frontend set up an input arg for a particular interpolation mode, but 2192 // nothing uses that input arg. Really we should have an earlier pass 2193 // that removes such an arg.) 2194 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2195 if ((PsInputBits & 0x7F) == 0 || 2196 ((PsInputBits & 0xF) == 0 && 2197 (PsInputBits >> 11 & 1))) 2198 Info->markPSInputEnabled( 2199 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2200 } 2201 } 2202 2203 assert(!Info->hasDispatchPtr() && 2204 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2205 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2206 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2207 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2208 !Info->hasWorkItemIDZ()); 2209 } else if (IsKernel) { 2210 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2211 } else { 2212 Splits.append(Ins.begin(), Ins.end()); 2213 } 2214 2215 if (IsEntryFunc) { 2216 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2217 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2218 } else { 2219 // For the fixed ABI, pass workitem IDs in the last argument register. 2220 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2221 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2222 } 2223 2224 if (IsKernel) { 2225 analyzeFormalArgumentsCompute(CCInfo, Ins); 2226 } else { 2227 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2228 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2229 } 2230 2231 SmallVector<SDValue, 16> Chains; 2232 2233 // FIXME: This is the minimum kernel argument alignment. We should improve 2234 // this to the maximum alignment of the arguments. 2235 // 2236 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2237 // kern arg offset. 2238 const Align KernelArgBaseAlign = Align(16); 2239 2240 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2241 const ISD::InputArg &Arg = Ins[i]; 2242 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2243 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2244 continue; 2245 } 2246 2247 CCValAssign &VA = ArgLocs[ArgIdx++]; 2248 MVT VT = VA.getLocVT(); 2249 2250 if (IsEntryFunc && VA.isMemLoc()) { 2251 VT = Ins[i].VT; 2252 EVT MemVT = VA.getLocVT(); 2253 2254 const uint64_t Offset = VA.getLocMemOffset(); 2255 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2256 2257 if (Arg.Flags.isByRef()) { 2258 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2259 2260 if (!isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2261 Arg.Flags.getPointerAddrSpace())) { 2262 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2263 Arg.Flags.getPointerAddrSpace()); 2264 } 2265 2266 InVals.push_back(Ptr); 2267 continue; 2268 } 2269 2270 SDValue Arg = lowerKernargMemParameter( 2271 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2272 Chains.push_back(Arg.getValue(1)); 2273 2274 auto *ParamTy = 2275 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2276 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2277 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2278 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2279 // On SI local pointers are just offsets into LDS, so they are always 2280 // less than 16-bits. On CI and newer they could potentially be 2281 // real pointers, so we can't guarantee their size. 2282 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2283 DAG.getValueType(MVT::i16)); 2284 } 2285 2286 InVals.push_back(Arg); 2287 continue; 2288 } else if (!IsEntryFunc && VA.isMemLoc()) { 2289 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2290 InVals.push_back(Val); 2291 if (!Arg.Flags.isByVal()) 2292 Chains.push_back(Val.getValue(1)); 2293 continue; 2294 } 2295 2296 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2297 2298 Register Reg = VA.getLocReg(); 2299 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2300 EVT ValVT = VA.getValVT(); 2301 2302 Reg = MF.addLiveIn(Reg, RC); 2303 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2304 2305 if (Arg.Flags.isSRet()) { 2306 // The return object should be reasonably addressable. 2307 2308 // FIXME: This helps when the return is a real sret. If it is a 2309 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2310 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2311 unsigned NumBits 2312 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2313 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2314 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2315 } 2316 2317 // If this is an 8 or 16-bit value, it is really passed promoted 2318 // to 32 bits. Insert an assert[sz]ext to capture this, then 2319 // truncate to the right size. 2320 switch (VA.getLocInfo()) { 2321 case CCValAssign::Full: 2322 break; 2323 case CCValAssign::BCvt: 2324 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2325 break; 2326 case CCValAssign::SExt: 2327 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2328 DAG.getValueType(ValVT)); 2329 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2330 break; 2331 case CCValAssign::ZExt: 2332 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2333 DAG.getValueType(ValVT)); 2334 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2335 break; 2336 case CCValAssign::AExt: 2337 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2338 break; 2339 default: 2340 llvm_unreachable("Unknown loc info!"); 2341 } 2342 2343 InVals.push_back(Val); 2344 } 2345 2346 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2347 // Special inputs come after user arguments. 2348 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2349 } 2350 2351 // Start adding system SGPRs. 2352 if (IsEntryFunc) { 2353 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2354 } else { 2355 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2356 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2357 } 2358 2359 auto &ArgUsageInfo = 2360 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2361 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2362 2363 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2364 Info->setBytesInStackArgArea(StackArgSize); 2365 2366 return Chains.empty() ? Chain : 2367 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2368 } 2369 2370 // TODO: If return values can't fit in registers, we should return as many as 2371 // possible in registers before passing on stack. 2372 bool SITargetLowering::CanLowerReturn( 2373 CallingConv::ID CallConv, 2374 MachineFunction &MF, bool IsVarArg, 2375 const SmallVectorImpl<ISD::OutputArg> &Outs, 2376 LLVMContext &Context) const { 2377 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2378 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2379 // for shaders. Vector types should be explicitly handled by CC. 2380 if (AMDGPU::isEntryFunctionCC(CallConv)) 2381 return true; 2382 2383 SmallVector<CCValAssign, 16> RVLocs; 2384 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2385 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2386 } 2387 2388 SDValue 2389 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2390 bool isVarArg, 2391 const SmallVectorImpl<ISD::OutputArg> &Outs, 2392 const SmallVectorImpl<SDValue> &OutVals, 2393 const SDLoc &DL, SelectionDAG &DAG) const { 2394 MachineFunction &MF = DAG.getMachineFunction(); 2395 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2396 2397 if (AMDGPU::isKernel(CallConv)) { 2398 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2399 OutVals, DL, DAG); 2400 } 2401 2402 bool IsShader = AMDGPU::isShader(CallConv); 2403 2404 Info->setIfReturnsVoid(Outs.empty()); 2405 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2406 2407 // CCValAssign - represent the assignment of the return value to a location. 2408 SmallVector<CCValAssign, 48> RVLocs; 2409 SmallVector<ISD::OutputArg, 48> Splits; 2410 2411 // CCState - Info about the registers and stack slots. 2412 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2413 *DAG.getContext()); 2414 2415 // Analyze outgoing return values. 2416 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2417 2418 SDValue Flag; 2419 SmallVector<SDValue, 48> RetOps; 2420 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2421 2422 // Add return address for callable functions. 2423 if (!Info->isEntryFunction()) { 2424 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2425 SDValue ReturnAddrReg = CreateLiveInRegister( 2426 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2427 2428 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2429 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2430 MVT::i64); 2431 Chain = 2432 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2433 Flag = Chain.getValue(1); 2434 RetOps.push_back(ReturnAddrVirtualReg); 2435 } 2436 2437 // Copy the result values into the output registers. 2438 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2439 ++I, ++RealRVLocIdx) { 2440 CCValAssign &VA = RVLocs[I]; 2441 assert(VA.isRegLoc() && "Can only return in registers!"); 2442 // TODO: Partially return in registers if return values don't fit. 2443 SDValue Arg = OutVals[RealRVLocIdx]; 2444 2445 // Copied from other backends. 2446 switch (VA.getLocInfo()) { 2447 case CCValAssign::Full: 2448 break; 2449 case CCValAssign::BCvt: 2450 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2451 break; 2452 case CCValAssign::SExt: 2453 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2454 break; 2455 case CCValAssign::ZExt: 2456 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2457 break; 2458 case CCValAssign::AExt: 2459 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2460 break; 2461 default: 2462 llvm_unreachable("Unknown loc info!"); 2463 } 2464 2465 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2466 Flag = Chain.getValue(1); 2467 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2468 } 2469 2470 // FIXME: Does sret work properly? 2471 if (!Info->isEntryFunction()) { 2472 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2473 const MCPhysReg *I = 2474 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2475 if (I) { 2476 for (; *I; ++I) { 2477 if (AMDGPU::SReg_64RegClass.contains(*I)) 2478 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2479 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2480 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2481 else 2482 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2483 } 2484 } 2485 } 2486 2487 // Update chain and glue. 2488 RetOps[0] = Chain; 2489 if (Flag.getNode()) 2490 RetOps.push_back(Flag); 2491 2492 unsigned Opc = AMDGPUISD::ENDPGM; 2493 if (!IsWaveEnd) 2494 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2495 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2496 } 2497 2498 SDValue SITargetLowering::LowerCallResult( 2499 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2500 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2501 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2502 SDValue ThisVal) const { 2503 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2504 2505 // Assign locations to each value returned by this call. 2506 SmallVector<CCValAssign, 16> RVLocs; 2507 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2508 *DAG.getContext()); 2509 CCInfo.AnalyzeCallResult(Ins, RetCC); 2510 2511 // Copy all of the result registers out of their specified physreg. 2512 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2513 CCValAssign VA = RVLocs[i]; 2514 SDValue Val; 2515 2516 if (VA.isRegLoc()) { 2517 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2518 Chain = Val.getValue(1); 2519 InFlag = Val.getValue(2); 2520 } else if (VA.isMemLoc()) { 2521 report_fatal_error("TODO: return values in memory"); 2522 } else 2523 llvm_unreachable("unknown argument location type"); 2524 2525 switch (VA.getLocInfo()) { 2526 case CCValAssign::Full: 2527 break; 2528 case CCValAssign::BCvt: 2529 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2530 break; 2531 case CCValAssign::ZExt: 2532 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2533 DAG.getValueType(VA.getValVT())); 2534 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2535 break; 2536 case CCValAssign::SExt: 2537 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2538 DAG.getValueType(VA.getValVT())); 2539 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2540 break; 2541 case CCValAssign::AExt: 2542 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2543 break; 2544 default: 2545 llvm_unreachable("Unknown loc info!"); 2546 } 2547 2548 InVals.push_back(Val); 2549 } 2550 2551 return Chain; 2552 } 2553 2554 // Add code to pass special inputs required depending on used features separate 2555 // from the explicit user arguments present in the IR. 2556 void SITargetLowering::passSpecialInputs( 2557 CallLoweringInfo &CLI, 2558 CCState &CCInfo, 2559 const SIMachineFunctionInfo &Info, 2560 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2561 SmallVectorImpl<SDValue> &MemOpChains, 2562 SDValue Chain) const { 2563 // If we don't have a call site, this was a call inserted by 2564 // legalization. These can never use special inputs. 2565 if (!CLI.CB) 2566 return; 2567 2568 SelectionDAG &DAG = CLI.DAG; 2569 const SDLoc &DL = CLI.DL; 2570 2571 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2572 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2573 2574 const AMDGPUFunctionArgInfo *CalleeArgInfo 2575 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2576 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2577 auto &ArgUsageInfo = 2578 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2579 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2580 } 2581 2582 // TODO: Unify with private memory register handling. This is complicated by 2583 // the fact that at least in kernels, the input argument is not necessarily 2584 // in the same location as the input. 2585 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2586 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2587 AMDGPUFunctionArgInfo::QUEUE_PTR, 2588 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2589 AMDGPUFunctionArgInfo::DISPATCH_ID, 2590 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2591 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2592 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2593 }; 2594 2595 for (auto InputID : InputRegs) { 2596 const ArgDescriptor *OutgoingArg; 2597 const TargetRegisterClass *ArgRC; 2598 LLT ArgTy; 2599 2600 std::tie(OutgoingArg, ArgRC, ArgTy) = 2601 CalleeArgInfo->getPreloadedValue(InputID); 2602 if (!OutgoingArg) 2603 continue; 2604 2605 const ArgDescriptor *IncomingArg; 2606 const TargetRegisterClass *IncomingArgRC; 2607 LLT Ty; 2608 std::tie(IncomingArg, IncomingArgRC, Ty) = 2609 CallerArgInfo.getPreloadedValue(InputID); 2610 assert(IncomingArgRC == ArgRC); 2611 2612 // All special arguments are ints for now. 2613 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2614 SDValue InputReg; 2615 2616 if (IncomingArg) { 2617 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2618 } else { 2619 // The implicit arg ptr is special because it doesn't have a corresponding 2620 // input for kernels, and is computed from the kernarg segment pointer. 2621 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2622 InputReg = getImplicitArgPtr(DAG, DL); 2623 } 2624 2625 if (OutgoingArg->isRegister()) { 2626 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2627 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2628 report_fatal_error("failed to allocate implicit input argument"); 2629 } else { 2630 unsigned SpecialArgOffset = 2631 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2632 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2633 SpecialArgOffset); 2634 MemOpChains.push_back(ArgStore); 2635 } 2636 } 2637 2638 // Pack workitem IDs into a single register or pass it as is if already 2639 // packed. 2640 const ArgDescriptor *OutgoingArg; 2641 const TargetRegisterClass *ArgRC; 2642 LLT Ty; 2643 2644 std::tie(OutgoingArg, ArgRC, Ty) = 2645 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2646 if (!OutgoingArg) 2647 std::tie(OutgoingArg, ArgRC, Ty) = 2648 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2649 if (!OutgoingArg) 2650 std::tie(OutgoingArg, ArgRC, Ty) = 2651 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2652 if (!OutgoingArg) 2653 return; 2654 2655 const ArgDescriptor *IncomingArgX = std::get<0>( 2656 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2657 const ArgDescriptor *IncomingArgY = std::get<0>( 2658 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2659 const ArgDescriptor *IncomingArgZ = std::get<0>( 2660 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2661 2662 SDValue InputReg; 2663 SDLoc SL; 2664 2665 // If incoming ids are not packed we need to pack them. 2666 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2667 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2668 2669 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2670 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2671 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2672 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2673 InputReg = InputReg.getNode() ? 2674 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2675 } 2676 2677 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2678 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2679 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2680 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2681 InputReg = InputReg.getNode() ? 2682 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2683 } 2684 2685 if (!InputReg.getNode()) { 2686 // Workitem ids are already packed, any of present incoming arguments 2687 // will carry all required fields. 2688 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2689 IncomingArgX ? *IncomingArgX : 2690 IncomingArgY ? *IncomingArgY : 2691 *IncomingArgZ, ~0u); 2692 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2693 } 2694 2695 if (OutgoingArg->isRegister()) { 2696 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2697 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2698 } else { 2699 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2700 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2701 SpecialArgOffset); 2702 MemOpChains.push_back(ArgStore); 2703 } 2704 } 2705 2706 static bool canGuaranteeTCO(CallingConv::ID CC) { 2707 return CC == CallingConv::Fast; 2708 } 2709 2710 /// Return true if we might ever do TCO for calls with this calling convention. 2711 static bool mayTailCallThisCC(CallingConv::ID CC) { 2712 switch (CC) { 2713 case CallingConv::C: 2714 return true; 2715 default: 2716 return canGuaranteeTCO(CC); 2717 } 2718 } 2719 2720 bool SITargetLowering::isEligibleForTailCallOptimization( 2721 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2722 const SmallVectorImpl<ISD::OutputArg> &Outs, 2723 const SmallVectorImpl<SDValue> &OutVals, 2724 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2725 if (!mayTailCallThisCC(CalleeCC)) 2726 return false; 2727 2728 MachineFunction &MF = DAG.getMachineFunction(); 2729 const Function &CallerF = MF.getFunction(); 2730 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2731 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2732 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2733 2734 // Kernels aren't callable, and don't have a live in return address so it 2735 // doesn't make sense to do a tail call with entry functions. 2736 if (!CallerPreserved) 2737 return false; 2738 2739 bool CCMatch = CallerCC == CalleeCC; 2740 2741 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2742 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2743 return true; 2744 return false; 2745 } 2746 2747 // TODO: Can we handle var args? 2748 if (IsVarArg) 2749 return false; 2750 2751 for (const Argument &Arg : CallerF.args()) { 2752 if (Arg.hasByValAttr()) 2753 return false; 2754 } 2755 2756 LLVMContext &Ctx = *DAG.getContext(); 2757 2758 // Check that the call results are passed in the same way. 2759 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2760 CCAssignFnForCall(CalleeCC, IsVarArg), 2761 CCAssignFnForCall(CallerCC, IsVarArg))) 2762 return false; 2763 2764 // The callee has to preserve all registers the caller needs to preserve. 2765 if (!CCMatch) { 2766 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2767 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2768 return false; 2769 } 2770 2771 // Nothing more to check if the callee is taking no arguments. 2772 if (Outs.empty()) 2773 return true; 2774 2775 SmallVector<CCValAssign, 16> ArgLocs; 2776 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2777 2778 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2779 2780 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2781 // If the stack arguments for this call do not fit into our own save area then 2782 // the call cannot be made tail. 2783 // TODO: Is this really necessary? 2784 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2785 return false; 2786 2787 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2788 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2789 } 2790 2791 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2792 if (!CI->isTailCall()) 2793 return false; 2794 2795 const Function *ParentFn = CI->getParent()->getParent(); 2796 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2797 return false; 2798 return true; 2799 } 2800 2801 // The wave scratch offset register is used as the global base pointer. 2802 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2803 SmallVectorImpl<SDValue> &InVals) const { 2804 SelectionDAG &DAG = CLI.DAG; 2805 const SDLoc &DL = CLI.DL; 2806 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2807 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2808 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2809 SDValue Chain = CLI.Chain; 2810 SDValue Callee = CLI.Callee; 2811 bool &IsTailCall = CLI.IsTailCall; 2812 CallingConv::ID CallConv = CLI.CallConv; 2813 bool IsVarArg = CLI.IsVarArg; 2814 bool IsSibCall = false; 2815 bool IsThisReturn = false; 2816 MachineFunction &MF = DAG.getMachineFunction(); 2817 2818 if (Callee.isUndef() || isNullConstant(Callee)) { 2819 if (!CLI.IsTailCall) { 2820 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2821 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2822 } 2823 2824 return Chain; 2825 } 2826 2827 if (IsVarArg) { 2828 return lowerUnhandledCall(CLI, InVals, 2829 "unsupported call to variadic function "); 2830 } 2831 2832 if (!CLI.CB) 2833 report_fatal_error("unsupported libcall legalization"); 2834 2835 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2836 !CLI.CB->getCalledFunction()) { 2837 return lowerUnhandledCall(CLI, InVals, 2838 "unsupported indirect call to function "); 2839 } 2840 2841 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2842 return lowerUnhandledCall(CLI, InVals, 2843 "unsupported required tail call to function "); 2844 } 2845 2846 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2847 // Note the issue is with the CC of the calling function, not of the call 2848 // itself. 2849 return lowerUnhandledCall(CLI, InVals, 2850 "unsupported call from graphics shader of function "); 2851 } 2852 2853 if (IsTailCall) { 2854 IsTailCall = isEligibleForTailCallOptimization( 2855 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2856 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2857 report_fatal_error("failed to perform tail call elimination on a call " 2858 "site marked musttail"); 2859 } 2860 2861 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2862 2863 // A sibling call is one where we're under the usual C ABI and not planning 2864 // to change that but can still do a tail call: 2865 if (!TailCallOpt && IsTailCall) 2866 IsSibCall = true; 2867 2868 if (IsTailCall) 2869 ++NumTailCalls; 2870 } 2871 2872 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2873 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2874 SmallVector<SDValue, 8> MemOpChains; 2875 2876 // Analyze operands of the call, assigning locations to each operand. 2877 SmallVector<CCValAssign, 16> ArgLocs; 2878 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2879 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2880 2881 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2882 // With a fixed ABI, allocate fixed registers before user arguments. 2883 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2884 } 2885 2886 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2887 2888 // Get a count of how many bytes are to be pushed on the stack. 2889 unsigned NumBytes = CCInfo.getNextStackOffset(); 2890 2891 if (IsSibCall) { 2892 // Since we're not changing the ABI to make this a tail call, the memory 2893 // operands are already available in the caller's incoming argument space. 2894 NumBytes = 0; 2895 } 2896 2897 // FPDiff is the byte offset of the call's argument area from the callee's. 2898 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2899 // by this amount for a tail call. In a sibling call it must be 0 because the 2900 // caller will deallocate the entire stack and the callee still expects its 2901 // arguments to begin at SP+0. Completely unused for non-tail calls. 2902 int32_t FPDiff = 0; 2903 MachineFrameInfo &MFI = MF.getFrameInfo(); 2904 2905 // Adjust the stack pointer for the new arguments... 2906 // These operations are automatically eliminated by the prolog/epilog pass 2907 if (!IsSibCall) { 2908 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2909 2910 SmallVector<SDValue, 4> CopyFromChains; 2911 2912 // In the HSA case, this should be an identity copy. 2913 SDValue ScratchRSrcReg 2914 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2915 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2916 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2917 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2918 } 2919 2920 MVT PtrVT = MVT::i32; 2921 2922 // Walk the register/memloc assignments, inserting copies/loads. 2923 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2924 CCValAssign &VA = ArgLocs[i]; 2925 SDValue Arg = OutVals[i]; 2926 2927 // Promote the value if needed. 2928 switch (VA.getLocInfo()) { 2929 case CCValAssign::Full: 2930 break; 2931 case CCValAssign::BCvt: 2932 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2933 break; 2934 case CCValAssign::ZExt: 2935 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2936 break; 2937 case CCValAssign::SExt: 2938 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2939 break; 2940 case CCValAssign::AExt: 2941 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2942 break; 2943 case CCValAssign::FPExt: 2944 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2945 break; 2946 default: 2947 llvm_unreachable("Unknown loc info!"); 2948 } 2949 2950 if (VA.isRegLoc()) { 2951 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2952 } else { 2953 assert(VA.isMemLoc()); 2954 2955 SDValue DstAddr; 2956 MachinePointerInfo DstInfo; 2957 2958 unsigned LocMemOffset = VA.getLocMemOffset(); 2959 int32_t Offset = LocMemOffset; 2960 2961 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2962 MaybeAlign Alignment; 2963 2964 if (IsTailCall) { 2965 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2966 unsigned OpSize = Flags.isByVal() ? 2967 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2968 2969 // FIXME: We can have better than the minimum byval required alignment. 2970 Alignment = 2971 Flags.isByVal() 2972 ? Flags.getNonZeroByValAlign() 2973 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2974 2975 Offset = Offset + FPDiff; 2976 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2977 2978 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2979 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2980 2981 // Make sure any stack arguments overlapping with where we're storing 2982 // are loaded before this eventual operation. Otherwise they'll be 2983 // clobbered. 2984 2985 // FIXME: Why is this really necessary? This seems to just result in a 2986 // lot of code to copy the stack and write them back to the same 2987 // locations, which are supposed to be immutable? 2988 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2989 } else { 2990 DstAddr = PtrOff; 2991 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2992 Alignment = 2993 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2994 } 2995 2996 if (Outs[i].Flags.isByVal()) { 2997 SDValue SizeNode = 2998 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2999 SDValue Cpy = 3000 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3001 Outs[i].Flags.getNonZeroByValAlign(), 3002 /*isVol = */ false, /*AlwaysInline = */ true, 3003 /*isTailCall = */ false, DstInfo, 3004 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3005 3006 MemOpChains.push_back(Cpy); 3007 } else { 3008 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 3009 Alignment ? Alignment->value() : 0); 3010 MemOpChains.push_back(Store); 3011 } 3012 } 3013 } 3014 3015 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3016 // Copy special input registers after user input arguments. 3017 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3018 } 3019 3020 if (!MemOpChains.empty()) 3021 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3022 3023 // Build a sequence of copy-to-reg nodes chained together with token chain 3024 // and flag operands which copy the outgoing args into the appropriate regs. 3025 SDValue InFlag; 3026 for (auto &RegToPass : RegsToPass) { 3027 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3028 RegToPass.second, InFlag); 3029 InFlag = Chain.getValue(1); 3030 } 3031 3032 3033 SDValue PhysReturnAddrReg; 3034 if (IsTailCall) { 3035 // Since the return is being combined with the call, we need to pass on the 3036 // return address. 3037 3038 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3039 SDValue ReturnAddrReg = CreateLiveInRegister( 3040 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3041 3042 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3043 MVT::i64); 3044 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3045 InFlag = Chain.getValue(1); 3046 } 3047 3048 // We don't usually want to end the call-sequence here because we would tidy 3049 // the frame up *after* the call, however in the ABI-changing tail-call case 3050 // we've carefully laid out the parameters so that when sp is reset they'll be 3051 // in the correct location. 3052 if (IsTailCall && !IsSibCall) { 3053 Chain = DAG.getCALLSEQ_END(Chain, 3054 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3055 DAG.getTargetConstant(0, DL, MVT::i32), 3056 InFlag, DL); 3057 InFlag = Chain.getValue(1); 3058 } 3059 3060 std::vector<SDValue> Ops; 3061 Ops.push_back(Chain); 3062 Ops.push_back(Callee); 3063 // Add a redundant copy of the callee global which will not be legalized, as 3064 // we need direct access to the callee later. 3065 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3066 const GlobalValue *GV = GSD->getGlobal(); 3067 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3068 } else { 3069 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3070 } 3071 3072 if (IsTailCall) { 3073 // Each tail call may have to adjust the stack by a different amount, so 3074 // this information must travel along with the operation for eventual 3075 // consumption by emitEpilogue. 3076 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3077 3078 Ops.push_back(PhysReturnAddrReg); 3079 } 3080 3081 // Add argument registers to the end of the list so that they are known live 3082 // into the call. 3083 for (auto &RegToPass : RegsToPass) { 3084 Ops.push_back(DAG.getRegister(RegToPass.first, 3085 RegToPass.second.getValueType())); 3086 } 3087 3088 // Add a register mask operand representing the call-preserved registers. 3089 3090 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3091 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3092 assert(Mask && "Missing call preserved mask for calling convention"); 3093 Ops.push_back(DAG.getRegisterMask(Mask)); 3094 3095 if (InFlag.getNode()) 3096 Ops.push_back(InFlag); 3097 3098 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3099 3100 // If we're doing a tall call, use a TC_RETURN here rather than an 3101 // actual call instruction. 3102 if (IsTailCall) { 3103 MFI.setHasTailCall(); 3104 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3105 } 3106 3107 // Returns a chain and a flag for retval copy to use. 3108 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3109 Chain = Call.getValue(0); 3110 InFlag = Call.getValue(1); 3111 3112 uint64_t CalleePopBytes = NumBytes; 3113 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3114 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3115 InFlag, DL); 3116 if (!Ins.empty()) 3117 InFlag = Chain.getValue(1); 3118 3119 // Handle result values, copying them out of physregs into vregs that we 3120 // return. 3121 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3122 InVals, IsThisReturn, 3123 IsThisReturn ? OutVals[0] : SDValue()); 3124 } 3125 3126 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3127 // except for applying the wave size scale to the increment amount. 3128 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3129 SDValue Op, SelectionDAG &DAG) const { 3130 const MachineFunction &MF = DAG.getMachineFunction(); 3131 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3132 3133 SDLoc dl(Op); 3134 EVT VT = Op.getValueType(); 3135 SDValue Tmp1 = Op; 3136 SDValue Tmp2 = Op.getValue(1); 3137 SDValue Tmp3 = Op.getOperand(2); 3138 SDValue Chain = Tmp1.getOperand(0); 3139 3140 Register SPReg = Info->getStackPtrOffsetReg(); 3141 3142 // Chain the dynamic stack allocation so that it doesn't modify the stack 3143 // pointer when other instructions are using the stack. 3144 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3145 3146 SDValue Size = Tmp2.getOperand(1); 3147 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3148 Chain = SP.getValue(1); 3149 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3150 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3151 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3152 unsigned Opc = 3153 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3154 ISD::ADD : ISD::SUB; 3155 3156 SDValue ScaledSize = DAG.getNode( 3157 ISD::SHL, dl, VT, Size, 3158 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3159 3160 Align StackAlign = TFL->getStackAlign(); 3161 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3162 if (Alignment && *Alignment > StackAlign) { 3163 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3164 DAG.getConstant(-(uint64_t)Alignment->value() 3165 << ST.getWavefrontSizeLog2(), 3166 dl, VT)); 3167 } 3168 3169 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3170 Tmp2 = DAG.getCALLSEQ_END( 3171 Chain, DAG.getIntPtrConstant(0, dl, true), 3172 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3173 3174 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3175 } 3176 3177 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3178 SelectionDAG &DAG) const { 3179 // We only handle constant sizes here to allow non-entry block, static sized 3180 // allocas. A truly dynamic value is more difficult to support because we 3181 // don't know if the size value is uniform or not. If the size isn't uniform, 3182 // we would need to do a wave reduction to get the maximum size to know how 3183 // much to increment the uniform stack pointer. 3184 SDValue Size = Op.getOperand(1); 3185 if (isa<ConstantSDNode>(Size)) 3186 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3187 3188 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3189 } 3190 3191 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3192 const MachineFunction &MF) const { 3193 Register Reg = StringSwitch<Register>(RegName) 3194 .Case("m0", AMDGPU::M0) 3195 .Case("exec", AMDGPU::EXEC) 3196 .Case("exec_lo", AMDGPU::EXEC_LO) 3197 .Case("exec_hi", AMDGPU::EXEC_HI) 3198 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3199 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3200 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3201 .Default(Register()); 3202 3203 if (Reg == AMDGPU::NoRegister) { 3204 report_fatal_error(Twine("invalid register name \"" 3205 + StringRef(RegName) + "\".")); 3206 3207 } 3208 3209 if (!Subtarget->hasFlatScrRegister() && 3210 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3211 report_fatal_error(Twine("invalid register \"" 3212 + StringRef(RegName) + "\" for subtarget.")); 3213 } 3214 3215 switch (Reg) { 3216 case AMDGPU::M0: 3217 case AMDGPU::EXEC_LO: 3218 case AMDGPU::EXEC_HI: 3219 case AMDGPU::FLAT_SCR_LO: 3220 case AMDGPU::FLAT_SCR_HI: 3221 if (VT.getSizeInBits() == 32) 3222 return Reg; 3223 break; 3224 case AMDGPU::EXEC: 3225 case AMDGPU::FLAT_SCR: 3226 if (VT.getSizeInBits() == 64) 3227 return Reg; 3228 break; 3229 default: 3230 llvm_unreachable("missing register type checking"); 3231 } 3232 3233 report_fatal_error(Twine("invalid type for register \"" 3234 + StringRef(RegName) + "\".")); 3235 } 3236 3237 // If kill is not the last instruction, split the block so kill is always a 3238 // proper terminator. 3239 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3240 MachineBasicBlock *BB) const { 3241 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3242 3243 MachineBasicBlock::iterator SplitPoint(&MI); 3244 ++SplitPoint; 3245 3246 if (SplitPoint == BB->end()) { 3247 // Don't bother with a new block. 3248 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3249 return BB; 3250 } 3251 3252 MachineFunction *MF = BB->getParent(); 3253 MachineBasicBlock *SplitBB 3254 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3255 3256 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3257 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3258 3259 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3260 BB->addSuccessor(SplitBB); 3261 3262 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3263 return SplitBB; 3264 } 3265 3266 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3267 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3268 // be the first instruction in the remainder block. 3269 // 3270 /// \returns { LoopBody, Remainder } 3271 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3272 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3273 MachineFunction *MF = MBB.getParent(); 3274 MachineBasicBlock::iterator I(&MI); 3275 3276 // To insert the loop we need to split the block. Move everything after this 3277 // point to a new block, and insert a new empty block between the two. 3278 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3279 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3280 MachineFunction::iterator MBBI(MBB); 3281 ++MBBI; 3282 3283 MF->insert(MBBI, LoopBB); 3284 MF->insert(MBBI, RemainderBB); 3285 3286 LoopBB->addSuccessor(LoopBB); 3287 LoopBB->addSuccessor(RemainderBB); 3288 3289 // Move the rest of the block into a new block. 3290 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3291 3292 if (InstInLoop) { 3293 auto Next = std::next(I); 3294 3295 // Move instruction to loop body. 3296 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3297 3298 // Move the rest of the block. 3299 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3300 } else { 3301 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3302 } 3303 3304 MBB.addSuccessor(LoopBB); 3305 3306 return std::make_pair(LoopBB, RemainderBB); 3307 } 3308 3309 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3310 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3311 MachineBasicBlock *MBB = MI.getParent(); 3312 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3313 auto I = MI.getIterator(); 3314 auto E = std::next(I); 3315 3316 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3317 .addImm(0); 3318 3319 MIBundleBuilder Bundler(*MBB, I, E); 3320 finalizeBundle(*MBB, Bundler.begin()); 3321 } 3322 3323 MachineBasicBlock * 3324 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3325 MachineBasicBlock *BB) const { 3326 const DebugLoc &DL = MI.getDebugLoc(); 3327 3328 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3329 3330 MachineBasicBlock *LoopBB; 3331 MachineBasicBlock *RemainderBB; 3332 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3333 3334 // Apparently kill flags are only valid if the def is in the same block? 3335 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3336 Src->setIsKill(false); 3337 3338 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3339 3340 MachineBasicBlock::iterator I = LoopBB->end(); 3341 3342 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3343 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3344 3345 // Clear TRAP_STS.MEM_VIOL 3346 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3347 .addImm(0) 3348 .addImm(EncodedReg); 3349 3350 bundleInstWithWaitcnt(MI); 3351 3352 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3353 3354 // Load and check TRAP_STS.MEM_VIOL 3355 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3356 .addImm(EncodedReg); 3357 3358 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3359 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3360 .addReg(Reg, RegState::Kill) 3361 .addImm(0); 3362 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3363 .addMBB(LoopBB); 3364 3365 return RemainderBB; 3366 } 3367 3368 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3369 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3370 // will only do one iteration. In the worst case, this will loop 64 times. 3371 // 3372 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3373 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3374 const SIInstrInfo *TII, 3375 MachineRegisterInfo &MRI, 3376 MachineBasicBlock &OrigBB, 3377 MachineBasicBlock &LoopBB, 3378 const DebugLoc &DL, 3379 const MachineOperand &IdxReg, 3380 unsigned InitReg, 3381 unsigned ResultReg, 3382 unsigned PhiReg, 3383 unsigned InitSaveExecReg, 3384 int Offset, 3385 bool UseGPRIdxMode, 3386 bool IsIndirectSrc) { 3387 MachineFunction *MF = OrigBB.getParent(); 3388 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3389 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3390 MachineBasicBlock::iterator I = LoopBB.begin(); 3391 3392 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3393 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3394 Register NewExec = MRI.createVirtualRegister(BoolRC); 3395 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3396 Register CondReg = MRI.createVirtualRegister(BoolRC); 3397 3398 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3399 .addReg(InitReg) 3400 .addMBB(&OrigBB) 3401 .addReg(ResultReg) 3402 .addMBB(&LoopBB); 3403 3404 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3405 .addReg(InitSaveExecReg) 3406 .addMBB(&OrigBB) 3407 .addReg(NewExec) 3408 .addMBB(&LoopBB); 3409 3410 // Read the next variant <- also loop target. 3411 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3412 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3413 3414 // Compare the just read M0 value to all possible Idx values. 3415 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3416 .addReg(CurrentIdxReg) 3417 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3418 3419 // Update EXEC, save the original EXEC value to VCC. 3420 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3421 : AMDGPU::S_AND_SAVEEXEC_B64), 3422 NewExec) 3423 .addReg(CondReg, RegState::Kill); 3424 3425 MRI.setSimpleHint(NewExec, CondReg); 3426 3427 if (UseGPRIdxMode) { 3428 unsigned IdxReg; 3429 if (Offset == 0) { 3430 IdxReg = CurrentIdxReg; 3431 } else { 3432 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3433 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3434 .addReg(CurrentIdxReg, RegState::Kill) 3435 .addImm(Offset); 3436 } 3437 unsigned IdxMode = IsIndirectSrc ? 3438 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3439 MachineInstr *SetOn = 3440 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3441 .addReg(IdxReg, RegState::Kill) 3442 .addImm(IdxMode); 3443 SetOn->getOperand(3).setIsUndef(); 3444 } else { 3445 // Move index from VCC into M0 3446 if (Offset == 0) { 3447 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3448 .addReg(CurrentIdxReg, RegState::Kill); 3449 } else { 3450 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3451 .addReg(CurrentIdxReg, RegState::Kill) 3452 .addImm(Offset); 3453 } 3454 } 3455 3456 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3457 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3458 MachineInstr *InsertPt = 3459 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3460 : AMDGPU::S_XOR_B64_term), Exec) 3461 .addReg(Exec) 3462 .addReg(NewExec); 3463 3464 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3465 // s_cbranch_scc0? 3466 3467 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3468 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3469 .addMBB(&LoopBB); 3470 3471 return InsertPt->getIterator(); 3472 } 3473 3474 // This has slightly sub-optimal regalloc when the source vector is killed by 3475 // the read. The register allocator does not understand that the kill is 3476 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3477 // subregister from it, using 1 more VGPR than necessary. This was saved when 3478 // this was expanded after register allocation. 3479 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3480 MachineBasicBlock &MBB, 3481 MachineInstr &MI, 3482 unsigned InitResultReg, 3483 unsigned PhiReg, 3484 int Offset, 3485 bool UseGPRIdxMode, 3486 bool IsIndirectSrc) { 3487 MachineFunction *MF = MBB.getParent(); 3488 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3489 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3490 MachineRegisterInfo &MRI = MF->getRegInfo(); 3491 const DebugLoc &DL = MI.getDebugLoc(); 3492 MachineBasicBlock::iterator I(&MI); 3493 3494 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3495 Register DstReg = MI.getOperand(0).getReg(); 3496 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3497 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3498 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3499 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3500 3501 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3502 3503 // Save the EXEC mask 3504 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3505 .addReg(Exec); 3506 3507 MachineBasicBlock *LoopBB; 3508 MachineBasicBlock *RemainderBB; 3509 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3510 3511 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3512 3513 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3514 InitResultReg, DstReg, PhiReg, TmpExec, 3515 Offset, UseGPRIdxMode, IsIndirectSrc); 3516 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3517 MachineFunction::iterator MBBI(LoopBB); 3518 ++MBBI; 3519 MF->insert(MBBI, LandingPad); 3520 LoopBB->removeSuccessor(RemainderBB); 3521 LandingPad->addSuccessor(RemainderBB); 3522 LoopBB->addSuccessor(LandingPad); 3523 MachineBasicBlock::iterator First = LandingPad->begin(); 3524 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3525 .addReg(SaveExec); 3526 3527 return InsPt; 3528 } 3529 3530 // Returns subreg index, offset 3531 static std::pair<unsigned, int> 3532 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3533 const TargetRegisterClass *SuperRC, 3534 unsigned VecReg, 3535 int Offset) { 3536 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3537 3538 // Skip out of bounds offsets, or else we would end up using an undefined 3539 // register. 3540 if (Offset >= NumElts || Offset < 0) 3541 return std::make_pair(AMDGPU::sub0, Offset); 3542 3543 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3544 } 3545 3546 // Return true if the index is an SGPR and was set. 3547 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3548 MachineRegisterInfo &MRI, 3549 MachineInstr &MI, 3550 int Offset, 3551 bool UseGPRIdxMode, 3552 bool IsIndirectSrc) { 3553 MachineBasicBlock *MBB = MI.getParent(); 3554 const DebugLoc &DL = MI.getDebugLoc(); 3555 MachineBasicBlock::iterator I(&MI); 3556 3557 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3558 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3559 3560 assert(Idx->getReg() != AMDGPU::NoRegister); 3561 3562 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3563 return false; 3564 3565 if (UseGPRIdxMode) { 3566 unsigned IdxMode = IsIndirectSrc ? 3567 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3568 if (Offset == 0) { 3569 MachineInstr *SetOn = 3570 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3571 .add(*Idx) 3572 .addImm(IdxMode); 3573 3574 SetOn->getOperand(3).setIsUndef(); 3575 } else { 3576 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3577 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3578 .add(*Idx) 3579 .addImm(Offset); 3580 MachineInstr *SetOn = 3581 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3582 .addReg(Tmp, RegState::Kill) 3583 .addImm(IdxMode); 3584 3585 SetOn->getOperand(3).setIsUndef(); 3586 } 3587 3588 return true; 3589 } 3590 3591 if (Offset == 0) { 3592 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3593 .add(*Idx); 3594 } else { 3595 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3596 .add(*Idx) 3597 .addImm(Offset); 3598 } 3599 3600 return true; 3601 } 3602 3603 // Control flow needs to be inserted if indexing with a VGPR. 3604 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3605 MachineBasicBlock &MBB, 3606 const GCNSubtarget &ST) { 3607 const SIInstrInfo *TII = ST.getInstrInfo(); 3608 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3609 MachineFunction *MF = MBB.getParent(); 3610 MachineRegisterInfo &MRI = MF->getRegInfo(); 3611 3612 Register Dst = MI.getOperand(0).getReg(); 3613 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3614 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3615 3616 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3617 3618 unsigned SubReg; 3619 std::tie(SubReg, Offset) 3620 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3621 3622 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3623 3624 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3625 MachineBasicBlock::iterator I(&MI); 3626 const DebugLoc &DL = MI.getDebugLoc(); 3627 3628 if (UseGPRIdxMode) { 3629 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3630 // to avoid interfering with other uses, so probably requires a new 3631 // optimization pass. 3632 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3633 .addReg(SrcReg, RegState::Undef, SubReg) 3634 .addReg(SrcReg, RegState::Implicit) 3635 .addReg(AMDGPU::M0, RegState::Implicit); 3636 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3637 } else { 3638 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3639 .addReg(SrcReg, RegState::Undef, SubReg) 3640 .addReg(SrcReg, RegState::Implicit); 3641 } 3642 3643 MI.eraseFromParent(); 3644 3645 return &MBB; 3646 } 3647 3648 const DebugLoc &DL = MI.getDebugLoc(); 3649 MachineBasicBlock::iterator I(&MI); 3650 3651 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3652 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3653 3654 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3655 3656 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3657 Offset, UseGPRIdxMode, true); 3658 MachineBasicBlock *LoopBB = InsPt->getParent(); 3659 3660 if (UseGPRIdxMode) { 3661 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3662 .addReg(SrcReg, RegState::Undef, SubReg) 3663 .addReg(SrcReg, RegState::Implicit) 3664 .addReg(AMDGPU::M0, RegState::Implicit); 3665 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3666 } else { 3667 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3668 .addReg(SrcReg, RegState::Undef, SubReg) 3669 .addReg(SrcReg, RegState::Implicit); 3670 } 3671 3672 MI.eraseFromParent(); 3673 3674 return LoopBB; 3675 } 3676 3677 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3678 MachineBasicBlock &MBB, 3679 const GCNSubtarget &ST) { 3680 const SIInstrInfo *TII = ST.getInstrInfo(); 3681 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3682 MachineFunction *MF = MBB.getParent(); 3683 MachineRegisterInfo &MRI = MF->getRegInfo(); 3684 3685 Register Dst = MI.getOperand(0).getReg(); 3686 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3687 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3688 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3689 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3690 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3691 3692 // This can be an immediate, but will be folded later. 3693 assert(Val->getReg()); 3694 3695 unsigned SubReg; 3696 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3697 SrcVec->getReg(), 3698 Offset); 3699 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3700 3701 if (Idx->getReg() == AMDGPU::NoRegister) { 3702 MachineBasicBlock::iterator I(&MI); 3703 const DebugLoc &DL = MI.getDebugLoc(); 3704 3705 assert(Offset == 0); 3706 3707 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3708 .add(*SrcVec) 3709 .add(*Val) 3710 .addImm(SubReg); 3711 3712 MI.eraseFromParent(); 3713 return &MBB; 3714 } 3715 3716 const MCInstrDesc &MovRelDesc 3717 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3718 3719 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3720 MachineBasicBlock::iterator I(&MI); 3721 const DebugLoc &DL = MI.getDebugLoc(); 3722 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3723 .addReg(SrcVec->getReg()) 3724 .add(*Val) 3725 .addImm(SubReg); 3726 if (UseGPRIdxMode) 3727 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3728 3729 MI.eraseFromParent(); 3730 return &MBB; 3731 } 3732 3733 if (Val->isReg()) 3734 MRI.clearKillFlags(Val->getReg()); 3735 3736 const DebugLoc &DL = MI.getDebugLoc(); 3737 3738 Register PhiReg = MRI.createVirtualRegister(VecRC); 3739 3740 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3741 Offset, UseGPRIdxMode, false); 3742 MachineBasicBlock *LoopBB = InsPt->getParent(); 3743 3744 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3745 .addReg(PhiReg) 3746 .add(*Val) 3747 .addImm(AMDGPU::sub0); 3748 if (UseGPRIdxMode) 3749 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3750 3751 MI.eraseFromParent(); 3752 return LoopBB; 3753 } 3754 3755 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3756 MachineInstr &MI, MachineBasicBlock *BB) const { 3757 3758 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3759 MachineFunction *MF = BB->getParent(); 3760 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3761 3762 switch (MI.getOpcode()) { 3763 case AMDGPU::S_UADDO_PSEUDO: 3764 case AMDGPU::S_USUBO_PSEUDO: { 3765 const DebugLoc &DL = MI.getDebugLoc(); 3766 MachineOperand &Dest0 = MI.getOperand(0); 3767 MachineOperand &Dest1 = MI.getOperand(1); 3768 MachineOperand &Src0 = MI.getOperand(2); 3769 MachineOperand &Src1 = MI.getOperand(3); 3770 3771 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3772 ? AMDGPU::S_ADD_I32 3773 : AMDGPU::S_SUB_I32; 3774 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3775 3776 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3777 .addImm(1) 3778 .addImm(0); 3779 3780 MI.eraseFromParent(); 3781 return BB; 3782 } 3783 case AMDGPU::S_ADD_U64_PSEUDO: 3784 case AMDGPU::S_SUB_U64_PSEUDO: { 3785 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3786 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3787 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3788 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3789 const DebugLoc &DL = MI.getDebugLoc(); 3790 3791 MachineOperand &Dest = MI.getOperand(0); 3792 MachineOperand &Src0 = MI.getOperand(1); 3793 MachineOperand &Src1 = MI.getOperand(2); 3794 3795 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3796 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3797 3798 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3799 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3800 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3801 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3802 3803 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3804 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3805 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3806 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3807 3808 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3809 3810 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3811 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3812 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3813 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3814 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3815 .addReg(DestSub0) 3816 .addImm(AMDGPU::sub0) 3817 .addReg(DestSub1) 3818 .addImm(AMDGPU::sub1); 3819 MI.eraseFromParent(); 3820 return BB; 3821 } 3822 case AMDGPU::V_ADD_U64_PSEUDO: 3823 case AMDGPU::V_SUB_U64_PSEUDO: { 3824 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3825 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3826 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3827 const DebugLoc &DL = MI.getDebugLoc(); 3828 3829 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3830 3831 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3832 3833 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3834 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3835 3836 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3837 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3838 3839 MachineOperand &Dest = MI.getOperand(0); 3840 MachineOperand &Src0 = MI.getOperand(1); 3841 MachineOperand &Src1 = MI.getOperand(2); 3842 3843 const TargetRegisterClass *Src0RC = Src0.isReg() 3844 ? MRI.getRegClass(Src0.getReg()) 3845 : &AMDGPU::VReg_64RegClass; 3846 const TargetRegisterClass *Src1RC = Src1.isReg() 3847 ? MRI.getRegClass(Src1.getReg()) 3848 : &AMDGPU::VReg_64RegClass; 3849 3850 const TargetRegisterClass *Src0SubRC = 3851 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3852 const TargetRegisterClass *Src1SubRC = 3853 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3854 3855 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3856 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3857 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3858 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3859 3860 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3861 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3862 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3863 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3864 3865 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3866 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3867 .addReg(CarryReg, RegState::Define) 3868 .add(SrcReg0Sub0) 3869 .add(SrcReg1Sub0) 3870 .addImm(0); // clamp bit 3871 3872 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3873 MachineInstr *HiHalf = 3874 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3875 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3876 .add(SrcReg0Sub1) 3877 .add(SrcReg1Sub1) 3878 .addReg(CarryReg, RegState::Kill) 3879 .addImm(0); // clamp bit 3880 3881 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3882 .addReg(DestSub0) 3883 .addImm(AMDGPU::sub0) 3884 .addReg(DestSub1) 3885 .addImm(AMDGPU::sub1); 3886 TII->legalizeOperands(*LoHalf); 3887 TII->legalizeOperands(*HiHalf); 3888 MI.eraseFromParent(); 3889 return BB; 3890 } 3891 case AMDGPU::S_ADD_CO_PSEUDO: 3892 case AMDGPU::S_SUB_CO_PSEUDO: { 3893 // This pseudo has a chance to be selected 3894 // only from uniform add/subcarry node. All the VGPR operands 3895 // therefore assumed to be splat vectors. 3896 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3897 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3898 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3899 MachineBasicBlock::iterator MII = MI; 3900 const DebugLoc &DL = MI.getDebugLoc(); 3901 MachineOperand &Dest = MI.getOperand(0); 3902 MachineOperand &CarryDest = MI.getOperand(1); 3903 MachineOperand &Src0 = MI.getOperand(2); 3904 MachineOperand &Src1 = MI.getOperand(3); 3905 MachineOperand &Src2 = MI.getOperand(4); 3906 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3907 ? AMDGPU::S_ADDC_U32 3908 : AMDGPU::S_SUBB_U32; 3909 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3910 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3911 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3912 .addReg(Src0.getReg()); 3913 Src0.setReg(RegOp0); 3914 } 3915 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3916 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3917 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3918 .addReg(Src1.getReg()); 3919 Src1.setReg(RegOp1); 3920 } 3921 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3922 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3923 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3924 .addReg(Src2.getReg()); 3925 Src2.setReg(RegOp2); 3926 } 3927 3928 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3929 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3930 .addReg(Src2.getReg()) 3931 .addImm(0); 3932 } else { 3933 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3934 .addReg(Src2.getReg()) 3935 .addImm(0); 3936 } 3937 3938 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3939 3940 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 3941 .addReg(AMDGPU::SCC); 3942 MI.eraseFromParent(); 3943 return BB; 3944 } 3945 case AMDGPU::SI_INIT_M0: { 3946 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3947 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3948 .add(MI.getOperand(0)); 3949 MI.eraseFromParent(); 3950 return BB; 3951 } 3952 case AMDGPU::SI_INIT_EXEC: 3953 // This should be before all vector instructions. 3954 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3955 AMDGPU::EXEC) 3956 .addImm(MI.getOperand(0).getImm()); 3957 MI.eraseFromParent(); 3958 return BB; 3959 3960 case AMDGPU::SI_INIT_EXEC_LO: 3961 // This should be before all vector instructions. 3962 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3963 AMDGPU::EXEC_LO) 3964 .addImm(MI.getOperand(0).getImm()); 3965 MI.eraseFromParent(); 3966 return BB; 3967 3968 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3969 // Extract the thread count from an SGPR input and set EXEC accordingly. 3970 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3971 // 3972 // S_BFE_U32 count, input, {shift, 7} 3973 // S_BFM_B64 exec, count, 0 3974 // S_CMP_EQ_U32 count, 64 3975 // S_CMOV_B64 exec, -1 3976 MachineInstr *FirstMI = &*BB->begin(); 3977 MachineRegisterInfo &MRI = MF->getRegInfo(); 3978 Register InputReg = MI.getOperand(0).getReg(); 3979 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3980 bool Found = false; 3981 3982 // Move the COPY of the input reg to the beginning, so that we can use it. 3983 for (auto I = BB->begin(); I != &MI; I++) { 3984 if (I->getOpcode() != TargetOpcode::COPY || 3985 I->getOperand(0).getReg() != InputReg) 3986 continue; 3987 3988 if (I == FirstMI) { 3989 FirstMI = &*++BB->begin(); 3990 } else { 3991 I->removeFromParent(); 3992 BB->insert(FirstMI, &*I); 3993 } 3994 Found = true; 3995 break; 3996 } 3997 assert(Found); 3998 (void)Found; 3999 4000 // This should be before all vector instructions. 4001 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4002 bool isWave32 = getSubtarget()->isWave32(); 4003 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4004 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4005 .addReg(InputReg) 4006 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4007 BuildMI(*BB, FirstMI, DebugLoc(), 4008 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4009 Exec) 4010 .addReg(CountReg) 4011 .addImm(0); 4012 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4013 .addReg(CountReg, RegState::Kill) 4014 .addImm(getSubtarget()->getWavefrontSize()); 4015 BuildMI(*BB, FirstMI, DebugLoc(), 4016 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4017 Exec) 4018 .addImm(-1); 4019 MI.eraseFromParent(); 4020 return BB; 4021 } 4022 4023 case AMDGPU::GET_GROUPSTATICSIZE: { 4024 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4025 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4026 DebugLoc DL = MI.getDebugLoc(); 4027 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4028 .add(MI.getOperand(0)) 4029 .addImm(MFI->getLDSSize()); 4030 MI.eraseFromParent(); 4031 return BB; 4032 } 4033 case AMDGPU::SI_INDIRECT_SRC_V1: 4034 case AMDGPU::SI_INDIRECT_SRC_V2: 4035 case AMDGPU::SI_INDIRECT_SRC_V4: 4036 case AMDGPU::SI_INDIRECT_SRC_V8: 4037 case AMDGPU::SI_INDIRECT_SRC_V16: 4038 case AMDGPU::SI_INDIRECT_SRC_V32: 4039 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4040 case AMDGPU::SI_INDIRECT_DST_V1: 4041 case AMDGPU::SI_INDIRECT_DST_V2: 4042 case AMDGPU::SI_INDIRECT_DST_V4: 4043 case AMDGPU::SI_INDIRECT_DST_V8: 4044 case AMDGPU::SI_INDIRECT_DST_V16: 4045 case AMDGPU::SI_INDIRECT_DST_V32: 4046 return emitIndirectDst(MI, *BB, *getSubtarget()); 4047 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4048 case AMDGPU::SI_KILL_I1_PSEUDO: 4049 return splitKillBlock(MI, BB); 4050 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4051 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4052 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4053 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4054 4055 Register Dst = MI.getOperand(0).getReg(); 4056 Register Src0 = MI.getOperand(1).getReg(); 4057 Register Src1 = MI.getOperand(2).getReg(); 4058 const DebugLoc &DL = MI.getDebugLoc(); 4059 Register SrcCond = MI.getOperand(3).getReg(); 4060 4061 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4062 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4063 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4064 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4065 4066 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4067 .addReg(SrcCond); 4068 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4069 .addImm(0) 4070 .addReg(Src0, 0, AMDGPU::sub0) 4071 .addImm(0) 4072 .addReg(Src1, 0, AMDGPU::sub0) 4073 .addReg(SrcCondCopy); 4074 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4075 .addImm(0) 4076 .addReg(Src0, 0, AMDGPU::sub1) 4077 .addImm(0) 4078 .addReg(Src1, 0, AMDGPU::sub1) 4079 .addReg(SrcCondCopy); 4080 4081 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4082 .addReg(DstLo) 4083 .addImm(AMDGPU::sub0) 4084 .addReg(DstHi) 4085 .addImm(AMDGPU::sub1); 4086 MI.eraseFromParent(); 4087 return BB; 4088 } 4089 case AMDGPU::SI_BR_UNDEF: { 4090 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4091 const DebugLoc &DL = MI.getDebugLoc(); 4092 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4093 .add(MI.getOperand(0)); 4094 Br->getOperand(1).setIsUndef(true); // read undef SCC 4095 MI.eraseFromParent(); 4096 return BB; 4097 } 4098 case AMDGPU::ADJCALLSTACKUP: 4099 case AMDGPU::ADJCALLSTACKDOWN: { 4100 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4101 MachineInstrBuilder MIB(*MF, &MI); 4102 4103 // Add an implicit use of the frame offset reg to prevent the restore copy 4104 // inserted after the call from being reorderd after stack operations in the 4105 // the caller's frame. 4106 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4107 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4108 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4109 return BB; 4110 } 4111 case AMDGPU::SI_CALL_ISEL: { 4112 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4113 const DebugLoc &DL = MI.getDebugLoc(); 4114 4115 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4116 4117 MachineInstrBuilder MIB; 4118 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4119 4120 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4121 MIB.add(MI.getOperand(I)); 4122 4123 MIB.cloneMemRefs(MI); 4124 MI.eraseFromParent(); 4125 return BB; 4126 } 4127 case AMDGPU::V_ADD_CO_U32_e32: 4128 case AMDGPU::V_SUB_CO_U32_e32: 4129 case AMDGPU::V_SUBREV_CO_U32_e32: { 4130 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4131 const DebugLoc &DL = MI.getDebugLoc(); 4132 unsigned Opc = MI.getOpcode(); 4133 4134 bool NeedClampOperand = false; 4135 if (TII->pseudoToMCOpcode(Opc) == -1) { 4136 Opc = AMDGPU::getVOPe64(Opc); 4137 NeedClampOperand = true; 4138 } 4139 4140 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4141 if (TII->isVOP3(*I)) { 4142 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4143 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4144 I.addReg(TRI->getVCC(), RegState::Define); 4145 } 4146 I.add(MI.getOperand(1)) 4147 .add(MI.getOperand(2)); 4148 if (NeedClampOperand) 4149 I.addImm(0); // clamp bit for e64 encoding 4150 4151 TII->legalizeOperands(*I); 4152 4153 MI.eraseFromParent(); 4154 return BB; 4155 } 4156 case AMDGPU::DS_GWS_INIT: 4157 case AMDGPU::DS_GWS_SEMA_V: 4158 case AMDGPU::DS_GWS_SEMA_BR: 4159 case AMDGPU::DS_GWS_SEMA_P: 4160 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4161 case AMDGPU::DS_GWS_BARRIER: 4162 // A s_waitcnt 0 is required to be the instruction immediately following. 4163 if (getSubtarget()->hasGWSAutoReplay()) { 4164 bundleInstWithWaitcnt(MI); 4165 return BB; 4166 } 4167 4168 return emitGWSMemViolTestLoop(MI, BB); 4169 case AMDGPU::S_SETREG_B32: { 4170 if (!getSubtarget()->hasDenormModeInst()) 4171 return BB; 4172 4173 // Try to optimize cases that only set the denormal mode or rounding mode. 4174 // 4175 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4176 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4177 // instead. 4178 // 4179 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4180 // allow you to have a no side effect instruction in the output of a 4181 // sideeffecting pattern. 4182 4183 // TODO: Should also emit a no side effects pseudo if only FP bits are 4184 // touched, even if not all of them or to a variable. 4185 unsigned ID, Offset, Width; 4186 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4187 if (ID != AMDGPU::Hwreg::ID_MODE) 4188 return BB; 4189 4190 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4191 const unsigned SetMask = WidthMask << Offset; 4192 unsigned SetDenormOp = 0; 4193 unsigned SetRoundOp = 0; 4194 4195 // The dedicated instructions can only set the whole denorm or round mode at 4196 // once, not a subset of bits in either. 4197 if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4198 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) { 4199 // If this fully sets both the round and denorm mode, emit the two 4200 // dedicated instructions for these. 4201 assert(Offset == 0); 4202 SetRoundOp = AMDGPU::S_ROUND_MODE; 4203 SetDenormOp = AMDGPU::S_DENORM_MODE; 4204 } else if (Width == 4) { 4205 if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) { 4206 SetRoundOp = AMDGPU::S_ROUND_MODE; 4207 assert(Offset == 0); 4208 } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) { 4209 SetDenormOp = AMDGPU::S_DENORM_MODE; 4210 assert(Offset == 4); 4211 } 4212 } 4213 4214 if (SetRoundOp || SetDenormOp) { 4215 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4216 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4217 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4218 unsigned ImmVal = Def->getOperand(1).getImm(); 4219 if (SetRoundOp) { 4220 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4221 .addImm(ImmVal & 0xf); 4222 4223 // If we also have the denorm mode, get just the denorm mode bits. 4224 ImmVal >>= 4; 4225 } 4226 4227 if (SetDenormOp) { 4228 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4229 .addImm(ImmVal & 0xf); 4230 } 4231 4232 MI.eraseFromParent(); 4233 } 4234 } 4235 4236 return BB; 4237 } 4238 default: 4239 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4240 } 4241 } 4242 4243 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4244 return isTypeLegal(VT.getScalarType()); 4245 } 4246 4247 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4248 // This currently forces unfolding various combinations of fsub into fma with 4249 // free fneg'd operands. As long as we have fast FMA (controlled by 4250 // isFMAFasterThanFMulAndFAdd), we should perform these. 4251 4252 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4253 // most of these combines appear to be cycle neutral but save on instruction 4254 // count / code size. 4255 return true; 4256 } 4257 4258 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4259 EVT VT) const { 4260 if (!VT.isVector()) { 4261 return MVT::i1; 4262 } 4263 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4264 } 4265 4266 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4267 // TODO: Should i16 be used always if legal? For now it would force VALU 4268 // shifts. 4269 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4270 } 4271 4272 // Answering this is somewhat tricky and depends on the specific device which 4273 // have different rates for fma or all f64 operations. 4274 // 4275 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4276 // regardless of which device (although the number of cycles differs between 4277 // devices), so it is always profitable for f64. 4278 // 4279 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4280 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4281 // which we can always do even without fused FP ops since it returns the same 4282 // result as the separate operations and since it is always full 4283 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4284 // however does not support denormals, so we do report fma as faster if we have 4285 // a fast fma device and require denormals. 4286 // 4287 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4288 EVT VT) const { 4289 VT = VT.getScalarType(); 4290 4291 switch (VT.getSimpleVT().SimpleTy) { 4292 case MVT::f32: { 4293 // If mad is not available this depends only on if f32 fma is full rate. 4294 if (!Subtarget->hasMadMacF32Insts()) 4295 return Subtarget->hasFastFMAF32(); 4296 4297 // Otherwise f32 mad is always full rate and returns the same result as 4298 // the separate operations so should be preferred over fma. 4299 // However does not support denomals. 4300 if (hasFP32Denormals(MF)) 4301 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4302 4303 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4304 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4305 } 4306 case MVT::f64: 4307 return true; 4308 case MVT::f16: 4309 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4310 default: 4311 break; 4312 } 4313 4314 return false; 4315 } 4316 4317 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4318 const SDNode *N) const { 4319 // TODO: Check future ftz flag 4320 // v_mad_f32/v_mac_f32 do not support denormals. 4321 EVT VT = N->getValueType(0); 4322 if (VT == MVT::f32) 4323 return Subtarget->hasMadMacF32Insts() && 4324 !hasFP32Denormals(DAG.getMachineFunction()); 4325 if (VT == MVT::f16) { 4326 return Subtarget->hasMadF16() && 4327 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4328 } 4329 4330 return false; 4331 } 4332 4333 //===----------------------------------------------------------------------===// 4334 // Custom DAG Lowering Operations 4335 //===----------------------------------------------------------------------===// 4336 4337 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4338 // wider vector type is legal. 4339 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4340 SelectionDAG &DAG) const { 4341 unsigned Opc = Op.getOpcode(); 4342 EVT VT = Op.getValueType(); 4343 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4344 4345 SDValue Lo, Hi; 4346 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4347 4348 SDLoc SL(Op); 4349 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4350 Op->getFlags()); 4351 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4352 Op->getFlags()); 4353 4354 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4355 } 4356 4357 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4358 // wider vector type is legal. 4359 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4360 SelectionDAG &DAG) const { 4361 unsigned Opc = Op.getOpcode(); 4362 EVT VT = Op.getValueType(); 4363 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4364 4365 SDValue Lo0, Hi0; 4366 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4367 SDValue Lo1, Hi1; 4368 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4369 4370 SDLoc SL(Op); 4371 4372 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4373 Op->getFlags()); 4374 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4375 Op->getFlags()); 4376 4377 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4378 } 4379 4380 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4381 SelectionDAG &DAG) const { 4382 unsigned Opc = Op.getOpcode(); 4383 EVT VT = Op.getValueType(); 4384 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4385 4386 SDValue Lo0, Hi0; 4387 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4388 SDValue Lo1, Hi1; 4389 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4390 SDValue Lo2, Hi2; 4391 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4392 4393 SDLoc SL(Op); 4394 4395 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4396 Op->getFlags()); 4397 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4398 Op->getFlags()); 4399 4400 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4401 } 4402 4403 4404 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4405 switch (Op.getOpcode()) { 4406 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4407 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4408 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4409 case ISD::LOAD: { 4410 SDValue Result = LowerLOAD(Op, DAG); 4411 assert((!Result.getNode() || 4412 Result.getNode()->getNumValues() == 2) && 4413 "Load should return a value and a chain"); 4414 return Result; 4415 } 4416 4417 case ISD::FSIN: 4418 case ISD::FCOS: 4419 return LowerTrig(Op, DAG); 4420 case ISD::SELECT: return LowerSELECT(Op, DAG); 4421 case ISD::FDIV: return LowerFDIV(Op, DAG); 4422 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4423 case ISD::STORE: return LowerSTORE(Op, DAG); 4424 case ISD::GlobalAddress: { 4425 MachineFunction &MF = DAG.getMachineFunction(); 4426 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4427 return LowerGlobalAddress(MFI, Op, DAG); 4428 } 4429 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4430 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4431 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4432 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4433 case ISD::INSERT_SUBVECTOR: 4434 return lowerINSERT_SUBVECTOR(Op, DAG); 4435 case ISD::INSERT_VECTOR_ELT: 4436 return lowerINSERT_VECTOR_ELT(Op, DAG); 4437 case ISD::EXTRACT_VECTOR_ELT: 4438 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4439 case ISD::VECTOR_SHUFFLE: 4440 return lowerVECTOR_SHUFFLE(Op, DAG); 4441 case ISD::BUILD_VECTOR: 4442 return lowerBUILD_VECTOR(Op, DAG); 4443 case ISD::FP_ROUND: 4444 return lowerFP_ROUND(Op, DAG); 4445 case ISD::TRAP: 4446 return lowerTRAP(Op, DAG); 4447 case ISD::DEBUGTRAP: 4448 return lowerDEBUGTRAP(Op, DAG); 4449 case ISD::FABS: 4450 case ISD::FNEG: 4451 case ISD::FCANONICALIZE: 4452 case ISD::BSWAP: 4453 return splitUnaryVectorOp(Op, DAG); 4454 case ISD::FMINNUM: 4455 case ISD::FMAXNUM: 4456 return lowerFMINNUM_FMAXNUM(Op, DAG); 4457 case ISD::FMA: 4458 return splitTernaryVectorOp(Op, DAG); 4459 case ISD::SHL: 4460 case ISD::SRA: 4461 case ISD::SRL: 4462 case ISD::ADD: 4463 case ISD::SUB: 4464 case ISD::MUL: 4465 case ISD::SMIN: 4466 case ISD::SMAX: 4467 case ISD::UMIN: 4468 case ISD::UMAX: 4469 case ISD::FADD: 4470 case ISD::FMUL: 4471 case ISD::FMINNUM_IEEE: 4472 case ISD::FMAXNUM_IEEE: 4473 return splitBinaryVectorOp(Op, DAG); 4474 case ISD::SMULO: 4475 case ISD::UMULO: 4476 return lowerXMULO(Op, DAG); 4477 case ISD::DYNAMIC_STACKALLOC: 4478 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4479 } 4480 return SDValue(); 4481 } 4482 4483 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4484 const SDLoc &DL, 4485 SelectionDAG &DAG, bool Unpacked) { 4486 if (!LoadVT.isVector()) 4487 return Result; 4488 4489 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4490 // Truncate to v2i16/v4i16. 4491 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4492 4493 // Workaround legalizer not scalarizing truncate after vector op 4494 // legalization byt not creating intermediate vector trunc. 4495 SmallVector<SDValue, 4> Elts; 4496 DAG.ExtractVectorElements(Result, Elts); 4497 for (SDValue &Elt : Elts) 4498 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4499 4500 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4501 4502 // Bitcast to original type (v2f16/v4f16). 4503 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4504 } 4505 4506 // Cast back to the original packed type. 4507 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4508 } 4509 4510 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4511 MemSDNode *M, 4512 SelectionDAG &DAG, 4513 ArrayRef<SDValue> Ops, 4514 bool IsIntrinsic) const { 4515 SDLoc DL(M); 4516 4517 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4518 EVT LoadVT = M->getValueType(0); 4519 4520 EVT EquivLoadVT = LoadVT; 4521 if (Unpacked && LoadVT.isVector()) { 4522 EquivLoadVT = LoadVT.isVector() ? 4523 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4524 LoadVT.getVectorNumElements()) : LoadVT; 4525 } 4526 4527 // Change from v4f16/v2f16 to EquivLoadVT. 4528 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4529 4530 SDValue Load 4531 = DAG.getMemIntrinsicNode( 4532 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4533 VTList, Ops, M->getMemoryVT(), 4534 M->getMemOperand()); 4535 if (!Unpacked) // Just adjusted the opcode. 4536 return Load; 4537 4538 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4539 4540 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4541 } 4542 4543 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4544 SelectionDAG &DAG, 4545 ArrayRef<SDValue> Ops) const { 4546 SDLoc DL(M); 4547 EVT LoadVT = M->getValueType(0); 4548 EVT EltType = LoadVT.getScalarType(); 4549 EVT IntVT = LoadVT.changeTypeToInteger(); 4550 4551 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4552 4553 unsigned Opc = 4554 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4555 4556 if (IsD16) { 4557 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4558 } 4559 4560 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4561 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4562 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4563 4564 if (isTypeLegal(LoadVT)) { 4565 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4566 M->getMemOperand(), DAG); 4567 } 4568 4569 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4570 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4571 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4572 M->getMemOperand(), DAG); 4573 return DAG.getMergeValues( 4574 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4575 DL); 4576 } 4577 4578 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4579 SDNode *N, SelectionDAG &DAG) { 4580 EVT VT = N->getValueType(0); 4581 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4582 unsigned CondCode = CD->getZExtValue(); 4583 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4584 return DAG.getUNDEF(VT); 4585 4586 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4587 4588 SDValue LHS = N->getOperand(1); 4589 SDValue RHS = N->getOperand(2); 4590 4591 SDLoc DL(N); 4592 4593 EVT CmpVT = LHS.getValueType(); 4594 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4595 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4596 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4597 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4598 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4599 } 4600 4601 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4602 4603 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4604 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4605 4606 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4607 DAG.getCondCode(CCOpcode)); 4608 if (VT.bitsEq(CCVT)) 4609 return SetCC; 4610 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4611 } 4612 4613 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4614 SDNode *N, SelectionDAG &DAG) { 4615 EVT VT = N->getValueType(0); 4616 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4617 4618 unsigned CondCode = CD->getZExtValue(); 4619 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4620 return DAG.getUNDEF(VT); 4621 4622 SDValue Src0 = N->getOperand(1); 4623 SDValue Src1 = N->getOperand(2); 4624 EVT CmpVT = Src0.getValueType(); 4625 SDLoc SL(N); 4626 4627 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4628 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4629 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4630 } 4631 4632 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4633 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4634 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4635 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4636 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4637 Src1, DAG.getCondCode(CCOpcode)); 4638 if (VT.bitsEq(CCVT)) 4639 return SetCC; 4640 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4641 } 4642 4643 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4644 SelectionDAG &DAG) { 4645 EVT VT = N->getValueType(0); 4646 SDValue Src = N->getOperand(1); 4647 SDLoc SL(N); 4648 4649 if (Src.getOpcode() == ISD::SETCC) { 4650 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4651 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4652 Src.getOperand(1), Src.getOperand(2)); 4653 } 4654 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4655 // (ballot 0) -> 0 4656 if (Arg->isNullValue()) 4657 return DAG.getConstant(0, SL, VT); 4658 4659 // (ballot 1) -> EXEC/EXEC_LO 4660 if (Arg->isOne()) { 4661 Register Exec; 4662 if (VT.getScalarSizeInBits() == 32) 4663 Exec = AMDGPU::EXEC_LO; 4664 else if (VT.getScalarSizeInBits() == 64) 4665 Exec = AMDGPU::EXEC; 4666 else 4667 return SDValue(); 4668 4669 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4670 } 4671 } 4672 4673 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4674 // ISD::SETNE) 4675 return DAG.getNode( 4676 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4677 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4678 } 4679 4680 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4681 SmallVectorImpl<SDValue> &Results, 4682 SelectionDAG &DAG) const { 4683 switch (N->getOpcode()) { 4684 case ISD::INSERT_VECTOR_ELT: { 4685 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4686 Results.push_back(Res); 4687 return; 4688 } 4689 case ISD::EXTRACT_VECTOR_ELT: { 4690 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4691 Results.push_back(Res); 4692 return; 4693 } 4694 case ISD::INTRINSIC_WO_CHAIN: { 4695 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4696 switch (IID) { 4697 case Intrinsic::amdgcn_cvt_pkrtz: { 4698 SDValue Src0 = N->getOperand(1); 4699 SDValue Src1 = N->getOperand(2); 4700 SDLoc SL(N); 4701 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4702 Src0, Src1); 4703 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4704 return; 4705 } 4706 case Intrinsic::amdgcn_cvt_pknorm_i16: 4707 case Intrinsic::amdgcn_cvt_pknorm_u16: 4708 case Intrinsic::amdgcn_cvt_pk_i16: 4709 case Intrinsic::amdgcn_cvt_pk_u16: { 4710 SDValue Src0 = N->getOperand(1); 4711 SDValue Src1 = N->getOperand(2); 4712 SDLoc SL(N); 4713 unsigned Opcode; 4714 4715 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4716 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4717 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4718 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4719 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4720 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4721 else 4722 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4723 4724 EVT VT = N->getValueType(0); 4725 if (isTypeLegal(VT)) 4726 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4727 else { 4728 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4729 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4730 } 4731 return; 4732 } 4733 } 4734 break; 4735 } 4736 case ISD::INTRINSIC_W_CHAIN: { 4737 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4738 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4739 // FIXME: Hacky 4740 Results.push_back(Res.getOperand(0)); 4741 Results.push_back(Res.getOperand(1)); 4742 } else { 4743 Results.push_back(Res); 4744 Results.push_back(Res.getValue(1)); 4745 } 4746 return; 4747 } 4748 4749 break; 4750 } 4751 case ISD::SELECT: { 4752 SDLoc SL(N); 4753 EVT VT = N->getValueType(0); 4754 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4755 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4756 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4757 4758 EVT SelectVT = NewVT; 4759 if (NewVT.bitsLT(MVT::i32)) { 4760 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4761 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4762 SelectVT = MVT::i32; 4763 } 4764 4765 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4766 N->getOperand(0), LHS, RHS); 4767 4768 if (NewVT != SelectVT) 4769 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4770 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4771 return; 4772 } 4773 case ISD::FNEG: { 4774 if (N->getValueType(0) != MVT::v2f16) 4775 break; 4776 4777 SDLoc SL(N); 4778 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4779 4780 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4781 BC, 4782 DAG.getConstant(0x80008000, SL, MVT::i32)); 4783 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4784 return; 4785 } 4786 case ISD::FABS: { 4787 if (N->getValueType(0) != MVT::v2f16) 4788 break; 4789 4790 SDLoc SL(N); 4791 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4792 4793 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4794 BC, 4795 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4796 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4797 return; 4798 } 4799 default: 4800 break; 4801 } 4802 } 4803 4804 /// Helper function for LowerBRCOND 4805 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4806 4807 SDNode *Parent = Value.getNode(); 4808 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4809 I != E; ++I) { 4810 4811 if (I.getUse().get() != Value) 4812 continue; 4813 4814 if (I->getOpcode() == Opcode) 4815 return *I; 4816 } 4817 return nullptr; 4818 } 4819 4820 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4821 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4822 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4823 case Intrinsic::amdgcn_if: 4824 return AMDGPUISD::IF; 4825 case Intrinsic::amdgcn_else: 4826 return AMDGPUISD::ELSE; 4827 case Intrinsic::amdgcn_loop: 4828 return AMDGPUISD::LOOP; 4829 case Intrinsic::amdgcn_end_cf: 4830 llvm_unreachable("should not occur"); 4831 default: 4832 return 0; 4833 } 4834 } 4835 4836 // break, if_break, else_break are all only used as inputs to loop, not 4837 // directly as branch conditions. 4838 return 0; 4839 } 4840 4841 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4842 const Triple &TT = getTargetMachine().getTargetTriple(); 4843 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4844 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4845 AMDGPU::shouldEmitConstantsToTextSection(TT); 4846 } 4847 4848 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4849 // FIXME: Either avoid relying on address space here or change the default 4850 // address space for functions to avoid the explicit check. 4851 return (GV->getValueType()->isFunctionTy() || 4852 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4853 !shouldEmitFixup(GV) && 4854 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4855 } 4856 4857 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4858 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4859 } 4860 4861 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4862 if (!GV->hasExternalLinkage()) 4863 return true; 4864 4865 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4866 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4867 } 4868 4869 /// This transforms the control flow intrinsics to get the branch destination as 4870 /// last parameter, also switches branch target with BR if the need arise 4871 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4872 SelectionDAG &DAG) const { 4873 SDLoc DL(BRCOND); 4874 4875 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4876 SDValue Target = BRCOND.getOperand(2); 4877 SDNode *BR = nullptr; 4878 SDNode *SetCC = nullptr; 4879 4880 if (Intr->getOpcode() == ISD::SETCC) { 4881 // As long as we negate the condition everything is fine 4882 SetCC = Intr; 4883 Intr = SetCC->getOperand(0).getNode(); 4884 4885 } else { 4886 // Get the target from BR if we don't negate the condition 4887 BR = findUser(BRCOND, ISD::BR); 4888 assert(BR && "brcond missing unconditional branch user"); 4889 Target = BR->getOperand(1); 4890 } 4891 4892 unsigned CFNode = isCFIntrinsic(Intr); 4893 if (CFNode == 0) { 4894 // This is a uniform branch so we don't need to legalize. 4895 return BRCOND; 4896 } 4897 4898 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4899 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4900 4901 assert(!SetCC || 4902 (SetCC->getConstantOperandVal(1) == 1 && 4903 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4904 ISD::SETNE)); 4905 4906 // operands of the new intrinsic call 4907 SmallVector<SDValue, 4> Ops; 4908 if (HaveChain) 4909 Ops.push_back(BRCOND.getOperand(0)); 4910 4911 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4912 Ops.push_back(Target); 4913 4914 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4915 4916 // build the new intrinsic call 4917 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4918 4919 if (!HaveChain) { 4920 SDValue Ops[] = { 4921 SDValue(Result, 0), 4922 BRCOND.getOperand(0) 4923 }; 4924 4925 Result = DAG.getMergeValues(Ops, DL).getNode(); 4926 } 4927 4928 if (BR) { 4929 // Give the branch instruction our target 4930 SDValue Ops[] = { 4931 BR->getOperand(0), 4932 BRCOND.getOperand(2) 4933 }; 4934 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4935 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4936 } 4937 4938 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4939 4940 // Copy the intrinsic results to registers 4941 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4942 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4943 if (!CopyToReg) 4944 continue; 4945 4946 Chain = DAG.getCopyToReg( 4947 Chain, DL, 4948 CopyToReg->getOperand(1), 4949 SDValue(Result, i - 1), 4950 SDValue()); 4951 4952 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4953 } 4954 4955 // Remove the old intrinsic from the chain 4956 DAG.ReplaceAllUsesOfValueWith( 4957 SDValue(Intr, Intr->getNumValues() - 1), 4958 Intr->getOperand(0)); 4959 4960 return Chain; 4961 } 4962 4963 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4964 SelectionDAG &DAG) const { 4965 MVT VT = Op.getSimpleValueType(); 4966 SDLoc DL(Op); 4967 // Checking the depth 4968 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4969 return DAG.getConstant(0, DL, VT); 4970 4971 MachineFunction &MF = DAG.getMachineFunction(); 4972 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4973 // Check for kernel and shader functions 4974 if (Info->isEntryFunction()) 4975 return DAG.getConstant(0, DL, VT); 4976 4977 MachineFrameInfo &MFI = MF.getFrameInfo(); 4978 // There is a call to @llvm.returnaddress in this function 4979 MFI.setReturnAddressIsTaken(true); 4980 4981 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4982 // Get the return address reg and mark it as an implicit live-in 4983 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4984 4985 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4986 } 4987 4988 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4989 SDValue Op, 4990 const SDLoc &DL, 4991 EVT VT) const { 4992 return Op.getValueType().bitsLE(VT) ? 4993 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4994 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4995 DAG.getTargetConstant(0, DL, MVT::i32)); 4996 } 4997 4998 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4999 assert(Op.getValueType() == MVT::f16 && 5000 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5001 5002 SDValue Src = Op.getOperand(0); 5003 EVT SrcVT = Src.getValueType(); 5004 if (SrcVT != MVT::f64) 5005 return Op; 5006 5007 SDLoc DL(Op); 5008 5009 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5010 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5011 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5012 } 5013 5014 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5015 SelectionDAG &DAG) const { 5016 EVT VT = Op.getValueType(); 5017 const MachineFunction &MF = DAG.getMachineFunction(); 5018 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5019 bool IsIEEEMode = Info->getMode().IEEE; 5020 5021 // FIXME: Assert during selection that this is only selected for 5022 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5023 // mode functions, but this happens to be OK since it's only done in cases 5024 // where there is known no sNaN. 5025 if (IsIEEEMode) 5026 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5027 5028 if (VT == MVT::v4f16) 5029 return splitBinaryVectorOp(Op, DAG); 5030 return Op; 5031 } 5032 5033 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5034 EVT VT = Op.getValueType(); 5035 SDLoc SL(Op); 5036 SDValue LHS = Op.getOperand(0); 5037 SDValue RHS = Op.getOperand(1); 5038 bool isSigned = Op.getOpcode() == ISD::SMULO; 5039 5040 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5041 const APInt &C = RHSC->getAPIntValue(); 5042 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5043 if (C.isPowerOf2()) { 5044 // smulo(x, signed_min) is same as umulo(x, signed_min). 5045 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5046 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5047 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5048 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5049 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5050 SL, VT, Result, ShiftAmt), 5051 LHS, ISD::SETNE); 5052 return DAG.getMergeValues({ Result, Overflow }, SL); 5053 } 5054 } 5055 5056 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5057 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5058 SL, VT, LHS, RHS); 5059 5060 SDValue Sign = isSigned 5061 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5062 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5063 : DAG.getConstant(0, SL, VT); 5064 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5065 5066 return DAG.getMergeValues({ Result, Overflow }, SL); 5067 } 5068 5069 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5070 SDLoc SL(Op); 5071 SDValue Chain = Op.getOperand(0); 5072 5073 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5074 !Subtarget->isTrapHandlerEnabled()) 5075 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5076 5077 MachineFunction &MF = DAG.getMachineFunction(); 5078 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5079 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 5080 assert(UserSGPR != AMDGPU::NoRegister); 5081 SDValue QueuePtr = CreateLiveInRegister( 5082 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5083 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5084 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5085 QueuePtr, SDValue()); 5086 SDValue Ops[] = { 5087 ToReg, 5088 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5089 SGPR01, 5090 ToReg.getValue(1) 5091 }; 5092 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5093 } 5094 5095 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5096 SDLoc SL(Op); 5097 SDValue Chain = Op.getOperand(0); 5098 MachineFunction &MF = DAG.getMachineFunction(); 5099 5100 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5101 !Subtarget->isTrapHandlerEnabled()) { 5102 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5103 "debugtrap handler not supported", 5104 Op.getDebugLoc(), 5105 DS_Warning); 5106 LLVMContext &Ctx = MF.getFunction().getContext(); 5107 Ctx.diagnose(NoTrap); 5108 return Chain; 5109 } 5110 5111 SDValue Ops[] = { 5112 Chain, 5113 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5114 }; 5115 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5116 } 5117 5118 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5119 SelectionDAG &DAG) const { 5120 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5121 if (Subtarget->hasApertureRegs()) { 5122 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5123 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5124 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5125 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5126 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5127 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5128 unsigned Encoding = 5129 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5130 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5131 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5132 5133 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5134 SDValue ApertureReg = SDValue( 5135 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5136 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5137 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5138 } 5139 5140 MachineFunction &MF = DAG.getMachineFunction(); 5141 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5142 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5143 assert(UserSGPR != AMDGPU::NoRegister); 5144 5145 SDValue QueuePtr = CreateLiveInRegister( 5146 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5147 5148 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5149 // private_segment_aperture_base_hi. 5150 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5151 5152 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 5153 5154 // TODO: Use custom target PseudoSourceValue. 5155 // TODO: We should use the value from the IR intrinsic call, but it might not 5156 // be available and how do we get it? 5157 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5158 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5159 MinAlign(64, StructOffset), 5160 MachineMemOperand::MODereferenceable | 5161 MachineMemOperand::MOInvariant); 5162 } 5163 5164 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5165 SelectionDAG &DAG) const { 5166 SDLoc SL(Op); 5167 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5168 5169 SDValue Src = ASC->getOperand(0); 5170 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5171 5172 const AMDGPUTargetMachine &TM = 5173 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5174 5175 // flat -> local/private 5176 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5177 unsigned DestAS = ASC->getDestAddressSpace(); 5178 5179 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5180 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5181 unsigned NullVal = TM.getNullPointerValue(DestAS); 5182 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5183 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5184 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5185 5186 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5187 NonNull, Ptr, SegmentNullPtr); 5188 } 5189 } 5190 5191 // local/private -> flat 5192 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5193 unsigned SrcAS = ASC->getSrcAddressSpace(); 5194 5195 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5196 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5197 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5198 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5199 5200 SDValue NonNull 5201 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5202 5203 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5204 SDValue CvtPtr 5205 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5206 5207 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5208 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5209 FlatNullPtr); 5210 } 5211 } 5212 5213 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5214 Src.getValueType() == MVT::i64) 5215 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5216 5217 // global <-> flat are no-ops and never emitted. 5218 5219 const MachineFunction &MF = DAG.getMachineFunction(); 5220 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5221 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5222 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5223 5224 return DAG.getUNDEF(ASC->getValueType(0)); 5225 } 5226 5227 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5228 // the small vector and inserting them into the big vector. That is better than 5229 // the default expansion of doing it via a stack slot. Even though the use of 5230 // the stack slot would be optimized away afterwards, the stack slot itself 5231 // remains. 5232 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5233 SelectionDAG &DAG) const { 5234 SDValue Vec = Op.getOperand(0); 5235 SDValue Ins = Op.getOperand(1); 5236 SDValue Idx = Op.getOperand(2); 5237 EVT VecVT = Vec.getValueType(); 5238 EVT InsVT = Ins.getValueType(); 5239 EVT EltVT = VecVT.getVectorElementType(); 5240 unsigned InsNumElts = InsVT.getVectorNumElements(); 5241 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5242 SDLoc SL(Op); 5243 5244 for (unsigned I = 0; I != InsNumElts; ++I) { 5245 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5246 DAG.getConstant(I, SL, MVT::i32)); 5247 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5248 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5249 } 5250 return Vec; 5251 } 5252 5253 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5254 SelectionDAG &DAG) const { 5255 SDValue Vec = Op.getOperand(0); 5256 SDValue InsVal = Op.getOperand(1); 5257 SDValue Idx = Op.getOperand(2); 5258 EVT VecVT = Vec.getValueType(); 5259 EVT EltVT = VecVT.getVectorElementType(); 5260 unsigned VecSize = VecVT.getSizeInBits(); 5261 unsigned EltSize = EltVT.getSizeInBits(); 5262 5263 5264 assert(VecSize <= 64); 5265 5266 unsigned NumElts = VecVT.getVectorNumElements(); 5267 SDLoc SL(Op); 5268 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5269 5270 if (NumElts == 4 && EltSize == 16 && KIdx) { 5271 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5272 5273 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5274 DAG.getConstant(0, SL, MVT::i32)); 5275 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5276 DAG.getConstant(1, SL, MVT::i32)); 5277 5278 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5279 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5280 5281 unsigned Idx = KIdx->getZExtValue(); 5282 bool InsertLo = Idx < 2; 5283 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5284 InsertLo ? LoVec : HiVec, 5285 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5286 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5287 5288 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5289 5290 SDValue Concat = InsertLo ? 5291 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5292 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5293 5294 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5295 } 5296 5297 if (isa<ConstantSDNode>(Idx)) 5298 return SDValue(); 5299 5300 MVT IntVT = MVT::getIntegerVT(VecSize); 5301 5302 // Avoid stack access for dynamic indexing. 5303 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5304 5305 // Create a congruent vector with the target value in each element so that 5306 // the required element can be masked and ORed into the target vector. 5307 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5308 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5309 5310 assert(isPowerOf2_32(EltSize)); 5311 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5312 5313 // Convert vector index to bit-index. 5314 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5315 5316 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5317 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5318 DAG.getConstant(0xffff, SL, IntVT), 5319 ScaledIdx); 5320 5321 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5322 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5323 DAG.getNOT(SL, BFM, IntVT), BCVec); 5324 5325 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5326 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5327 } 5328 5329 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5330 SelectionDAG &DAG) const { 5331 SDLoc SL(Op); 5332 5333 EVT ResultVT = Op.getValueType(); 5334 SDValue Vec = Op.getOperand(0); 5335 SDValue Idx = Op.getOperand(1); 5336 EVT VecVT = Vec.getValueType(); 5337 unsigned VecSize = VecVT.getSizeInBits(); 5338 EVT EltVT = VecVT.getVectorElementType(); 5339 assert(VecSize <= 64); 5340 5341 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5342 5343 // Make sure we do any optimizations that will make it easier to fold 5344 // source modifiers before obscuring it with bit operations. 5345 5346 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5347 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5348 return Combined; 5349 5350 unsigned EltSize = EltVT.getSizeInBits(); 5351 assert(isPowerOf2_32(EltSize)); 5352 5353 MVT IntVT = MVT::getIntegerVT(VecSize); 5354 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5355 5356 // Convert vector index to bit-index (* EltSize) 5357 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5358 5359 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5360 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5361 5362 if (ResultVT == MVT::f16) { 5363 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5364 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5365 } 5366 5367 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5368 } 5369 5370 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5371 assert(Elt % 2 == 0); 5372 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5373 } 5374 5375 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5376 SelectionDAG &DAG) const { 5377 SDLoc SL(Op); 5378 EVT ResultVT = Op.getValueType(); 5379 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5380 5381 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5382 EVT EltVT = PackVT.getVectorElementType(); 5383 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5384 5385 // vector_shuffle <0,1,6,7> lhs, rhs 5386 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5387 // 5388 // vector_shuffle <6,7,2,3> lhs, rhs 5389 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5390 // 5391 // vector_shuffle <6,7,0,1> lhs, rhs 5392 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5393 5394 // Avoid scalarizing when both halves are reading from consecutive elements. 5395 SmallVector<SDValue, 4> Pieces; 5396 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5397 if (elementPairIsContiguous(SVN->getMask(), I)) { 5398 const int Idx = SVN->getMaskElt(I); 5399 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5400 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5401 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5402 PackVT, SVN->getOperand(VecIdx), 5403 DAG.getConstant(EltIdx, SL, MVT::i32)); 5404 Pieces.push_back(SubVec); 5405 } else { 5406 const int Idx0 = SVN->getMaskElt(I); 5407 const int Idx1 = SVN->getMaskElt(I + 1); 5408 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5409 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5410 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5411 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5412 5413 SDValue Vec0 = SVN->getOperand(VecIdx0); 5414 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5415 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5416 5417 SDValue Vec1 = SVN->getOperand(VecIdx1); 5418 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5419 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5420 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5421 } 5422 } 5423 5424 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5425 } 5426 5427 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5428 SelectionDAG &DAG) const { 5429 SDLoc SL(Op); 5430 EVT VT = Op.getValueType(); 5431 5432 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5433 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5434 5435 // Turn into pair of packed build_vectors. 5436 // TODO: Special case for constants that can be materialized with s_mov_b64. 5437 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5438 { Op.getOperand(0), Op.getOperand(1) }); 5439 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5440 { Op.getOperand(2), Op.getOperand(3) }); 5441 5442 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5443 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5444 5445 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5446 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5447 } 5448 5449 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5450 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5451 5452 SDValue Lo = Op.getOperand(0); 5453 SDValue Hi = Op.getOperand(1); 5454 5455 // Avoid adding defined bits with the zero_extend. 5456 if (Hi.isUndef()) { 5457 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5458 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5459 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5460 } 5461 5462 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5463 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5464 5465 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5466 DAG.getConstant(16, SL, MVT::i32)); 5467 if (Lo.isUndef()) 5468 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5469 5470 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5471 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5472 5473 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5474 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5475 } 5476 5477 bool 5478 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5479 // We can fold offsets for anything that doesn't require a GOT relocation. 5480 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5481 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5482 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5483 !shouldEmitGOTReloc(GA->getGlobal()); 5484 } 5485 5486 static SDValue 5487 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5488 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5489 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5490 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5491 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5492 // lowered to the following code sequence: 5493 // 5494 // For constant address space: 5495 // s_getpc_b64 s[0:1] 5496 // s_add_u32 s0, s0, $symbol 5497 // s_addc_u32 s1, s1, 0 5498 // 5499 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5500 // a fixup or relocation is emitted to replace $symbol with a literal 5501 // constant, which is a pc-relative offset from the encoding of the $symbol 5502 // operand to the global variable. 5503 // 5504 // For global address space: 5505 // s_getpc_b64 s[0:1] 5506 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5507 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5508 // 5509 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5510 // fixups or relocations are emitted to replace $symbol@*@lo and 5511 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5512 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5513 // operand to the global variable. 5514 // 5515 // What we want here is an offset from the value returned by s_getpc 5516 // (which is the address of the s_add_u32 instruction) to the global 5517 // variable, but since the encoding of $symbol starts 4 bytes after the start 5518 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5519 // small. This requires us to add 4 to the global variable offset in order to 5520 // compute the correct address. 5521 SDValue PtrLo = 5522 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5523 SDValue PtrHi; 5524 if (GAFlags == SIInstrInfo::MO_NONE) { 5525 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5526 } else { 5527 PtrHi = 5528 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5529 } 5530 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5531 } 5532 5533 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5534 SDValue Op, 5535 SelectionDAG &DAG) const { 5536 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5537 const GlobalValue *GV = GSD->getGlobal(); 5538 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5539 shouldUseLDSConstAddress(GV)) || 5540 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5541 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5542 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5543 5544 SDLoc DL(GSD); 5545 EVT PtrVT = Op.getValueType(); 5546 5547 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5548 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5549 SIInstrInfo::MO_ABS32_LO); 5550 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5551 } 5552 5553 if (shouldEmitFixup(GV)) 5554 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5555 else if (shouldEmitPCReloc(GV)) 5556 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5557 SIInstrInfo::MO_REL32); 5558 5559 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5560 SIInstrInfo::MO_GOTPCREL32); 5561 5562 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5563 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5564 const DataLayout &DataLayout = DAG.getDataLayout(); 5565 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5566 MachinePointerInfo PtrInfo 5567 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5568 5569 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5570 MachineMemOperand::MODereferenceable | 5571 MachineMemOperand::MOInvariant); 5572 } 5573 5574 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5575 const SDLoc &DL, SDValue V) const { 5576 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5577 // the destination register. 5578 // 5579 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5580 // so we will end up with redundant moves to m0. 5581 // 5582 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5583 5584 // A Null SDValue creates a glue result. 5585 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5586 V, Chain); 5587 return SDValue(M0, 0); 5588 } 5589 5590 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5591 SDValue Op, 5592 MVT VT, 5593 unsigned Offset) const { 5594 SDLoc SL(Op); 5595 SDValue Param = lowerKernargMemParameter( 5596 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5597 // The local size values will have the hi 16-bits as zero. 5598 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5599 DAG.getValueType(VT)); 5600 } 5601 5602 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5603 EVT VT) { 5604 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5605 "non-hsa intrinsic with hsa target", 5606 DL.getDebugLoc()); 5607 DAG.getContext()->diagnose(BadIntrin); 5608 return DAG.getUNDEF(VT); 5609 } 5610 5611 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5612 EVT VT) { 5613 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5614 "intrinsic not supported on subtarget", 5615 DL.getDebugLoc()); 5616 DAG.getContext()->diagnose(BadIntrin); 5617 return DAG.getUNDEF(VT); 5618 } 5619 5620 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5621 ArrayRef<SDValue> Elts) { 5622 assert(!Elts.empty()); 5623 MVT Type; 5624 unsigned NumElts; 5625 5626 if (Elts.size() == 1) { 5627 Type = MVT::f32; 5628 NumElts = 1; 5629 } else if (Elts.size() == 2) { 5630 Type = MVT::v2f32; 5631 NumElts = 2; 5632 } else if (Elts.size() == 3) { 5633 Type = MVT::v3f32; 5634 NumElts = 3; 5635 } else if (Elts.size() <= 4) { 5636 Type = MVT::v4f32; 5637 NumElts = 4; 5638 } else if (Elts.size() <= 8) { 5639 Type = MVT::v8f32; 5640 NumElts = 8; 5641 } else { 5642 assert(Elts.size() <= 16); 5643 Type = MVT::v16f32; 5644 NumElts = 16; 5645 } 5646 5647 SmallVector<SDValue, 16> VecElts(NumElts); 5648 for (unsigned i = 0; i < Elts.size(); ++i) { 5649 SDValue Elt = Elts[i]; 5650 if (Elt.getValueType() != MVT::f32) 5651 Elt = DAG.getBitcast(MVT::f32, Elt); 5652 VecElts[i] = Elt; 5653 } 5654 for (unsigned i = Elts.size(); i < NumElts; ++i) 5655 VecElts[i] = DAG.getUNDEF(MVT::f32); 5656 5657 if (NumElts == 1) 5658 return VecElts[0]; 5659 return DAG.getBuildVector(Type, DL, VecElts); 5660 } 5661 5662 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5663 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5664 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5665 5666 uint64_t Value = CachePolicyConst->getZExtValue(); 5667 SDLoc DL(CachePolicy); 5668 if (GLC) { 5669 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5670 Value &= ~(uint64_t)0x1; 5671 } 5672 if (SLC) { 5673 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5674 Value &= ~(uint64_t)0x2; 5675 } 5676 if (DLC) { 5677 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5678 Value &= ~(uint64_t)0x4; 5679 } 5680 5681 return Value == 0; 5682 } 5683 5684 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5685 SDValue Src, int ExtraElts) { 5686 EVT SrcVT = Src.getValueType(); 5687 5688 SmallVector<SDValue, 8> Elts; 5689 5690 if (SrcVT.isVector()) 5691 DAG.ExtractVectorElements(Src, Elts); 5692 else 5693 Elts.push_back(Src); 5694 5695 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5696 while (ExtraElts--) 5697 Elts.push_back(Undef); 5698 5699 return DAG.getBuildVector(CastVT, DL, Elts); 5700 } 5701 5702 // Re-construct the required return value for a image load intrinsic. 5703 // This is more complicated due to the optional use TexFailCtrl which means the required 5704 // return type is an aggregate 5705 static SDValue constructRetValue(SelectionDAG &DAG, 5706 MachineSDNode *Result, 5707 ArrayRef<EVT> ResultTypes, 5708 bool IsTexFail, bool Unpacked, bool IsD16, 5709 int DMaskPop, int NumVDataDwords, 5710 const SDLoc &DL, LLVMContext &Context) { 5711 // Determine the required return type. This is the same regardless of IsTexFail flag 5712 EVT ReqRetVT = ResultTypes[0]; 5713 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5714 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5715 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5716 5717 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5718 DMaskPop : (DMaskPop + 1) / 2; 5719 5720 MVT DataDwordVT = NumDataDwords == 1 ? 5721 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5722 5723 MVT MaskPopVT = MaskPopDwords == 1 ? 5724 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5725 5726 SDValue Data(Result, 0); 5727 SDValue TexFail; 5728 5729 if (IsTexFail) { 5730 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5731 if (MaskPopVT.isVector()) { 5732 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5733 SDValue(Result, 0), ZeroIdx); 5734 } else { 5735 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5736 SDValue(Result, 0), ZeroIdx); 5737 } 5738 5739 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5740 SDValue(Result, 0), 5741 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5742 } 5743 5744 if (DataDwordVT.isVector()) 5745 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5746 NumDataDwords - MaskPopDwords); 5747 5748 if (IsD16) 5749 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5750 5751 if (!ReqRetVT.isVector()) 5752 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5753 5754 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5755 5756 if (TexFail) 5757 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5758 5759 if (Result->getNumValues() == 1) 5760 return Data; 5761 5762 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5763 } 5764 5765 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5766 SDValue *LWE, bool &IsTexFail) { 5767 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5768 5769 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5770 if (Value) { 5771 IsTexFail = true; 5772 } 5773 5774 SDLoc DL(TexFailCtrlConst); 5775 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5776 Value &= ~(uint64_t)0x1; 5777 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5778 Value &= ~(uint64_t)0x2; 5779 5780 return Value == 0; 5781 } 5782 5783 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5784 MVT PackVectorVT, 5785 SmallVectorImpl<SDValue> &PackedAddrs, 5786 unsigned DimIdx, unsigned EndIdx, 5787 unsigned NumGradients) { 5788 SDLoc DL(Op); 5789 for (unsigned I = DimIdx; I < EndIdx; I++) { 5790 SDValue Addr = Op.getOperand(I); 5791 5792 // Gradients are packed with undef for each coordinate. 5793 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5794 // 1D: undef,dx/dh; undef,dx/dv 5795 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5796 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5797 if (((I + 1) >= EndIdx) || 5798 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5799 I == DimIdx + NumGradients - 1))) { 5800 if (Addr.getValueType() != MVT::i16) 5801 Addr = DAG.getBitcast(MVT::i16, Addr); 5802 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5803 } else { 5804 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5805 I++; 5806 } 5807 Addr = DAG.getBitcast(MVT::f32, Addr); 5808 PackedAddrs.push_back(Addr); 5809 } 5810 } 5811 5812 SDValue SITargetLowering::lowerImage(SDValue Op, 5813 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5814 SelectionDAG &DAG) const { 5815 SDLoc DL(Op); 5816 MachineFunction &MF = DAG.getMachineFunction(); 5817 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5818 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5819 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5820 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5821 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5822 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5823 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5824 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5825 unsigned IntrOpcode = Intr->BaseOpcode; 5826 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5827 5828 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5829 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5830 bool IsD16 = false; 5831 bool IsG16 = false; 5832 bool IsA16 = false; 5833 SDValue VData; 5834 int NumVDataDwords; 5835 bool AdjustRetType = false; 5836 5837 unsigned AddrIdx; // Index of first address argument 5838 unsigned DMask; 5839 unsigned DMaskLanes = 0; 5840 5841 if (BaseOpcode->Atomic) { 5842 VData = Op.getOperand(2); 5843 5844 bool Is64Bit = VData.getValueType() == MVT::i64; 5845 if (BaseOpcode->AtomicX2) { 5846 SDValue VData2 = Op.getOperand(3); 5847 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5848 {VData, VData2}); 5849 if (Is64Bit) 5850 VData = DAG.getBitcast(MVT::v4i32, VData); 5851 5852 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5853 DMask = Is64Bit ? 0xf : 0x3; 5854 NumVDataDwords = Is64Bit ? 4 : 2; 5855 AddrIdx = 4; 5856 } else { 5857 DMask = Is64Bit ? 0x3 : 0x1; 5858 NumVDataDwords = Is64Bit ? 2 : 1; 5859 AddrIdx = 3; 5860 } 5861 } else { 5862 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5863 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5864 DMask = DMaskConst->getZExtValue(); 5865 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5866 5867 if (BaseOpcode->Store) { 5868 VData = Op.getOperand(2); 5869 5870 MVT StoreVT = VData.getSimpleValueType(); 5871 if (StoreVT.getScalarType() == MVT::f16) { 5872 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5873 return Op; // D16 is unsupported for this instruction 5874 5875 IsD16 = true; 5876 VData = handleD16VData(VData, DAG); 5877 } 5878 5879 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5880 } else { 5881 // Work out the num dwords based on the dmask popcount and underlying type 5882 // and whether packing is supported. 5883 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5884 if (LoadVT.getScalarType() == MVT::f16) { 5885 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5886 return Op; // D16 is unsupported for this instruction 5887 5888 IsD16 = true; 5889 } 5890 5891 // Confirm that the return type is large enough for the dmask specified 5892 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5893 (!LoadVT.isVector() && DMaskLanes > 1)) 5894 return Op; 5895 5896 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5897 NumVDataDwords = (DMaskLanes + 1) / 2; 5898 else 5899 NumVDataDwords = DMaskLanes; 5900 5901 AdjustRetType = true; 5902 } 5903 5904 AddrIdx = DMaskIdx + 1; 5905 } 5906 5907 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5908 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5909 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5910 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5911 NumCoords + NumLCM; 5912 unsigned NumMIVAddrs = NumVAddrs; 5913 5914 SmallVector<SDValue, 4> VAddrs; 5915 5916 // Optimize _L to _LZ when _L is zero 5917 if (LZMappingInfo) { 5918 if (auto ConstantLod = 5919 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5920 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5921 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5922 NumMIVAddrs--; // remove 'lod' 5923 } 5924 } 5925 } 5926 5927 // Optimize _mip away, when 'lod' is zero 5928 if (MIPMappingInfo) { 5929 if (auto ConstantLod = 5930 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5931 if (ConstantLod->isNullValue()) { 5932 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5933 NumMIVAddrs--; // remove 'lod' 5934 } 5935 } 5936 } 5937 5938 // Push back extra arguments. 5939 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 5940 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 5941 5942 // Check for 16 bit addresses or derivatives and pack if true. 5943 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5944 unsigned CoordIdx = DimIdx + NumGradients; 5945 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 5946 5947 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5948 MVT VAddrScalarVT = VAddrVT.getScalarType(); 5949 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5950 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5951 5952 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 5953 VAddrScalarVT = VAddrVT.getScalarType(); 5954 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5955 if (IsA16 || IsG16) { 5956 if (IsA16) { 5957 if (!ST->hasA16()) { 5958 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5959 "support 16 bit addresses\n"); 5960 return Op; 5961 } 5962 if (!IsG16) { 5963 LLVM_DEBUG( 5964 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 5965 "need 16 bit derivatives but got 32 bit derivatives\n"); 5966 return Op; 5967 } 5968 } else if (!ST->hasG16()) { 5969 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5970 "support 16 bit derivatives\n"); 5971 return Op; 5972 } 5973 5974 if (BaseOpcode->Gradients && !IsA16) { 5975 if (!ST->hasG16()) { 5976 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5977 "support 16 bit derivatives\n"); 5978 return Op; 5979 } 5980 // Activate g16 5981 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 5982 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 5983 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 5984 } 5985 5986 // Don't compress addresses for G16 5987 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 5988 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 5989 PackEndIdx, NumGradients); 5990 5991 if (!IsA16) { 5992 // Add uncompressed address 5993 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 5994 VAddrs.push_back(Op.getOperand(I)); 5995 } 5996 } else { 5997 for (unsigned I = DimIdx; I < CoordsEnd; I++) 5998 VAddrs.push_back(Op.getOperand(I)); 5999 } 6000 6001 // If the register allocator cannot place the address registers contiguously 6002 // without introducing moves, then using the non-sequential address encoding 6003 // is always preferable, since it saves VALU instructions and is usually a 6004 // wash in terms of code size or even better. 6005 // 6006 // However, we currently have no way of hinting to the register allocator that 6007 // MIMG addresses should be placed contiguously when it is possible to do so, 6008 // so force non-NSA for the common 2-address case as a heuristic. 6009 // 6010 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6011 // allocation when possible. 6012 bool UseNSA = 6013 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6014 SDValue VAddr; 6015 if (!UseNSA) 6016 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6017 6018 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6019 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6020 unsigned CtrlIdx; // Index of texfailctrl argument 6021 SDValue Unorm; 6022 if (!BaseOpcode->Sampler) { 6023 Unorm = True; 6024 CtrlIdx = AddrIdx + NumVAddrs + 1; 6025 } else { 6026 auto UnormConst = 6027 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6028 6029 Unorm = UnormConst->getZExtValue() ? True : False; 6030 CtrlIdx = AddrIdx + NumVAddrs + 3; 6031 } 6032 6033 SDValue TFE; 6034 SDValue LWE; 6035 SDValue TexFail = Op.getOperand(CtrlIdx); 6036 bool IsTexFail = false; 6037 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6038 return Op; 6039 6040 if (IsTexFail) { 6041 if (!DMaskLanes) { 6042 // Expecting to get an error flag since TFC is on - and dmask is 0 6043 // Force dmask to be at least 1 otherwise the instruction will fail 6044 DMask = 0x1; 6045 DMaskLanes = 1; 6046 NumVDataDwords = 1; 6047 } 6048 NumVDataDwords += 1; 6049 AdjustRetType = true; 6050 } 6051 6052 // Has something earlier tagged that the return type needs adjusting 6053 // This happens if the instruction is a load or has set TexFailCtrl flags 6054 if (AdjustRetType) { 6055 // NumVDataDwords reflects the true number of dwords required in the return type 6056 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6057 // This is a no-op load. This can be eliminated 6058 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6059 if (isa<MemSDNode>(Op)) 6060 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6061 return Undef; 6062 } 6063 6064 EVT NewVT = NumVDataDwords > 1 ? 6065 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6066 : MVT::i32; 6067 6068 ResultTypes[0] = NewVT; 6069 if (ResultTypes.size() == 3) { 6070 // Original result was aggregate type used for TexFailCtrl results 6071 // The actual instruction returns as a vector type which has now been 6072 // created. Remove the aggregate result. 6073 ResultTypes.erase(&ResultTypes[1]); 6074 } 6075 } 6076 6077 SDValue GLC; 6078 SDValue SLC; 6079 SDValue DLC; 6080 if (BaseOpcode->Atomic) { 6081 GLC = True; // TODO no-return optimization 6082 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6083 IsGFX10 ? &DLC : nullptr)) 6084 return Op; 6085 } else { 6086 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6087 IsGFX10 ? &DLC : nullptr)) 6088 return Op; 6089 } 6090 6091 SmallVector<SDValue, 26> Ops; 6092 if (BaseOpcode->Store || BaseOpcode->Atomic) 6093 Ops.push_back(VData); // vdata 6094 if (UseNSA) { 6095 for (const SDValue &Addr : VAddrs) 6096 Ops.push_back(Addr); 6097 } else { 6098 Ops.push_back(VAddr); 6099 } 6100 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6101 if (BaseOpcode->Sampler) 6102 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6103 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6104 if (IsGFX10) 6105 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6106 Ops.push_back(Unorm); 6107 if (IsGFX10) 6108 Ops.push_back(DLC); 6109 Ops.push_back(GLC); 6110 Ops.push_back(SLC); 6111 Ops.push_back(IsA16 && // r128, a16 for gfx9 6112 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6113 if (IsGFX10) 6114 Ops.push_back(IsA16 ? True : False); 6115 Ops.push_back(TFE); 6116 Ops.push_back(LWE); 6117 if (!IsGFX10) 6118 Ops.push_back(DimInfo->DA ? True : False); 6119 if (BaseOpcode->HasD16) 6120 Ops.push_back(IsD16 ? True : False); 6121 if (isa<MemSDNode>(Op)) 6122 Ops.push_back(Op.getOperand(0)); // chain 6123 6124 int NumVAddrDwords = 6125 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6126 int Opcode = -1; 6127 6128 if (IsGFX10) { 6129 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6130 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6131 : AMDGPU::MIMGEncGfx10Default, 6132 NumVDataDwords, NumVAddrDwords); 6133 } else { 6134 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6135 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6136 NumVDataDwords, NumVAddrDwords); 6137 if (Opcode == -1) 6138 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6139 NumVDataDwords, NumVAddrDwords); 6140 } 6141 assert(Opcode != -1); 6142 6143 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6144 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6145 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6146 DAG.setNodeMemRefs(NewNode, {MemRef}); 6147 } 6148 6149 if (BaseOpcode->AtomicX2) { 6150 SmallVector<SDValue, 1> Elt; 6151 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6152 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6153 } else if (!BaseOpcode->Store) { 6154 return constructRetValue(DAG, NewNode, 6155 OrigResultTypes, IsTexFail, 6156 Subtarget->hasUnpackedD16VMem(), IsD16, 6157 DMaskLanes, NumVDataDwords, DL, 6158 *DAG.getContext()); 6159 } 6160 6161 return SDValue(NewNode, 0); 6162 } 6163 6164 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6165 SDValue Offset, SDValue CachePolicy, 6166 SelectionDAG &DAG) const { 6167 MachineFunction &MF = DAG.getMachineFunction(); 6168 6169 const DataLayout &DataLayout = DAG.getDataLayout(); 6170 Align Alignment = 6171 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6172 6173 MachineMemOperand *MMO = MF.getMachineMemOperand( 6174 MachinePointerInfo(), 6175 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6176 MachineMemOperand::MOInvariant, 6177 VT.getStoreSize(), Alignment); 6178 6179 if (!Offset->isDivergent()) { 6180 SDValue Ops[] = { 6181 Rsrc, 6182 Offset, // Offset 6183 CachePolicy 6184 }; 6185 6186 // Widen vec3 load to vec4. 6187 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6188 EVT WidenedVT = 6189 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6190 auto WidenedOp = DAG.getMemIntrinsicNode( 6191 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6192 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6193 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6194 DAG.getVectorIdxConstant(0, DL)); 6195 return Subvector; 6196 } 6197 6198 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6199 DAG.getVTList(VT), Ops, VT, MMO); 6200 } 6201 6202 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6203 // assume that the buffer is unswizzled. 6204 SmallVector<SDValue, 4> Loads; 6205 unsigned NumLoads = 1; 6206 MVT LoadVT = VT.getSimpleVT(); 6207 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6208 assert((LoadVT.getScalarType() == MVT::i32 || 6209 LoadVT.getScalarType() == MVT::f32)); 6210 6211 if (NumElts == 8 || NumElts == 16) { 6212 NumLoads = NumElts / 4; 6213 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6214 } 6215 6216 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6217 SDValue Ops[] = { 6218 DAG.getEntryNode(), // Chain 6219 Rsrc, // rsrc 6220 DAG.getConstant(0, DL, MVT::i32), // vindex 6221 {}, // voffset 6222 {}, // soffset 6223 {}, // offset 6224 CachePolicy, // cachepolicy 6225 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6226 }; 6227 6228 // Use the alignment to ensure that the required offsets will fit into the 6229 // immediate offsets. 6230 setBufferOffsets(Offset, DAG, &Ops[3], 6231 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6232 6233 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6234 for (unsigned i = 0; i < NumLoads; ++i) { 6235 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6236 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6237 LoadVT, MMO, DAG)); 6238 } 6239 6240 if (NumElts == 8 || NumElts == 16) 6241 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6242 6243 return Loads[0]; 6244 } 6245 6246 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6247 SelectionDAG &DAG) const { 6248 MachineFunction &MF = DAG.getMachineFunction(); 6249 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6250 6251 EVT VT = Op.getValueType(); 6252 SDLoc DL(Op); 6253 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6254 6255 // TODO: Should this propagate fast-math-flags? 6256 6257 switch (IntrinsicID) { 6258 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6259 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6260 return emitNonHSAIntrinsicError(DAG, DL, VT); 6261 return getPreloadedValue(DAG, *MFI, VT, 6262 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6263 } 6264 case Intrinsic::amdgcn_dispatch_ptr: 6265 case Intrinsic::amdgcn_queue_ptr: { 6266 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6267 DiagnosticInfoUnsupported BadIntrin( 6268 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6269 DL.getDebugLoc()); 6270 DAG.getContext()->diagnose(BadIntrin); 6271 return DAG.getUNDEF(VT); 6272 } 6273 6274 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6275 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6276 return getPreloadedValue(DAG, *MFI, VT, RegID); 6277 } 6278 case Intrinsic::amdgcn_implicitarg_ptr: { 6279 if (MFI->isEntryFunction()) 6280 return getImplicitArgPtr(DAG, DL); 6281 return getPreloadedValue(DAG, *MFI, VT, 6282 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6283 } 6284 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6285 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6286 // This only makes sense to call in a kernel, so just lower to null. 6287 return DAG.getConstant(0, DL, VT); 6288 } 6289 6290 return getPreloadedValue(DAG, *MFI, VT, 6291 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6292 } 6293 case Intrinsic::amdgcn_dispatch_id: { 6294 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6295 } 6296 case Intrinsic::amdgcn_rcp: 6297 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6298 case Intrinsic::amdgcn_rsq: 6299 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6300 case Intrinsic::amdgcn_rsq_legacy: 6301 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6302 return emitRemovedIntrinsicError(DAG, DL, VT); 6303 return SDValue(); 6304 case Intrinsic::amdgcn_rcp_legacy: 6305 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6306 return emitRemovedIntrinsicError(DAG, DL, VT); 6307 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6308 case Intrinsic::amdgcn_rsq_clamp: { 6309 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6310 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6311 6312 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6313 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6314 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6315 6316 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6317 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6318 DAG.getConstantFP(Max, DL, VT)); 6319 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6320 DAG.getConstantFP(Min, DL, VT)); 6321 } 6322 case Intrinsic::r600_read_ngroups_x: 6323 if (Subtarget->isAmdHsaOS()) 6324 return emitNonHSAIntrinsicError(DAG, DL, VT); 6325 6326 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6327 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6328 false); 6329 case Intrinsic::r600_read_ngroups_y: 6330 if (Subtarget->isAmdHsaOS()) 6331 return emitNonHSAIntrinsicError(DAG, DL, VT); 6332 6333 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6334 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6335 false); 6336 case Intrinsic::r600_read_ngroups_z: 6337 if (Subtarget->isAmdHsaOS()) 6338 return emitNonHSAIntrinsicError(DAG, DL, VT); 6339 6340 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6341 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6342 false); 6343 case Intrinsic::r600_read_global_size_x: 6344 if (Subtarget->isAmdHsaOS()) 6345 return emitNonHSAIntrinsicError(DAG, DL, VT); 6346 6347 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6348 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6349 Align(4), false); 6350 case Intrinsic::r600_read_global_size_y: 6351 if (Subtarget->isAmdHsaOS()) 6352 return emitNonHSAIntrinsicError(DAG, DL, VT); 6353 6354 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6355 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6356 Align(4), false); 6357 case Intrinsic::r600_read_global_size_z: 6358 if (Subtarget->isAmdHsaOS()) 6359 return emitNonHSAIntrinsicError(DAG, DL, VT); 6360 6361 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6362 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6363 Align(4), false); 6364 case Intrinsic::r600_read_local_size_x: 6365 if (Subtarget->isAmdHsaOS()) 6366 return emitNonHSAIntrinsicError(DAG, DL, VT); 6367 6368 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6369 SI::KernelInputOffsets::LOCAL_SIZE_X); 6370 case Intrinsic::r600_read_local_size_y: 6371 if (Subtarget->isAmdHsaOS()) 6372 return emitNonHSAIntrinsicError(DAG, DL, VT); 6373 6374 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6375 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6376 case Intrinsic::r600_read_local_size_z: 6377 if (Subtarget->isAmdHsaOS()) 6378 return emitNonHSAIntrinsicError(DAG, DL, VT); 6379 6380 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6381 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6382 case Intrinsic::amdgcn_workgroup_id_x: 6383 return getPreloadedValue(DAG, *MFI, VT, 6384 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6385 case Intrinsic::amdgcn_workgroup_id_y: 6386 return getPreloadedValue(DAG, *MFI, VT, 6387 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6388 case Intrinsic::amdgcn_workgroup_id_z: 6389 return getPreloadedValue(DAG, *MFI, VT, 6390 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6391 case Intrinsic::amdgcn_workitem_id_x: 6392 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6393 SDLoc(DAG.getEntryNode()), 6394 MFI->getArgInfo().WorkItemIDX); 6395 case Intrinsic::amdgcn_workitem_id_y: 6396 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6397 SDLoc(DAG.getEntryNode()), 6398 MFI->getArgInfo().WorkItemIDY); 6399 case Intrinsic::amdgcn_workitem_id_z: 6400 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6401 SDLoc(DAG.getEntryNode()), 6402 MFI->getArgInfo().WorkItemIDZ); 6403 case Intrinsic::amdgcn_wavefrontsize: 6404 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6405 SDLoc(Op), MVT::i32); 6406 case Intrinsic::amdgcn_s_buffer_load: { 6407 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6408 SDValue GLC; 6409 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6410 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6411 IsGFX10 ? &DLC : nullptr)) 6412 return Op; 6413 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6414 DAG); 6415 } 6416 case Intrinsic::amdgcn_fdiv_fast: 6417 return lowerFDIV_FAST(Op, DAG); 6418 case Intrinsic::amdgcn_sin: 6419 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6420 6421 case Intrinsic::amdgcn_cos: 6422 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6423 6424 case Intrinsic::amdgcn_mul_u24: 6425 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6426 case Intrinsic::amdgcn_mul_i24: 6427 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6428 6429 case Intrinsic::amdgcn_log_clamp: { 6430 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6431 return SDValue(); 6432 6433 DiagnosticInfoUnsupported BadIntrin( 6434 MF.getFunction(), "intrinsic not supported on subtarget", 6435 DL.getDebugLoc()); 6436 DAG.getContext()->diagnose(BadIntrin); 6437 return DAG.getUNDEF(VT); 6438 } 6439 case Intrinsic::amdgcn_ldexp: 6440 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6441 Op.getOperand(1), Op.getOperand(2)); 6442 6443 case Intrinsic::amdgcn_fract: 6444 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6445 6446 case Intrinsic::amdgcn_class: 6447 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6448 Op.getOperand(1), Op.getOperand(2)); 6449 case Intrinsic::amdgcn_div_fmas: 6450 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6451 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6452 Op.getOperand(4)); 6453 6454 case Intrinsic::amdgcn_div_fixup: 6455 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6456 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6457 6458 case Intrinsic::amdgcn_div_scale: { 6459 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6460 6461 // Translate to the operands expected by the machine instruction. The 6462 // first parameter must be the same as the first instruction. 6463 SDValue Numerator = Op.getOperand(1); 6464 SDValue Denominator = Op.getOperand(2); 6465 6466 // Note this order is opposite of the machine instruction's operations, 6467 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6468 // intrinsic has the numerator as the first operand to match a normal 6469 // division operation. 6470 6471 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6472 6473 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6474 Denominator, Numerator); 6475 } 6476 case Intrinsic::amdgcn_icmp: { 6477 // There is a Pat that handles this variant, so return it as-is. 6478 if (Op.getOperand(1).getValueType() == MVT::i1 && 6479 Op.getConstantOperandVal(2) == 0 && 6480 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6481 return Op; 6482 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6483 } 6484 case Intrinsic::amdgcn_fcmp: { 6485 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6486 } 6487 case Intrinsic::amdgcn_ballot: 6488 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6489 case Intrinsic::amdgcn_fmed3: 6490 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6491 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6492 case Intrinsic::amdgcn_fdot2: 6493 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6494 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6495 Op.getOperand(4)); 6496 case Intrinsic::amdgcn_fmul_legacy: 6497 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6498 Op.getOperand(1), Op.getOperand(2)); 6499 case Intrinsic::amdgcn_sffbh: 6500 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6501 case Intrinsic::amdgcn_sbfe: 6502 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6503 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6504 case Intrinsic::amdgcn_ubfe: 6505 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6506 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6507 case Intrinsic::amdgcn_cvt_pkrtz: 6508 case Intrinsic::amdgcn_cvt_pknorm_i16: 6509 case Intrinsic::amdgcn_cvt_pknorm_u16: 6510 case Intrinsic::amdgcn_cvt_pk_i16: 6511 case Intrinsic::amdgcn_cvt_pk_u16: { 6512 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6513 EVT VT = Op.getValueType(); 6514 unsigned Opcode; 6515 6516 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6517 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6518 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6519 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6520 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6521 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6522 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6523 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6524 else 6525 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6526 6527 if (isTypeLegal(VT)) 6528 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6529 6530 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6531 Op.getOperand(1), Op.getOperand(2)); 6532 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6533 } 6534 case Intrinsic::amdgcn_fmad_ftz: 6535 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6536 Op.getOperand(2), Op.getOperand(3)); 6537 6538 case Intrinsic::amdgcn_if_break: 6539 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6540 Op->getOperand(1), Op->getOperand(2)), 0); 6541 6542 case Intrinsic::amdgcn_groupstaticsize: { 6543 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6544 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6545 return Op; 6546 6547 const Module *M = MF.getFunction().getParent(); 6548 const GlobalValue *GV = 6549 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6550 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6551 SIInstrInfo::MO_ABS32_LO); 6552 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6553 } 6554 case Intrinsic::amdgcn_is_shared: 6555 case Intrinsic::amdgcn_is_private: { 6556 SDLoc SL(Op); 6557 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6558 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6559 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6560 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6561 Op.getOperand(1)); 6562 6563 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6564 DAG.getConstant(1, SL, MVT::i32)); 6565 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6566 } 6567 case Intrinsic::amdgcn_alignbit: 6568 return DAG.getNode(ISD::FSHR, DL, VT, 6569 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6570 case Intrinsic::amdgcn_reloc_constant: { 6571 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6572 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6573 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6574 auto RelocSymbol = cast<GlobalVariable>( 6575 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6576 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6577 SIInstrInfo::MO_ABS32_LO); 6578 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6579 } 6580 default: 6581 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6582 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6583 return lowerImage(Op, ImageDimIntr, DAG); 6584 6585 return Op; 6586 } 6587 } 6588 6589 // This function computes an appropriate offset to pass to 6590 // MachineMemOperand::setOffset() based on the offset inputs to 6591 // an intrinsic. If any of the offsets are non-contstant or 6592 // if VIndex is non-zero then this function returns 0. Otherwise, 6593 // it returns the sum of VOffset, SOffset, and Offset. 6594 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6595 SDValue SOffset, 6596 SDValue Offset, 6597 SDValue VIndex = SDValue()) { 6598 6599 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6600 !isa<ConstantSDNode>(Offset)) 6601 return 0; 6602 6603 if (VIndex) { 6604 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6605 return 0; 6606 } 6607 6608 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6609 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6610 cast<ConstantSDNode>(Offset)->getSExtValue(); 6611 } 6612 6613 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6614 switch (MF.getFunction().getCallingConv()) { 6615 case CallingConv::AMDGPU_PS: 6616 return 1; 6617 case CallingConv::AMDGPU_VS: 6618 return 2; 6619 case CallingConv::AMDGPU_GS: 6620 return 3; 6621 case CallingConv::AMDGPU_HS: 6622 case CallingConv::AMDGPU_LS: 6623 case CallingConv::AMDGPU_ES: 6624 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6625 case CallingConv::AMDGPU_CS: 6626 case CallingConv::AMDGPU_KERNEL: 6627 case CallingConv::C: 6628 case CallingConv::Fast: 6629 default: 6630 // Assume other calling conventions are various compute callable functions 6631 return 0; 6632 } 6633 } 6634 6635 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6636 SelectionDAG &DAG) const { 6637 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6638 SDLoc DL(Op); 6639 6640 switch (IntrID) { 6641 case Intrinsic::amdgcn_ds_ordered_add: 6642 case Intrinsic::amdgcn_ds_ordered_swap: { 6643 MemSDNode *M = cast<MemSDNode>(Op); 6644 SDValue Chain = M->getOperand(0); 6645 SDValue M0 = M->getOperand(2); 6646 SDValue Value = M->getOperand(3); 6647 unsigned IndexOperand = M->getConstantOperandVal(7); 6648 unsigned WaveRelease = M->getConstantOperandVal(8); 6649 unsigned WaveDone = M->getConstantOperandVal(9); 6650 6651 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6652 IndexOperand &= ~0x3f; 6653 unsigned CountDw = 0; 6654 6655 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6656 CountDw = (IndexOperand >> 24) & 0xf; 6657 IndexOperand &= ~(0xf << 24); 6658 6659 if (CountDw < 1 || CountDw > 4) { 6660 report_fatal_error( 6661 "ds_ordered_count: dword count must be between 1 and 4"); 6662 } 6663 } 6664 6665 if (IndexOperand) 6666 report_fatal_error("ds_ordered_count: bad index operand"); 6667 6668 if (WaveDone && !WaveRelease) 6669 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6670 6671 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6672 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6673 unsigned Offset0 = OrderedCountIndex << 2; 6674 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6675 (Instruction << 4); 6676 6677 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6678 Offset1 |= (CountDw - 1) << 6; 6679 6680 unsigned Offset = Offset0 | (Offset1 << 8); 6681 6682 SDValue Ops[] = { 6683 Chain, 6684 Value, 6685 DAG.getTargetConstant(Offset, DL, MVT::i16), 6686 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6687 }; 6688 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6689 M->getVTList(), Ops, M->getMemoryVT(), 6690 M->getMemOperand()); 6691 } 6692 case Intrinsic::amdgcn_ds_fadd: { 6693 MemSDNode *M = cast<MemSDNode>(Op); 6694 unsigned Opc; 6695 switch (IntrID) { 6696 case Intrinsic::amdgcn_ds_fadd: 6697 Opc = ISD::ATOMIC_LOAD_FADD; 6698 break; 6699 } 6700 6701 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6702 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6703 M->getMemOperand()); 6704 } 6705 case Intrinsic::amdgcn_atomic_inc: 6706 case Intrinsic::amdgcn_atomic_dec: 6707 case Intrinsic::amdgcn_ds_fmin: 6708 case Intrinsic::amdgcn_ds_fmax: { 6709 MemSDNode *M = cast<MemSDNode>(Op); 6710 unsigned Opc; 6711 switch (IntrID) { 6712 case Intrinsic::amdgcn_atomic_inc: 6713 Opc = AMDGPUISD::ATOMIC_INC; 6714 break; 6715 case Intrinsic::amdgcn_atomic_dec: 6716 Opc = AMDGPUISD::ATOMIC_DEC; 6717 break; 6718 case Intrinsic::amdgcn_ds_fmin: 6719 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6720 break; 6721 case Intrinsic::amdgcn_ds_fmax: 6722 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6723 break; 6724 default: 6725 llvm_unreachable("Unknown intrinsic!"); 6726 } 6727 SDValue Ops[] = { 6728 M->getOperand(0), // Chain 6729 M->getOperand(2), // Ptr 6730 M->getOperand(3) // Value 6731 }; 6732 6733 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6734 M->getMemoryVT(), M->getMemOperand()); 6735 } 6736 case Intrinsic::amdgcn_buffer_load: 6737 case Intrinsic::amdgcn_buffer_load_format: { 6738 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6739 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6740 unsigned IdxEn = 1; 6741 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6742 IdxEn = Idx->getZExtValue() != 0; 6743 SDValue Ops[] = { 6744 Op.getOperand(0), // Chain 6745 Op.getOperand(2), // rsrc 6746 Op.getOperand(3), // vindex 6747 SDValue(), // voffset -- will be set by setBufferOffsets 6748 SDValue(), // soffset -- will be set by setBufferOffsets 6749 SDValue(), // offset -- will be set by setBufferOffsets 6750 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6751 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6752 }; 6753 6754 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6755 // We don't know the offset if vindex is non-zero, so clear it. 6756 if (IdxEn) 6757 Offset = 0; 6758 6759 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6760 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6761 6762 EVT VT = Op.getValueType(); 6763 EVT IntVT = VT.changeTypeToInteger(); 6764 auto *M = cast<MemSDNode>(Op); 6765 M->getMemOperand()->setOffset(Offset); 6766 EVT LoadVT = Op.getValueType(); 6767 6768 if (LoadVT.getScalarType() == MVT::f16) 6769 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6770 M, DAG, Ops); 6771 6772 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6773 if (LoadVT.getScalarType() == MVT::i8 || 6774 LoadVT.getScalarType() == MVT::i16) 6775 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6776 6777 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6778 M->getMemOperand(), DAG); 6779 } 6780 case Intrinsic::amdgcn_raw_buffer_load: 6781 case Intrinsic::amdgcn_raw_buffer_load_format: { 6782 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6783 6784 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6785 SDValue Ops[] = { 6786 Op.getOperand(0), // Chain 6787 Op.getOperand(2), // rsrc 6788 DAG.getConstant(0, DL, MVT::i32), // vindex 6789 Offsets.first, // voffset 6790 Op.getOperand(4), // soffset 6791 Offsets.second, // offset 6792 Op.getOperand(5), // cachepolicy, swizzled buffer 6793 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6794 }; 6795 6796 auto *M = cast<MemSDNode>(Op); 6797 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6798 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6799 } 6800 case Intrinsic::amdgcn_struct_buffer_load: 6801 case Intrinsic::amdgcn_struct_buffer_load_format: { 6802 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6803 6804 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6805 SDValue Ops[] = { 6806 Op.getOperand(0), // Chain 6807 Op.getOperand(2), // rsrc 6808 Op.getOperand(3), // vindex 6809 Offsets.first, // voffset 6810 Op.getOperand(5), // soffset 6811 Offsets.second, // offset 6812 Op.getOperand(6), // cachepolicy, swizzled buffer 6813 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6814 }; 6815 6816 auto *M = cast<MemSDNode>(Op); 6817 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6818 Ops[2])); 6819 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6820 } 6821 case Intrinsic::amdgcn_tbuffer_load: { 6822 MemSDNode *M = cast<MemSDNode>(Op); 6823 EVT LoadVT = Op.getValueType(); 6824 6825 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6826 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6827 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6828 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6829 unsigned IdxEn = 1; 6830 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6831 IdxEn = Idx->getZExtValue() != 0; 6832 SDValue Ops[] = { 6833 Op.getOperand(0), // Chain 6834 Op.getOperand(2), // rsrc 6835 Op.getOperand(3), // vindex 6836 Op.getOperand(4), // voffset 6837 Op.getOperand(5), // soffset 6838 Op.getOperand(6), // offset 6839 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6840 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6841 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6842 }; 6843 6844 if (LoadVT.getScalarType() == MVT::f16) 6845 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6846 M, DAG, Ops); 6847 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6848 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6849 DAG); 6850 } 6851 case Intrinsic::amdgcn_raw_tbuffer_load: { 6852 MemSDNode *M = cast<MemSDNode>(Op); 6853 EVT LoadVT = Op.getValueType(); 6854 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6855 6856 SDValue Ops[] = { 6857 Op.getOperand(0), // Chain 6858 Op.getOperand(2), // rsrc 6859 DAG.getConstant(0, DL, MVT::i32), // vindex 6860 Offsets.first, // voffset 6861 Op.getOperand(4), // soffset 6862 Offsets.second, // offset 6863 Op.getOperand(5), // format 6864 Op.getOperand(6), // cachepolicy, swizzled buffer 6865 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6866 }; 6867 6868 if (LoadVT.getScalarType() == MVT::f16) 6869 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6870 M, DAG, Ops); 6871 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6872 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6873 DAG); 6874 } 6875 case Intrinsic::amdgcn_struct_tbuffer_load: { 6876 MemSDNode *M = cast<MemSDNode>(Op); 6877 EVT LoadVT = Op.getValueType(); 6878 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6879 6880 SDValue Ops[] = { 6881 Op.getOperand(0), // Chain 6882 Op.getOperand(2), // rsrc 6883 Op.getOperand(3), // vindex 6884 Offsets.first, // voffset 6885 Op.getOperand(5), // soffset 6886 Offsets.second, // offset 6887 Op.getOperand(6), // format 6888 Op.getOperand(7), // cachepolicy, swizzled buffer 6889 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6890 }; 6891 6892 if (LoadVT.getScalarType() == MVT::f16) 6893 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6894 M, DAG, Ops); 6895 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6896 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6897 DAG); 6898 } 6899 case Intrinsic::amdgcn_buffer_atomic_swap: 6900 case Intrinsic::amdgcn_buffer_atomic_add: 6901 case Intrinsic::amdgcn_buffer_atomic_sub: 6902 case Intrinsic::amdgcn_buffer_atomic_csub: 6903 case Intrinsic::amdgcn_buffer_atomic_smin: 6904 case Intrinsic::amdgcn_buffer_atomic_umin: 6905 case Intrinsic::amdgcn_buffer_atomic_smax: 6906 case Intrinsic::amdgcn_buffer_atomic_umax: 6907 case Intrinsic::amdgcn_buffer_atomic_and: 6908 case Intrinsic::amdgcn_buffer_atomic_or: 6909 case Intrinsic::amdgcn_buffer_atomic_xor: { 6910 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6911 unsigned IdxEn = 1; 6912 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6913 IdxEn = Idx->getZExtValue() != 0; 6914 SDValue Ops[] = { 6915 Op.getOperand(0), // Chain 6916 Op.getOperand(2), // vdata 6917 Op.getOperand(3), // rsrc 6918 Op.getOperand(4), // vindex 6919 SDValue(), // voffset -- will be set by setBufferOffsets 6920 SDValue(), // soffset -- will be set by setBufferOffsets 6921 SDValue(), // offset -- will be set by setBufferOffsets 6922 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6923 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6924 }; 6925 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6926 // We don't know the offset if vindex is non-zero, so clear it. 6927 if (IdxEn) 6928 Offset = 0; 6929 EVT VT = Op.getValueType(); 6930 6931 auto *M = cast<MemSDNode>(Op); 6932 M->getMemOperand()->setOffset(Offset); 6933 unsigned Opcode = 0; 6934 6935 switch (IntrID) { 6936 case Intrinsic::amdgcn_buffer_atomic_swap: 6937 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6938 break; 6939 case Intrinsic::amdgcn_buffer_atomic_add: 6940 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6941 break; 6942 case Intrinsic::amdgcn_buffer_atomic_sub: 6943 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6944 break; 6945 case Intrinsic::amdgcn_buffer_atomic_csub: 6946 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 6947 break; 6948 case Intrinsic::amdgcn_buffer_atomic_smin: 6949 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6950 break; 6951 case Intrinsic::amdgcn_buffer_atomic_umin: 6952 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6953 break; 6954 case Intrinsic::amdgcn_buffer_atomic_smax: 6955 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6956 break; 6957 case Intrinsic::amdgcn_buffer_atomic_umax: 6958 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6959 break; 6960 case Intrinsic::amdgcn_buffer_atomic_and: 6961 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6962 break; 6963 case Intrinsic::amdgcn_buffer_atomic_or: 6964 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6965 break; 6966 case Intrinsic::amdgcn_buffer_atomic_xor: 6967 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6968 break; 6969 default: 6970 llvm_unreachable("unhandled atomic opcode"); 6971 } 6972 6973 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6974 M->getMemOperand()); 6975 } 6976 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6977 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6978 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6979 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6980 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6981 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6982 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6983 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6984 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6985 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6986 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6987 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6988 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6989 SDValue Ops[] = { 6990 Op.getOperand(0), // Chain 6991 Op.getOperand(2), // vdata 6992 Op.getOperand(3), // rsrc 6993 DAG.getConstant(0, DL, MVT::i32), // vindex 6994 Offsets.first, // voffset 6995 Op.getOperand(5), // soffset 6996 Offsets.second, // offset 6997 Op.getOperand(6), // cachepolicy 6998 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6999 }; 7000 EVT VT = Op.getValueType(); 7001 7002 auto *M = cast<MemSDNode>(Op); 7003 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7004 unsigned Opcode = 0; 7005 7006 switch (IntrID) { 7007 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7008 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7009 break; 7010 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7011 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7012 break; 7013 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7014 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7015 break; 7016 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7017 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7018 break; 7019 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7020 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7021 break; 7022 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7023 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7024 break; 7025 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7026 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7027 break; 7028 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7029 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7030 break; 7031 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7032 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7033 break; 7034 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7035 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7036 break; 7037 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7038 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7039 break; 7040 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7041 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7042 break; 7043 default: 7044 llvm_unreachable("unhandled atomic opcode"); 7045 } 7046 7047 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7048 M->getMemOperand()); 7049 } 7050 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7051 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7052 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7053 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7054 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7055 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7056 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7057 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7058 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7059 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7060 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7061 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 7062 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7063 SDValue Ops[] = { 7064 Op.getOperand(0), // Chain 7065 Op.getOperand(2), // vdata 7066 Op.getOperand(3), // rsrc 7067 Op.getOperand(4), // vindex 7068 Offsets.first, // voffset 7069 Op.getOperand(6), // soffset 7070 Offsets.second, // offset 7071 Op.getOperand(7), // cachepolicy 7072 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7073 }; 7074 EVT VT = Op.getValueType(); 7075 7076 auto *M = cast<MemSDNode>(Op); 7077 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7078 Ops[3])); 7079 unsigned Opcode = 0; 7080 7081 switch (IntrID) { 7082 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7083 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7084 break; 7085 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7086 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7087 break; 7088 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7089 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7090 break; 7091 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7092 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7093 break; 7094 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7095 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7096 break; 7097 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7098 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7099 break; 7100 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7101 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7102 break; 7103 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7104 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7105 break; 7106 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7107 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7108 break; 7109 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7110 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7111 break; 7112 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7113 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7114 break; 7115 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7116 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7117 break; 7118 default: 7119 llvm_unreachable("unhandled atomic opcode"); 7120 } 7121 7122 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7123 M->getMemOperand()); 7124 } 7125 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7126 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7127 unsigned IdxEn = 1; 7128 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7129 IdxEn = Idx->getZExtValue() != 0; 7130 SDValue Ops[] = { 7131 Op.getOperand(0), // Chain 7132 Op.getOperand(2), // src 7133 Op.getOperand(3), // cmp 7134 Op.getOperand(4), // rsrc 7135 Op.getOperand(5), // vindex 7136 SDValue(), // voffset -- will be set by setBufferOffsets 7137 SDValue(), // soffset -- will be set by setBufferOffsets 7138 SDValue(), // offset -- will be set by setBufferOffsets 7139 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7140 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7141 }; 7142 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7143 // We don't know the offset if vindex is non-zero, so clear it. 7144 if (IdxEn) 7145 Offset = 0; 7146 EVT VT = Op.getValueType(); 7147 auto *M = cast<MemSDNode>(Op); 7148 M->getMemOperand()->setOffset(Offset); 7149 7150 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7151 Op->getVTList(), Ops, VT, M->getMemOperand()); 7152 } 7153 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7154 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7155 SDValue Ops[] = { 7156 Op.getOperand(0), // Chain 7157 Op.getOperand(2), // src 7158 Op.getOperand(3), // cmp 7159 Op.getOperand(4), // rsrc 7160 DAG.getConstant(0, DL, MVT::i32), // vindex 7161 Offsets.first, // voffset 7162 Op.getOperand(6), // soffset 7163 Offsets.second, // offset 7164 Op.getOperand(7), // cachepolicy 7165 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7166 }; 7167 EVT VT = Op.getValueType(); 7168 auto *M = cast<MemSDNode>(Op); 7169 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7170 7171 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7172 Op->getVTList(), Ops, VT, M->getMemOperand()); 7173 } 7174 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7175 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7176 SDValue Ops[] = { 7177 Op.getOperand(0), // Chain 7178 Op.getOperand(2), // src 7179 Op.getOperand(3), // cmp 7180 Op.getOperand(4), // rsrc 7181 Op.getOperand(5), // vindex 7182 Offsets.first, // voffset 7183 Op.getOperand(7), // soffset 7184 Offsets.second, // offset 7185 Op.getOperand(8), // cachepolicy 7186 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7187 }; 7188 EVT VT = Op.getValueType(); 7189 auto *M = cast<MemSDNode>(Op); 7190 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7191 Ops[4])); 7192 7193 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7194 Op->getVTList(), Ops, VT, M->getMemOperand()); 7195 } 7196 case Intrinsic::amdgcn_global_atomic_csub: { 7197 MemSDNode *M = cast<MemSDNode>(Op); 7198 SDValue Ops[] = { 7199 M->getOperand(0), // Chain 7200 M->getOperand(2), // Ptr 7201 M->getOperand(3) // Value 7202 }; 7203 7204 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_LOAD_CSUB, SDLoc(Op), 7205 M->getVTList(), Ops, M->getMemoryVT(), 7206 M->getMemOperand()); 7207 } 7208 7209 default: 7210 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7211 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7212 return lowerImage(Op, ImageDimIntr, DAG); 7213 7214 return SDValue(); 7215 } 7216 } 7217 7218 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7219 // dwordx4 if on SI. 7220 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7221 SDVTList VTList, 7222 ArrayRef<SDValue> Ops, EVT MemVT, 7223 MachineMemOperand *MMO, 7224 SelectionDAG &DAG) const { 7225 EVT VT = VTList.VTs[0]; 7226 EVT WidenedVT = VT; 7227 EVT WidenedMemVT = MemVT; 7228 if (!Subtarget->hasDwordx3LoadStores() && 7229 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7230 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7231 WidenedVT.getVectorElementType(), 4); 7232 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7233 WidenedMemVT.getVectorElementType(), 4); 7234 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7235 } 7236 7237 assert(VTList.NumVTs == 2); 7238 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7239 7240 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7241 WidenedMemVT, MMO); 7242 if (WidenedVT != VT) { 7243 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7244 DAG.getVectorIdxConstant(0, DL)); 7245 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7246 } 7247 return NewOp; 7248 } 7249 7250 SDValue SITargetLowering::handleD16VData(SDValue VData, 7251 SelectionDAG &DAG) const { 7252 EVT StoreVT = VData.getValueType(); 7253 7254 // No change for f16 and legal vector D16 types. 7255 if (!StoreVT.isVector()) 7256 return VData; 7257 7258 SDLoc DL(VData); 7259 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7260 7261 if (Subtarget->hasUnpackedD16VMem()) { 7262 // We need to unpack the packed data to store. 7263 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7264 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7265 7266 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7267 StoreVT.getVectorNumElements()); 7268 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7269 return DAG.UnrollVectorOp(ZExt.getNode()); 7270 } 7271 7272 assert(isTypeLegal(StoreVT)); 7273 return VData; 7274 } 7275 7276 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7277 SelectionDAG &DAG) const { 7278 SDLoc DL(Op); 7279 SDValue Chain = Op.getOperand(0); 7280 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7281 MachineFunction &MF = DAG.getMachineFunction(); 7282 7283 switch (IntrinsicID) { 7284 case Intrinsic::amdgcn_exp_compr: { 7285 SDValue Src0 = Op.getOperand(4); 7286 SDValue Src1 = Op.getOperand(5); 7287 // Hack around illegal type on SI by directly selecting it. 7288 if (isTypeLegal(Src0.getValueType())) 7289 return SDValue(); 7290 7291 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7292 SDValue Undef = DAG.getUNDEF(MVT::f32); 7293 const SDValue Ops[] = { 7294 Op.getOperand(2), // tgt 7295 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7296 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7297 Undef, // src2 7298 Undef, // src3 7299 Op.getOperand(7), // vm 7300 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7301 Op.getOperand(3), // en 7302 Op.getOperand(0) // Chain 7303 }; 7304 7305 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7306 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7307 } 7308 case Intrinsic::amdgcn_s_barrier: { 7309 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7310 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7311 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7312 if (WGSize <= ST.getWavefrontSize()) 7313 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7314 Op.getOperand(0)), 0); 7315 } 7316 return SDValue(); 7317 }; 7318 case Intrinsic::amdgcn_tbuffer_store: { 7319 SDValue VData = Op.getOperand(2); 7320 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7321 if (IsD16) 7322 VData = handleD16VData(VData, DAG); 7323 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7324 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7325 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7326 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7327 unsigned IdxEn = 1; 7328 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7329 IdxEn = Idx->getZExtValue() != 0; 7330 SDValue Ops[] = { 7331 Chain, 7332 VData, // vdata 7333 Op.getOperand(3), // rsrc 7334 Op.getOperand(4), // vindex 7335 Op.getOperand(5), // voffset 7336 Op.getOperand(6), // soffset 7337 Op.getOperand(7), // offset 7338 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7339 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7340 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7341 }; 7342 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7343 AMDGPUISD::TBUFFER_STORE_FORMAT; 7344 MemSDNode *M = cast<MemSDNode>(Op); 7345 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7346 M->getMemoryVT(), M->getMemOperand()); 7347 } 7348 7349 case Intrinsic::amdgcn_struct_tbuffer_store: { 7350 SDValue VData = Op.getOperand(2); 7351 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7352 if (IsD16) 7353 VData = handleD16VData(VData, DAG); 7354 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7355 SDValue Ops[] = { 7356 Chain, 7357 VData, // vdata 7358 Op.getOperand(3), // rsrc 7359 Op.getOperand(4), // vindex 7360 Offsets.first, // voffset 7361 Op.getOperand(6), // soffset 7362 Offsets.second, // offset 7363 Op.getOperand(7), // format 7364 Op.getOperand(8), // cachepolicy, swizzled buffer 7365 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7366 }; 7367 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7368 AMDGPUISD::TBUFFER_STORE_FORMAT; 7369 MemSDNode *M = cast<MemSDNode>(Op); 7370 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7371 M->getMemoryVT(), M->getMemOperand()); 7372 } 7373 7374 case Intrinsic::amdgcn_raw_tbuffer_store: { 7375 SDValue VData = Op.getOperand(2); 7376 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7377 if (IsD16) 7378 VData = handleD16VData(VData, DAG); 7379 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7380 SDValue Ops[] = { 7381 Chain, 7382 VData, // vdata 7383 Op.getOperand(3), // rsrc 7384 DAG.getConstant(0, DL, MVT::i32), // vindex 7385 Offsets.first, // voffset 7386 Op.getOperand(5), // soffset 7387 Offsets.second, // offset 7388 Op.getOperand(6), // format 7389 Op.getOperand(7), // cachepolicy, swizzled buffer 7390 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7391 }; 7392 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7393 AMDGPUISD::TBUFFER_STORE_FORMAT; 7394 MemSDNode *M = cast<MemSDNode>(Op); 7395 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7396 M->getMemoryVT(), M->getMemOperand()); 7397 } 7398 7399 case Intrinsic::amdgcn_buffer_store: 7400 case Intrinsic::amdgcn_buffer_store_format: { 7401 SDValue VData = Op.getOperand(2); 7402 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7403 if (IsD16) 7404 VData = handleD16VData(VData, DAG); 7405 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7406 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7407 unsigned IdxEn = 1; 7408 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7409 IdxEn = Idx->getZExtValue() != 0; 7410 SDValue Ops[] = { 7411 Chain, 7412 VData, 7413 Op.getOperand(3), // rsrc 7414 Op.getOperand(4), // vindex 7415 SDValue(), // voffset -- will be set by setBufferOffsets 7416 SDValue(), // soffset -- will be set by setBufferOffsets 7417 SDValue(), // offset -- will be set by setBufferOffsets 7418 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7419 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7420 }; 7421 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7422 // We don't know the offset if vindex is non-zero, so clear it. 7423 if (IdxEn) 7424 Offset = 0; 7425 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7426 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7427 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7428 MemSDNode *M = cast<MemSDNode>(Op); 7429 M->getMemOperand()->setOffset(Offset); 7430 7431 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7432 EVT VDataType = VData.getValueType().getScalarType(); 7433 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7434 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7435 7436 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7437 M->getMemoryVT(), M->getMemOperand()); 7438 } 7439 7440 case Intrinsic::amdgcn_raw_buffer_store: 7441 case Intrinsic::amdgcn_raw_buffer_store_format: { 7442 const bool IsFormat = 7443 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7444 7445 SDValue VData = Op.getOperand(2); 7446 EVT VDataVT = VData.getValueType(); 7447 EVT EltType = VDataVT.getScalarType(); 7448 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7449 if (IsD16) 7450 VData = handleD16VData(VData, DAG); 7451 7452 if (!isTypeLegal(VDataVT)) { 7453 VData = 7454 DAG.getNode(ISD::BITCAST, DL, 7455 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7456 } 7457 7458 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7459 SDValue Ops[] = { 7460 Chain, 7461 VData, 7462 Op.getOperand(3), // rsrc 7463 DAG.getConstant(0, DL, MVT::i32), // vindex 7464 Offsets.first, // voffset 7465 Op.getOperand(5), // soffset 7466 Offsets.second, // offset 7467 Op.getOperand(6), // cachepolicy, swizzled buffer 7468 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7469 }; 7470 unsigned Opc = 7471 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7472 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7473 MemSDNode *M = cast<MemSDNode>(Op); 7474 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7475 7476 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7477 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7478 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7479 7480 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7481 M->getMemoryVT(), M->getMemOperand()); 7482 } 7483 7484 case Intrinsic::amdgcn_struct_buffer_store: 7485 case Intrinsic::amdgcn_struct_buffer_store_format: { 7486 const bool IsFormat = 7487 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7488 7489 SDValue VData = Op.getOperand(2); 7490 EVT VDataVT = VData.getValueType(); 7491 EVT EltType = VDataVT.getScalarType(); 7492 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7493 7494 if (IsD16) 7495 VData = handleD16VData(VData, DAG); 7496 7497 if (!isTypeLegal(VDataVT)) { 7498 VData = 7499 DAG.getNode(ISD::BITCAST, DL, 7500 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7501 } 7502 7503 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7504 SDValue Ops[] = { 7505 Chain, 7506 VData, 7507 Op.getOperand(3), // rsrc 7508 Op.getOperand(4), // vindex 7509 Offsets.first, // voffset 7510 Op.getOperand(6), // soffset 7511 Offsets.second, // offset 7512 Op.getOperand(7), // cachepolicy, swizzled buffer 7513 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7514 }; 7515 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7516 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7517 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7518 MemSDNode *M = cast<MemSDNode>(Op); 7519 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7520 Ops[3])); 7521 7522 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7523 EVT VDataType = VData.getValueType().getScalarType(); 7524 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7525 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7526 7527 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7528 M->getMemoryVT(), M->getMemOperand()); 7529 } 7530 7531 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7532 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7533 unsigned IdxEn = 1; 7534 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7535 IdxEn = Idx->getZExtValue() != 0; 7536 SDValue Ops[] = { 7537 Chain, 7538 Op.getOperand(2), // vdata 7539 Op.getOperand(3), // rsrc 7540 Op.getOperand(4), // vindex 7541 SDValue(), // voffset -- will be set by setBufferOffsets 7542 SDValue(), // soffset -- will be set by setBufferOffsets 7543 SDValue(), // offset -- will be set by setBufferOffsets 7544 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7545 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7546 }; 7547 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7548 // We don't know the offset if vindex is non-zero, so clear it. 7549 if (IdxEn) 7550 Offset = 0; 7551 EVT VT = Op.getOperand(2).getValueType(); 7552 7553 auto *M = cast<MemSDNode>(Op); 7554 M->getMemOperand()->setOffset(Offset); 7555 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7556 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7557 7558 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7559 M->getMemOperand()); 7560 } 7561 7562 case Intrinsic::amdgcn_global_atomic_fadd: { 7563 SDValue Ops[] = { 7564 Chain, 7565 Op.getOperand(2), // ptr 7566 Op.getOperand(3) // vdata 7567 }; 7568 EVT VT = Op.getOperand(3).getValueType(); 7569 7570 auto *M = cast<MemSDNode>(Op); 7571 if (VT.isVector()) { 7572 return DAG.getMemIntrinsicNode( 7573 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7574 M->getMemOperand()); 7575 } 7576 7577 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7578 DAG.getVTList(VT, MVT::Other), Ops, 7579 M->getMemOperand()).getValue(1); 7580 } 7581 case Intrinsic::amdgcn_end_cf: 7582 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7583 Op->getOperand(2), Chain), 0); 7584 7585 default: { 7586 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7587 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7588 return lowerImage(Op, ImageDimIntr, DAG); 7589 7590 return Op; 7591 } 7592 } 7593 } 7594 7595 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7596 // offset (the offset that is included in bounds checking and swizzling, to be 7597 // split between the instruction's voffset and immoffset fields) and soffset 7598 // (the offset that is excluded from bounds checking and swizzling, to go in 7599 // the instruction's soffset field). This function takes the first kind of 7600 // offset and figures out how to split it between voffset and immoffset. 7601 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7602 SDValue Offset, SelectionDAG &DAG) const { 7603 SDLoc DL(Offset); 7604 const unsigned MaxImm = 4095; 7605 SDValue N0 = Offset; 7606 ConstantSDNode *C1 = nullptr; 7607 7608 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7609 N0 = SDValue(); 7610 else if (DAG.isBaseWithConstantOffset(N0)) { 7611 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7612 N0 = N0.getOperand(0); 7613 } 7614 7615 if (C1) { 7616 unsigned ImmOffset = C1->getZExtValue(); 7617 // If the immediate value is too big for the immoffset field, put the value 7618 // and -4096 into the immoffset field so that the value that is copied/added 7619 // for the voffset field is a multiple of 4096, and it stands more chance 7620 // of being CSEd with the copy/add for another similar load/store. 7621 // However, do not do that rounding down to a multiple of 4096 if that is a 7622 // negative number, as it appears to be illegal to have a negative offset 7623 // in the vgpr, even if adding the immediate offset makes it positive. 7624 unsigned Overflow = ImmOffset & ~MaxImm; 7625 ImmOffset -= Overflow; 7626 if ((int32_t)Overflow < 0) { 7627 Overflow += ImmOffset; 7628 ImmOffset = 0; 7629 } 7630 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7631 if (Overflow) { 7632 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7633 if (!N0) 7634 N0 = OverflowVal; 7635 else { 7636 SDValue Ops[] = { N0, OverflowVal }; 7637 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7638 } 7639 } 7640 } 7641 if (!N0) 7642 N0 = DAG.getConstant(0, DL, MVT::i32); 7643 if (!C1) 7644 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7645 return {N0, SDValue(C1, 0)}; 7646 } 7647 7648 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7649 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7650 // pointed to by Offsets. 7651 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7652 SelectionDAG &DAG, SDValue *Offsets, 7653 Align Alignment) const { 7654 SDLoc DL(CombinedOffset); 7655 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7656 uint32_t Imm = C->getZExtValue(); 7657 uint32_t SOffset, ImmOffset; 7658 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7659 Alignment)) { 7660 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7661 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7662 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7663 return SOffset + ImmOffset; 7664 } 7665 } 7666 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7667 SDValue N0 = CombinedOffset.getOperand(0); 7668 SDValue N1 = CombinedOffset.getOperand(1); 7669 uint32_t SOffset, ImmOffset; 7670 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7671 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7672 Subtarget, Alignment)) { 7673 Offsets[0] = N0; 7674 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7675 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7676 return 0; 7677 } 7678 } 7679 Offsets[0] = CombinedOffset; 7680 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7681 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7682 return 0; 7683 } 7684 7685 // Handle 8 bit and 16 bit buffer loads 7686 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7687 EVT LoadVT, SDLoc DL, 7688 ArrayRef<SDValue> Ops, 7689 MemSDNode *M) const { 7690 EVT IntVT = LoadVT.changeTypeToInteger(); 7691 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7692 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7693 7694 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7695 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7696 Ops, IntVT, 7697 M->getMemOperand()); 7698 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7699 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7700 7701 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7702 } 7703 7704 // Handle 8 bit and 16 bit buffer stores 7705 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7706 EVT VDataType, SDLoc DL, 7707 SDValue Ops[], 7708 MemSDNode *M) const { 7709 if (VDataType == MVT::f16) 7710 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7711 7712 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7713 Ops[1] = BufferStoreExt; 7714 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7715 AMDGPUISD::BUFFER_STORE_SHORT; 7716 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7717 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7718 M->getMemOperand()); 7719 } 7720 7721 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7722 ISD::LoadExtType ExtType, SDValue Op, 7723 const SDLoc &SL, EVT VT) { 7724 if (VT.bitsLT(Op.getValueType())) 7725 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7726 7727 switch (ExtType) { 7728 case ISD::SEXTLOAD: 7729 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7730 case ISD::ZEXTLOAD: 7731 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7732 case ISD::EXTLOAD: 7733 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7734 case ISD::NON_EXTLOAD: 7735 return Op; 7736 } 7737 7738 llvm_unreachable("invalid ext type"); 7739 } 7740 7741 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7742 SelectionDAG &DAG = DCI.DAG; 7743 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7744 return SDValue(); 7745 7746 // FIXME: Constant loads should all be marked invariant. 7747 unsigned AS = Ld->getAddressSpace(); 7748 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7749 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7750 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7751 return SDValue(); 7752 7753 // Don't do this early, since it may interfere with adjacent load merging for 7754 // illegal types. We can avoid losing alignment information for exotic types 7755 // pre-legalize. 7756 EVT MemVT = Ld->getMemoryVT(); 7757 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7758 MemVT.getSizeInBits() >= 32) 7759 return SDValue(); 7760 7761 SDLoc SL(Ld); 7762 7763 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7764 "unexpected vector extload"); 7765 7766 // TODO: Drop only high part of range. 7767 SDValue Ptr = Ld->getBasePtr(); 7768 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7769 MVT::i32, SL, Ld->getChain(), Ptr, 7770 Ld->getOffset(), 7771 Ld->getPointerInfo(), MVT::i32, 7772 Ld->getAlignment(), 7773 Ld->getMemOperand()->getFlags(), 7774 Ld->getAAInfo(), 7775 nullptr); // Drop ranges 7776 7777 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7778 if (MemVT.isFloatingPoint()) { 7779 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7780 "unexpected fp extload"); 7781 TruncVT = MemVT.changeTypeToInteger(); 7782 } 7783 7784 SDValue Cvt = NewLoad; 7785 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7786 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7787 DAG.getValueType(TruncVT)); 7788 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7789 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7790 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7791 } else { 7792 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7793 } 7794 7795 EVT VT = Ld->getValueType(0); 7796 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7797 7798 DCI.AddToWorklist(Cvt.getNode()); 7799 7800 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7801 // the appropriate extension from the 32-bit load. 7802 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7803 DCI.AddToWorklist(Cvt.getNode()); 7804 7805 // Handle conversion back to floating point if necessary. 7806 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7807 7808 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7809 } 7810 7811 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7812 SDLoc DL(Op); 7813 LoadSDNode *Load = cast<LoadSDNode>(Op); 7814 ISD::LoadExtType ExtType = Load->getExtensionType(); 7815 EVT MemVT = Load->getMemoryVT(); 7816 7817 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7818 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7819 return SDValue(); 7820 7821 // FIXME: Copied from PPC 7822 // First, load into 32 bits, then truncate to 1 bit. 7823 7824 SDValue Chain = Load->getChain(); 7825 SDValue BasePtr = Load->getBasePtr(); 7826 MachineMemOperand *MMO = Load->getMemOperand(); 7827 7828 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7829 7830 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7831 BasePtr, RealMemVT, MMO); 7832 7833 if (!MemVT.isVector()) { 7834 SDValue Ops[] = { 7835 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7836 NewLD.getValue(1) 7837 }; 7838 7839 return DAG.getMergeValues(Ops, DL); 7840 } 7841 7842 SmallVector<SDValue, 3> Elts; 7843 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7844 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7845 DAG.getConstant(I, DL, MVT::i32)); 7846 7847 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7848 } 7849 7850 SDValue Ops[] = { 7851 DAG.getBuildVector(MemVT, DL, Elts), 7852 NewLD.getValue(1) 7853 }; 7854 7855 return DAG.getMergeValues(Ops, DL); 7856 } 7857 7858 if (!MemVT.isVector()) 7859 return SDValue(); 7860 7861 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7862 "Custom lowering for non-i32 vectors hasn't been implemented."); 7863 7864 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7865 MemVT, *Load->getMemOperand())) { 7866 SDValue Ops[2]; 7867 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7868 return DAG.getMergeValues(Ops, DL); 7869 } 7870 7871 unsigned Alignment = Load->getAlignment(); 7872 unsigned AS = Load->getAddressSpace(); 7873 if (Subtarget->hasLDSMisalignedBug() && 7874 AS == AMDGPUAS::FLAT_ADDRESS && 7875 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7876 return SplitVectorLoad(Op, DAG); 7877 } 7878 7879 MachineFunction &MF = DAG.getMachineFunction(); 7880 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7881 // If there is a possibilty that flat instruction access scratch memory 7882 // then we need to use the same legalization rules we use for private. 7883 if (AS == AMDGPUAS::FLAT_ADDRESS && 7884 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7885 AS = MFI->hasFlatScratchInit() ? 7886 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7887 7888 unsigned NumElements = MemVT.getVectorNumElements(); 7889 7890 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7891 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7892 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7893 if (MemVT.isPow2VectorType()) 7894 return SDValue(); 7895 if (NumElements == 3) 7896 return WidenVectorLoad(Op, DAG); 7897 return SplitVectorLoad(Op, DAG); 7898 } 7899 // Non-uniform loads will be selected to MUBUF instructions, so they 7900 // have the same legalization requirements as global and private 7901 // loads. 7902 // 7903 } 7904 7905 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7906 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7907 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7908 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7909 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7910 Alignment >= 4 && NumElements < 32) { 7911 if (MemVT.isPow2VectorType()) 7912 return SDValue(); 7913 if (NumElements == 3) 7914 return WidenVectorLoad(Op, DAG); 7915 return SplitVectorLoad(Op, DAG); 7916 } 7917 // Non-uniform loads will be selected to MUBUF instructions, so they 7918 // have the same legalization requirements as global and private 7919 // loads. 7920 // 7921 } 7922 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7923 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7924 AS == AMDGPUAS::GLOBAL_ADDRESS || 7925 AS == AMDGPUAS::FLAT_ADDRESS) { 7926 if (NumElements > 4) 7927 return SplitVectorLoad(Op, DAG); 7928 // v3 loads not supported on SI. 7929 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7930 return WidenVectorLoad(Op, DAG); 7931 // v3 and v4 loads are supported for private and global memory. 7932 return SDValue(); 7933 } 7934 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7935 // Depending on the setting of the private_element_size field in the 7936 // resource descriptor, we can only make private accesses up to a certain 7937 // size. 7938 switch (Subtarget->getMaxPrivateElementSize()) { 7939 case 4: { 7940 SDValue Ops[2]; 7941 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7942 return DAG.getMergeValues(Ops, DL); 7943 } 7944 case 8: 7945 if (NumElements > 2) 7946 return SplitVectorLoad(Op, DAG); 7947 return SDValue(); 7948 case 16: 7949 // Same as global/flat 7950 if (NumElements > 4) 7951 return SplitVectorLoad(Op, DAG); 7952 // v3 loads not supported on SI. 7953 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7954 return WidenVectorLoad(Op, DAG); 7955 return SDValue(); 7956 default: 7957 llvm_unreachable("unsupported private_element_size"); 7958 } 7959 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7960 // Use ds_read_b128 if possible. 7961 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7962 MemVT.getStoreSize() == 16) 7963 return SDValue(); 7964 7965 if (NumElements > 2) 7966 return SplitVectorLoad(Op, DAG); 7967 7968 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7969 // address is negative, then the instruction is incorrectly treated as 7970 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7971 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7972 // load later in the SILoadStoreOptimizer. 7973 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7974 NumElements == 2 && MemVT.getStoreSize() == 8 && 7975 Load->getAlignment() < 8) { 7976 return SplitVectorLoad(Op, DAG); 7977 } 7978 } 7979 return SDValue(); 7980 } 7981 7982 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7983 EVT VT = Op.getValueType(); 7984 assert(VT.getSizeInBits() == 64); 7985 7986 SDLoc DL(Op); 7987 SDValue Cond = Op.getOperand(0); 7988 7989 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7990 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7991 7992 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7993 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7994 7995 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7996 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7997 7998 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7999 8000 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8001 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8002 8003 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8004 8005 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8006 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8007 } 8008 8009 // Catch division cases where we can use shortcuts with rcp and rsq 8010 // instructions. 8011 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8012 SelectionDAG &DAG) const { 8013 SDLoc SL(Op); 8014 SDValue LHS = Op.getOperand(0); 8015 SDValue RHS = Op.getOperand(1); 8016 EVT VT = Op.getValueType(); 8017 const SDNodeFlags Flags = Op->getFlags(); 8018 8019 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8020 Flags.hasApproximateFuncs(); 8021 8022 // Without !fpmath accuracy information, we can't do more because we don't 8023 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8024 if (!AllowInaccurateRcp) 8025 return SDValue(); 8026 8027 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8028 if (CLHS->isExactlyValue(1.0)) { 8029 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8030 // the CI documentation has a worst case error of 1 ulp. 8031 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8032 // use it as long as we aren't trying to use denormals. 8033 // 8034 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8035 8036 // 1.0 / sqrt(x) -> rsq(x) 8037 8038 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8039 // error seems really high at 2^29 ULP. 8040 if (RHS.getOpcode() == ISD::FSQRT) 8041 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8042 8043 // 1.0 / x -> rcp(x) 8044 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8045 } 8046 8047 // Same as for 1.0, but expand the sign out of the constant. 8048 if (CLHS->isExactlyValue(-1.0)) { 8049 // -1.0 / x -> rcp (fneg x) 8050 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8051 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8052 } 8053 } 8054 8055 // Turn into multiply by the reciprocal. 8056 // x / y -> x * (1.0 / y) 8057 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8058 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8059 } 8060 8061 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8062 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8063 SDNodeFlags Flags) { 8064 if (GlueChain->getNumValues() <= 1) { 8065 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8066 } 8067 8068 assert(GlueChain->getNumValues() == 3); 8069 8070 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8071 switch (Opcode) { 8072 default: llvm_unreachable("no chain equivalent for opcode"); 8073 case ISD::FMUL: 8074 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8075 break; 8076 } 8077 8078 return DAG.getNode(Opcode, SL, VTList, 8079 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8080 Flags); 8081 } 8082 8083 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8084 EVT VT, SDValue A, SDValue B, SDValue C, 8085 SDValue GlueChain, SDNodeFlags Flags) { 8086 if (GlueChain->getNumValues() <= 1) { 8087 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8088 } 8089 8090 assert(GlueChain->getNumValues() == 3); 8091 8092 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8093 switch (Opcode) { 8094 default: llvm_unreachable("no chain equivalent for opcode"); 8095 case ISD::FMA: 8096 Opcode = AMDGPUISD::FMA_W_CHAIN; 8097 break; 8098 } 8099 8100 return DAG.getNode(Opcode, SL, VTList, 8101 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8102 Flags); 8103 } 8104 8105 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8106 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8107 return FastLowered; 8108 8109 SDLoc SL(Op); 8110 SDValue Src0 = Op.getOperand(0); 8111 SDValue Src1 = Op.getOperand(1); 8112 8113 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8114 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8115 8116 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8117 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8118 8119 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8120 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8121 8122 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8123 } 8124 8125 // Faster 2.5 ULP division that does not support denormals. 8126 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8127 SDLoc SL(Op); 8128 SDValue LHS = Op.getOperand(1); 8129 SDValue RHS = Op.getOperand(2); 8130 8131 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8132 8133 const APFloat K0Val(BitsToFloat(0x6f800000)); 8134 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8135 8136 const APFloat K1Val(BitsToFloat(0x2f800000)); 8137 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8138 8139 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8140 8141 EVT SetCCVT = 8142 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8143 8144 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8145 8146 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8147 8148 // TODO: Should this propagate fast-math-flags? 8149 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8150 8151 // rcp does not support denormals. 8152 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8153 8154 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8155 8156 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8157 } 8158 8159 // Returns immediate value for setting the F32 denorm mode when using the 8160 // S_DENORM_MODE instruction. 8161 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8162 const SDLoc &SL, const GCNSubtarget *ST) { 8163 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8164 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8165 ? FP_DENORM_FLUSH_NONE 8166 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8167 8168 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8169 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8170 } 8171 8172 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8173 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8174 return FastLowered; 8175 8176 // The selection matcher assumes anything with a chain selecting to a 8177 // mayRaiseFPException machine instruction. Since we're introducing a chain 8178 // here, we need to explicitly report nofpexcept for the regular fdiv 8179 // lowering. 8180 SDNodeFlags Flags = Op->getFlags(); 8181 Flags.setNoFPExcept(true); 8182 8183 SDLoc SL(Op); 8184 SDValue LHS = Op.getOperand(0); 8185 SDValue RHS = Op.getOperand(1); 8186 8187 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8188 8189 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8190 8191 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8192 {RHS, RHS, LHS}, Flags); 8193 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8194 {LHS, RHS, LHS}, Flags); 8195 8196 // Denominator is scaled to not be denormal, so using rcp is ok. 8197 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8198 DenominatorScaled, Flags); 8199 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8200 DenominatorScaled, Flags); 8201 8202 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8203 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8204 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8205 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8206 8207 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8208 8209 if (!HasFP32Denormals) { 8210 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8211 // lowering. The chain dependence is insufficient, and we need glue. We do 8212 // not need the glue variants in a strictfp function. 8213 8214 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8215 8216 SDNode *EnableDenorm; 8217 if (Subtarget->hasDenormModeInst()) { 8218 const SDValue EnableDenormValue = 8219 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8220 8221 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8222 DAG.getEntryNode(), EnableDenormValue).getNode(); 8223 } else { 8224 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8225 SL, MVT::i32); 8226 EnableDenorm = 8227 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8228 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8229 } 8230 8231 SDValue Ops[3] = { 8232 NegDivScale0, 8233 SDValue(EnableDenorm, 0), 8234 SDValue(EnableDenorm, 1) 8235 }; 8236 8237 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8238 } 8239 8240 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8241 ApproxRcp, One, NegDivScale0, Flags); 8242 8243 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8244 ApproxRcp, Fma0, Flags); 8245 8246 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8247 Fma1, Fma1, Flags); 8248 8249 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8250 NumeratorScaled, Mul, Flags); 8251 8252 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8253 Fma2, Fma1, Mul, Fma2, Flags); 8254 8255 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8256 NumeratorScaled, Fma3, Flags); 8257 8258 if (!HasFP32Denormals) { 8259 SDNode *DisableDenorm; 8260 if (Subtarget->hasDenormModeInst()) { 8261 const SDValue DisableDenormValue = 8262 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8263 8264 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8265 Fma4.getValue(1), DisableDenormValue, 8266 Fma4.getValue(2)).getNode(); 8267 } else { 8268 const SDValue DisableDenormValue = 8269 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8270 8271 DisableDenorm = DAG.getMachineNode( 8272 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8273 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8274 } 8275 8276 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8277 SDValue(DisableDenorm, 0), DAG.getRoot()); 8278 DAG.setRoot(OutputChain); 8279 } 8280 8281 SDValue Scale = NumeratorScaled.getValue(1); 8282 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8283 {Fma4, Fma1, Fma3, Scale}, Flags); 8284 8285 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8286 } 8287 8288 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8289 if (DAG.getTarget().Options.UnsafeFPMath) 8290 return lowerFastUnsafeFDIV(Op, DAG); 8291 8292 SDLoc SL(Op); 8293 SDValue X = Op.getOperand(0); 8294 SDValue Y = Op.getOperand(1); 8295 8296 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8297 8298 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8299 8300 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8301 8302 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8303 8304 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8305 8306 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8307 8308 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8309 8310 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8311 8312 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8313 8314 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8315 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8316 8317 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8318 NegDivScale0, Mul, DivScale1); 8319 8320 SDValue Scale; 8321 8322 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8323 // Workaround a hardware bug on SI where the condition output from div_scale 8324 // is not usable. 8325 8326 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8327 8328 // Figure out if the scale to use for div_fmas. 8329 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8330 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8331 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8332 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8333 8334 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8335 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8336 8337 SDValue Scale0Hi 8338 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8339 SDValue Scale1Hi 8340 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8341 8342 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8343 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8344 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8345 } else { 8346 Scale = DivScale1.getValue(1); 8347 } 8348 8349 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8350 Fma4, Fma3, Mul, Scale); 8351 8352 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8353 } 8354 8355 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8356 EVT VT = Op.getValueType(); 8357 8358 if (VT == MVT::f32) 8359 return LowerFDIV32(Op, DAG); 8360 8361 if (VT == MVT::f64) 8362 return LowerFDIV64(Op, DAG); 8363 8364 if (VT == MVT::f16) 8365 return LowerFDIV16(Op, DAG); 8366 8367 llvm_unreachable("Unexpected type for fdiv"); 8368 } 8369 8370 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8371 SDLoc DL(Op); 8372 StoreSDNode *Store = cast<StoreSDNode>(Op); 8373 EVT VT = Store->getMemoryVT(); 8374 8375 if (VT == MVT::i1) { 8376 return DAG.getTruncStore(Store->getChain(), DL, 8377 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8378 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8379 } 8380 8381 assert(VT.isVector() && 8382 Store->getValue().getValueType().getScalarType() == MVT::i32); 8383 8384 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8385 VT, *Store->getMemOperand())) { 8386 return expandUnalignedStore(Store, DAG); 8387 } 8388 8389 unsigned AS = Store->getAddressSpace(); 8390 if (Subtarget->hasLDSMisalignedBug() && 8391 AS == AMDGPUAS::FLAT_ADDRESS && 8392 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8393 return SplitVectorStore(Op, DAG); 8394 } 8395 8396 MachineFunction &MF = DAG.getMachineFunction(); 8397 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8398 // If there is a possibilty that flat instruction access scratch memory 8399 // then we need to use the same legalization rules we use for private. 8400 if (AS == AMDGPUAS::FLAT_ADDRESS && 8401 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8402 AS = MFI->hasFlatScratchInit() ? 8403 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8404 8405 unsigned NumElements = VT.getVectorNumElements(); 8406 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8407 AS == AMDGPUAS::FLAT_ADDRESS) { 8408 if (NumElements > 4) 8409 return SplitVectorStore(Op, DAG); 8410 // v3 stores not supported on SI. 8411 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8412 return SplitVectorStore(Op, DAG); 8413 return SDValue(); 8414 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8415 switch (Subtarget->getMaxPrivateElementSize()) { 8416 case 4: 8417 return scalarizeVectorStore(Store, DAG); 8418 case 8: 8419 if (NumElements > 2) 8420 return SplitVectorStore(Op, DAG); 8421 return SDValue(); 8422 case 16: 8423 if (NumElements > 4 || NumElements == 3) 8424 return SplitVectorStore(Op, DAG); 8425 return SDValue(); 8426 default: 8427 llvm_unreachable("unsupported private_element_size"); 8428 } 8429 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8430 // Use ds_write_b128 if possible. 8431 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8432 VT.getStoreSize() == 16 && NumElements != 3) 8433 return SDValue(); 8434 8435 if (NumElements > 2) 8436 return SplitVectorStore(Op, DAG); 8437 8438 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8439 // address is negative, then the instruction is incorrectly treated as 8440 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8441 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8442 // store later in the SILoadStoreOptimizer. 8443 if (!Subtarget->hasUsableDSOffset() && 8444 NumElements == 2 && VT.getStoreSize() == 8 && 8445 Store->getAlignment() < 8) { 8446 return SplitVectorStore(Op, DAG); 8447 } 8448 8449 return SDValue(); 8450 } else { 8451 llvm_unreachable("unhandled address space"); 8452 } 8453 } 8454 8455 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8456 SDLoc DL(Op); 8457 EVT VT = Op.getValueType(); 8458 SDValue Arg = Op.getOperand(0); 8459 SDValue TrigVal; 8460 8461 // Propagate fast-math flags so that the multiply we introduce can be folded 8462 // if Arg is already the result of a multiply by constant. 8463 auto Flags = Op->getFlags(); 8464 8465 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8466 8467 if (Subtarget->hasTrigReducedRange()) { 8468 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8469 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8470 } else { 8471 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8472 } 8473 8474 switch (Op.getOpcode()) { 8475 case ISD::FCOS: 8476 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8477 case ISD::FSIN: 8478 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8479 default: 8480 llvm_unreachable("Wrong trig opcode"); 8481 } 8482 } 8483 8484 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8485 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8486 assert(AtomicNode->isCompareAndSwap()); 8487 unsigned AS = AtomicNode->getAddressSpace(); 8488 8489 // No custom lowering required for local address space 8490 if (!isFlatGlobalAddrSpace(AS)) 8491 return Op; 8492 8493 // Non-local address space requires custom lowering for atomic compare 8494 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8495 SDLoc DL(Op); 8496 SDValue ChainIn = Op.getOperand(0); 8497 SDValue Addr = Op.getOperand(1); 8498 SDValue Old = Op.getOperand(2); 8499 SDValue New = Op.getOperand(3); 8500 EVT VT = Op.getValueType(); 8501 MVT SimpleVT = VT.getSimpleVT(); 8502 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8503 8504 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8505 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8506 8507 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8508 Ops, VT, AtomicNode->getMemOperand()); 8509 } 8510 8511 //===----------------------------------------------------------------------===// 8512 // Custom DAG optimizations 8513 //===----------------------------------------------------------------------===// 8514 8515 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8516 DAGCombinerInfo &DCI) const { 8517 EVT VT = N->getValueType(0); 8518 EVT ScalarVT = VT.getScalarType(); 8519 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8520 return SDValue(); 8521 8522 SelectionDAG &DAG = DCI.DAG; 8523 SDLoc DL(N); 8524 8525 SDValue Src = N->getOperand(0); 8526 EVT SrcVT = Src.getValueType(); 8527 8528 // TODO: We could try to match extracting the higher bytes, which would be 8529 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8530 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8531 // about in practice. 8532 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8533 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8534 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8535 DCI.AddToWorklist(Cvt.getNode()); 8536 8537 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8538 if (ScalarVT != MVT::f32) { 8539 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8540 DAG.getTargetConstant(0, DL, MVT::i32)); 8541 } 8542 return Cvt; 8543 } 8544 } 8545 8546 return SDValue(); 8547 } 8548 8549 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8550 8551 // This is a variant of 8552 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8553 // 8554 // The normal DAG combiner will do this, but only if the add has one use since 8555 // that would increase the number of instructions. 8556 // 8557 // This prevents us from seeing a constant offset that can be folded into a 8558 // memory instruction's addressing mode. If we know the resulting add offset of 8559 // a pointer can be folded into an addressing offset, we can replace the pointer 8560 // operand with the add of new constant offset. This eliminates one of the uses, 8561 // and may allow the remaining use to also be simplified. 8562 // 8563 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8564 unsigned AddrSpace, 8565 EVT MemVT, 8566 DAGCombinerInfo &DCI) const { 8567 SDValue N0 = N->getOperand(0); 8568 SDValue N1 = N->getOperand(1); 8569 8570 // We only do this to handle cases where it's profitable when there are 8571 // multiple uses of the add, so defer to the standard combine. 8572 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8573 N0->hasOneUse()) 8574 return SDValue(); 8575 8576 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8577 if (!CN1) 8578 return SDValue(); 8579 8580 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8581 if (!CAdd) 8582 return SDValue(); 8583 8584 // If the resulting offset is too large, we can't fold it into the addressing 8585 // mode offset. 8586 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8587 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8588 8589 AddrMode AM; 8590 AM.HasBaseReg = true; 8591 AM.BaseOffs = Offset.getSExtValue(); 8592 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8593 return SDValue(); 8594 8595 SelectionDAG &DAG = DCI.DAG; 8596 SDLoc SL(N); 8597 EVT VT = N->getValueType(0); 8598 8599 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8600 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8601 8602 SDNodeFlags Flags; 8603 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8604 (N0.getOpcode() == ISD::OR || 8605 N0->getFlags().hasNoUnsignedWrap())); 8606 8607 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8608 } 8609 8610 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8611 DAGCombinerInfo &DCI) const { 8612 SDValue Ptr = N->getBasePtr(); 8613 SelectionDAG &DAG = DCI.DAG; 8614 SDLoc SL(N); 8615 8616 // TODO: We could also do this for multiplies. 8617 if (Ptr.getOpcode() == ISD::SHL) { 8618 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8619 N->getMemoryVT(), DCI); 8620 if (NewPtr) { 8621 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8622 8623 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8624 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8625 } 8626 } 8627 8628 return SDValue(); 8629 } 8630 8631 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8632 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8633 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8634 (Opc == ISD::XOR && Val == 0); 8635 } 8636 8637 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8638 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8639 // integer combine opportunities since most 64-bit operations are decomposed 8640 // this way. TODO: We won't want this for SALU especially if it is an inline 8641 // immediate. 8642 SDValue SITargetLowering::splitBinaryBitConstantOp( 8643 DAGCombinerInfo &DCI, 8644 const SDLoc &SL, 8645 unsigned Opc, SDValue LHS, 8646 const ConstantSDNode *CRHS) const { 8647 uint64_t Val = CRHS->getZExtValue(); 8648 uint32_t ValLo = Lo_32(Val); 8649 uint32_t ValHi = Hi_32(Val); 8650 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8651 8652 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8653 bitOpWithConstantIsReducible(Opc, ValHi)) || 8654 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8655 // If we need to materialize a 64-bit immediate, it will be split up later 8656 // anyway. Avoid creating the harder to understand 64-bit immediate 8657 // materialization. 8658 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8659 } 8660 8661 return SDValue(); 8662 } 8663 8664 // Returns true if argument is a boolean value which is not serialized into 8665 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8666 static bool isBoolSGPR(SDValue V) { 8667 if (V.getValueType() != MVT::i1) 8668 return false; 8669 switch (V.getOpcode()) { 8670 default: break; 8671 case ISD::SETCC: 8672 case ISD::AND: 8673 case ISD::OR: 8674 case ISD::XOR: 8675 case AMDGPUISD::FP_CLASS: 8676 return true; 8677 } 8678 return false; 8679 } 8680 8681 // If a constant has all zeroes or all ones within each byte return it. 8682 // Otherwise return 0. 8683 static uint32_t getConstantPermuteMask(uint32_t C) { 8684 // 0xff for any zero byte in the mask 8685 uint32_t ZeroByteMask = 0; 8686 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8687 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8688 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8689 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8690 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8691 if ((NonZeroByteMask & C) != NonZeroByteMask) 8692 return 0; // Partial bytes selected. 8693 return C; 8694 } 8695 8696 // Check if a node selects whole bytes from its operand 0 starting at a byte 8697 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8698 // or -1 if not succeeded. 8699 // Note byte select encoding: 8700 // value 0-3 selects corresponding source byte; 8701 // value 0xc selects zero; 8702 // value 0xff selects 0xff. 8703 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8704 assert(V.getValueSizeInBits() == 32); 8705 8706 if (V.getNumOperands() != 2) 8707 return ~0; 8708 8709 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8710 if (!N1) 8711 return ~0; 8712 8713 uint32_t C = N1->getZExtValue(); 8714 8715 switch (V.getOpcode()) { 8716 default: 8717 break; 8718 case ISD::AND: 8719 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8720 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8721 } 8722 break; 8723 8724 case ISD::OR: 8725 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8726 return (0x03020100 & ~ConstMask) | ConstMask; 8727 } 8728 break; 8729 8730 case ISD::SHL: 8731 if (C % 8) 8732 return ~0; 8733 8734 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8735 8736 case ISD::SRL: 8737 if (C % 8) 8738 return ~0; 8739 8740 return uint32_t(0x0c0c0c0c03020100ull >> C); 8741 } 8742 8743 return ~0; 8744 } 8745 8746 SDValue SITargetLowering::performAndCombine(SDNode *N, 8747 DAGCombinerInfo &DCI) const { 8748 if (DCI.isBeforeLegalize()) 8749 return SDValue(); 8750 8751 SelectionDAG &DAG = DCI.DAG; 8752 EVT VT = N->getValueType(0); 8753 SDValue LHS = N->getOperand(0); 8754 SDValue RHS = N->getOperand(1); 8755 8756 8757 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8758 if (VT == MVT::i64 && CRHS) { 8759 if (SDValue Split 8760 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8761 return Split; 8762 } 8763 8764 if (CRHS && VT == MVT::i32) { 8765 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8766 // nb = number of trailing zeroes in mask 8767 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8768 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8769 uint64_t Mask = CRHS->getZExtValue(); 8770 unsigned Bits = countPopulation(Mask); 8771 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8772 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8773 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8774 unsigned Shift = CShift->getZExtValue(); 8775 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8776 unsigned Offset = NB + Shift; 8777 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8778 SDLoc SL(N); 8779 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8780 LHS->getOperand(0), 8781 DAG.getConstant(Offset, SL, MVT::i32), 8782 DAG.getConstant(Bits, SL, MVT::i32)); 8783 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8784 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8785 DAG.getValueType(NarrowVT)); 8786 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8787 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8788 return Shl; 8789 } 8790 } 8791 } 8792 8793 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8794 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8795 isa<ConstantSDNode>(LHS.getOperand(2))) { 8796 uint32_t Sel = getConstantPermuteMask(Mask); 8797 if (!Sel) 8798 return SDValue(); 8799 8800 // Select 0xc for all zero bytes 8801 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8802 SDLoc DL(N); 8803 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8804 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8805 } 8806 } 8807 8808 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8809 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8810 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8811 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8812 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8813 8814 SDValue X = LHS.getOperand(0); 8815 SDValue Y = RHS.getOperand(0); 8816 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8817 return SDValue(); 8818 8819 if (LCC == ISD::SETO) { 8820 if (X != LHS.getOperand(1)) 8821 return SDValue(); 8822 8823 if (RCC == ISD::SETUNE) { 8824 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8825 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8826 return SDValue(); 8827 8828 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8829 SIInstrFlags::N_SUBNORMAL | 8830 SIInstrFlags::N_ZERO | 8831 SIInstrFlags::P_ZERO | 8832 SIInstrFlags::P_SUBNORMAL | 8833 SIInstrFlags::P_NORMAL; 8834 8835 static_assert(((~(SIInstrFlags::S_NAN | 8836 SIInstrFlags::Q_NAN | 8837 SIInstrFlags::N_INFINITY | 8838 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8839 "mask not equal"); 8840 8841 SDLoc DL(N); 8842 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8843 X, DAG.getConstant(Mask, DL, MVT::i32)); 8844 } 8845 } 8846 } 8847 8848 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8849 std::swap(LHS, RHS); 8850 8851 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8852 RHS.hasOneUse()) { 8853 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8854 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8855 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8856 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8857 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8858 (RHS.getOperand(0) == LHS.getOperand(0) && 8859 LHS.getOperand(0) == LHS.getOperand(1))) { 8860 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8861 unsigned NewMask = LCC == ISD::SETO ? 8862 Mask->getZExtValue() & ~OrdMask : 8863 Mask->getZExtValue() & OrdMask; 8864 8865 SDLoc DL(N); 8866 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8867 DAG.getConstant(NewMask, DL, MVT::i32)); 8868 } 8869 } 8870 8871 if (VT == MVT::i32 && 8872 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8873 // and x, (sext cc from i1) => select cc, x, 0 8874 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8875 std::swap(LHS, RHS); 8876 if (isBoolSGPR(RHS.getOperand(0))) 8877 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8878 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8879 } 8880 8881 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8882 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8883 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8884 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8885 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8886 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8887 if (LHSMask != ~0u && RHSMask != ~0u) { 8888 // Canonicalize the expression in an attempt to have fewer unique masks 8889 // and therefore fewer registers used to hold the masks. 8890 if (LHSMask > RHSMask) { 8891 std::swap(LHSMask, RHSMask); 8892 std::swap(LHS, RHS); 8893 } 8894 8895 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8896 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8897 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8898 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8899 8900 // Check of we need to combine values from two sources within a byte. 8901 if (!(LHSUsedLanes & RHSUsedLanes) && 8902 // If we select high and lower word keep it for SDWA. 8903 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8904 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8905 // Each byte in each mask is either selector mask 0-3, or has higher 8906 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8907 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8908 // mask which is not 0xff wins. By anding both masks we have a correct 8909 // result except that 0x0c shall be corrected to give 0x0c only. 8910 uint32_t Mask = LHSMask & RHSMask; 8911 for (unsigned I = 0; I < 32; I += 8) { 8912 uint32_t ByteSel = 0xff << I; 8913 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8914 Mask &= (0x0c << I) & 0xffffffff; 8915 } 8916 8917 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8918 // or 0x0c. 8919 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8920 SDLoc DL(N); 8921 8922 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8923 LHS.getOperand(0), RHS.getOperand(0), 8924 DAG.getConstant(Sel, DL, MVT::i32)); 8925 } 8926 } 8927 } 8928 8929 return SDValue(); 8930 } 8931 8932 SDValue SITargetLowering::performOrCombine(SDNode *N, 8933 DAGCombinerInfo &DCI) const { 8934 SelectionDAG &DAG = DCI.DAG; 8935 SDValue LHS = N->getOperand(0); 8936 SDValue RHS = N->getOperand(1); 8937 8938 EVT VT = N->getValueType(0); 8939 if (VT == MVT::i1) { 8940 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8941 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8942 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8943 SDValue Src = LHS.getOperand(0); 8944 if (Src != RHS.getOperand(0)) 8945 return SDValue(); 8946 8947 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8948 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8949 if (!CLHS || !CRHS) 8950 return SDValue(); 8951 8952 // Only 10 bits are used. 8953 static const uint32_t MaxMask = 0x3ff; 8954 8955 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8956 SDLoc DL(N); 8957 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8958 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8959 } 8960 8961 return SDValue(); 8962 } 8963 8964 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8965 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8966 LHS.getOpcode() == AMDGPUISD::PERM && 8967 isa<ConstantSDNode>(LHS.getOperand(2))) { 8968 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8969 if (!Sel) 8970 return SDValue(); 8971 8972 Sel |= LHS.getConstantOperandVal(2); 8973 SDLoc DL(N); 8974 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8975 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8976 } 8977 8978 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8979 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8980 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8981 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8982 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8983 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8984 if (LHSMask != ~0u && RHSMask != ~0u) { 8985 // Canonicalize the expression in an attempt to have fewer unique masks 8986 // and therefore fewer registers used to hold the masks. 8987 if (LHSMask > RHSMask) { 8988 std::swap(LHSMask, RHSMask); 8989 std::swap(LHS, RHS); 8990 } 8991 8992 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8993 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8994 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8995 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8996 8997 // Check of we need to combine values from two sources within a byte. 8998 if (!(LHSUsedLanes & RHSUsedLanes) && 8999 // If we select high and lower word keep it for SDWA. 9000 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9001 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9002 // Kill zero bytes selected by other mask. Zero value is 0xc. 9003 LHSMask &= ~RHSUsedLanes; 9004 RHSMask &= ~LHSUsedLanes; 9005 // Add 4 to each active LHS lane 9006 LHSMask |= LHSUsedLanes & 0x04040404; 9007 // Combine masks 9008 uint32_t Sel = LHSMask | RHSMask; 9009 SDLoc DL(N); 9010 9011 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9012 LHS.getOperand(0), RHS.getOperand(0), 9013 DAG.getConstant(Sel, DL, MVT::i32)); 9014 } 9015 } 9016 } 9017 9018 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9019 return SDValue(); 9020 9021 // TODO: This could be a generic combine with a predicate for extracting the 9022 // high half of an integer being free. 9023 9024 // (or i64:x, (zero_extend i32:y)) -> 9025 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9026 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9027 RHS.getOpcode() != ISD::ZERO_EXTEND) 9028 std::swap(LHS, RHS); 9029 9030 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9031 SDValue ExtSrc = RHS.getOperand(0); 9032 EVT SrcVT = ExtSrc.getValueType(); 9033 if (SrcVT == MVT::i32) { 9034 SDLoc SL(N); 9035 SDValue LowLHS, HiBits; 9036 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9037 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9038 9039 DCI.AddToWorklist(LowOr.getNode()); 9040 DCI.AddToWorklist(HiBits.getNode()); 9041 9042 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9043 LowOr, HiBits); 9044 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9045 } 9046 } 9047 9048 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9049 if (CRHS) { 9050 if (SDValue Split 9051 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9052 return Split; 9053 } 9054 9055 return SDValue(); 9056 } 9057 9058 SDValue SITargetLowering::performXorCombine(SDNode *N, 9059 DAGCombinerInfo &DCI) const { 9060 EVT VT = N->getValueType(0); 9061 if (VT != MVT::i64) 9062 return SDValue(); 9063 9064 SDValue LHS = N->getOperand(0); 9065 SDValue RHS = N->getOperand(1); 9066 9067 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9068 if (CRHS) { 9069 if (SDValue Split 9070 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9071 return Split; 9072 } 9073 9074 return SDValue(); 9075 } 9076 9077 // Instructions that will be lowered with a final instruction that zeros the 9078 // high result bits. 9079 // XXX - probably only need to list legal operations. 9080 static bool fp16SrcZerosHighBits(unsigned Opc) { 9081 switch (Opc) { 9082 case ISD::FADD: 9083 case ISD::FSUB: 9084 case ISD::FMUL: 9085 case ISD::FDIV: 9086 case ISD::FREM: 9087 case ISD::FMA: 9088 case ISD::FMAD: 9089 case ISD::FCANONICALIZE: 9090 case ISD::FP_ROUND: 9091 case ISD::UINT_TO_FP: 9092 case ISD::SINT_TO_FP: 9093 case ISD::FABS: 9094 // Fabs is lowered to a bit operation, but it's an and which will clear the 9095 // high bits anyway. 9096 case ISD::FSQRT: 9097 case ISD::FSIN: 9098 case ISD::FCOS: 9099 case ISD::FPOWI: 9100 case ISD::FPOW: 9101 case ISD::FLOG: 9102 case ISD::FLOG2: 9103 case ISD::FLOG10: 9104 case ISD::FEXP: 9105 case ISD::FEXP2: 9106 case ISD::FCEIL: 9107 case ISD::FTRUNC: 9108 case ISD::FRINT: 9109 case ISD::FNEARBYINT: 9110 case ISD::FROUND: 9111 case ISD::FFLOOR: 9112 case ISD::FMINNUM: 9113 case ISD::FMAXNUM: 9114 case AMDGPUISD::FRACT: 9115 case AMDGPUISD::CLAMP: 9116 case AMDGPUISD::COS_HW: 9117 case AMDGPUISD::SIN_HW: 9118 case AMDGPUISD::FMIN3: 9119 case AMDGPUISD::FMAX3: 9120 case AMDGPUISD::FMED3: 9121 case AMDGPUISD::FMAD_FTZ: 9122 case AMDGPUISD::RCP: 9123 case AMDGPUISD::RSQ: 9124 case AMDGPUISD::RCP_IFLAG: 9125 case AMDGPUISD::LDEXP: 9126 return true; 9127 default: 9128 // fcopysign, select and others may be lowered to 32-bit bit operations 9129 // which don't zero the high bits. 9130 return false; 9131 } 9132 } 9133 9134 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9135 DAGCombinerInfo &DCI) const { 9136 if (!Subtarget->has16BitInsts() || 9137 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9138 return SDValue(); 9139 9140 EVT VT = N->getValueType(0); 9141 if (VT != MVT::i32) 9142 return SDValue(); 9143 9144 SDValue Src = N->getOperand(0); 9145 if (Src.getValueType() != MVT::i16) 9146 return SDValue(); 9147 9148 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9149 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9150 if (Src.getOpcode() == ISD::BITCAST) { 9151 SDValue BCSrc = Src.getOperand(0); 9152 if (BCSrc.getValueType() == MVT::f16 && 9153 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9154 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9155 } 9156 9157 return SDValue(); 9158 } 9159 9160 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9161 DAGCombinerInfo &DCI) 9162 const { 9163 SDValue Src = N->getOperand(0); 9164 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9165 9166 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9167 VTSign->getVT() == MVT::i8) || 9168 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9169 VTSign->getVT() == MVT::i16)) && 9170 Src.hasOneUse()) { 9171 auto *M = cast<MemSDNode>(Src); 9172 SDValue Ops[] = { 9173 Src.getOperand(0), // Chain 9174 Src.getOperand(1), // rsrc 9175 Src.getOperand(2), // vindex 9176 Src.getOperand(3), // voffset 9177 Src.getOperand(4), // soffset 9178 Src.getOperand(5), // offset 9179 Src.getOperand(6), 9180 Src.getOperand(7) 9181 }; 9182 // replace with BUFFER_LOAD_BYTE/SHORT 9183 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9184 Src.getOperand(0).getValueType()); 9185 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9186 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9187 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9188 ResList, 9189 Ops, M->getMemoryVT(), 9190 M->getMemOperand()); 9191 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9192 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9193 } 9194 return SDValue(); 9195 } 9196 9197 SDValue SITargetLowering::performClassCombine(SDNode *N, 9198 DAGCombinerInfo &DCI) const { 9199 SelectionDAG &DAG = DCI.DAG; 9200 SDValue Mask = N->getOperand(1); 9201 9202 // fp_class x, 0 -> false 9203 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9204 if (CMask->isNullValue()) 9205 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9206 } 9207 9208 if (N->getOperand(0).isUndef()) 9209 return DAG.getUNDEF(MVT::i1); 9210 9211 return SDValue(); 9212 } 9213 9214 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9215 DAGCombinerInfo &DCI) const { 9216 EVT VT = N->getValueType(0); 9217 SDValue N0 = N->getOperand(0); 9218 9219 if (N0.isUndef()) 9220 return N0; 9221 9222 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9223 N0.getOpcode() == ISD::SINT_TO_FP)) { 9224 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9225 N->getFlags()); 9226 } 9227 9228 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9229 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9230 N0.getOperand(0), N->getFlags()); 9231 } 9232 9233 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9234 } 9235 9236 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9237 unsigned MaxDepth) const { 9238 unsigned Opcode = Op.getOpcode(); 9239 if (Opcode == ISD::FCANONICALIZE) 9240 return true; 9241 9242 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9243 auto F = CFP->getValueAPF(); 9244 if (F.isNaN() && F.isSignaling()) 9245 return false; 9246 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9247 } 9248 9249 // If source is a result of another standard FP operation it is already in 9250 // canonical form. 9251 if (MaxDepth == 0) 9252 return false; 9253 9254 switch (Opcode) { 9255 // These will flush denorms if required. 9256 case ISD::FADD: 9257 case ISD::FSUB: 9258 case ISD::FMUL: 9259 case ISD::FCEIL: 9260 case ISD::FFLOOR: 9261 case ISD::FMA: 9262 case ISD::FMAD: 9263 case ISD::FSQRT: 9264 case ISD::FDIV: 9265 case ISD::FREM: 9266 case ISD::FP_ROUND: 9267 case ISD::FP_EXTEND: 9268 case AMDGPUISD::FMUL_LEGACY: 9269 case AMDGPUISD::FMAD_FTZ: 9270 case AMDGPUISD::RCP: 9271 case AMDGPUISD::RSQ: 9272 case AMDGPUISD::RSQ_CLAMP: 9273 case AMDGPUISD::RCP_LEGACY: 9274 case AMDGPUISD::RCP_IFLAG: 9275 case AMDGPUISD::DIV_SCALE: 9276 case AMDGPUISD::DIV_FMAS: 9277 case AMDGPUISD::DIV_FIXUP: 9278 case AMDGPUISD::FRACT: 9279 case AMDGPUISD::LDEXP: 9280 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9281 case AMDGPUISD::CVT_F32_UBYTE0: 9282 case AMDGPUISD::CVT_F32_UBYTE1: 9283 case AMDGPUISD::CVT_F32_UBYTE2: 9284 case AMDGPUISD::CVT_F32_UBYTE3: 9285 return true; 9286 9287 // It can/will be lowered or combined as a bit operation. 9288 // Need to check their input recursively to handle. 9289 case ISD::FNEG: 9290 case ISD::FABS: 9291 case ISD::FCOPYSIGN: 9292 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9293 9294 case ISD::FSIN: 9295 case ISD::FCOS: 9296 case ISD::FSINCOS: 9297 return Op.getValueType().getScalarType() != MVT::f16; 9298 9299 case ISD::FMINNUM: 9300 case ISD::FMAXNUM: 9301 case ISD::FMINNUM_IEEE: 9302 case ISD::FMAXNUM_IEEE: 9303 case AMDGPUISD::CLAMP: 9304 case AMDGPUISD::FMED3: 9305 case AMDGPUISD::FMAX3: 9306 case AMDGPUISD::FMIN3: { 9307 // FIXME: Shouldn't treat the generic operations different based these. 9308 // However, we aren't really required to flush the result from 9309 // minnum/maxnum.. 9310 9311 // snans will be quieted, so we only need to worry about denormals. 9312 if (Subtarget->supportsMinMaxDenormModes() || 9313 denormalsEnabledForType(DAG, Op.getValueType())) 9314 return true; 9315 9316 // Flushing may be required. 9317 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9318 // targets need to check their input recursively. 9319 9320 // FIXME: Does this apply with clamp? It's implemented with max. 9321 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9322 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9323 return false; 9324 } 9325 9326 return true; 9327 } 9328 case ISD::SELECT: { 9329 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9330 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9331 } 9332 case ISD::BUILD_VECTOR: { 9333 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9334 SDValue SrcOp = Op.getOperand(i); 9335 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9336 return false; 9337 } 9338 9339 return true; 9340 } 9341 case ISD::EXTRACT_VECTOR_ELT: 9342 case ISD::EXTRACT_SUBVECTOR: { 9343 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9344 } 9345 case ISD::INSERT_VECTOR_ELT: { 9346 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9347 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9348 } 9349 case ISD::UNDEF: 9350 // Could be anything. 9351 return false; 9352 9353 case ISD::BITCAST: { 9354 // Hack round the mess we make when legalizing extract_vector_elt 9355 SDValue Src = Op.getOperand(0); 9356 if (Src.getValueType() == MVT::i16 && 9357 Src.getOpcode() == ISD::TRUNCATE) { 9358 SDValue TruncSrc = Src.getOperand(0); 9359 if (TruncSrc.getValueType() == MVT::i32 && 9360 TruncSrc.getOpcode() == ISD::BITCAST && 9361 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9362 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9363 } 9364 } 9365 9366 return false; 9367 } 9368 case ISD::INTRINSIC_WO_CHAIN: { 9369 unsigned IntrinsicID 9370 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9371 // TODO: Handle more intrinsics 9372 switch (IntrinsicID) { 9373 case Intrinsic::amdgcn_cvt_pkrtz: 9374 case Intrinsic::amdgcn_cubeid: 9375 case Intrinsic::amdgcn_frexp_mant: 9376 case Intrinsic::amdgcn_fdot2: 9377 case Intrinsic::amdgcn_rcp: 9378 case Intrinsic::amdgcn_rsq: 9379 case Intrinsic::amdgcn_rsq_clamp: 9380 case Intrinsic::amdgcn_rcp_legacy: 9381 case Intrinsic::amdgcn_rsq_legacy: 9382 case Intrinsic::amdgcn_trig_preop: 9383 return true; 9384 default: 9385 break; 9386 } 9387 9388 LLVM_FALLTHROUGH; 9389 } 9390 default: 9391 return denormalsEnabledForType(DAG, Op.getValueType()) && 9392 DAG.isKnownNeverSNaN(Op); 9393 } 9394 9395 llvm_unreachable("invalid operation"); 9396 } 9397 9398 // Constant fold canonicalize. 9399 SDValue SITargetLowering::getCanonicalConstantFP( 9400 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9401 // Flush denormals to 0 if not enabled. 9402 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9403 return DAG.getConstantFP(0.0, SL, VT); 9404 9405 if (C.isNaN()) { 9406 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9407 if (C.isSignaling()) { 9408 // Quiet a signaling NaN. 9409 // FIXME: Is this supposed to preserve payload bits? 9410 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9411 } 9412 9413 // Make sure it is the canonical NaN bitpattern. 9414 // 9415 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9416 // immediate? 9417 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9418 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9419 } 9420 9421 // Already canonical. 9422 return DAG.getConstantFP(C, SL, VT); 9423 } 9424 9425 static bool vectorEltWillFoldAway(SDValue Op) { 9426 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9427 } 9428 9429 SDValue SITargetLowering::performFCanonicalizeCombine( 9430 SDNode *N, 9431 DAGCombinerInfo &DCI) const { 9432 SelectionDAG &DAG = DCI.DAG; 9433 SDValue N0 = N->getOperand(0); 9434 EVT VT = N->getValueType(0); 9435 9436 // fcanonicalize undef -> qnan 9437 if (N0.isUndef()) { 9438 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9439 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9440 } 9441 9442 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9443 EVT VT = N->getValueType(0); 9444 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9445 } 9446 9447 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9448 // (fcanonicalize k) 9449 // 9450 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9451 9452 // TODO: This could be better with wider vectors that will be split to v2f16, 9453 // and to consider uses since there aren't that many packed operations. 9454 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9455 isTypeLegal(MVT::v2f16)) { 9456 SDLoc SL(N); 9457 SDValue NewElts[2]; 9458 SDValue Lo = N0.getOperand(0); 9459 SDValue Hi = N0.getOperand(1); 9460 EVT EltVT = Lo.getValueType(); 9461 9462 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9463 for (unsigned I = 0; I != 2; ++I) { 9464 SDValue Op = N0.getOperand(I); 9465 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9466 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9467 CFP->getValueAPF()); 9468 } else if (Op.isUndef()) { 9469 // Handled below based on what the other operand is. 9470 NewElts[I] = Op; 9471 } else { 9472 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9473 } 9474 } 9475 9476 // If one half is undef, and one is constant, perfer a splat vector rather 9477 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9478 // cheaper to use and may be free with a packed operation. 9479 if (NewElts[0].isUndef()) { 9480 if (isa<ConstantFPSDNode>(NewElts[1])) 9481 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9482 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9483 } 9484 9485 if (NewElts[1].isUndef()) { 9486 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9487 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9488 } 9489 9490 return DAG.getBuildVector(VT, SL, NewElts); 9491 } 9492 } 9493 9494 unsigned SrcOpc = N0.getOpcode(); 9495 9496 // If it's free to do so, push canonicalizes further up the source, which may 9497 // find a canonical source. 9498 // 9499 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9500 // sNaNs. 9501 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9502 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9503 if (CRHS && N0.hasOneUse()) { 9504 SDLoc SL(N); 9505 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9506 N0.getOperand(0)); 9507 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9508 DCI.AddToWorklist(Canon0.getNode()); 9509 9510 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9511 } 9512 } 9513 9514 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9515 } 9516 9517 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9518 switch (Opc) { 9519 case ISD::FMAXNUM: 9520 case ISD::FMAXNUM_IEEE: 9521 return AMDGPUISD::FMAX3; 9522 case ISD::SMAX: 9523 return AMDGPUISD::SMAX3; 9524 case ISD::UMAX: 9525 return AMDGPUISD::UMAX3; 9526 case ISD::FMINNUM: 9527 case ISD::FMINNUM_IEEE: 9528 return AMDGPUISD::FMIN3; 9529 case ISD::SMIN: 9530 return AMDGPUISD::SMIN3; 9531 case ISD::UMIN: 9532 return AMDGPUISD::UMIN3; 9533 default: 9534 llvm_unreachable("Not a min/max opcode"); 9535 } 9536 } 9537 9538 SDValue SITargetLowering::performIntMed3ImmCombine( 9539 SelectionDAG &DAG, const SDLoc &SL, 9540 SDValue Op0, SDValue Op1, bool Signed) const { 9541 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9542 if (!K1) 9543 return SDValue(); 9544 9545 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9546 if (!K0) 9547 return SDValue(); 9548 9549 if (Signed) { 9550 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9551 return SDValue(); 9552 } else { 9553 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9554 return SDValue(); 9555 } 9556 9557 EVT VT = K0->getValueType(0); 9558 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9559 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9560 return DAG.getNode(Med3Opc, SL, VT, 9561 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9562 } 9563 9564 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9565 MVT NVT = MVT::i32; 9566 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9567 9568 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9569 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9570 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9571 9572 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9573 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9574 } 9575 9576 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9577 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9578 return C; 9579 9580 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9581 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9582 return C; 9583 } 9584 9585 return nullptr; 9586 } 9587 9588 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9589 const SDLoc &SL, 9590 SDValue Op0, 9591 SDValue Op1) const { 9592 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9593 if (!K1) 9594 return SDValue(); 9595 9596 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9597 if (!K0) 9598 return SDValue(); 9599 9600 // Ordered >= (although NaN inputs should have folded away by now). 9601 if (K0->getValueAPF() > K1->getValueAPF()) 9602 return SDValue(); 9603 9604 const MachineFunction &MF = DAG.getMachineFunction(); 9605 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9606 9607 // TODO: Check IEEE bit enabled? 9608 EVT VT = Op0.getValueType(); 9609 if (Info->getMode().DX10Clamp) { 9610 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9611 // hardware fmed3 behavior converting to a min. 9612 // FIXME: Should this be allowing -0.0? 9613 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9614 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9615 } 9616 9617 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9618 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9619 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9620 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9621 // then give the other result, which is different from med3 with a NaN 9622 // input. 9623 SDValue Var = Op0.getOperand(0); 9624 if (!DAG.isKnownNeverSNaN(Var)) 9625 return SDValue(); 9626 9627 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9628 9629 if ((!K0->hasOneUse() || 9630 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9631 (!K1->hasOneUse() || 9632 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9633 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9634 Var, SDValue(K0, 0), SDValue(K1, 0)); 9635 } 9636 } 9637 9638 return SDValue(); 9639 } 9640 9641 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9642 DAGCombinerInfo &DCI) const { 9643 SelectionDAG &DAG = DCI.DAG; 9644 9645 EVT VT = N->getValueType(0); 9646 unsigned Opc = N->getOpcode(); 9647 SDValue Op0 = N->getOperand(0); 9648 SDValue Op1 = N->getOperand(1); 9649 9650 // Only do this if the inner op has one use since this will just increases 9651 // register pressure for no benefit. 9652 9653 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9654 !VT.isVector() && 9655 (VT == MVT::i32 || VT == MVT::f32 || 9656 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9657 // max(max(a, b), c) -> max3(a, b, c) 9658 // min(min(a, b), c) -> min3(a, b, c) 9659 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9660 SDLoc DL(N); 9661 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9662 DL, 9663 N->getValueType(0), 9664 Op0.getOperand(0), 9665 Op0.getOperand(1), 9666 Op1); 9667 } 9668 9669 // Try commuted. 9670 // max(a, max(b, c)) -> max3(a, b, c) 9671 // min(a, min(b, c)) -> min3(a, b, c) 9672 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9673 SDLoc DL(N); 9674 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9675 DL, 9676 N->getValueType(0), 9677 Op0, 9678 Op1.getOperand(0), 9679 Op1.getOperand(1)); 9680 } 9681 } 9682 9683 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9684 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9685 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9686 return Med3; 9687 } 9688 9689 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9690 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9691 return Med3; 9692 } 9693 9694 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9695 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9696 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9697 (Opc == AMDGPUISD::FMIN_LEGACY && 9698 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9699 (VT == MVT::f32 || VT == MVT::f64 || 9700 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9701 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9702 Op0.hasOneUse()) { 9703 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9704 return Res; 9705 } 9706 9707 return SDValue(); 9708 } 9709 9710 static bool isClampZeroToOne(SDValue A, SDValue B) { 9711 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9712 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9713 // FIXME: Should this be allowing -0.0? 9714 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9715 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9716 } 9717 } 9718 9719 return false; 9720 } 9721 9722 // FIXME: Should only worry about snans for version with chain. 9723 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9724 DAGCombinerInfo &DCI) const { 9725 EVT VT = N->getValueType(0); 9726 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9727 // NaNs. With a NaN input, the order of the operands may change the result. 9728 9729 SelectionDAG &DAG = DCI.DAG; 9730 SDLoc SL(N); 9731 9732 SDValue Src0 = N->getOperand(0); 9733 SDValue Src1 = N->getOperand(1); 9734 SDValue Src2 = N->getOperand(2); 9735 9736 if (isClampZeroToOne(Src0, Src1)) { 9737 // const_a, const_b, x -> clamp is safe in all cases including signaling 9738 // nans. 9739 // FIXME: Should this be allowing -0.0? 9740 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9741 } 9742 9743 const MachineFunction &MF = DAG.getMachineFunction(); 9744 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9745 9746 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9747 // handling no dx10-clamp? 9748 if (Info->getMode().DX10Clamp) { 9749 // If NaNs is clamped to 0, we are free to reorder the inputs. 9750 9751 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9752 std::swap(Src0, Src1); 9753 9754 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9755 std::swap(Src1, Src2); 9756 9757 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9758 std::swap(Src0, Src1); 9759 9760 if (isClampZeroToOne(Src1, Src2)) 9761 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9762 } 9763 9764 return SDValue(); 9765 } 9766 9767 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9768 DAGCombinerInfo &DCI) const { 9769 SDValue Src0 = N->getOperand(0); 9770 SDValue Src1 = N->getOperand(1); 9771 if (Src0.isUndef() && Src1.isUndef()) 9772 return DCI.DAG.getUNDEF(N->getValueType(0)); 9773 return SDValue(); 9774 } 9775 9776 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9777 // expanded into a set of cmp/select instructions. 9778 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9779 unsigned NumElem, 9780 bool IsDivergentIdx) { 9781 if (UseDivergentRegisterIndexing) 9782 return false; 9783 9784 unsigned VecSize = EltSize * NumElem; 9785 9786 // Sub-dword vectors of size 2 dword or less have better implementation. 9787 if (VecSize <= 64 && EltSize < 32) 9788 return false; 9789 9790 // Always expand the rest of sub-dword instructions, otherwise it will be 9791 // lowered via memory. 9792 if (EltSize < 32) 9793 return true; 9794 9795 // Always do this if var-idx is divergent, otherwise it will become a loop. 9796 if (IsDivergentIdx) 9797 return true; 9798 9799 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9800 unsigned NumInsts = NumElem /* Number of compares */ + 9801 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9802 return NumInsts <= 16; 9803 } 9804 9805 static bool shouldExpandVectorDynExt(SDNode *N) { 9806 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9807 if (isa<ConstantSDNode>(Idx)) 9808 return false; 9809 9810 SDValue Vec = N->getOperand(0); 9811 EVT VecVT = Vec.getValueType(); 9812 EVT EltVT = VecVT.getVectorElementType(); 9813 unsigned EltSize = EltVT.getSizeInBits(); 9814 unsigned NumElem = VecVT.getVectorNumElements(); 9815 9816 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9817 Idx->isDivergent()); 9818 } 9819 9820 SDValue SITargetLowering::performExtractVectorEltCombine( 9821 SDNode *N, DAGCombinerInfo &DCI) const { 9822 SDValue Vec = N->getOperand(0); 9823 SelectionDAG &DAG = DCI.DAG; 9824 9825 EVT VecVT = Vec.getValueType(); 9826 EVT EltVT = VecVT.getVectorElementType(); 9827 9828 if ((Vec.getOpcode() == ISD::FNEG || 9829 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9830 SDLoc SL(N); 9831 EVT EltVT = N->getValueType(0); 9832 SDValue Idx = N->getOperand(1); 9833 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9834 Vec.getOperand(0), Idx); 9835 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9836 } 9837 9838 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9839 // => 9840 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9841 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9842 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9843 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9844 SDLoc SL(N); 9845 EVT EltVT = N->getValueType(0); 9846 SDValue Idx = N->getOperand(1); 9847 unsigned Opc = Vec.getOpcode(); 9848 9849 switch(Opc) { 9850 default: 9851 break; 9852 // TODO: Support other binary operations. 9853 case ISD::FADD: 9854 case ISD::FSUB: 9855 case ISD::FMUL: 9856 case ISD::ADD: 9857 case ISD::UMIN: 9858 case ISD::UMAX: 9859 case ISD::SMIN: 9860 case ISD::SMAX: 9861 case ISD::FMAXNUM: 9862 case ISD::FMINNUM: 9863 case ISD::FMAXNUM_IEEE: 9864 case ISD::FMINNUM_IEEE: { 9865 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9866 Vec.getOperand(0), Idx); 9867 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9868 Vec.getOperand(1), Idx); 9869 9870 DCI.AddToWorklist(Elt0.getNode()); 9871 DCI.AddToWorklist(Elt1.getNode()); 9872 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9873 } 9874 } 9875 } 9876 9877 unsigned VecSize = VecVT.getSizeInBits(); 9878 unsigned EltSize = EltVT.getSizeInBits(); 9879 9880 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9881 if (::shouldExpandVectorDynExt(N)) { 9882 SDLoc SL(N); 9883 SDValue Idx = N->getOperand(1); 9884 SDValue V; 9885 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9886 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9887 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9888 if (I == 0) 9889 V = Elt; 9890 else 9891 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9892 } 9893 return V; 9894 } 9895 9896 if (!DCI.isBeforeLegalize()) 9897 return SDValue(); 9898 9899 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9900 // elements. This exposes more load reduction opportunities by replacing 9901 // multiple small extract_vector_elements with a single 32-bit extract. 9902 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9903 if (isa<MemSDNode>(Vec) && 9904 EltSize <= 16 && 9905 EltVT.isByteSized() && 9906 VecSize > 32 && 9907 VecSize % 32 == 0 && 9908 Idx) { 9909 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9910 9911 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9912 unsigned EltIdx = BitIndex / 32; 9913 unsigned LeftoverBitIdx = BitIndex % 32; 9914 SDLoc SL(N); 9915 9916 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9917 DCI.AddToWorklist(Cast.getNode()); 9918 9919 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9920 DAG.getConstant(EltIdx, SL, MVT::i32)); 9921 DCI.AddToWorklist(Elt.getNode()); 9922 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9923 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9924 DCI.AddToWorklist(Srl.getNode()); 9925 9926 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9927 DCI.AddToWorklist(Trunc.getNode()); 9928 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9929 } 9930 9931 return SDValue(); 9932 } 9933 9934 SDValue 9935 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9936 DAGCombinerInfo &DCI) const { 9937 SDValue Vec = N->getOperand(0); 9938 SDValue Idx = N->getOperand(2); 9939 EVT VecVT = Vec.getValueType(); 9940 EVT EltVT = VecVT.getVectorElementType(); 9941 9942 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9943 // => BUILD_VECTOR n x select (e, const-idx) 9944 if (!::shouldExpandVectorDynExt(N)) 9945 return SDValue(); 9946 9947 SelectionDAG &DAG = DCI.DAG; 9948 SDLoc SL(N); 9949 SDValue Ins = N->getOperand(1); 9950 EVT IdxVT = Idx.getValueType(); 9951 9952 SmallVector<SDValue, 16> Ops; 9953 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9954 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9955 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9956 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9957 Ops.push_back(V); 9958 } 9959 9960 return DAG.getBuildVector(VecVT, SL, Ops); 9961 } 9962 9963 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9964 const SDNode *N0, 9965 const SDNode *N1) const { 9966 EVT VT = N0->getValueType(0); 9967 9968 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9969 // support denormals ever. 9970 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9971 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9972 getSubtarget()->hasMadF16())) && 9973 isOperationLegal(ISD::FMAD, VT)) 9974 return ISD::FMAD; 9975 9976 const TargetOptions &Options = DAG.getTarget().Options; 9977 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9978 (N0->getFlags().hasAllowContract() && 9979 N1->getFlags().hasAllowContract())) && 9980 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9981 return ISD::FMA; 9982 } 9983 9984 return 0; 9985 } 9986 9987 // For a reassociatable opcode perform: 9988 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9989 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9990 SelectionDAG &DAG) const { 9991 EVT VT = N->getValueType(0); 9992 if (VT != MVT::i32 && VT != MVT::i64) 9993 return SDValue(); 9994 9995 unsigned Opc = N->getOpcode(); 9996 SDValue Op0 = N->getOperand(0); 9997 SDValue Op1 = N->getOperand(1); 9998 9999 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10000 return SDValue(); 10001 10002 if (Op0->isDivergent()) 10003 std::swap(Op0, Op1); 10004 10005 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10006 return SDValue(); 10007 10008 SDValue Op2 = Op1.getOperand(1); 10009 Op1 = Op1.getOperand(0); 10010 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10011 return SDValue(); 10012 10013 if (Op1->isDivergent()) 10014 std::swap(Op1, Op2); 10015 10016 // If either operand is constant this will conflict with 10017 // DAGCombiner::ReassociateOps(). 10018 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10019 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10020 return SDValue(); 10021 10022 SDLoc SL(N); 10023 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10024 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10025 } 10026 10027 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10028 EVT VT, 10029 SDValue N0, SDValue N1, SDValue N2, 10030 bool Signed) { 10031 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10032 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10033 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10034 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10035 } 10036 10037 SDValue SITargetLowering::performAddCombine(SDNode *N, 10038 DAGCombinerInfo &DCI) const { 10039 SelectionDAG &DAG = DCI.DAG; 10040 EVT VT = N->getValueType(0); 10041 SDLoc SL(N); 10042 SDValue LHS = N->getOperand(0); 10043 SDValue RHS = N->getOperand(1); 10044 10045 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10046 && Subtarget->hasMad64_32() && 10047 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10048 VT.getScalarSizeInBits() <= 64) { 10049 if (LHS.getOpcode() != ISD::MUL) 10050 std::swap(LHS, RHS); 10051 10052 SDValue MulLHS = LHS.getOperand(0); 10053 SDValue MulRHS = LHS.getOperand(1); 10054 SDValue AddRHS = RHS; 10055 10056 // TODO: Maybe restrict if SGPR inputs. 10057 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10058 numBitsUnsigned(MulRHS, DAG) <= 32) { 10059 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10060 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10061 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10062 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10063 } 10064 10065 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10066 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10067 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10068 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10069 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10070 } 10071 10072 return SDValue(); 10073 } 10074 10075 if (SDValue V = reassociateScalarOps(N, DAG)) { 10076 return V; 10077 } 10078 10079 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10080 return SDValue(); 10081 10082 // add x, zext (setcc) => addcarry x, 0, setcc 10083 // add x, sext (setcc) => subcarry x, 0, setcc 10084 unsigned Opc = LHS.getOpcode(); 10085 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10086 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10087 std::swap(RHS, LHS); 10088 10089 Opc = RHS.getOpcode(); 10090 switch (Opc) { 10091 default: break; 10092 case ISD::ZERO_EXTEND: 10093 case ISD::SIGN_EXTEND: 10094 case ISD::ANY_EXTEND: { 10095 auto Cond = RHS.getOperand(0); 10096 // If this won't be a real VOPC output, we would still need to insert an 10097 // extra instruction anyway. 10098 if (!isBoolSGPR(Cond)) 10099 break; 10100 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10101 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10102 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10103 return DAG.getNode(Opc, SL, VTList, Args); 10104 } 10105 case ISD::ADDCARRY: { 10106 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10107 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10108 if (!C || C->getZExtValue() != 0) break; 10109 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10110 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10111 } 10112 } 10113 return SDValue(); 10114 } 10115 10116 SDValue SITargetLowering::performSubCombine(SDNode *N, 10117 DAGCombinerInfo &DCI) const { 10118 SelectionDAG &DAG = DCI.DAG; 10119 EVT VT = N->getValueType(0); 10120 10121 if (VT != MVT::i32) 10122 return SDValue(); 10123 10124 SDLoc SL(N); 10125 SDValue LHS = N->getOperand(0); 10126 SDValue RHS = N->getOperand(1); 10127 10128 // sub x, zext (setcc) => subcarry x, 0, setcc 10129 // sub x, sext (setcc) => addcarry x, 0, setcc 10130 unsigned Opc = RHS.getOpcode(); 10131 switch (Opc) { 10132 default: break; 10133 case ISD::ZERO_EXTEND: 10134 case ISD::SIGN_EXTEND: 10135 case ISD::ANY_EXTEND: { 10136 auto Cond = RHS.getOperand(0); 10137 // If this won't be a real VOPC output, we would still need to insert an 10138 // extra instruction anyway. 10139 if (!isBoolSGPR(Cond)) 10140 break; 10141 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10142 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10143 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10144 return DAG.getNode(Opc, SL, VTList, Args); 10145 } 10146 } 10147 10148 if (LHS.getOpcode() == ISD::SUBCARRY) { 10149 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10150 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10151 if (!C || !C->isNullValue()) 10152 return SDValue(); 10153 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10154 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10155 } 10156 return SDValue(); 10157 } 10158 10159 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10160 DAGCombinerInfo &DCI) const { 10161 10162 if (N->getValueType(0) != MVT::i32) 10163 return SDValue(); 10164 10165 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10166 if (!C || C->getZExtValue() != 0) 10167 return SDValue(); 10168 10169 SelectionDAG &DAG = DCI.DAG; 10170 SDValue LHS = N->getOperand(0); 10171 10172 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10173 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10174 unsigned LHSOpc = LHS.getOpcode(); 10175 unsigned Opc = N->getOpcode(); 10176 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10177 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10178 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10179 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10180 } 10181 return SDValue(); 10182 } 10183 10184 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10185 DAGCombinerInfo &DCI) const { 10186 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10187 return SDValue(); 10188 10189 SelectionDAG &DAG = DCI.DAG; 10190 EVT VT = N->getValueType(0); 10191 10192 SDLoc SL(N); 10193 SDValue LHS = N->getOperand(0); 10194 SDValue RHS = N->getOperand(1); 10195 10196 // These should really be instruction patterns, but writing patterns with 10197 // source modiifiers is a pain. 10198 10199 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10200 if (LHS.getOpcode() == ISD::FADD) { 10201 SDValue A = LHS.getOperand(0); 10202 if (A == LHS.getOperand(1)) { 10203 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10204 if (FusedOp != 0) { 10205 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10206 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10207 } 10208 } 10209 } 10210 10211 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10212 if (RHS.getOpcode() == ISD::FADD) { 10213 SDValue A = RHS.getOperand(0); 10214 if (A == RHS.getOperand(1)) { 10215 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10216 if (FusedOp != 0) { 10217 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10218 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10219 } 10220 } 10221 } 10222 10223 return SDValue(); 10224 } 10225 10226 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10227 DAGCombinerInfo &DCI) const { 10228 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10229 return SDValue(); 10230 10231 SelectionDAG &DAG = DCI.DAG; 10232 SDLoc SL(N); 10233 EVT VT = N->getValueType(0); 10234 assert(!VT.isVector()); 10235 10236 // Try to get the fneg to fold into the source modifier. This undoes generic 10237 // DAG combines and folds them into the mad. 10238 // 10239 // Only do this if we are not trying to support denormals. v_mad_f32 does 10240 // not support denormals ever. 10241 SDValue LHS = N->getOperand(0); 10242 SDValue RHS = N->getOperand(1); 10243 if (LHS.getOpcode() == ISD::FADD) { 10244 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10245 SDValue A = LHS.getOperand(0); 10246 if (A == LHS.getOperand(1)) { 10247 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10248 if (FusedOp != 0){ 10249 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10250 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10251 10252 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10253 } 10254 } 10255 } 10256 10257 if (RHS.getOpcode() == ISD::FADD) { 10258 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10259 10260 SDValue A = RHS.getOperand(0); 10261 if (A == RHS.getOperand(1)) { 10262 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10263 if (FusedOp != 0){ 10264 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10265 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10266 } 10267 } 10268 } 10269 10270 return SDValue(); 10271 } 10272 10273 SDValue SITargetLowering::performFMACombine(SDNode *N, 10274 DAGCombinerInfo &DCI) const { 10275 SelectionDAG &DAG = DCI.DAG; 10276 EVT VT = N->getValueType(0); 10277 SDLoc SL(N); 10278 10279 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10280 return SDValue(); 10281 10282 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10283 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10284 SDValue Op1 = N->getOperand(0); 10285 SDValue Op2 = N->getOperand(1); 10286 SDValue FMA = N->getOperand(2); 10287 10288 if (FMA.getOpcode() != ISD::FMA || 10289 Op1.getOpcode() != ISD::FP_EXTEND || 10290 Op2.getOpcode() != ISD::FP_EXTEND) 10291 return SDValue(); 10292 10293 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10294 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10295 // is sufficient to allow generaing fdot2. 10296 const TargetOptions &Options = DAG.getTarget().Options; 10297 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10298 (N->getFlags().hasAllowContract() && 10299 FMA->getFlags().hasAllowContract())) { 10300 Op1 = Op1.getOperand(0); 10301 Op2 = Op2.getOperand(0); 10302 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10303 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10304 return SDValue(); 10305 10306 SDValue Vec1 = Op1.getOperand(0); 10307 SDValue Idx1 = Op1.getOperand(1); 10308 SDValue Vec2 = Op2.getOperand(0); 10309 10310 SDValue FMAOp1 = FMA.getOperand(0); 10311 SDValue FMAOp2 = FMA.getOperand(1); 10312 SDValue FMAAcc = FMA.getOperand(2); 10313 10314 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10315 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10316 return SDValue(); 10317 10318 FMAOp1 = FMAOp1.getOperand(0); 10319 FMAOp2 = FMAOp2.getOperand(0); 10320 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10321 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10322 return SDValue(); 10323 10324 SDValue Vec3 = FMAOp1.getOperand(0); 10325 SDValue Vec4 = FMAOp2.getOperand(0); 10326 SDValue Idx2 = FMAOp1.getOperand(1); 10327 10328 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10329 // Idx1 and Idx2 cannot be the same. 10330 Idx1 == Idx2) 10331 return SDValue(); 10332 10333 if (Vec1 == Vec2 || Vec3 == Vec4) 10334 return SDValue(); 10335 10336 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10337 return SDValue(); 10338 10339 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10340 (Vec1 == Vec4 && Vec2 == Vec3)) { 10341 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10342 DAG.getTargetConstant(0, SL, MVT::i1)); 10343 } 10344 } 10345 return SDValue(); 10346 } 10347 10348 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10349 DAGCombinerInfo &DCI) const { 10350 SelectionDAG &DAG = DCI.DAG; 10351 SDLoc SL(N); 10352 10353 SDValue LHS = N->getOperand(0); 10354 SDValue RHS = N->getOperand(1); 10355 EVT VT = LHS.getValueType(); 10356 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10357 10358 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10359 if (!CRHS) { 10360 CRHS = dyn_cast<ConstantSDNode>(LHS); 10361 if (CRHS) { 10362 std::swap(LHS, RHS); 10363 CC = getSetCCSwappedOperands(CC); 10364 } 10365 } 10366 10367 if (CRHS) { 10368 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10369 isBoolSGPR(LHS.getOperand(0))) { 10370 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10371 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10372 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10373 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10374 if ((CRHS->isAllOnesValue() && 10375 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10376 (CRHS->isNullValue() && 10377 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10378 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10379 DAG.getConstant(-1, SL, MVT::i1)); 10380 if ((CRHS->isAllOnesValue() && 10381 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10382 (CRHS->isNullValue() && 10383 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10384 return LHS.getOperand(0); 10385 } 10386 10387 uint64_t CRHSVal = CRHS->getZExtValue(); 10388 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10389 LHS.getOpcode() == ISD::SELECT && 10390 isa<ConstantSDNode>(LHS.getOperand(1)) && 10391 isa<ConstantSDNode>(LHS.getOperand(2)) && 10392 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10393 isBoolSGPR(LHS.getOperand(0))) { 10394 // Given CT != FT: 10395 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10396 // setcc (select cc, CT, CF), CF, ne => cc 10397 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10398 // setcc (select cc, CT, CF), CT, eq => cc 10399 uint64_t CT = LHS.getConstantOperandVal(1); 10400 uint64_t CF = LHS.getConstantOperandVal(2); 10401 10402 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10403 (CT == CRHSVal && CC == ISD::SETNE)) 10404 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10405 DAG.getConstant(-1, SL, MVT::i1)); 10406 if ((CF == CRHSVal && CC == ISD::SETNE) || 10407 (CT == CRHSVal && CC == ISD::SETEQ)) 10408 return LHS.getOperand(0); 10409 } 10410 } 10411 10412 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10413 VT != MVT::f16)) 10414 return SDValue(); 10415 10416 // Match isinf/isfinite pattern 10417 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10418 // (fcmp one (fabs x), inf) -> (fp_class x, 10419 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10420 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10421 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10422 if (!CRHS) 10423 return SDValue(); 10424 10425 const APFloat &APF = CRHS->getValueAPF(); 10426 if (APF.isInfinity() && !APF.isNegative()) { 10427 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10428 SIInstrFlags::N_INFINITY; 10429 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10430 SIInstrFlags::P_ZERO | 10431 SIInstrFlags::N_NORMAL | 10432 SIInstrFlags::P_NORMAL | 10433 SIInstrFlags::N_SUBNORMAL | 10434 SIInstrFlags::P_SUBNORMAL; 10435 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10436 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10437 DAG.getConstant(Mask, SL, MVT::i32)); 10438 } 10439 } 10440 10441 return SDValue(); 10442 } 10443 10444 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10445 DAGCombinerInfo &DCI) const { 10446 SelectionDAG &DAG = DCI.DAG; 10447 SDLoc SL(N); 10448 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10449 10450 SDValue Src = N->getOperand(0); 10451 SDValue Shift = N->getOperand(0); 10452 10453 // TODO: Extend type shouldn't matter (assuming legal types). 10454 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10455 Shift = Shift.getOperand(0); 10456 10457 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10458 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10459 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10460 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10461 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10462 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10463 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10464 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10465 SDLoc(Shift.getOperand(0)), MVT::i32); 10466 10467 unsigned ShiftOffset = 8 * Offset; 10468 if (Shift.getOpcode() == ISD::SHL) 10469 ShiftOffset -= C->getZExtValue(); 10470 else 10471 ShiftOffset += C->getZExtValue(); 10472 10473 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10474 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10475 MVT::f32, Shift); 10476 } 10477 } 10478 } 10479 10480 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10481 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10482 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10483 // We simplified Src. If this node is not dead, visit it again so it is 10484 // folded properly. 10485 if (N->getOpcode() != ISD::DELETED_NODE) 10486 DCI.AddToWorklist(N); 10487 return SDValue(N, 0); 10488 } 10489 10490 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10491 if (SDValue DemandedSrc = 10492 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10493 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10494 10495 return SDValue(); 10496 } 10497 10498 SDValue SITargetLowering::performClampCombine(SDNode *N, 10499 DAGCombinerInfo &DCI) const { 10500 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10501 if (!CSrc) 10502 return SDValue(); 10503 10504 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10505 const APFloat &F = CSrc->getValueAPF(); 10506 APFloat Zero = APFloat::getZero(F.getSemantics()); 10507 if (F < Zero || 10508 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10509 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10510 } 10511 10512 APFloat One(F.getSemantics(), "1.0"); 10513 if (F > One) 10514 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10515 10516 return SDValue(CSrc, 0); 10517 } 10518 10519 10520 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10521 DAGCombinerInfo &DCI) const { 10522 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10523 return SDValue(); 10524 switch (N->getOpcode()) { 10525 default: 10526 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10527 case ISD::ADD: 10528 return performAddCombine(N, DCI); 10529 case ISD::SUB: 10530 return performSubCombine(N, DCI); 10531 case ISD::ADDCARRY: 10532 case ISD::SUBCARRY: 10533 return performAddCarrySubCarryCombine(N, DCI); 10534 case ISD::FADD: 10535 return performFAddCombine(N, DCI); 10536 case ISD::FSUB: 10537 return performFSubCombine(N, DCI); 10538 case ISD::SETCC: 10539 return performSetCCCombine(N, DCI); 10540 case ISD::FMAXNUM: 10541 case ISD::FMINNUM: 10542 case ISD::FMAXNUM_IEEE: 10543 case ISD::FMINNUM_IEEE: 10544 case ISD::SMAX: 10545 case ISD::SMIN: 10546 case ISD::UMAX: 10547 case ISD::UMIN: 10548 case AMDGPUISD::FMIN_LEGACY: 10549 case AMDGPUISD::FMAX_LEGACY: 10550 return performMinMaxCombine(N, DCI); 10551 case ISD::FMA: 10552 return performFMACombine(N, DCI); 10553 case ISD::LOAD: { 10554 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10555 return Widended; 10556 LLVM_FALLTHROUGH; 10557 } 10558 case ISD::STORE: 10559 case ISD::ATOMIC_LOAD: 10560 case ISD::ATOMIC_STORE: 10561 case ISD::ATOMIC_CMP_SWAP: 10562 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10563 case ISD::ATOMIC_SWAP: 10564 case ISD::ATOMIC_LOAD_ADD: 10565 case ISD::ATOMIC_LOAD_SUB: 10566 case ISD::ATOMIC_LOAD_AND: 10567 case ISD::ATOMIC_LOAD_OR: 10568 case ISD::ATOMIC_LOAD_XOR: 10569 case ISD::ATOMIC_LOAD_NAND: 10570 case ISD::ATOMIC_LOAD_MIN: 10571 case ISD::ATOMIC_LOAD_MAX: 10572 case ISD::ATOMIC_LOAD_UMIN: 10573 case ISD::ATOMIC_LOAD_UMAX: 10574 case ISD::ATOMIC_LOAD_FADD: 10575 case AMDGPUISD::ATOMIC_INC: 10576 case AMDGPUISD::ATOMIC_DEC: 10577 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10578 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10579 if (DCI.isBeforeLegalize()) 10580 break; 10581 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10582 case ISD::AND: 10583 return performAndCombine(N, DCI); 10584 case ISD::OR: 10585 return performOrCombine(N, DCI); 10586 case ISD::XOR: 10587 return performXorCombine(N, DCI); 10588 case ISD::ZERO_EXTEND: 10589 return performZeroExtendCombine(N, DCI); 10590 case ISD::SIGN_EXTEND_INREG: 10591 return performSignExtendInRegCombine(N , DCI); 10592 case AMDGPUISD::FP_CLASS: 10593 return performClassCombine(N, DCI); 10594 case ISD::FCANONICALIZE: 10595 return performFCanonicalizeCombine(N, DCI); 10596 case AMDGPUISD::RCP: 10597 return performRcpCombine(N, DCI); 10598 case AMDGPUISD::FRACT: 10599 case AMDGPUISD::RSQ: 10600 case AMDGPUISD::RCP_LEGACY: 10601 case AMDGPUISD::RCP_IFLAG: 10602 case AMDGPUISD::RSQ_CLAMP: 10603 case AMDGPUISD::LDEXP: { 10604 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10605 SDValue Src = N->getOperand(0); 10606 if (Src.isUndef()) 10607 return Src; 10608 break; 10609 } 10610 case ISD::SINT_TO_FP: 10611 case ISD::UINT_TO_FP: 10612 return performUCharToFloatCombine(N, DCI); 10613 case AMDGPUISD::CVT_F32_UBYTE0: 10614 case AMDGPUISD::CVT_F32_UBYTE1: 10615 case AMDGPUISD::CVT_F32_UBYTE2: 10616 case AMDGPUISD::CVT_F32_UBYTE3: 10617 return performCvtF32UByteNCombine(N, DCI); 10618 case AMDGPUISD::FMED3: 10619 return performFMed3Combine(N, DCI); 10620 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10621 return performCvtPkRTZCombine(N, DCI); 10622 case AMDGPUISD::CLAMP: 10623 return performClampCombine(N, DCI); 10624 case ISD::SCALAR_TO_VECTOR: { 10625 SelectionDAG &DAG = DCI.DAG; 10626 EVT VT = N->getValueType(0); 10627 10628 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10629 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10630 SDLoc SL(N); 10631 SDValue Src = N->getOperand(0); 10632 EVT EltVT = Src.getValueType(); 10633 if (EltVT == MVT::f16) 10634 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10635 10636 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10637 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10638 } 10639 10640 break; 10641 } 10642 case ISD::EXTRACT_VECTOR_ELT: 10643 return performExtractVectorEltCombine(N, DCI); 10644 case ISD::INSERT_VECTOR_ELT: 10645 return performInsertVectorEltCombine(N, DCI); 10646 } 10647 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10648 } 10649 10650 /// Helper function for adjustWritemask 10651 static unsigned SubIdx2Lane(unsigned Idx) { 10652 switch (Idx) { 10653 default: return 0; 10654 case AMDGPU::sub0: return 0; 10655 case AMDGPU::sub1: return 1; 10656 case AMDGPU::sub2: return 2; 10657 case AMDGPU::sub3: return 3; 10658 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10659 } 10660 } 10661 10662 /// Adjust the writemask of MIMG instructions 10663 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10664 SelectionDAG &DAG) const { 10665 unsigned Opcode = Node->getMachineOpcode(); 10666 10667 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10668 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10669 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10670 return Node; // not implemented for D16 10671 10672 SDNode *Users[5] = { nullptr }; 10673 unsigned Lane = 0; 10674 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10675 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10676 unsigned NewDmask = 0; 10677 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10678 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10679 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10680 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10681 unsigned TFCLane = 0; 10682 bool HasChain = Node->getNumValues() > 1; 10683 10684 if (OldDmask == 0) { 10685 // These are folded out, but on the chance it happens don't assert. 10686 return Node; 10687 } 10688 10689 unsigned OldBitsSet = countPopulation(OldDmask); 10690 // Work out which is the TFE/LWE lane if that is enabled. 10691 if (UsesTFC) { 10692 TFCLane = OldBitsSet; 10693 } 10694 10695 // Try to figure out the used register components 10696 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10697 I != E; ++I) { 10698 10699 // Don't look at users of the chain. 10700 if (I.getUse().getResNo() != 0) 10701 continue; 10702 10703 // Abort if we can't understand the usage 10704 if (!I->isMachineOpcode() || 10705 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10706 return Node; 10707 10708 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10709 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10710 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10711 // set, etc. 10712 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10713 10714 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10715 if (UsesTFC && Lane == TFCLane) { 10716 Users[Lane] = *I; 10717 } else { 10718 // Set which texture component corresponds to the lane. 10719 unsigned Comp; 10720 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10721 Comp = countTrailingZeros(Dmask); 10722 Dmask &= ~(1 << Comp); 10723 } 10724 10725 // Abort if we have more than one user per component. 10726 if (Users[Lane]) 10727 return Node; 10728 10729 Users[Lane] = *I; 10730 NewDmask |= 1 << Comp; 10731 } 10732 } 10733 10734 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10735 bool NoChannels = !NewDmask; 10736 if (NoChannels) { 10737 if (!UsesTFC) { 10738 // No uses of the result and not using TFC. Then do nothing. 10739 return Node; 10740 } 10741 // If the original dmask has one channel - then nothing to do 10742 if (OldBitsSet == 1) 10743 return Node; 10744 // Use an arbitrary dmask - required for the instruction to work 10745 NewDmask = 1; 10746 } 10747 // Abort if there's no change 10748 if (NewDmask == OldDmask) 10749 return Node; 10750 10751 unsigned BitsSet = countPopulation(NewDmask); 10752 10753 // Check for TFE or LWE - increase the number of channels by one to account 10754 // for the extra return value 10755 // This will need adjustment for D16 if this is also included in 10756 // adjustWriteMask (this function) but at present D16 are excluded. 10757 unsigned NewChannels = BitsSet + UsesTFC; 10758 10759 int NewOpcode = 10760 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10761 assert(NewOpcode != -1 && 10762 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10763 "failed to find equivalent MIMG op"); 10764 10765 // Adjust the writemask in the node 10766 SmallVector<SDValue, 12> Ops; 10767 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10768 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10769 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10770 10771 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10772 10773 MVT ResultVT = NewChannels == 1 ? 10774 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10775 NewChannels == 5 ? 8 : NewChannels); 10776 SDVTList NewVTList = HasChain ? 10777 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10778 10779 10780 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10781 NewVTList, Ops); 10782 10783 if (HasChain) { 10784 // Update chain. 10785 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10786 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10787 } 10788 10789 if (NewChannels == 1) { 10790 assert(Node->hasNUsesOfValue(1, 0)); 10791 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10792 SDLoc(Node), Users[Lane]->getValueType(0), 10793 SDValue(NewNode, 0)); 10794 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10795 return nullptr; 10796 } 10797 10798 // Update the users of the node with the new indices 10799 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10800 SDNode *User = Users[i]; 10801 if (!User) { 10802 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10803 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10804 if (i || !NoChannels) 10805 continue; 10806 } else { 10807 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10808 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10809 } 10810 10811 switch (Idx) { 10812 default: break; 10813 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10814 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10815 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10816 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10817 } 10818 } 10819 10820 DAG.RemoveDeadNode(Node); 10821 return nullptr; 10822 } 10823 10824 static bool isFrameIndexOp(SDValue Op) { 10825 if (Op.getOpcode() == ISD::AssertZext) 10826 Op = Op.getOperand(0); 10827 10828 return isa<FrameIndexSDNode>(Op); 10829 } 10830 10831 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10832 /// with frame index operands. 10833 /// LLVM assumes that inputs are to these instructions are registers. 10834 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10835 SelectionDAG &DAG) const { 10836 if (Node->getOpcode() == ISD::CopyToReg) { 10837 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10838 SDValue SrcVal = Node->getOperand(2); 10839 10840 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10841 // to try understanding copies to physical registers. 10842 if (SrcVal.getValueType() == MVT::i1 && 10843 Register::isPhysicalRegister(DestReg->getReg())) { 10844 SDLoc SL(Node); 10845 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10846 SDValue VReg = DAG.getRegister( 10847 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10848 10849 SDNode *Glued = Node->getGluedNode(); 10850 SDValue ToVReg 10851 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10852 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10853 SDValue ToResultReg 10854 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10855 VReg, ToVReg.getValue(1)); 10856 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10857 DAG.RemoveDeadNode(Node); 10858 return ToResultReg.getNode(); 10859 } 10860 } 10861 10862 SmallVector<SDValue, 8> Ops; 10863 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10864 if (!isFrameIndexOp(Node->getOperand(i))) { 10865 Ops.push_back(Node->getOperand(i)); 10866 continue; 10867 } 10868 10869 SDLoc DL(Node); 10870 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10871 Node->getOperand(i).getValueType(), 10872 Node->getOperand(i)), 0)); 10873 } 10874 10875 return DAG.UpdateNodeOperands(Node, Ops); 10876 } 10877 10878 /// Fold the instructions after selecting them. 10879 /// Returns null if users were already updated. 10880 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10881 SelectionDAG &DAG) const { 10882 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10883 unsigned Opcode = Node->getMachineOpcode(); 10884 10885 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10886 !TII->isGather4(Opcode)) { 10887 return adjustWritemask(Node, DAG); 10888 } 10889 10890 if (Opcode == AMDGPU::INSERT_SUBREG || 10891 Opcode == AMDGPU::REG_SEQUENCE) { 10892 legalizeTargetIndependentNode(Node, DAG); 10893 return Node; 10894 } 10895 10896 switch (Opcode) { 10897 case AMDGPU::V_DIV_SCALE_F32: 10898 case AMDGPU::V_DIV_SCALE_F64: { 10899 // Satisfy the operand register constraint when one of the inputs is 10900 // undefined. Ordinarily each undef value will have its own implicit_def of 10901 // a vreg, so force these to use a single register. 10902 SDValue Src0 = Node->getOperand(0); 10903 SDValue Src1 = Node->getOperand(1); 10904 SDValue Src2 = Node->getOperand(2); 10905 10906 if ((Src0.isMachineOpcode() && 10907 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10908 (Src0 == Src1 || Src0 == Src2)) 10909 break; 10910 10911 MVT VT = Src0.getValueType().getSimpleVT(); 10912 const TargetRegisterClass *RC = 10913 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10914 10915 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10916 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10917 10918 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10919 UndefReg, Src0, SDValue()); 10920 10921 // src0 must be the same register as src1 or src2, even if the value is 10922 // undefined, so make sure we don't violate this constraint. 10923 if (Src0.isMachineOpcode() && 10924 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10925 if (Src1.isMachineOpcode() && 10926 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10927 Src0 = Src1; 10928 else if (Src2.isMachineOpcode() && 10929 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10930 Src0 = Src2; 10931 else { 10932 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10933 Src0 = UndefReg; 10934 Src1 = UndefReg; 10935 } 10936 } else 10937 break; 10938 10939 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10940 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10941 Ops.push_back(Node->getOperand(I)); 10942 10943 Ops.push_back(ImpDef.getValue(1)); 10944 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10945 } 10946 default: 10947 break; 10948 } 10949 10950 return Node; 10951 } 10952 10953 /// Assign the register class depending on the number of 10954 /// bits set in the writemask 10955 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10956 SDNode *Node) const { 10957 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10958 10959 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10960 10961 if (TII->isVOP3(MI.getOpcode())) { 10962 // Make sure constant bus requirements are respected. 10963 TII->legalizeOperandsVOP3(MRI, MI); 10964 10965 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10966 // This saves a chain-copy of registers and better ballance register 10967 // use between vgpr and agpr as agpr tuples tend to be big. 10968 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10969 unsigned Opc = MI.getOpcode(); 10970 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10971 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10972 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10973 if (I == -1) 10974 break; 10975 MachineOperand &Op = MI.getOperand(I); 10976 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10977 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10978 !Register::isVirtualRegister(Op.getReg()) || 10979 !TRI->isAGPR(MRI, Op.getReg())) 10980 continue; 10981 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10982 if (!Src || !Src->isCopy() || 10983 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10984 continue; 10985 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10986 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10987 // All uses of agpr64 and agpr32 can also accept vgpr except for 10988 // v_accvgpr_read, but we do not produce agpr reads during selection, 10989 // so no use checks are needed. 10990 MRI.setRegClass(Op.getReg(), NewRC); 10991 } 10992 } 10993 10994 return; 10995 } 10996 10997 // Replace unused atomics with the no return version. 10998 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10999 if (NoRetAtomicOp != -1) { 11000 if (!Node->hasAnyUseOfValue(0)) { 11001 MI.setDesc(TII->get(NoRetAtomicOp)); 11002 MI.RemoveOperand(0); 11003 return; 11004 } 11005 11006 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11007 // instruction, because the return type of these instructions is a vec2 of 11008 // the memory type, so it can be tied to the input operand. 11009 // This means these instructions always have a use, so we need to add a 11010 // special case to check if the atomic has only one extract_subreg use, 11011 // which itself has no uses. 11012 if ((Node->hasNUsesOfValue(1, 0) && 11013 Node->use_begin()->isMachineOpcode() && 11014 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11015 !Node->use_begin()->hasAnyUseOfValue(0))) { 11016 Register Def = MI.getOperand(0).getReg(); 11017 11018 // Change this into a noret atomic. 11019 MI.setDesc(TII->get(NoRetAtomicOp)); 11020 MI.RemoveOperand(0); 11021 11022 // If we only remove the def operand from the atomic instruction, the 11023 // extract_subreg will be left with a use of a vreg without a def. 11024 // So we need to insert an implicit_def to avoid machine verifier 11025 // errors. 11026 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11027 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11028 } 11029 return; 11030 } 11031 } 11032 11033 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11034 uint64_t Val) { 11035 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11036 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11037 } 11038 11039 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11040 const SDLoc &DL, 11041 SDValue Ptr) const { 11042 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11043 11044 // Build the half of the subregister with the constants before building the 11045 // full 128-bit register. If we are building multiple resource descriptors, 11046 // this will allow CSEing of the 2-component register. 11047 const SDValue Ops0[] = { 11048 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11049 buildSMovImm32(DAG, DL, 0), 11050 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11051 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11052 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11053 }; 11054 11055 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11056 MVT::v2i32, Ops0), 0); 11057 11058 // Combine the constants and the pointer. 11059 const SDValue Ops1[] = { 11060 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11061 Ptr, 11062 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11063 SubRegHi, 11064 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11065 }; 11066 11067 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11068 } 11069 11070 /// Return a resource descriptor with the 'Add TID' bit enabled 11071 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11072 /// of the resource descriptor) to create an offset, which is added to 11073 /// the resource pointer. 11074 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11075 SDValue Ptr, uint32_t RsrcDword1, 11076 uint64_t RsrcDword2And3) const { 11077 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11078 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11079 if (RsrcDword1) { 11080 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11081 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11082 0); 11083 } 11084 11085 SDValue DataLo = buildSMovImm32(DAG, DL, 11086 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11087 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11088 11089 const SDValue Ops[] = { 11090 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11091 PtrLo, 11092 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11093 PtrHi, 11094 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11095 DataLo, 11096 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11097 DataHi, 11098 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11099 }; 11100 11101 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11102 } 11103 11104 //===----------------------------------------------------------------------===// 11105 // SI Inline Assembly Support 11106 //===----------------------------------------------------------------------===// 11107 11108 std::pair<unsigned, const TargetRegisterClass *> 11109 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11110 StringRef Constraint, 11111 MVT VT) const { 11112 const TargetRegisterClass *RC = nullptr; 11113 if (Constraint.size() == 1) { 11114 const unsigned BitWidth = VT.getSizeInBits(); 11115 switch (Constraint[0]) { 11116 default: 11117 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11118 case 's': 11119 case 'r': 11120 switch (BitWidth) { 11121 case 16: 11122 RC = &AMDGPU::SReg_32RegClass; 11123 break; 11124 case 64: 11125 RC = &AMDGPU::SGPR_64RegClass; 11126 break; 11127 default: 11128 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11129 if (!RC) 11130 return std::make_pair(0U, nullptr); 11131 break; 11132 } 11133 break; 11134 case 'v': 11135 switch (BitWidth) { 11136 case 16: 11137 RC = &AMDGPU::VGPR_32RegClass; 11138 break; 11139 default: 11140 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11141 if (!RC) 11142 return std::make_pair(0U, nullptr); 11143 break; 11144 } 11145 break; 11146 case 'a': 11147 if (!Subtarget->hasMAIInsts()) 11148 break; 11149 switch (BitWidth) { 11150 case 16: 11151 RC = &AMDGPU::AGPR_32RegClass; 11152 break; 11153 default: 11154 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11155 if (!RC) 11156 return std::make_pair(0U, nullptr); 11157 break; 11158 } 11159 break; 11160 } 11161 // We actually support i128, i16 and f16 as inline parameters 11162 // even if they are not reported as legal 11163 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11164 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11165 return std::make_pair(0U, RC); 11166 } 11167 11168 if (Constraint.size() > 1) { 11169 if (Constraint[1] == 'v') { 11170 RC = &AMDGPU::VGPR_32RegClass; 11171 } else if (Constraint[1] == 's') { 11172 RC = &AMDGPU::SGPR_32RegClass; 11173 } else if (Constraint[1] == 'a') { 11174 RC = &AMDGPU::AGPR_32RegClass; 11175 } 11176 11177 if (RC) { 11178 uint32_t Idx; 11179 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11180 if (!Failed && Idx < RC->getNumRegs()) 11181 return std::make_pair(RC->getRegister(Idx), RC); 11182 } 11183 } 11184 11185 // FIXME: Returns VS_32 for physical SGPR constraints 11186 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11187 } 11188 11189 static bool isImmConstraint(StringRef Constraint) { 11190 if (Constraint.size() == 1) { 11191 switch (Constraint[0]) { 11192 default: break; 11193 case 'I': 11194 case 'J': 11195 case 'A': 11196 case 'B': 11197 case 'C': 11198 return true; 11199 } 11200 } else if (Constraint == "DA" || 11201 Constraint == "DB") { 11202 return true; 11203 } 11204 return false; 11205 } 11206 11207 SITargetLowering::ConstraintType 11208 SITargetLowering::getConstraintType(StringRef Constraint) const { 11209 if (Constraint.size() == 1) { 11210 switch (Constraint[0]) { 11211 default: break; 11212 case 's': 11213 case 'v': 11214 case 'a': 11215 return C_RegisterClass; 11216 } 11217 } 11218 if (isImmConstraint(Constraint)) { 11219 return C_Other; 11220 } 11221 return TargetLowering::getConstraintType(Constraint); 11222 } 11223 11224 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11225 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11226 Val = Val & maskTrailingOnes<uint64_t>(Size); 11227 } 11228 return Val; 11229 } 11230 11231 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11232 std::string &Constraint, 11233 std::vector<SDValue> &Ops, 11234 SelectionDAG &DAG) const { 11235 if (isImmConstraint(Constraint)) { 11236 uint64_t Val; 11237 if (getAsmOperandConstVal(Op, Val) && 11238 checkAsmConstraintVal(Op, Constraint, Val)) { 11239 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11240 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11241 } 11242 } else { 11243 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11244 } 11245 } 11246 11247 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11248 unsigned Size = Op.getScalarValueSizeInBits(); 11249 if (Size > 64) 11250 return false; 11251 11252 if (Size == 16 && !Subtarget->has16BitInsts()) 11253 return false; 11254 11255 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11256 Val = C->getSExtValue(); 11257 return true; 11258 } 11259 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11260 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11261 return true; 11262 } 11263 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11264 if (Size != 16 || Op.getNumOperands() != 2) 11265 return false; 11266 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11267 return false; 11268 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11269 Val = C->getSExtValue(); 11270 return true; 11271 } 11272 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11273 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11274 return true; 11275 } 11276 } 11277 11278 return false; 11279 } 11280 11281 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11282 const std::string &Constraint, 11283 uint64_t Val) const { 11284 if (Constraint.size() == 1) { 11285 switch (Constraint[0]) { 11286 case 'I': 11287 return AMDGPU::isInlinableIntLiteral(Val); 11288 case 'J': 11289 return isInt<16>(Val); 11290 case 'A': 11291 return checkAsmConstraintValA(Op, Val); 11292 case 'B': 11293 return isInt<32>(Val); 11294 case 'C': 11295 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11296 AMDGPU::isInlinableIntLiteral(Val); 11297 default: 11298 break; 11299 } 11300 } else if (Constraint.size() == 2) { 11301 if (Constraint == "DA") { 11302 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11303 int64_t LoBits = static_cast<int32_t>(Val); 11304 return checkAsmConstraintValA(Op, HiBits, 32) && 11305 checkAsmConstraintValA(Op, LoBits, 32); 11306 } 11307 if (Constraint == "DB") { 11308 return true; 11309 } 11310 } 11311 llvm_unreachable("Invalid asm constraint"); 11312 } 11313 11314 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11315 uint64_t Val, 11316 unsigned MaxSize) const { 11317 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11318 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11319 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11320 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11321 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11322 return true; 11323 } 11324 return false; 11325 } 11326 11327 // Figure out which registers should be reserved for stack access. Only after 11328 // the function is legalized do we know all of the non-spill stack objects or if 11329 // calls are present. 11330 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11331 MachineRegisterInfo &MRI = MF.getRegInfo(); 11332 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11333 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11334 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11335 11336 if (Info->isEntryFunction()) { 11337 // Callable functions have fixed registers used for stack access. 11338 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11339 } 11340 11341 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11342 Info->getStackPtrOffsetReg())); 11343 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11344 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11345 11346 // We need to worry about replacing the default register with itself in case 11347 // of MIR testcases missing the MFI. 11348 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11349 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11350 11351 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11352 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11353 11354 Info->limitOccupancy(MF); 11355 11356 if (ST.isWave32() && !MF.empty()) { 11357 // Add VCC_HI def because many instructions marked as imp-use VCC where 11358 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11359 // having a use of undef. 11360 11361 const SIInstrInfo *TII = ST.getInstrInfo(); 11362 DebugLoc DL; 11363 11364 MachineBasicBlock &MBB = MF.front(); 11365 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11366 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11367 11368 for (auto &MBB : MF) { 11369 for (auto &MI : MBB) { 11370 TII->fixImplicitOperands(MI); 11371 } 11372 } 11373 } 11374 11375 TargetLoweringBase::finalizeLowering(MF); 11376 11377 // Allocate a VGPR for future SGPR Spill if 11378 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11379 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11380 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11381 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11382 Info->reserveVGPRforSGPRSpills(MF); 11383 } 11384 11385 void SITargetLowering::computeKnownBitsForFrameIndex( 11386 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11387 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11388 11389 // Set the high bits to zero based on the maximum allowed scratch size per 11390 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11391 // calculation won't overflow, so assume the sign bit is never set. 11392 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11393 } 11394 11395 Align SITargetLowering::computeKnownAlignForTargetInstr( 11396 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11397 unsigned Depth) const { 11398 const MachineInstr *MI = MRI.getVRegDef(R); 11399 switch (MI->getOpcode()) { 11400 case AMDGPU::G_INTRINSIC: 11401 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11402 // FIXME: Can this move to generic code? What about the case where the call 11403 // site specifies a lower alignment? 11404 Intrinsic::ID IID = MI->getIntrinsicID(); 11405 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11406 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11407 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11408 return *RetAlign; 11409 return Align(1); 11410 } 11411 default: 11412 return Align(1); 11413 } 11414 } 11415 11416 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11417 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11418 const Align CacheLineAlign = Align(64); 11419 11420 // Pre-GFX10 target did not benefit from loop alignment 11421 if (!ML || DisableLoopAlignment || 11422 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11423 getSubtarget()->hasInstFwdPrefetchBug()) 11424 return PrefAlign; 11425 11426 // On GFX10 I$ is 4 x 64 bytes cache lines. 11427 // By default prefetcher keeps one cache line behind and reads two ahead. 11428 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11429 // behind and one ahead. 11430 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11431 // If loop fits 64 bytes it always spans no more than two cache lines and 11432 // does not need an alignment. 11433 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11434 // Else if loop is less or equal 192 bytes we need two lines behind. 11435 11436 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11437 const MachineBasicBlock *Header = ML->getHeader(); 11438 if (Header->getAlignment() != PrefAlign) 11439 return Header->getAlignment(); // Already processed. 11440 11441 unsigned LoopSize = 0; 11442 for (const MachineBasicBlock *MBB : ML->blocks()) { 11443 // If inner loop block is aligned assume in average half of the alignment 11444 // size to be added as nops. 11445 if (MBB != Header) 11446 LoopSize += MBB->getAlignment().value() / 2; 11447 11448 for (const MachineInstr &MI : *MBB) { 11449 LoopSize += TII->getInstSizeInBytes(MI); 11450 if (LoopSize > 192) 11451 return PrefAlign; 11452 } 11453 } 11454 11455 if (LoopSize <= 64) 11456 return PrefAlign; 11457 11458 if (LoopSize <= 128) 11459 return CacheLineAlign; 11460 11461 // If any of parent loops is surrounded by prefetch instructions do not 11462 // insert new for inner loop, which would reset parent's settings. 11463 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11464 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11465 auto I = Exit->getFirstNonDebugInstr(); 11466 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11467 return CacheLineAlign; 11468 } 11469 } 11470 11471 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11472 MachineBasicBlock *Exit = ML->getExitBlock(); 11473 11474 if (Pre && Exit) { 11475 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11476 TII->get(AMDGPU::S_INST_PREFETCH)) 11477 .addImm(1); // prefetch 2 lines behind PC 11478 11479 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11480 TII->get(AMDGPU::S_INST_PREFETCH)) 11481 .addImm(2); // prefetch 1 line behind PC 11482 } 11483 11484 return CacheLineAlign; 11485 } 11486 11487 LLVM_ATTRIBUTE_UNUSED 11488 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11489 assert(N->getOpcode() == ISD::CopyFromReg); 11490 do { 11491 // Follow the chain until we find an INLINEASM node. 11492 N = N->getOperand(0).getNode(); 11493 if (N->getOpcode() == ISD::INLINEASM || 11494 N->getOpcode() == ISD::INLINEASM_BR) 11495 return true; 11496 } while (N->getOpcode() == ISD::CopyFromReg); 11497 return false; 11498 } 11499 11500 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11501 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11502 { 11503 switch (N->getOpcode()) { 11504 case ISD::CopyFromReg: 11505 { 11506 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11507 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11508 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11509 Register Reg = R->getReg(); 11510 11511 // FIXME: Why does this need to consider isLiveIn? 11512 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11513 return !TRI->isSGPRReg(MRI, Reg); 11514 11515 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11516 return KDA->isDivergent(V); 11517 11518 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11519 return !TRI->isSGPRReg(MRI, Reg); 11520 } 11521 break; 11522 case ISD::LOAD: { 11523 const LoadSDNode *L = cast<LoadSDNode>(N); 11524 unsigned AS = L->getAddressSpace(); 11525 // A flat load may access private memory. 11526 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11527 } break; 11528 case ISD::CALLSEQ_END: 11529 return true; 11530 break; 11531 case ISD::INTRINSIC_WO_CHAIN: 11532 { 11533 11534 } 11535 return AMDGPU::isIntrinsicSourceOfDivergence( 11536 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11537 case ISD::INTRINSIC_W_CHAIN: 11538 return AMDGPU::isIntrinsicSourceOfDivergence( 11539 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11540 } 11541 return false; 11542 } 11543 11544 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11545 EVT VT) const { 11546 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11547 case MVT::f32: 11548 return hasFP32Denormals(DAG.getMachineFunction()); 11549 case MVT::f64: 11550 case MVT::f16: 11551 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11552 default: 11553 return false; 11554 } 11555 } 11556 11557 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11558 const SelectionDAG &DAG, 11559 bool SNaN, 11560 unsigned Depth) const { 11561 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11562 const MachineFunction &MF = DAG.getMachineFunction(); 11563 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11564 11565 if (Info->getMode().DX10Clamp) 11566 return true; // Clamped to 0. 11567 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11568 } 11569 11570 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11571 SNaN, Depth); 11572 } 11573 11574 TargetLowering::AtomicExpansionKind 11575 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11576 switch (RMW->getOperation()) { 11577 case AtomicRMWInst::FAdd: { 11578 Type *Ty = RMW->getType(); 11579 11580 // We don't have a way to support 16-bit atomics now, so just leave them 11581 // as-is. 11582 if (Ty->isHalfTy()) 11583 return AtomicExpansionKind::None; 11584 11585 if (!Ty->isFloatTy()) 11586 return AtomicExpansionKind::CmpXChg; 11587 11588 // TODO: Do have these for flat. Older targets also had them for buffers. 11589 unsigned AS = RMW->getPointerAddressSpace(); 11590 11591 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11592 return RMW->use_empty() ? AtomicExpansionKind::None : 11593 AtomicExpansionKind::CmpXChg; 11594 } 11595 11596 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11597 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11598 } 11599 default: 11600 break; 11601 } 11602 11603 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11604 } 11605 11606 const TargetRegisterClass * 11607 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11608 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11609 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11610 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11611 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11612 : &AMDGPU::SReg_32RegClass; 11613 if (!TRI->isSGPRClass(RC) && !isDivergent) 11614 return TRI->getEquivalentSGPRClass(RC); 11615 else if (TRI->isSGPRClass(RC) && isDivergent) 11616 return TRI->getEquivalentVGPRClass(RC); 11617 11618 return RC; 11619 } 11620 11621 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11622 // uniform values (as produced by the mask results of control flow intrinsics) 11623 // used outside of divergent blocks. The phi users need to also be treated as 11624 // always uniform. 11625 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11626 unsigned WaveSize) { 11627 // FIXME: We asssume we never cast the mask results of a control flow 11628 // intrinsic. 11629 // Early exit if the type won't be consistent as a compile time hack. 11630 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11631 if (!IT || IT->getBitWidth() != WaveSize) 11632 return false; 11633 11634 if (!isa<Instruction>(V)) 11635 return false; 11636 if (!Visited.insert(V).second) 11637 return false; 11638 bool Result = false; 11639 for (auto U : V->users()) { 11640 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11641 if (V == U->getOperand(1)) { 11642 switch (Intrinsic->getIntrinsicID()) { 11643 default: 11644 Result = false; 11645 break; 11646 case Intrinsic::amdgcn_if_break: 11647 case Intrinsic::amdgcn_if: 11648 case Intrinsic::amdgcn_else: 11649 Result = true; 11650 break; 11651 } 11652 } 11653 if (V == U->getOperand(0)) { 11654 switch (Intrinsic->getIntrinsicID()) { 11655 default: 11656 Result = false; 11657 break; 11658 case Intrinsic::amdgcn_end_cf: 11659 case Intrinsic::amdgcn_loop: 11660 Result = true; 11661 break; 11662 } 11663 } 11664 } else { 11665 Result = hasCFUser(U, Visited, WaveSize); 11666 } 11667 if (Result) 11668 break; 11669 } 11670 return Result; 11671 } 11672 11673 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11674 const Value *V) const { 11675 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11676 if (CI->isInlineAsm()) { 11677 // FIXME: This cannot give a correct answer. This should only trigger in 11678 // the case where inline asm returns mixed SGPR and VGPR results, used 11679 // outside the defining block. We don't have a specific result to 11680 // consider, so this assumes if any value is SGPR, the overall register 11681 // also needs to be SGPR. 11682 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11683 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11684 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11685 for (auto &TC : TargetConstraints) { 11686 if (TC.Type == InlineAsm::isOutput) { 11687 ComputeConstraintToUse(TC, SDValue()); 11688 unsigned AssignedReg; 11689 const TargetRegisterClass *RC; 11690 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11691 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11692 if (RC) { 11693 MachineRegisterInfo &MRI = MF.getRegInfo(); 11694 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11695 return true; 11696 else if (SIRI->isSGPRClass(RC)) 11697 return true; 11698 } 11699 } 11700 } 11701 } 11702 } 11703 SmallPtrSet<const Value *, 16> Visited; 11704 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11705 } 11706 11707 std::pair<int, MVT> 11708 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11709 Type *Ty) const { 11710 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11711 auto Size = DL.getTypeSizeInBits(Ty); 11712 // Maximum load or store can handle 8 dwords for scalar and 4 for 11713 // vector ALU. Let's assume anything above 8 dwords is expensive 11714 // even if legal. 11715 if (Size <= 256) 11716 return Cost; 11717 11718 Cost.first = (Size + 255) / 256; 11719 return Cost; 11720 } 11721