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 // Clamp modifier on add/sub 491 if (Subtarget->hasIntClamp()) { 492 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 493 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 494 } 495 496 if (Subtarget->hasAddNoCarry()) { 497 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 498 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 500 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 501 } 502 503 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 504 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 506 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 507 508 509 // These are really only legal for ieee_mode functions. We should be avoiding 510 // them for functions that don't have ieee_mode enabled, so just say they are 511 // legal. 512 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 513 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 515 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 516 517 518 if (Subtarget->haveRoundOpsF64()) { 519 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 520 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 521 setOperationAction(ISD::FRINT, MVT::f64, Legal); 522 } else { 523 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 524 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 525 setOperationAction(ISD::FRINT, MVT::f64, Custom); 526 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 527 } 528 529 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 530 531 setOperationAction(ISD::FSIN, MVT::f32, Custom); 532 setOperationAction(ISD::FCOS, MVT::f32, Custom); 533 setOperationAction(ISD::FDIV, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f64, Custom); 535 536 if (Subtarget->has16BitInsts()) { 537 setOperationAction(ISD::Constant, MVT::i16, Legal); 538 539 setOperationAction(ISD::SMIN, MVT::i16, Legal); 540 setOperationAction(ISD::SMAX, MVT::i16, Legal); 541 542 setOperationAction(ISD::UMIN, MVT::i16, Legal); 543 setOperationAction(ISD::UMAX, MVT::i16, Legal); 544 545 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 546 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 547 548 setOperationAction(ISD::ROTR, MVT::i16, Promote); 549 setOperationAction(ISD::ROTL, MVT::i16, Promote); 550 551 setOperationAction(ISD::SDIV, MVT::i16, Promote); 552 setOperationAction(ISD::UDIV, MVT::i16, Promote); 553 setOperationAction(ISD::SREM, MVT::i16, Promote); 554 setOperationAction(ISD::UREM, MVT::i16, Promote); 555 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 556 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 557 558 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 559 560 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 561 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 562 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 564 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 565 566 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 567 568 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 569 570 setOperationAction(ISD::LOAD, MVT::i16, Custom); 571 572 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 573 574 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 575 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 576 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 577 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 578 579 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 580 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 581 582 // F16 - Constant Actions. 583 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 584 585 // F16 - Load/Store Actions. 586 setOperationAction(ISD::LOAD, MVT::f16, Promote); 587 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 588 setOperationAction(ISD::STORE, MVT::f16, Promote); 589 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 590 591 // F16 - VOP1 Actions. 592 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 593 setOperationAction(ISD::FCOS, MVT::f16, Custom); 594 setOperationAction(ISD::FSIN, MVT::f16, Custom); 595 596 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 597 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 598 599 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 600 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 601 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 602 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::FROUND, MVT::f16, Custom); 604 605 // F16 - VOP2 Actions. 606 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 607 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 608 609 setOperationAction(ISD::FDIV, MVT::f16, Custom); 610 611 // F16 - VOP3 Actions. 612 setOperationAction(ISD::FMA, MVT::f16, Legal); 613 if (STI.hasMadF16()) 614 setOperationAction(ISD::FMAD, MVT::f16, Legal); 615 616 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 617 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 618 switch (Op) { 619 case ISD::LOAD: 620 case ISD::STORE: 621 case ISD::BUILD_VECTOR: 622 case ISD::BITCAST: 623 case ISD::EXTRACT_VECTOR_ELT: 624 case ISD::INSERT_VECTOR_ELT: 625 case ISD::INSERT_SUBVECTOR: 626 case ISD::EXTRACT_SUBVECTOR: 627 case ISD::SCALAR_TO_VECTOR: 628 break; 629 case ISD::CONCAT_VECTORS: 630 setOperationAction(Op, VT, Custom); 631 break; 632 default: 633 setOperationAction(Op, VT, Expand); 634 break; 635 } 636 } 637 } 638 639 // v_perm_b32 can handle either of these. 640 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 641 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 643 644 // XXX - Do these do anything? Vector constants turn into build_vector. 645 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 646 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 647 648 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 649 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 650 651 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 652 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 653 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 654 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 655 656 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 659 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 660 661 setOperationAction(ISD::AND, MVT::v2i16, Promote); 662 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 663 setOperationAction(ISD::OR, MVT::v2i16, Promote); 664 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 665 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 666 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 667 668 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 669 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 670 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 671 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 672 673 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 674 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 675 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 676 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 677 678 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 679 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 682 683 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 684 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 686 687 if (!Subtarget->hasVOP3PInsts()) { 688 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 690 } 691 692 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 693 // This isn't really legal, but this avoids the legalizer unrolling it (and 694 // allows matching fneg (fabs x) patterns) 695 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 696 697 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 698 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 700 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 701 702 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 703 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 704 705 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 706 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 707 } 708 709 if (Subtarget->hasVOP3PInsts()) { 710 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 711 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 712 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 713 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 716 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 717 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 719 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 720 721 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 722 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 725 726 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 727 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 729 730 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 731 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 732 733 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 734 735 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 737 738 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 740 741 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 742 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 744 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 745 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 746 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 747 748 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 749 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 750 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 752 753 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 754 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 757 758 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 759 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 761 762 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 763 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 764 765 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 766 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 768 769 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 770 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 772 } 773 774 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 775 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 776 777 if (Subtarget->has16BitInsts()) { 778 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 779 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 780 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 781 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 782 } else { 783 // Legalization hack. 784 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 785 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 786 787 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 788 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 789 } 790 791 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 792 setOperationAction(ISD::SELECT, VT, Custom); 793 } 794 795 setOperationAction(ISD::SMULO, MVT::i64, Custom); 796 setOperationAction(ISD::UMULO, MVT::i64, Custom); 797 798 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 799 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 801 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 802 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 803 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 805 806 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 807 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 808 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 809 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 810 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 811 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 812 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 813 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 815 816 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 817 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 818 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 819 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 820 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 821 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 822 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 823 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 824 825 setTargetDAGCombine(ISD::ADD); 826 setTargetDAGCombine(ISD::ADDCARRY); 827 setTargetDAGCombine(ISD::SUB); 828 setTargetDAGCombine(ISD::SUBCARRY); 829 setTargetDAGCombine(ISD::FADD); 830 setTargetDAGCombine(ISD::FSUB); 831 setTargetDAGCombine(ISD::FMINNUM); 832 setTargetDAGCombine(ISD::FMAXNUM); 833 setTargetDAGCombine(ISD::FMINNUM_IEEE); 834 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 835 setTargetDAGCombine(ISD::FMA); 836 setTargetDAGCombine(ISD::SMIN); 837 setTargetDAGCombine(ISD::SMAX); 838 setTargetDAGCombine(ISD::UMIN); 839 setTargetDAGCombine(ISD::UMAX); 840 setTargetDAGCombine(ISD::SETCC); 841 setTargetDAGCombine(ISD::AND); 842 setTargetDAGCombine(ISD::OR); 843 setTargetDAGCombine(ISD::XOR); 844 setTargetDAGCombine(ISD::SINT_TO_FP); 845 setTargetDAGCombine(ISD::UINT_TO_FP); 846 setTargetDAGCombine(ISD::FCANONICALIZE); 847 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 848 setTargetDAGCombine(ISD::ZERO_EXTEND); 849 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 850 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 851 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 852 853 // All memory operations. Some folding on the pointer operand is done to help 854 // matching the constant offsets in the addressing modes. 855 setTargetDAGCombine(ISD::LOAD); 856 setTargetDAGCombine(ISD::STORE); 857 setTargetDAGCombine(ISD::ATOMIC_LOAD); 858 setTargetDAGCombine(ISD::ATOMIC_STORE); 859 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 860 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 861 setTargetDAGCombine(ISD::ATOMIC_SWAP); 862 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 863 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 864 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 865 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 866 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 867 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 868 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 870 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 871 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 872 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 873 874 // FIXME: In other contexts we pretend this is a per-function property. 875 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 876 877 setSchedulingPreference(Sched::RegPressure); 878 } 879 880 const GCNSubtarget *SITargetLowering::getSubtarget() const { 881 return Subtarget; 882 } 883 884 //===----------------------------------------------------------------------===// 885 // TargetLowering queries 886 //===----------------------------------------------------------------------===// 887 888 // v_mad_mix* support a conversion from f16 to f32. 889 // 890 // There is only one special case when denormals are enabled we don't currently, 891 // where this is OK to use. 892 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 893 EVT DestVT, EVT SrcVT) const { 894 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 895 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 896 DestVT.getScalarType() == MVT::f32 && 897 SrcVT.getScalarType() == MVT::f16 && 898 // TODO: This probably only requires no input flushing? 899 !hasFP32Denormals(DAG.getMachineFunction()); 900 } 901 902 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 903 // SI has some legal vector types, but no legal vector operations. Say no 904 // shuffles are legal in order to prefer scalarizing some vector operations. 905 return false; 906 } 907 908 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 909 CallingConv::ID CC, 910 EVT VT) const { 911 if (CC == CallingConv::AMDGPU_KERNEL) 912 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 913 914 if (VT.isVector()) { 915 EVT ScalarVT = VT.getScalarType(); 916 unsigned Size = ScalarVT.getSizeInBits(); 917 if (Size == 32) 918 return ScalarVT.getSimpleVT(); 919 920 if (Size > 32) 921 return MVT::i32; 922 923 if (Size == 16 && Subtarget->has16BitInsts()) 924 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 925 } else if (VT.getSizeInBits() > 32) 926 return MVT::i32; 927 928 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 929 } 930 931 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 932 CallingConv::ID CC, 933 EVT VT) const { 934 if (CC == CallingConv::AMDGPU_KERNEL) 935 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 936 937 if (VT.isVector()) { 938 unsigned NumElts = VT.getVectorNumElements(); 939 EVT ScalarVT = VT.getScalarType(); 940 unsigned Size = ScalarVT.getSizeInBits(); 941 942 if (Size == 32) 943 return NumElts; 944 945 if (Size > 32) 946 return NumElts * ((Size + 31) / 32); 947 948 if (Size == 16 && Subtarget->has16BitInsts()) 949 return (NumElts + 1) / 2; 950 } else if (VT.getSizeInBits() > 32) 951 return (VT.getSizeInBits() + 31) / 32; 952 953 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 954 } 955 956 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 957 LLVMContext &Context, CallingConv::ID CC, 958 EVT VT, EVT &IntermediateVT, 959 unsigned &NumIntermediates, MVT &RegisterVT) const { 960 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 961 unsigned NumElts = VT.getVectorNumElements(); 962 EVT ScalarVT = VT.getScalarType(); 963 unsigned Size = ScalarVT.getSizeInBits(); 964 if (Size == 32) { 965 RegisterVT = ScalarVT.getSimpleVT(); 966 IntermediateVT = RegisterVT; 967 NumIntermediates = NumElts; 968 return NumIntermediates; 969 } 970 971 if (Size > 32) { 972 RegisterVT = MVT::i32; 973 IntermediateVT = RegisterVT; 974 NumIntermediates = NumElts * ((Size + 31) / 32); 975 return NumIntermediates; 976 } 977 978 // FIXME: We should fix the ABI to be the same on targets without 16-bit 979 // support, but unless we can properly handle 3-vectors, it will be still be 980 // inconsistent. 981 if (Size == 16 && Subtarget->has16BitInsts()) { 982 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 983 IntermediateVT = RegisterVT; 984 NumIntermediates = (NumElts + 1) / 2; 985 return NumIntermediates; 986 } 987 } 988 989 return TargetLowering::getVectorTypeBreakdownForCallingConv( 990 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 991 } 992 993 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 994 assert(DMaskLanes != 0); 995 996 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 997 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 998 return EVT::getVectorVT(Ty->getContext(), 999 EVT::getEVT(VT->getElementType()), 1000 NumElts); 1001 } 1002 1003 return EVT::getEVT(Ty); 1004 } 1005 1006 // Peek through TFE struct returns to only use the data size. 1007 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1008 auto *ST = dyn_cast<StructType>(Ty); 1009 if (!ST) 1010 return memVTFromImageData(Ty, DMaskLanes); 1011 1012 // Some intrinsics return an aggregate type - special case to work out the 1013 // correct memVT. 1014 // 1015 // Only limited forms of aggregate type currently expected. 1016 if (ST->getNumContainedTypes() != 2 || 1017 !ST->getContainedType(1)->isIntegerTy(32)) 1018 return EVT(); 1019 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1020 } 1021 1022 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1023 const CallInst &CI, 1024 MachineFunction &MF, 1025 unsigned IntrID) const { 1026 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1027 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1028 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1029 (Intrinsic::ID)IntrID); 1030 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1031 return false; 1032 1033 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1034 1035 if (RsrcIntr->IsImage) { 1036 Info.ptrVal = MFI->getImagePSV( 1037 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1038 CI.getArgOperand(RsrcIntr->RsrcArg)); 1039 Info.align.reset(); 1040 } else { 1041 Info.ptrVal = MFI->getBufferPSV( 1042 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1043 CI.getArgOperand(RsrcIntr->RsrcArg)); 1044 } 1045 1046 Info.flags = MachineMemOperand::MODereferenceable; 1047 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1048 unsigned DMaskLanes = 4; 1049 1050 if (RsrcIntr->IsImage) { 1051 const AMDGPU::ImageDimIntrinsicInfo *Intr 1052 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1053 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1054 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1055 1056 if (!BaseOpcode->Gather4) { 1057 // If this isn't a gather, we may have excess loaded elements in the 1058 // IR type. Check the dmask for the real number of elements loaded. 1059 unsigned DMask 1060 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1061 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1062 } 1063 1064 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1065 } else 1066 Info.memVT = EVT::getEVT(CI.getType()); 1067 1068 // FIXME: What does alignment mean for an image? 1069 Info.opc = ISD::INTRINSIC_W_CHAIN; 1070 Info.flags |= MachineMemOperand::MOLoad; 1071 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1072 Info.opc = ISD::INTRINSIC_VOID; 1073 1074 Type *DataTy = CI.getArgOperand(0)->getType(); 1075 if (RsrcIntr->IsImage) { 1076 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1077 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1078 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1079 } else 1080 Info.memVT = EVT::getEVT(DataTy); 1081 1082 Info.flags |= MachineMemOperand::MOStore; 1083 } else { 1084 // Atomic 1085 Info.opc = ISD::INTRINSIC_W_CHAIN; 1086 Info.memVT = MVT::getVT(CI.getType()); 1087 Info.flags = MachineMemOperand::MOLoad | 1088 MachineMemOperand::MOStore | 1089 MachineMemOperand::MODereferenceable; 1090 1091 // XXX - Should this be volatile without known ordering? 1092 Info.flags |= MachineMemOperand::MOVolatile; 1093 } 1094 return true; 1095 } 1096 1097 switch (IntrID) { 1098 case Intrinsic::amdgcn_atomic_inc: 1099 case Intrinsic::amdgcn_atomic_dec: 1100 case Intrinsic::amdgcn_ds_ordered_add: 1101 case Intrinsic::amdgcn_ds_ordered_swap: 1102 case Intrinsic::amdgcn_ds_fadd: 1103 case Intrinsic::amdgcn_ds_fmin: 1104 case Intrinsic::amdgcn_ds_fmax: { 1105 Info.opc = ISD::INTRINSIC_W_CHAIN; 1106 Info.memVT = MVT::getVT(CI.getType()); 1107 Info.ptrVal = CI.getOperand(0); 1108 Info.align.reset(); 1109 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1110 1111 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1112 if (!Vol->isZero()) 1113 Info.flags |= MachineMemOperand::MOVolatile; 1114 1115 return true; 1116 } 1117 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1118 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1119 1120 Info.opc = ISD::INTRINSIC_VOID; 1121 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1122 Info.ptrVal = MFI->getBufferPSV( 1123 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1124 CI.getArgOperand(1)); 1125 Info.align.reset(); 1126 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1127 1128 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1129 if (!Vol || !Vol->isZero()) 1130 Info.flags |= MachineMemOperand::MOVolatile; 1131 1132 return true; 1133 } 1134 case Intrinsic::amdgcn_global_atomic_fadd: { 1135 Info.opc = ISD::INTRINSIC_VOID; 1136 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1137 ->getPointerElementType()); 1138 Info.ptrVal = CI.getOperand(0); 1139 Info.align.reset(); 1140 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1141 1142 return true; 1143 } 1144 case Intrinsic::amdgcn_ds_append: 1145 case Intrinsic::amdgcn_ds_consume: { 1146 Info.opc = ISD::INTRINSIC_W_CHAIN; 1147 Info.memVT = MVT::getVT(CI.getType()); 1148 Info.ptrVal = CI.getOperand(0); 1149 Info.align.reset(); 1150 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1151 1152 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1153 if (!Vol->isZero()) 1154 Info.flags |= MachineMemOperand::MOVolatile; 1155 1156 return true; 1157 } 1158 case Intrinsic::amdgcn_global_atomic_csub: { 1159 Info.opc = ISD::INTRINSIC_W_CHAIN; 1160 Info.memVT = MVT::getVT(CI.getType()); 1161 Info.ptrVal = CI.getOperand(0); 1162 Info.align.reset(); 1163 Info.flags = MachineMemOperand::MOLoad | 1164 MachineMemOperand::MOStore | 1165 MachineMemOperand::MOVolatile; 1166 return true; 1167 } 1168 case Intrinsic::amdgcn_ds_gws_init: 1169 case Intrinsic::amdgcn_ds_gws_barrier: 1170 case Intrinsic::amdgcn_ds_gws_sema_v: 1171 case Intrinsic::amdgcn_ds_gws_sema_br: 1172 case Intrinsic::amdgcn_ds_gws_sema_p: 1173 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1174 Info.opc = ISD::INTRINSIC_VOID; 1175 1176 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1177 Info.ptrVal = 1178 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1179 1180 // This is an abstract access, but we need to specify a type and size. 1181 Info.memVT = MVT::i32; 1182 Info.size = 4; 1183 Info.align = Align(4); 1184 1185 Info.flags = MachineMemOperand::MOStore; 1186 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1187 Info.flags = MachineMemOperand::MOLoad; 1188 return true; 1189 } 1190 default: 1191 return false; 1192 } 1193 } 1194 1195 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1196 SmallVectorImpl<Value*> &Ops, 1197 Type *&AccessTy) const { 1198 switch (II->getIntrinsicID()) { 1199 case Intrinsic::amdgcn_atomic_inc: 1200 case Intrinsic::amdgcn_atomic_dec: 1201 case Intrinsic::amdgcn_ds_ordered_add: 1202 case Intrinsic::amdgcn_ds_ordered_swap: 1203 case Intrinsic::amdgcn_ds_append: 1204 case Intrinsic::amdgcn_ds_consume: 1205 case Intrinsic::amdgcn_ds_fadd: 1206 case Intrinsic::amdgcn_ds_fmin: 1207 case Intrinsic::amdgcn_ds_fmax: 1208 case Intrinsic::amdgcn_global_atomic_fadd: 1209 case Intrinsic::amdgcn_global_atomic_csub: { 1210 Value *Ptr = II->getArgOperand(0); 1211 AccessTy = II->getType(); 1212 Ops.push_back(Ptr); 1213 return true; 1214 } 1215 default: 1216 return false; 1217 } 1218 } 1219 1220 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1221 if (!Subtarget->hasFlatInstOffsets()) { 1222 // Flat instructions do not have offsets, and only have the register 1223 // address. 1224 return AM.BaseOffs == 0 && AM.Scale == 0; 1225 } 1226 1227 return AM.Scale == 0 && 1228 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1229 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1230 /*Signed=*/false)); 1231 } 1232 1233 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1234 if (Subtarget->hasFlatGlobalInsts()) 1235 return AM.Scale == 0 && 1236 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1237 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1238 /*Signed=*/true)); 1239 1240 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1241 // Assume the we will use FLAT for all global memory accesses 1242 // on VI. 1243 // FIXME: This assumption is currently wrong. On VI we still use 1244 // MUBUF instructions for the r + i addressing mode. As currently 1245 // implemented, the MUBUF instructions only work on buffer < 4GB. 1246 // It may be possible to support > 4GB buffers with MUBUF instructions, 1247 // by setting the stride value in the resource descriptor which would 1248 // increase the size limit to (stride * 4GB). However, this is risky, 1249 // because it has never been validated. 1250 return isLegalFlatAddressingMode(AM); 1251 } 1252 1253 return isLegalMUBUFAddressingMode(AM); 1254 } 1255 1256 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1257 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1258 // additionally can do r + r + i with addr64. 32-bit has more addressing 1259 // mode options. Depending on the resource constant, it can also do 1260 // (i64 r0) + (i32 r1) * (i14 i). 1261 // 1262 // Private arrays end up using a scratch buffer most of the time, so also 1263 // assume those use MUBUF instructions. Scratch loads / stores are currently 1264 // implemented as mubuf instructions with offen bit set, so slightly 1265 // different than the normal addr64. 1266 if (!isUInt<12>(AM.BaseOffs)) 1267 return false; 1268 1269 // FIXME: Since we can split immediate into soffset and immediate offset, 1270 // would it make sense to allow any immediate? 1271 1272 switch (AM.Scale) { 1273 case 0: // r + i or just i, depending on HasBaseReg. 1274 return true; 1275 case 1: 1276 return true; // We have r + r or r + i. 1277 case 2: 1278 if (AM.HasBaseReg) { 1279 // Reject 2 * r + r. 1280 return false; 1281 } 1282 1283 // Allow 2 * r as r + r 1284 // Or 2 * r + i is allowed as r + r + i. 1285 return true; 1286 default: // Don't allow n * r 1287 return false; 1288 } 1289 } 1290 1291 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1292 const AddrMode &AM, Type *Ty, 1293 unsigned AS, Instruction *I) const { 1294 // No global is ever allowed as a base. 1295 if (AM.BaseGV) 1296 return false; 1297 1298 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1299 return isLegalGlobalAddressingMode(AM); 1300 1301 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1302 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1303 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1304 // If the offset isn't a multiple of 4, it probably isn't going to be 1305 // correctly aligned. 1306 // FIXME: Can we get the real alignment here? 1307 if (AM.BaseOffs % 4 != 0) 1308 return isLegalMUBUFAddressingMode(AM); 1309 1310 // There are no SMRD extloads, so if we have to do a small type access we 1311 // will use a MUBUF load. 1312 // FIXME?: We also need to do this if unaligned, but we don't know the 1313 // alignment here. 1314 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1315 return isLegalGlobalAddressingMode(AM); 1316 1317 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1318 // SMRD instructions have an 8-bit, dword offset on SI. 1319 if (!isUInt<8>(AM.BaseOffs / 4)) 1320 return false; 1321 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1322 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1323 // in 8-bits, it can use a smaller encoding. 1324 if (!isUInt<32>(AM.BaseOffs / 4)) 1325 return false; 1326 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1327 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1328 if (!isUInt<20>(AM.BaseOffs)) 1329 return false; 1330 } else 1331 llvm_unreachable("unhandled generation"); 1332 1333 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1334 return true; 1335 1336 if (AM.Scale == 1 && AM.HasBaseReg) 1337 return true; 1338 1339 return false; 1340 1341 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1342 return isLegalMUBUFAddressingMode(AM); 1343 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1344 AS == AMDGPUAS::REGION_ADDRESS) { 1345 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1346 // field. 1347 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1348 // an 8-bit dword offset but we don't know the alignment here. 1349 if (!isUInt<16>(AM.BaseOffs)) 1350 return false; 1351 1352 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1353 return true; 1354 1355 if (AM.Scale == 1 && AM.HasBaseReg) 1356 return true; 1357 1358 return false; 1359 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1360 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1361 // For an unknown address space, this usually means that this is for some 1362 // reason being used for pure arithmetic, and not based on some addressing 1363 // computation. We don't have instructions that compute pointers with any 1364 // addressing modes, so treat them as having no offset like flat 1365 // instructions. 1366 return isLegalFlatAddressingMode(AM); 1367 } 1368 1369 // Assume a user alias of global for unknown address spaces. 1370 return isLegalGlobalAddressingMode(AM); 1371 } 1372 1373 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1374 const SelectionDAG &DAG) const { 1375 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1376 return (MemVT.getSizeInBits() <= 4 * 32); 1377 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1378 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1379 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1380 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1381 return (MemVT.getSizeInBits() <= 2 * 32); 1382 } 1383 return true; 1384 } 1385 1386 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1387 unsigned Size, unsigned AddrSpace, unsigned Align, 1388 MachineMemOperand::Flags Flags, bool *IsFast) const { 1389 if (IsFast) 1390 *IsFast = false; 1391 1392 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1393 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1394 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1395 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1396 // with adjacent offsets. 1397 bool AlignedBy4 = (Align % 4 == 0); 1398 if (IsFast) 1399 *IsFast = AlignedBy4; 1400 1401 return AlignedBy4; 1402 } 1403 1404 // FIXME: We have to be conservative here and assume that flat operations 1405 // will access scratch. If we had access to the IR function, then we 1406 // could determine if any private memory was used in the function. 1407 if (!Subtarget->hasUnalignedScratchAccess() && 1408 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1409 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1410 bool AlignedBy4 = Align >= 4; 1411 if (IsFast) 1412 *IsFast = AlignedBy4; 1413 1414 return AlignedBy4; 1415 } 1416 1417 if (Subtarget->hasUnalignedBufferAccess()) { 1418 // If we have an uniform constant load, it still requires using a slow 1419 // buffer instruction if unaligned. 1420 if (IsFast) { 1421 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1422 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1423 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1424 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1425 Align >= 4 : Align != 2; 1426 } 1427 1428 return true; 1429 } 1430 1431 // Smaller than dword value must be aligned. 1432 if (Size < 32) 1433 return false; 1434 1435 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1436 // byte-address are ignored, thus forcing Dword alignment. 1437 // This applies to private, global, and constant memory. 1438 if (IsFast) 1439 *IsFast = true; 1440 1441 return Size >= 32 && Align >= 4; 1442 } 1443 1444 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1445 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1446 bool *IsFast) const { 1447 if (IsFast) 1448 *IsFast = false; 1449 1450 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1451 // which isn't a simple VT. 1452 // Until MVT is extended to handle this, simply check for the size and 1453 // rely on the condition below: allow accesses if the size is a multiple of 4. 1454 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1455 VT.getStoreSize() > 16)) { 1456 return false; 1457 } 1458 1459 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1460 Align, Flags, IsFast); 1461 } 1462 1463 EVT SITargetLowering::getOptimalMemOpType( 1464 const MemOp &Op, const AttributeList &FuncAttributes) const { 1465 // FIXME: Should account for address space here. 1466 1467 // The default fallback uses the private pointer size as a guess for a type to 1468 // use. Make sure we switch these to 64-bit accesses. 1469 1470 if (Op.size() >= 16 && 1471 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1472 return MVT::v4i32; 1473 1474 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1475 return MVT::v2i32; 1476 1477 // Use the default. 1478 return MVT::Other; 1479 } 1480 1481 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1482 const MemSDNode *MemNode = cast<MemSDNode>(N); 1483 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1484 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1485 return I && I->getMetadata("amdgpu.noclobber"); 1486 } 1487 1488 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1489 unsigned DestAS) const { 1490 // Flat -> private/local is a simple truncate. 1491 // Flat -> global is no-op 1492 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1493 return true; 1494 1495 const GCNTargetMachine &TM = 1496 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1497 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1498 } 1499 1500 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1501 const MemSDNode *MemNode = cast<MemSDNode>(N); 1502 1503 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1504 } 1505 1506 TargetLoweringBase::LegalizeTypeAction 1507 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1508 int NumElts = VT.getVectorNumElements(); 1509 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1510 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1511 return TargetLoweringBase::getPreferredVectorAction(VT); 1512 } 1513 1514 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1515 Type *Ty) const { 1516 // FIXME: Could be smarter if called for vector constants. 1517 return true; 1518 } 1519 1520 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1521 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1522 switch (Op) { 1523 case ISD::LOAD: 1524 case ISD::STORE: 1525 1526 // These operations are done with 32-bit instructions anyway. 1527 case ISD::AND: 1528 case ISD::OR: 1529 case ISD::XOR: 1530 case ISD::SELECT: 1531 // TODO: Extensions? 1532 return true; 1533 default: 1534 return false; 1535 } 1536 } 1537 1538 // SimplifySetCC uses this function to determine whether or not it should 1539 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1540 if (VT == MVT::i1 && Op == ISD::SETCC) 1541 return false; 1542 1543 return TargetLowering::isTypeDesirableForOp(Op, VT); 1544 } 1545 1546 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1547 const SDLoc &SL, 1548 SDValue Chain, 1549 uint64_t Offset) const { 1550 const DataLayout &DL = DAG.getDataLayout(); 1551 MachineFunction &MF = DAG.getMachineFunction(); 1552 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1553 1554 const ArgDescriptor *InputPtrReg; 1555 const TargetRegisterClass *RC; 1556 LLT ArgTy; 1557 1558 std::tie(InputPtrReg, RC, ArgTy) = 1559 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1560 1561 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1562 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1563 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1564 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1565 1566 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1567 } 1568 1569 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1570 const SDLoc &SL) const { 1571 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1572 FIRST_IMPLICIT); 1573 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1574 } 1575 1576 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1577 const SDLoc &SL, SDValue Val, 1578 bool Signed, 1579 const ISD::InputArg *Arg) const { 1580 // First, if it is a widened vector, narrow it. 1581 if (VT.isVector() && 1582 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1583 EVT NarrowedVT = 1584 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1585 VT.getVectorNumElements()); 1586 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1587 DAG.getConstant(0, SL, MVT::i32)); 1588 } 1589 1590 // Then convert the vector elements or scalar value. 1591 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1592 VT.bitsLT(MemVT)) { 1593 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1594 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1595 } 1596 1597 if (MemVT.isFloatingPoint()) 1598 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1599 else if (Signed) 1600 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1601 else 1602 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1603 1604 return Val; 1605 } 1606 1607 SDValue SITargetLowering::lowerKernargMemParameter( 1608 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1609 uint64_t Offset, Align Alignment, bool Signed, 1610 const ISD::InputArg *Arg) const { 1611 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1612 1613 // Try to avoid using an extload by loading earlier than the argument address, 1614 // and extracting the relevant bits. The load should hopefully be merged with 1615 // the previous argument. 1616 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1617 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1618 int64_t AlignDownOffset = alignDown(Offset, 4); 1619 int64_t OffsetDiff = Offset - AlignDownOffset; 1620 1621 EVT IntVT = MemVT.changeTypeToInteger(); 1622 1623 // TODO: If we passed in the base kernel offset we could have a better 1624 // alignment than 4, but we don't really need it. 1625 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1626 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1627 MachineMemOperand::MODereferenceable | 1628 MachineMemOperand::MOInvariant); 1629 1630 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1631 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1632 1633 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1634 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1635 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1636 1637 1638 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1639 } 1640 1641 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1642 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1643 MachineMemOperand::MODereferenceable | 1644 MachineMemOperand::MOInvariant); 1645 1646 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1647 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1648 } 1649 1650 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1651 const SDLoc &SL, SDValue Chain, 1652 const ISD::InputArg &Arg) const { 1653 MachineFunction &MF = DAG.getMachineFunction(); 1654 MachineFrameInfo &MFI = MF.getFrameInfo(); 1655 1656 if (Arg.Flags.isByVal()) { 1657 unsigned Size = Arg.Flags.getByValSize(); 1658 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1659 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1660 } 1661 1662 unsigned ArgOffset = VA.getLocMemOffset(); 1663 unsigned ArgSize = VA.getValVT().getStoreSize(); 1664 1665 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1666 1667 // Create load nodes to retrieve arguments from the stack. 1668 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1669 SDValue ArgValue; 1670 1671 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1672 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1673 MVT MemVT = VA.getValVT(); 1674 1675 switch (VA.getLocInfo()) { 1676 default: 1677 break; 1678 case CCValAssign::BCvt: 1679 MemVT = VA.getLocVT(); 1680 break; 1681 case CCValAssign::SExt: 1682 ExtType = ISD::SEXTLOAD; 1683 break; 1684 case CCValAssign::ZExt: 1685 ExtType = ISD::ZEXTLOAD; 1686 break; 1687 case CCValAssign::AExt: 1688 ExtType = ISD::EXTLOAD; 1689 break; 1690 } 1691 1692 ArgValue = DAG.getExtLoad( 1693 ExtType, SL, VA.getLocVT(), Chain, FIN, 1694 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1695 MemVT); 1696 return ArgValue; 1697 } 1698 1699 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1700 const SIMachineFunctionInfo &MFI, 1701 EVT VT, 1702 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1703 const ArgDescriptor *Reg; 1704 const TargetRegisterClass *RC; 1705 LLT Ty; 1706 1707 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1708 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1709 } 1710 1711 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1712 CallingConv::ID CallConv, 1713 ArrayRef<ISD::InputArg> Ins, 1714 BitVector &Skipped, 1715 FunctionType *FType, 1716 SIMachineFunctionInfo *Info) { 1717 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1718 const ISD::InputArg *Arg = &Ins[I]; 1719 1720 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1721 "vector type argument should have been split"); 1722 1723 // First check if it's a PS input addr. 1724 if (CallConv == CallingConv::AMDGPU_PS && 1725 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1726 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1727 1728 // Inconveniently only the first part of the split is marked as isSplit, 1729 // so skip to the end. We only want to increment PSInputNum once for the 1730 // entire split argument. 1731 if (Arg->Flags.isSplit()) { 1732 while (!Arg->Flags.isSplitEnd()) { 1733 assert((!Arg->VT.isVector() || 1734 Arg->VT.getScalarSizeInBits() == 16) && 1735 "unexpected vector split in ps argument type"); 1736 if (!SkipArg) 1737 Splits.push_back(*Arg); 1738 Arg = &Ins[++I]; 1739 } 1740 } 1741 1742 if (SkipArg) { 1743 // We can safely skip PS inputs. 1744 Skipped.set(Arg->getOrigArgIndex()); 1745 ++PSInputNum; 1746 continue; 1747 } 1748 1749 Info->markPSInputAllocated(PSInputNum); 1750 if (Arg->Used) 1751 Info->markPSInputEnabled(PSInputNum); 1752 1753 ++PSInputNum; 1754 } 1755 1756 Splits.push_back(*Arg); 1757 } 1758 } 1759 1760 // Allocate special inputs passed in VGPRs. 1761 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1762 MachineFunction &MF, 1763 const SIRegisterInfo &TRI, 1764 SIMachineFunctionInfo &Info) const { 1765 const LLT S32 = LLT::scalar(32); 1766 MachineRegisterInfo &MRI = MF.getRegInfo(); 1767 1768 if (Info.hasWorkItemIDX()) { 1769 Register Reg = AMDGPU::VGPR0; 1770 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1771 1772 CCInfo.AllocateReg(Reg); 1773 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1774 } 1775 1776 if (Info.hasWorkItemIDY()) { 1777 Register Reg = AMDGPU::VGPR1; 1778 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1779 1780 CCInfo.AllocateReg(Reg); 1781 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1782 } 1783 1784 if (Info.hasWorkItemIDZ()) { 1785 Register Reg = AMDGPU::VGPR2; 1786 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1787 1788 CCInfo.AllocateReg(Reg); 1789 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1790 } 1791 } 1792 1793 // Try to allocate a VGPR at the end of the argument list, or if no argument 1794 // VGPRs are left allocating a stack slot. 1795 // If \p Mask is is given it indicates bitfield position in the register. 1796 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1797 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1798 ArgDescriptor Arg = ArgDescriptor()) { 1799 if (Arg.isSet()) 1800 return ArgDescriptor::createArg(Arg, Mask); 1801 1802 ArrayRef<MCPhysReg> ArgVGPRs 1803 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1804 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1805 if (RegIdx == ArgVGPRs.size()) { 1806 // Spill to stack required. 1807 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1808 1809 return ArgDescriptor::createStack(Offset, Mask); 1810 } 1811 1812 unsigned Reg = ArgVGPRs[RegIdx]; 1813 Reg = CCInfo.AllocateReg(Reg); 1814 assert(Reg != AMDGPU::NoRegister); 1815 1816 MachineFunction &MF = CCInfo.getMachineFunction(); 1817 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1818 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1819 return ArgDescriptor::createRegister(Reg, Mask); 1820 } 1821 1822 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1823 const TargetRegisterClass *RC, 1824 unsigned NumArgRegs) { 1825 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1826 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1827 if (RegIdx == ArgSGPRs.size()) 1828 report_fatal_error("ran out of SGPRs for arguments"); 1829 1830 unsigned Reg = ArgSGPRs[RegIdx]; 1831 Reg = CCInfo.AllocateReg(Reg); 1832 assert(Reg != AMDGPU::NoRegister); 1833 1834 MachineFunction &MF = CCInfo.getMachineFunction(); 1835 MF.addLiveIn(Reg, RC); 1836 return ArgDescriptor::createRegister(Reg); 1837 } 1838 1839 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1840 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1841 } 1842 1843 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1844 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1845 } 1846 1847 /// Allocate implicit function VGPR arguments at the end of allocated user 1848 /// arguments. 1849 void SITargetLowering::allocateSpecialInputVGPRs( 1850 CCState &CCInfo, MachineFunction &MF, 1851 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1852 const unsigned Mask = 0x3ff; 1853 ArgDescriptor Arg; 1854 1855 if (Info.hasWorkItemIDX()) { 1856 Arg = allocateVGPR32Input(CCInfo, Mask); 1857 Info.setWorkItemIDX(Arg); 1858 } 1859 1860 if (Info.hasWorkItemIDY()) { 1861 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1862 Info.setWorkItemIDY(Arg); 1863 } 1864 1865 if (Info.hasWorkItemIDZ()) 1866 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1867 } 1868 1869 /// Allocate implicit function VGPR arguments in fixed registers. 1870 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1871 CCState &CCInfo, MachineFunction &MF, 1872 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1873 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1874 if (!Reg) 1875 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1876 1877 const unsigned Mask = 0x3ff; 1878 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1879 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1880 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1881 } 1882 1883 void SITargetLowering::allocateSpecialInputSGPRs( 1884 CCState &CCInfo, 1885 MachineFunction &MF, 1886 const SIRegisterInfo &TRI, 1887 SIMachineFunctionInfo &Info) const { 1888 auto &ArgInfo = Info.getArgInfo(); 1889 1890 // TODO: Unify handling with private memory pointers. 1891 1892 if (Info.hasDispatchPtr()) 1893 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1894 1895 if (Info.hasQueuePtr()) 1896 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1897 1898 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1899 // constant offset from the kernarg segment. 1900 if (Info.hasImplicitArgPtr()) 1901 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1902 1903 if (Info.hasDispatchID()) 1904 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1905 1906 // flat_scratch_init is not applicable for non-kernel functions. 1907 1908 if (Info.hasWorkGroupIDX()) 1909 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1910 1911 if (Info.hasWorkGroupIDY()) 1912 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1913 1914 if (Info.hasWorkGroupIDZ()) 1915 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1916 } 1917 1918 // Allocate special inputs passed in user SGPRs. 1919 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1920 MachineFunction &MF, 1921 const SIRegisterInfo &TRI, 1922 SIMachineFunctionInfo &Info) const { 1923 if (Info.hasImplicitBufferPtr()) { 1924 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1925 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1926 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1927 } 1928 1929 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1930 if (Info.hasPrivateSegmentBuffer()) { 1931 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1932 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1933 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1934 } 1935 1936 if (Info.hasDispatchPtr()) { 1937 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1938 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1939 CCInfo.AllocateReg(DispatchPtrReg); 1940 } 1941 1942 if (Info.hasQueuePtr()) { 1943 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1944 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1945 CCInfo.AllocateReg(QueuePtrReg); 1946 } 1947 1948 if (Info.hasKernargSegmentPtr()) { 1949 MachineRegisterInfo &MRI = MF.getRegInfo(); 1950 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1951 CCInfo.AllocateReg(InputPtrReg); 1952 1953 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1954 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1955 } 1956 1957 if (Info.hasDispatchID()) { 1958 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1959 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1960 CCInfo.AllocateReg(DispatchIDReg); 1961 } 1962 1963 if (Info.hasFlatScratchInit()) { 1964 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1965 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1966 CCInfo.AllocateReg(FlatScratchInitReg); 1967 } 1968 1969 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1970 // these from the dispatch pointer. 1971 } 1972 1973 // Allocate special input registers that are initialized per-wave. 1974 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1975 MachineFunction &MF, 1976 SIMachineFunctionInfo &Info, 1977 CallingConv::ID CallConv, 1978 bool IsShader) const { 1979 if (Info.hasWorkGroupIDX()) { 1980 unsigned Reg = Info.addWorkGroupIDX(); 1981 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1982 CCInfo.AllocateReg(Reg); 1983 } 1984 1985 if (Info.hasWorkGroupIDY()) { 1986 unsigned Reg = Info.addWorkGroupIDY(); 1987 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1988 CCInfo.AllocateReg(Reg); 1989 } 1990 1991 if (Info.hasWorkGroupIDZ()) { 1992 unsigned Reg = Info.addWorkGroupIDZ(); 1993 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1994 CCInfo.AllocateReg(Reg); 1995 } 1996 1997 if (Info.hasWorkGroupInfo()) { 1998 unsigned Reg = Info.addWorkGroupInfo(); 1999 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2000 CCInfo.AllocateReg(Reg); 2001 } 2002 2003 if (Info.hasPrivateSegmentWaveByteOffset()) { 2004 // Scratch wave offset passed in system SGPR. 2005 unsigned PrivateSegmentWaveByteOffsetReg; 2006 2007 if (IsShader) { 2008 PrivateSegmentWaveByteOffsetReg = 2009 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2010 2011 // This is true if the scratch wave byte offset doesn't have a fixed 2012 // location. 2013 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2014 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2015 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2016 } 2017 } else 2018 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2019 2020 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2021 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2022 } 2023 } 2024 2025 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2026 MachineFunction &MF, 2027 const SIRegisterInfo &TRI, 2028 SIMachineFunctionInfo &Info) { 2029 // Now that we've figured out where the scratch register inputs are, see if 2030 // should reserve the arguments and use them directly. 2031 MachineFrameInfo &MFI = MF.getFrameInfo(); 2032 bool HasStackObjects = MFI.hasStackObjects(); 2033 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2034 2035 // Record that we know we have non-spill stack objects so we don't need to 2036 // check all stack objects later. 2037 if (HasStackObjects) 2038 Info.setHasNonSpillStackObjects(true); 2039 2040 // Everything live out of a block is spilled with fast regalloc, so it's 2041 // almost certain that spilling will be required. 2042 if (TM.getOptLevel() == CodeGenOpt::None) 2043 HasStackObjects = true; 2044 2045 // For now assume stack access is needed in any callee functions, so we need 2046 // the scratch registers to pass in. 2047 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2048 2049 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2050 // If we have stack objects, we unquestionably need the private buffer 2051 // resource. For the Code Object V2 ABI, this will be the first 4 user 2052 // SGPR inputs. We can reserve those and use them directly. 2053 2054 Register PrivateSegmentBufferReg = 2055 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2056 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2057 } else { 2058 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2059 // We tentatively reserve the last registers (skipping the last registers 2060 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2061 // we'll replace these with the ones immediately after those which were 2062 // really allocated. In the prologue copies will be inserted from the 2063 // argument to these reserved registers. 2064 2065 // Without HSA, relocations are used for the scratch pointer and the 2066 // buffer resource setup is always inserted in the prologue. Scratch wave 2067 // offset is still in an input SGPR. 2068 Info.setScratchRSrcReg(ReservedBufferReg); 2069 } 2070 2071 MachineRegisterInfo &MRI = MF.getRegInfo(); 2072 2073 // For entry functions we have to set up the stack pointer if we use it, 2074 // whereas non-entry functions get this "for free". This means there is no 2075 // intrinsic advantage to using S32 over S34 in cases where we do not have 2076 // calls but do need a frame pointer (i.e. if we are requested to have one 2077 // because frame pointer elimination is disabled). To keep things simple we 2078 // only ever use S32 as the call ABI stack pointer, and so using it does not 2079 // imply we need a separate frame pointer. 2080 // 2081 // Try to use s32 as the SP, but move it if it would interfere with input 2082 // arguments. This won't work with calls though. 2083 // 2084 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2085 // registers. 2086 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2087 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2088 } else { 2089 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2090 2091 if (MFI.hasCalls()) 2092 report_fatal_error("call in graphics shader with too many input SGPRs"); 2093 2094 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2095 if (!MRI.isLiveIn(Reg)) { 2096 Info.setStackPtrOffsetReg(Reg); 2097 break; 2098 } 2099 } 2100 2101 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2102 report_fatal_error("failed to find register for SP"); 2103 } 2104 2105 // hasFP should be accurate for entry functions even before the frame is 2106 // finalized, because it does not rely on the known stack size, only 2107 // properties like whether variable sized objects are present. 2108 if (ST.getFrameLowering()->hasFP(MF)) { 2109 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2110 } 2111 } 2112 2113 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2114 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2115 return !Info->isEntryFunction(); 2116 } 2117 2118 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2119 2120 } 2121 2122 void SITargetLowering::insertCopiesSplitCSR( 2123 MachineBasicBlock *Entry, 2124 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2125 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2126 2127 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2128 if (!IStart) 2129 return; 2130 2131 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2132 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2133 MachineBasicBlock::iterator MBBI = Entry->begin(); 2134 for (const MCPhysReg *I = IStart; *I; ++I) { 2135 const TargetRegisterClass *RC = nullptr; 2136 if (AMDGPU::SReg_64RegClass.contains(*I)) 2137 RC = &AMDGPU::SGPR_64RegClass; 2138 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2139 RC = &AMDGPU::SGPR_32RegClass; 2140 else 2141 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2142 2143 Register NewVR = MRI->createVirtualRegister(RC); 2144 // Create copy from CSR to a virtual register. 2145 Entry->addLiveIn(*I); 2146 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2147 .addReg(*I); 2148 2149 // Insert the copy-back instructions right before the terminator. 2150 for (auto *Exit : Exits) 2151 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2152 TII->get(TargetOpcode::COPY), *I) 2153 .addReg(NewVR); 2154 } 2155 } 2156 2157 SDValue SITargetLowering::LowerFormalArguments( 2158 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2159 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2160 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2161 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2162 2163 MachineFunction &MF = DAG.getMachineFunction(); 2164 const Function &Fn = MF.getFunction(); 2165 FunctionType *FType = MF.getFunction().getFunctionType(); 2166 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2167 2168 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2169 DiagnosticInfoUnsupported NoGraphicsHSA( 2170 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2171 DAG.getContext()->diagnose(NoGraphicsHSA); 2172 return DAG.getEntryNode(); 2173 } 2174 2175 SmallVector<ISD::InputArg, 16> Splits; 2176 SmallVector<CCValAssign, 16> ArgLocs; 2177 BitVector Skipped(Ins.size()); 2178 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2179 *DAG.getContext()); 2180 2181 bool IsShader = AMDGPU::isShader(CallConv); 2182 bool IsKernel = AMDGPU::isKernel(CallConv); 2183 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2184 2185 if (IsShader) { 2186 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2187 2188 // At least one interpolation mode must be enabled or else the GPU will 2189 // hang. 2190 // 2191 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2192 // set PSInputAddr, the user wants to enable some bits after the compilation 2193 // based on run-time states. Since we can't know what the final PSInputEna 2194 // will look like, so we shouldn't do anything here and the user should take 2195 // responsibility for the correct programming. 2196 // 2197 // Otherwise, the following restrictions apply: 2198 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2199 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2200 // enabled too. 2201 if (CallConv == CallingConv::AMDGPU_PS) { 2202 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2203 ((Info->getPSInputAddr() & 0xF) == 0 && 2204 Info->isPSInputAllocated(11))) { 2205 CCInfo.AllocateReg(AMDGPU::VGPR0); 2206 CCInfo.AllocateReg(AMDGPU::VGPR1); 2207 Info->markPSInputAllocated(0); 2208 Info->markPSInputEnabled(0); 2209 } 2210 if (Subtarget->isAmdPalOS()) { 2211 // For isAmdPalOS, the user does not enable some bits after compilation 2212 // based on run-time states; the register values being generated here are 2213 // the final ones set in hardware. Therefore we need to apply the 2214 // workaround to PSInputAddr and PSInputEnable together. (The case where 2215 // a bit is set in PSInputAddr but not PSInputEnable is where the 2216 // frontend set up an input arg for a particular interpolation mode, but 2217 // nothing uses that input arg. Really we should have an earlier pass 2218 // that removes such an arg.) 2219 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2220 if ((PsInputBits & 0x7F) == 0 || 2221 ((PsInputBits & 0xF) == 0 && 2222 (PsInputBits >> 11 & 1))) 2223 Info->markPSInputEnabled( 2224 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2225 } 2226 } 2227 2228 assert(!Info->hasDispatchPtr() && 2229 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2230 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2231 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2232 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2233 !Info->hasWorkItemIDZ()); 2234 } else if (IsKernel) { 2235 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2236 } else { 2237 Splits.append(Ins.begin(), Ins.end()); 2238 } 2239 2240 if (IsEntryFunc) { 2241 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2242 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2243 } else { 2244 // For the fixed ABI, pass workitem IDs in the last argument register. 2245 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2246 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2247 } 2248 2249 if (IsKernel) { 2250 analyzeFormalArgumentsCompute(CCInfo, Ins); 2251 } else { 2252 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2253 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2254 } 2255 2256 SmallVector<SDValue, 16> Chains; 2257 2258 // FIXME: This is the minimum kernel argument alignment. We should improve 2259 // this to the maximum alignment of the arguments. 2260 // 2261 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2262 // kern arg offset. 2263 const Align KernelArgBaseAlign = Align(16); 2264 2265 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2266 const ISD::InputArg &Arg = Ins[i]; 2267 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2268 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2269 continue; 2270 } 2271 2272 CCValAssign &VA = ArgLocs[ArgIdx++]; 2273 MVT VT = VA.getLocVT(); 2274 2275 if (IsEntryFunc && VA.isMemLoc()) { 2276 VT = Ins[i].VT; 2277 EVT MemVT = VA.getLocVT(); 2278 2279 const uint64_t Offset = VA.getLocMemOffset(); 2280 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2281 2282 if (Arg.Flags.isByRef()) { 2283 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2284 2285 const GCNTargetMachine &TM = 2286 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2287 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2288 Arg.Flags.getPointerAddrSpace())) { 2289 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2290 Arg.Flags.getPointerAddrSpace()); 2291 } 2292 2293 InVals.push_back(Ptr); 2294 continue; 2295 } 2296 2297 SDValue Arg = lowerKernargMemParameter( 2298 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2299 Chains.push_back(Arg.getValue(1)); 2300 2301 auto *ParamTy = 2302 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2303 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2304 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2305 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2306 // On SI local pointers are just offsets into LDS, so they are always 2307 // less than 16-bits. On CI and newer they could potentially be 2308 // real pointers, so we can't guarantee their size. 2309 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2310 DAG.getValueType(MVT::i16)); 2311 } 2312 2313 InVals.push_back(Arg); 2314 continue; 2315 } else if (!IsEntryFunc && VA.isMemLoc()) { 2316 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2317 InVals.push_back(Val); 2318 if (!Arg.Flags.isByVal()) 2319 Chains.push_back(Val.getValue(1)); 2320 continue; 2321 } 2322 2323 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2324 2325 Register Reg = VA.getLocReg(); 2326 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2327 EVT ValVT = VA.getValVT(); 2328 2329 Reg = MF.addLiveIn(Reg, RC); 2330 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2331 2332 if (Arg.Flags.isSRet()) { 2333 // The return object should be reasonably addressable. 2334 2335 // FIXME: This helps when the return is a real sret. If it is a 2336 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2337 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2338 unsigned NumBits 2339 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2340 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2341 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2342 } 2343 2344 // If this is an 8 or 16-bit value, it is really passed promoted 2345 // to 32 bits. Insert an assert[sz]ext to capture this, then 2346 // truncate to the right size. 2347 switch (VA.getLocInfo()) { 2348 case CCValAssign::Full: 2349 break; 2350 case CCValAssign::BCvt: 2351 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2352 break; 2353 case CCValAssign::SExt: 2354 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2355 DAG.getValueType(ValVT)); 2356 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2357 break; 2358 case CCValAssign::ZExt: 2359 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2360 DAG.getValueType(ValVT)); 2361 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2362 break; 2363 case CCValAssign::AExt: 2364 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2365 break; 2366 default: 2367 llvm_unreachable("Unknown loc info!"); 2368 } 2369 2370 InVals.push_back(Val); 2371 } 2372 2373 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2374 // Special inputs come after user arguments. 2375 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2376 } 2377 2378 // Start adding system SGPRs. 2379 if (IsEntryFunc) { 2380 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2381 } else { 2382 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2383 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2384 } 2385 2386 auto &ArgUsageInfo = 2387 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2388 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2389 2390 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2391 Info->setBytesInStackArgArea(StackArgSize); 2392 2393 return Chains.empty() ? Chain : 2394 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2395 } 2396 2397 // TODO: If return values can't fit in registers, we should return as many as 2398 // possible in registers before passing on stack. 2399 bool SITargetLowering::CanLowerReturn( 2400 CallingConv::ID CallConv, 2401 MachineFunction &MF, bool IsVarArg, 2402 const SmallVectorImpl<ISD::OutputArg> &Outs, 2403 LLVMContext &Context) const { 2404 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2405 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2406 // for shaders. Vector types should be explicitly handled by CC. 2407 if (AMDGPU::isEntryFunctionCC(CallConv)) 2408 return true; 2409 2410 SmallVector<CCValAssign, 16> RVLocs; 2411 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2412 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2413 } 2414 2415 SDValue 2416 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2417 bool isVarArg, 2418 const SmallVectorImpl<ISD::OutputArg> &Outs, 2419 const SmallVectorImpl<SDValue> &OutVals, 2420 const SDLoc &DL, SelectionDAG &DAG) const { 2421 MachineFunction &MF = DAG.getMachineFunction(); 2422 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2423 2424 if (AMDGPU::isKernel(CallConv)) { 2425 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2426 OutVals, DL, DAG); 2427 } 2428 2429 bool IsShader = AMDGPU::isShader(CallConv); 2430 2431 Info->setIfReturnsVoid(Outs.empty()); 2432 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2433 2434 // CCValAssign - represent the assignment of the return value to a location. 2435 SmallVector<CCValAssign, 48> RVLocs; 2436 SmallVector<ISD::OutputArg, 48> Splits; 2437 2438 // CCState - Info about the registers and stack slots. 2439 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2440 *DAG.getContext()); 2441 2442 // Analyze outgoing return values. 2443 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2444 2445 SDValue Flag; 2446 SmallVector<SDValue, 48> RetOps; 2447 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2448 2449 // Add return address for callable functions. 2450 if (!Info->isEntryFunction()) { 2451 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2452 SDValue ReturnAddrReg = CreateLiveInRegister( 2453 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2454 2455 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2456 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2457 MVT::i64); 2458 Chain = 2459 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2460 Flag = Chain.getValue(1); 2461 RetOps.push_back(ReturnAddrVirtualReg); 2462 } 2463 2464 // Copy the result values into the output registers. 2465 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2466 ++I, ++RealRVLocIdx) { 2467 CCValAssign &VA = RVLocs[I]; 2468 assert(VA.isRegLoc() && "Can only return in registers!"); 2469 // TODO: Partially return in registers if return values don't fit. 2470 SDValue Arg = OutVals[RealRVLocIdx]; 2471 2472 // Copied from other backends. 2473 switch (VA.getLocInfo()) { 2474 case CCValAssign::Full: 2475 break; 2476 case CCValAssign::BCvt: 2477 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2478 break; 2479 case CCValAssign::SExt: 2480 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2481 break; 2482 case CCValAssign::ZExt: 2483 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2484 break; 2485 case CCValAssign::AExt: 2486 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2487 break; 2488 default: 2489 llvm_unreachable("Unknown loc info!"); 2490 } 2491 2492 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2493 Flag = Chain.getValue(1); 2494 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2495 } 2496 2497 // FIXME: Does sret work properly? 2498 if (!Info->isEntryFunction()) { 2499 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2500 const MCPhysReg *I = 2501 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2502 if (I) { 2503 for (; *I; ++I) { 2504 if (AMDGPU::SReg_64RegClass.contains(*I)) 2505 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2506 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2507 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2508 else 2509 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2510 } 2511 } 2512 } 2513 2514 // Update chain and glue. 2515 RetOps[0] = Chain; 2516 if (Flag.getNode()) 2517 RetOps.push_back(Flag); 2518 2519 unsigned Opc = AMDGPUISD::ENDPGM; 2520 if (!IsWaveEnd) 2521 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2522 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2523 } 2524 2525 SDValue SITargetLowering::LowerCallResult( 2526 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2527 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2528 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2529 SDValue ThisVal) const { 2530 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2531 2532 // Assign locations to each value returned by this call. 2533 SmallVector<CCValAssign, 16> RVLocs; 2534 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2535 *DAG.getContext()); 2536 CCInfo.AnalyzeCallResult(Ins, RetCC); 2537 2538 // Copy all of the result registers out of their specified physreg. 2539 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2540 CCValAssign VA = RVLocs[i]; 2541 SDValue Val; 2542 2543 if (VA.isRegLoc()) { 2544 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2545 Chain = Val.getValue(1); 2546 InFlag = Val.getValue(2); 2547 } else if (VA.isMemLoc()) { 2548 report_fatal_error("TODO: return values in memory"); 2549 } else 2550 llvm_unreachable("unknown argument location type"); 2551 2552 switch (VA.getLocInfo()) { 2553 case CCValAssign::Full: 2554 break; 2555 case CCValAssign::BCvt: 2556 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2557 break; 2558 case CCValAssign::ZExt: 2559 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2560 DAG.getValueType(VA.getValVT())); 2561 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2562 break; 2563 case CCValAssign::SExt: 2564 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2565 DAG.getValueType(VA.getValVT())); 2566 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2567 break; 2568 case CCValAssign::AExt: 2569 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2570 break; 2571 default: 2572 llvm_unreachable("Unknown loc info!"); 2573 } 2574 2575 InVals.push_back(Val); 2576 } 2577 2578 return Chain; 2579 } 2580 2581 // Add code to pass special inputs required depending on used features separate 2582 // from the explicit user arguments present in the IR. 2583 void SITargetLowering::passSpecialInputs( 2584 CallLoweringInfo &CLI, 2585 CCState &CCInfo, 2586 const SIMachineFunctionInfo &Info, 2587 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2588 SmallVectorImpl<SDValue> &MemOpChains, 2589 SDValue Chain) const { 2590 // If we don't have a call site, this was a call inserted by 2591 // legalization. These can never use special inputs. 2592 if (!CLI.CB) 2593 return; 2594 2595 SelectionDAG &DAG = CLI.DAG; 2596 const SDLoc &DL = CLI.DL; 2597 2598 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2599 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2600 2601 const AMDGPUFunctionArgInfo *CalleeArgInfo 2602 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2603 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2604 auto &ArgUsageInfo = 2605 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2606 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2607 } 2608 2609 // TODO: Unify with private memory register handling. This is complicated by 2610 // the fact that at least in kernels, the input argument is not necessarily 2611 // in the same location as the input. 2612 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2613 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2614 AMDGPUFunctionArgInfo::QUEUE_PTR, 2615 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2616 AMDGPUFunctionArgInfo::DISPATCH_ID, 2617 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2618 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2619 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2620 }; 2621 2622 for (auto InputID : InputRegs) { 2623 const ArgDescriptor *OutgoingArg; 2624 const TargetRegisterClass *ArgRC; 2625 LLT ArgTy; 2626 2627 std::tie(OutgoingArg, ArgRC, ArgTy) = 2628 CalleeArgInfo->getPreloadedValue(InputID); 2629 if (!OutgoingArg) 2630 continue; 2631 2632 const ArgDescriptor *IncomingArg; 2633 const TargetRegisterClass *IncomingArgRC; 2634 LLT Ty; 2635 std::tie(IncomingArg, IncomingArgRC, Ty) = 2636 CallerArgInfo.getPreloadedValue(InputID); 2637 assert(IncomingArgRC == ArgRC); 2638 2639 // All special arguments are ints for now. 2640 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2641 SDValue InputReg; 2642 2643 if (IncomingArg) { 2644 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2645 } else { 2646 // The implicit arg ptr is special because it doesn't have a corresponding 2647 // input for kernels, and is computed from the kernarg segment pointer. 2648 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2649 InputReg = getImplicitArgPtr(DAG, DL); 2650 } 2651 2652 if (OutgoingArg->isRegister()) { 2653 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2654 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2655 report_fatal_error("failed to allocate implicit input argument"); 2656 } else { 2657 unsigned SpecialArgOffset = 2658 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2659 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2660 SpecialArgOffset); 2661 MemOpChains.push_back(ArgStore); 2662 } 2663 } 2664 2665 // Pack workitem IDs into a single register or pass it as is if already 2666 // packed. 2667 const ArgDescriptor *OutgoingArg; 2668 const TargetRegisterClass *ArgRC; 2669 LLT Ty; 2670 2671 std::tie(OutgoingArg, ArgRC, Ty) = 2672 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2673 if (!OutgoingArg) 2674 std::tie(OutgoingArg, ArgRC, Ty) = 2675 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2676 if (!OutgoingArg) 2677 std::tie(OutgoingArg, ArgRC, Ty) = 2678 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2679 if (!OutgoingArg) 2680 return; 2681 2682 const ArgDescriptor *IncomingArgX = std::get<0>( 2683 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2684 const ArgDescriptor *IncomingArgY = std::get<0>( 2685 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2686 const ArgDescriptor *IncomingArgZ = std::get<0>( 2687 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2688 2689 SDValue InputReg; 2690 SDLoc SL; 2691 2692 // If incoming ids are not packed we need to pack them. 2693 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2694 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2695 2696 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2697 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2698 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2699 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2700 InputReg = InputReg.getNode() ? 2701 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2702 } 2703 2704 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2705 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2706 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2707 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2708 InputReg = InputReg.getNode() ? 2709 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2710 } 2711 2712 if (!InputReg.getNode()) { 2713 // Workitem ids are already packed, any of present incoming arguments 2714 // will carry all required fields. 2715 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2716 IncomingArgX ? *IncomingArgX : 2717 IncomingArgY ? *IncomingArgY : 2718 *IncomingArgZ, ~0u); 2719 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2720 } 2721 2722 if (OutgoingArg->isRegister()) { 2723 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2724 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2725 } else { 2726 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2727 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2728 SpecialArgOffset); 2729 MemOpChains.push_back(ArgStore); 2730 } 2731 } 2732 2733 static bool canGuaranteeTCO(CallingConv::ID CC) { 2734 return CC == CallingConv::Fast; 2735 } 2736 2737 /// Return true if we might ever do TCO for calls with this calling convention. 2738 static bool mayTailCallThisCC(CallingConv::ID CC) { 2739 switch (CC) { 2740 case CallingConv::C: 2741 return true; 2742 default: 2743 return canGuaranteeTCO(CC); 2744 } 2745 } 2746 2747 bool SITargetLowering::isEligibleForTailCallOptimization( 2748 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2749 const SmallVectorImpl<ISD::OutputArg> &Outs, 2750 const SmallVectorImpl<SDValue> &OutVals, 2751 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2752 if (!mayTailCallThisCC(CalleeCC)) 2753 return false; 2754 2755 MachineFunction &MF = DAG.getMachineFunction(); 2756 const Function &CallerF = MF.getFunction(); 2757 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2758 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2759 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2760 2761 // Kernels aren't callable, and don't have a live in return address so it 2762 // doesn't make sense to do a tail call with entry functions. 2763 if (!CallerPreserved) 2764 return false; 2765 2766 bool CCMatch = CallerCC == CalleeCC; 2767 2768 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2769 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2770 return true; 2771 return false; 2772 } 2773 2774 // TODO: Can we handle var args? 2775 if (IsVarArg) 2776 return false; 2777 2778 for (const Argument &Arg : CallerF.args()) { 2779 if (Arg.hasByValAttr()) 2780 return false; 2781 } 2782 2783 LLVMContext &Ctx = *DAG.getContext(); 2784 2785 // Check that the call results are passed in the same way. 2786 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2787 CCAssignFnForCall(CalleeCC, IsVarArg), 2788 CCAssignFnForCall(CallerCC, IsVarArg))) 2789 return false; 2790 2791 // The callee has to preserve all registers the caller needs to preserve. 2792 if (!CCMatch) { 2793 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2794 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2795 return false; 2796 } 2797 2798 // Nothing more to check if the callee is taking no arguments. 2799 if (Outs.empty()) 2800 return true; 2801 2802 SmallVector<CCValAssign, 16> ArgLocs; 2803 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2804 2805 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2806 2807 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2808 // If the stack arguments for this call do not fit into our own save area then 2809 // the call cannot be made tail. 2810 // TODO: Is this really necessary? 2811 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2812 return false; 2813 2814 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2815 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2816 } 2817 2818 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2819 if (!CI->isTailCall()) 2820 return false; 2821 2822 const Function *ParentFn = CI->getParent()->getParent(); 2823 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2824 return false; 2825 return true; 2826 } 2827 2828 // The wave scratch offset register is used as the global base pointer. 2829 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2830 SmallVectorImpl<SDValue> &InVals) const { 2831 SelectionDAG &DAG = CLI.DAG; 2832 const SDLoc &DL = CLI.DL; 2833 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2834 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2835 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2836 SDValue Chain = CLI.Chain; 2837 SDValue Callee = CLI.Callee; 2838 bool &IsTailCall = CLI.IsTailCall; 2839 CallingConv::ID CallConv = CLI.CallConv; 2840 bool IsVarArg = CLI.IsVarArg; 2841 bool IsSibCall = false; 2842 bool IsThisReturn = false; 2843 MachineFunction &MF = DAG.getMachineFunction(); 2844 2845 if (Callee.isUndef() || isNullConstant(Callee)) { 2846 if (!CLI.IsTailCall) { 2847 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2848 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2849 } 2850 2851 return Chain; 2852 } 2853 2854 if (IsVarArg) { 2855 return lowerUnhandledCall(CLI, InVals, 2856 "unsupported call to variadic function "); 2857 } 2858 2859 if (!CLI.CB) 2860 report_fatal_error("unsupported libcall legalization"); 2861 2862 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2863 !CLI.CB->getCalledFunction()) { 2864 return lowerUnhandledCall(CLI, InVals, 2865 "unsupported indirect call to function "); 2866 } 2867 2868 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2869 return lowerUnhandledCall(CLI, InVals, 2870 "unsupported required tail call to function "); 2871 } 2872 2873 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2874 // Note the issue is with the CC of the calling function, not of the call 2875 // itself. 2876 return lowerUnhandledCall(CLI, InVals, 2877 "unsupported call from graphics shader of function "); 2878 } 2879 2880 if (IsTailCall) { 2881 IsTailCall = isEligibleForTailCallOptimization( 2882 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2883 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2884 report_fatal_error("failed to perform tail call elimination on a call " 2885 "site marked musttail"); 2886 } 2887 2888 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2889 2890 // A sibling call is one where we're under the usual C ABI and not planning 2891 // to change that but can still do a tail call: 2892 if (!TailCallOpt && IsTailCall) 2893 IsSibCall = true; 2894 2895 if (IsTailCall) 2896 ++NumTailCalls; 2897 } 2898 2899 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2900 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2901 SmallVector<SDValue, 8> MemOpChains; 2902 2903 // Analyze operands of the call, assigning locations to each operand. 2904 SmallVector<CCValAssign, 16> ArgLocs; 2905 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2906 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2907 2908 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2909 // With a fixed ABI, allocate fixed registers before user arguments. 2910 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2911 } 2912 2913 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2914 2915 // Get a count of how many bytes are to be pushed on the stack. 2916 unsigned NumBytes = CCInfo.getNextStackOffset(); 2917 2918 if (IsSibCall) { 2919 // Since we're not changing the ABI to make this a tail call, the memory 2920 // operands are already available in the caller's incoming argument space. 2921 NumBytes = 0; 2922 } 2923 2924 // FPDiff is the byte offset of the call's argument area from the callee's. 2925 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2926 // by this amount for a tail call. In a sibling call it must be 0 because the 2927 // caller will deallocate the entire stack and the callee still expects its 2928 // arguments to begin at SP+0. Completely unused for non-tail calls. 2929 int32_t FPDiff = 0; 2930 MachineFrameInfo &MFI = MF.getFrameInfo(); 2931 2932 // Adjust the stack pointer for the new arguments... 2933 // These operations are automatically eliminated by the prolog/epilog pass 2934 if (!IsSibCall) { 2935 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2936 2937 SmallVector<SDValue, 4> CopyFromChains; 2938 2939 // In the HSA case, this should be an identity copy. 2940 SDValue ScratchRSrcReg 2941 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2942 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2943 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2944 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2945 } 2946 2947 MVT PtrVT = MVT::i32; 2948 2949 // Walk the register/memloc assignments, inserting copies/loads. 2950 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2951 CCValAssign &VA = ArgLocs[i]; 2952 SDValue Arg = OutVals[i]; 2953 2954 // Promote the value if needed. 2955 switch (VA.getLocInfo()) { 2956 case CCValAssign::Full: 2957 break; 2958 case CCValAssign::BCvt: 2959 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2960 break; 2961 case CCValAssign::ZExt: 2962 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2963 break; 2964 case CCValAssign::SExt: 2965 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2966 break; 2967 case CCValAssign::AExt: 2968 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2969 break; 2970 case CCValAssign::FPExt: 2971 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2972 break; 2973 default: 2974 llvm_unreachable("Unknown loc info!"); 2975 } 2976 2977 if (VA.isRegLoc()) { 2978 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2979 } else { 2980 assert(VA.isMemLoc()); 2981 2982 SDValue DstAddr; 2983 MachinePointerInfo DstInfo; 2984 2985 unsigned LocMemOffset = VA.getLocMemOffset(); 2986 int32_t Offset = LocMemOffset; 2987 2988 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2989 MaybeAlign Alignment; 2990 2991 if (IsTailCall) { 2992 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2993 unsigned OpSize = Flags.isByVal() ? 2994 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2995 2996 // FIXME: We can have better than the minimum byval required alignment. 2997 Alignment = 2998 Flags.isByVal() 2999 ? Flags.getNonZeroByValAlign() 3000 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3001 3002 Offset = Offset + FPDiff; 3003 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3004 3005 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3006 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3007 3008 // Make sure any stack arguments overlapping with where we're storing 3009 // are loaded before this eventual operation. Otherwise they'll be 3010 // clobbered. 3011 3012 // FIXME: Why is this really necessary? This seems to just result in a 3013 // lot of code to copy the stack and write them back to the same 3014 // locations, which are supposed to be immutable? 3015 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3016 } else { 3017 DstAddr = PtrOff; 3018 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3019 Alignment = 3020 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3021 } 3022 3023 if (Outs[i].Flags.isByVal()) { 3024 SDValue SizeNode = 3025 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3026 SDValue Cpy = 3027 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3028 Outs[i].Flags.getNonZeroByValAlign(), 3029 /*isVol = */ false, /*AlwaysInline = */ true, 3030 /*isTailCall = */ false, DstInfo, 3031 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3032 3033 MemOpChains.push_back(Cpy); 3034 } else { 3035 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 3036 Alignment ? Alignment->value() : 0); 3037 MemOpChains.push_back(Store); 3038 } 3039 } 3040 } 3041 3042 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3043 // Copy special input registers after user input arguments. 3044 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3045 } 3046 3047 if (!MemOpChains.empty()) 3048 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3049 3050 // Build a sequence of copy-to-reg nodes chained together with token chain 3051 // and flag operands which copy the outgoing args into the appropriate regs. 3052 SDValue InFlag; 3053 for (auto &RegToPass : RegsToPass) { 3054 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3055 RegToPass.second, InFlag); 3056 InFlag = Chain.getValue(1); 3057 } 3058 3059 3060 SDValue PhysReturnAddrReg; 3061 if (IsTailCall) { 3062 // Since the return is being combined with the call, we need to pass on the 3063 // return address. 3064 3065 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3066 SDValue ReturnAddrReg = CreateLiveInRegister( 3067 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3068 3069 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3070 MVT::i64); 3071 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3072 InFlag = Chain.getValue(1); 3073 } 3074 3075 // We don't usually want to end the call-sequence here because we would tidy 3076 // the frame up *after* the call, however in the ABI-changing tail-call case 3077 // we've carefully laid out the parameters so that when sp is reset they'll be 3078 // in the correct location. 3079 if (IsTailCall && !IsSibCall) { 3080 Chain = DAG.getCALLSEQ_END(Chain, 3081 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3082 DAG.getTargetConstant(0, DL, MVT::i32), 3083 InFlag, DL); 3084 InFlag = Chain.getValue(1); 3085 } 3086 3087 std::vector<SDValue> Ops; 3088 Ops.push_back(Chain); 3089 Ops.push_back(Callee); 3090 // Add a redundant copy of the callee global which will not be legalized, as 3091 // we need direct access to the callee later. 3092 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3093 const GlobalValue *GV = GSD->getGlobal(); 3094 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3095 } else { 3096 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3097 } 3098 3099 if (IsTailCall) { 3100 // Each tail call may have to adjust the stack by a different amount, so 3101 // this information must travel along with the operation for eventual 3102 // consumption by emitEpilogue. 3103 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3104 3105 Ops.push_back(PhysReturnAddrReg); 3106 } 3107 3108 // Add argument registers to the end of the list so that they are known live 3109 // into the call. 3110 for (auto &RegToPass : RegsToPass) { 3111 Ops.push_back(DAG.getRegister(RegToPass.first, 3112 RegToPass.second.getValueType())); 3113 } 3114 3115 // Add a register mask operand representing the call-preserved registers. 3116 3117 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3118 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3119 assert(Mask && "Missing call preserved mask for calling convention"); 3120 Ops.push_back(DAG.getRegisterMask(Mask)); 3121 3122 if (InFlag.getNode()) 3123 Ops.push_back(InFlag); 3124 3125 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3126 3127 // If we're doing a tall call, use a TC_RETURN here rather than an 3128 // actual call instruction. 3129 if (IsTailCall) { 3130 MFI.setHasTailCall(); 3131 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3132 } 3133 3134 // Returns a chain and a flag for retval copy to use. 3135 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3136 Chain = Call.getValue(0); 3137 InFlag = Call.getValue(1); 3138 3139 uint64_t CalleePopBytes = NumBytes; 3140 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3141 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3142 InFlag, DL); 3143 if (!Ins.empty()) 3144 InFlag = Chain.getValue(1); 3145 3146 // Handle result values, copying them out of physregs into vregs that we 3147 // return. 3148 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3149 InVals, IsThisReturn, 3150 IsThisReturn ? OutVals[0] : SDValue()); 3151 } 3152 3153 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3154 // except for applying the wave size scale to the increment amount. 3155 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3156 SDValue Op, SelectionDAG &DAG) const { 3157 const MachineFunction &MF = DAG.getMachineFunction(); 3158 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3159 3160 SDLoc dl(Op); 3161 EVT VT = Op.getValueType(); 3162 SDValue Tmp1 = Op; 3163 SDValue Tmp2 = Op.getValue(1); 3164 SDValue Tmp3 = Op.getOperand(2); 3165 SDValue Chain = Tmp1.getOperand(0); 3166 3167 Register SPReg = Info->getStackPtrOffsetReg(); 3168 3169 // Chain the dynamic stack allocation so that it doesn't modify the stack 3170 // pointer when other instructions are using the stack. 3171 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3172 3173 SDValue Size = Tmp2.getOperand(1); 3174 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3175 Chain = SP.getValue(1); 3176 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3177 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3178 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3179 unsigned Opc = 3180 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3181 ISD::ADD : ISD::SUB; 3182 3183 SDValue ScaledSize = DAG.getNode( 3184 ISD::SHL, dl, VT, Size, 3185 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3186 3187 Align StackAlign = TFL->getStackAlign(); 3188 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3189 if (Alignment && *Alignment > StackAlign) { 3190 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3191 DAG.getConstant(-(uint64_t)Alignment->value() 3192 << ST.getWavefrontSizeLog2(), 3193 dl, VT)); 3194 } 3195 3196 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3197 Tmp2 = DAG.getCALLSEQ_END( 3198 Chain, DAG.getIntPtrConstant(0, dl, true), 3199 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3200 3201 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3202 } 3203 3204 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3205 SelectionDAG &DAG) const { 3206 // We only handle constant sizes here to allow non-entry block, static sized 3207 // allocas. A truly dynamic value is more difficult to support because we 3208 // don't know if the size value is uniform or not. If the size isn't uniform, 3209 // we would need to do a wave reduction to get the maximum size to know how 3210 // much to increment the uniform stack pointer. 3211 SDValue Size = Op.getOperand(1); 3212 if (isa<ConstantSDNode>(Size)) 3213 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3214 3215 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3216 } 3217 3218 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3219 const MachineFunction &MF) const { 3220 Register Reg = StringSwitch<Register>(RegName) 3221 .Case("m0", AMDGPU::M0) 3222 .Case("exec", AMDGPU::EXEC) 3223 .Case("exec_lo", AMDGPU::EXEC_LO) 3224 .Case("exec_hi", AMDGPU::EXEC_HI) 3225 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3226 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3227 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3228 .Default(Register()); 3229 3230 if (Reg == AMDGPU::NoRegister) { 3231 report_fatal_error(Twine("invalid register name \"" 3232 + StringRef(RegName) + "\".")); 3233 3234 } 3235 3236 if (!Subtarget->hasFlatScrRegister() && 3237 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3238 report_fatal_error(Twine("invalid register \"" 3239 + StringRef(RegName) + "\" for subtarget.")); 3240 } 3241 3242 switch (Reg) { 3243 case AMDGPU::M0: 3244 case AMDGPU::EXEC_LO: 3245 case AMDGPU::EXEC_HI: 3246 case AMDGPU::FLAT_SCR_LO: 3247 case AMDGPU::FLAT_SCR_HI: 3248 if (VT.getSizeInBits() == 32) 3249 return Reg; 3250 break; 3251 case AMDGPU::EXEC: 3252 case AMDGPU::FLAT_SCR: 3253 if (VT.getSizeInBits() == 64) 3254 return Reg; 3255 break; 3256 default: 3257 llvm_unreachable("missing register type checking"); 3258 } 3259 3260 report_fatal_error(Twine("invalid type for register \"" 3261 + StringRef(RegName) + "\".")); 3262 } 3263 3264 // If kill is not the last instruction, split the block so kill is always a 3265 // proper terminator. 3266 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3267 MachineBasicBlock *BB) const { 3268 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3269 3270 MachineBasicBlock::iterator SplitPoint(&MI); 3271 ++SplitPoint; 3272 3273 if (SplitPoint == BB->end()) { 3274 // Don't bother with a new block. 3275 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3276 return BB; 3277 } 3278 3279 MachineFunction *MF = BB->getParent(); 3280 MachineBasicBlock *SplitBB 3281 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3282 3283 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3284 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3285 3286 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3287 BB->addSuccessor(SplitBB); 3288 3289 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3290 return SplitBB; 3291 } 3292 3293 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3294 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3295 // be the first instruction in the remainder block. 3296 // 3297 /// \returns { LoopBody, Remainder } 3298 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3299 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3300 MachineFunction *MF = MBB.getParent(); 3301 MachineBasicBlock::iterator I(&MI); 3302 3303 // To insert the loop we need to split the block. Move everything after this 3304 // point to a new block, and insert a new empty block between the two. 3305 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3306 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3307 MachineFunction::iterator MBBI(MBB); 3308 ++MBBI; 3309 3310 MF->insert(MBBI, LoopBB); 3311 MF->insert(MBBI, RemainderBB); 3312 3313 LoopBB->addSuccessor(LoopBB); 3314 LoopBB->addSuccessor(RemainderBB); 3315 3316 // Move the rest of the block into a new block. 3317 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3318 3319 if (InstInLoop) { 3320 auto Next = std::next(I); 3321 3322 // Move instruction to loop body. 3323 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3324 3325 // Move the rest of the block. 3326 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3327 } else { 3328 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3329 } 3330 3331 MBB.addSuccessor(LoopBB); 3332 3333 return std::make_pair(LoopBB, RemainderBB); 3334 } 3335 3336 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3337 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3338 MachineBasicBlock *MBB = MI.getParent(); 3339 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3340 auto I = MI.getIterator(); 3341 auto E = std::next(I); 3342 3343 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3344 .addImm(0); 3345 3346 MIBundleBuilder Bundler(*MBB, I, E); 3347 finalizeBundle(*MBB, Bundler.begin()); 3348 } 3349 3350 MachineBasicBlock * 3351 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3352 MachineBasicBlock *BB) const { 3353 const DebugLoc &DL = MI.getDebugLoc(); 3354 3355 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3356 3357 MachineBasicBlock *LoopBB; 3358 MachineBasicBlock *RemainderBB; 3359 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3360 3361 // Apparently kill flags are only valid if the def is in the same block? 3362 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3363 Src->setIsKill(false); 3364 3365 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3366 3367 MachineBasicBlock::iterator I = LoopBB->end(); 3368 3369 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3370 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3371 3372 // Clear TRAP_STS.MEM_VIOL 3373 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3374 .addImm(0) 3375 .addImm(EncodedReg); 3376 3377 bundleInstWithWaitcnt(MI); 3378 3379 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3380 3381 // Load and check TRAP_STS.MEM_VIOL 3382 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3383 .addImm(EncodedReg); 3384 3385 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3386 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3387 .addReg(Reg, RegState::Kill) 3388 .addImm(0); 3389 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3390 .addMBB(LoopBB); 3391 3392 return RemainderBB; 3393 } 3394 3395 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3396 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3397 // will only do one iteration. In the worst case, this will loop 64 times. 3398 // 3399 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3400 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3401 const SIInstrInfo *TII, 3402 MachineRegisterInfo &MRI, 3403 MachineBasicBlock &OrigBB, 3404 MachineBasicBlock &LoopBB, 3405 const DebugLoc &DL, 3406 const MachineOperand &IdxReg, 3407 unsigned InitReg, 3408 unsigned ResultReg, 3409 unsigned PhiReg, 3410 unsigned InitSaveExecReg, 3411 int Offset, 3412 bool UseGPRIdxMode, 3413 bool IsIndirectSrc) { 3414 MachineFunction *MF = OrigBB.getParent(); 3415 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3416 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3417 MachineBasicBlock::iterator I = LoopBB.begin(); 3418 3419 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3420 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3421 Register NewExec = MRI.createVirtualRegister(BoolRC); 3422 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3423 Register CondReg = MRI.createVirtualRegister(BoolRC); 3424 3425 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3426 .addReg(InitReg) 3427 .addMBB(&OrigBB) 3428 .addReg(ResultReg) 3429 .addMBB(&LoopBB); 3430 3431 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3432 .addReg(InitSaveExecReg) 3433 .addMBB(&OrigBB) 3434 .addReg(NewExec) 3435 .addMBB(&LoopBB); 3436 3437 // Read the next variant <- also loop target. 3438 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3439 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3440 3441 // Compare the just read M0 value to all possible Idx values. 3442 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3443 .addReg(CurrentIdxReg) 3444 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3445 3446 // Update EXEC, save the original EXEC value to VCC. 3447 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3448 : AMDGPU::S_AND_SAVEEXEC_B64), 3449 NewExec) 3450 .addReg(CondReg, RegState::Kill); 3451 3452 MRI.setSimpleHint(NewExec, CondReg); 3453 3454 if (UseGPRIdxMode) { 3455 unsigned IdxReg; 3456 if (Offset == 0) { 3457 IdxReg = CurrentIdxReg; 3458 } else { 3459 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3460 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3461 .addReg(CurrentIdxReg, RegState::Kill) 3462 .addImm(Offset); 3463 } 3464 unsigned IdxMode = IsIndirectSrc ? 3465 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3466 MachineInstr *SetOn = 3467 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3468 .addReg(IdxReg, RegState::Kill) 3469 .addImm(IdxMode); 3470 SetOn->getOperand(3).setIsUndef(); 3471 } else { 3472 // Move index from VCC into M0 3473 if (Offset == 0) { 3474 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3475 .addReg(CurrentIdxReg, RegState::Kill); 3476 } else { 3477 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3478 .addReg(CurrentIdxReg, RegState::Kill) 3479 .addImm(Offset); 3480 } 3481 } 3482 3483 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3484 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3485 MachineInstr *InsertPt = 3486 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3487 : AMDGPU::S_XOR_B64_term), Exec) 3488 .addReg(Exec) 3489 .addReg(NewExec); 3490 3491 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3492 // s_cbranch_scc0? 3493 3494 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3495 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3496 .addMBB(&LoopBB); 3497 3498 return InsertPt->getIterator(); 3499 } 3500 3501 // This has slightly sub-optimal regalloc when the source vector is killed by 3502 // the read. The register allocator does not understand that the kill is 3503 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3504 // subregister from it, using 1 more VGPR than necessary. This was saved when 3505 // this was expanded after register allocation. 3506 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3507 MachineBasicBlock &MBB, 3508 MachineInstr &MI, 3509 unsigned InitResultReg, 3510 unsigned PhiReg, 3511 int Offset, 3512 bool UseGPRIdxMode, 3513 bool IsIndirectSrc) { 3514 MachineFunction *MF = MBB.getParent(); 3515 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3516 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3517 MachineRegisterInfo &MRI = MF->getRegInfo(); 3518 const DebugLoc &DL = MI.getDebugLoc(); 3519 MachineBasicBlock::iterator I(&MI); 3520 3521 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3522 Register DstReg = MI.getOperand(0).getReg(); 3523 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3524 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3525 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3526 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3527 3528 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3529 3530 // Save the EXEC mask 3531 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3532 .addReg(Exec); 3533 3534 MachineBasicBlock *LoopBB; 3535 MachineBasicBlock *RemainderBB; 3536 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3537 3538 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3539 3540 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3541 InitResultReg, DstReg, PhiReg, TmpExec, 3542 Offset, UseGPRIdxMode, IsIndirectSrc); 3543 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3544 MachineFunction::iterator MBBI(LoopBB); 3545 ++MBBI; 3546 MF->insert(MBBI, LandingPad); 3547 LoopBB->removeSuccessor(RemainderBB); 3548 LandingPad->addSuccessor(RemainderBB); 3549 LoopBB->addSuccessor(LandingPad); 3550 MachineBasicBlock::iterator First = LandingPad->begin(); 3551 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3552 .addReg(SaveExec); 3553 3554 return InsPt; 3555 } 3556 3557 // Returns subreg index, offset 3558 static std::pair<unsigned, int> 3559 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3560 const TargetRegisterClass *SuperRC, 3561 unsigned VecReg, 3562 int Offset) { 3563 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3564 3565 // Skip out of bounds offsets, or else we would end up using an undefined 3566 // register. 3567 if (Offset >= NumElts || Offset < 0) 3568 return std::make_pair(AMDGPU::sub0, Offset); 3569 3570 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3571 } 3572 3573 // Return true if the index is an SGPR and was set. 3574 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3575 MachineRegisterInfo &MRI, 3576 MachineInstr &MI, 3577 int Offset, 3578 bool UseGPRIdxMode, 3579 bool IsIndirectSrc) { 3580 MachineBasicBlock *MBB = MI.getParent(); 3581 const DebugLoc &DL = MI.getDebugLoc(); 3582 MachineBasicBlock::iterator I(&MI); 3583 3584 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3585 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3586 3587 assert(Idx->getReg() != AMDGPU::NoRegister); 3588 3589 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3590 return false; 3591 3592 if (UseGPRIdxMode) { 3593 unsigned IdxMode = IsIndirectSrc ? 3594 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3595 if (Offset == 0) { 3596 MachineInstr *SetOn = 3597 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3598 .add(*Idx) 3599 .addImm(IdxMode); 3600 3601 SetOn->getOperand(3).setIsUndef(); 3602 } else { 3603 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3604 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3605 .add(*Idx) 3606 .addImm(Offset); 3607 MachineInstr *SetOn = 3608 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3609 .addReg(Tmp, RegState::Kill) 3610 .addImm(IdxMode); 3611 3612 SetOn->getOperand(3).setIsUndef(); 3613 } 3614 3615 return true; 3616 } 3617 3618 if (Offset == 0) { 3619 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3620 .add(*Idx); 3621 } else { 3622 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3623 .add(*Idx) 3624 .addImm(Offset); 3625 } 3626 3627 return true; 3628 } 3629 3630 // Control flow needs to be inserted if indexing with a VGPR. 3631 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3632 MachineBasicBlock &MBB, 3633 const GCNSubtarget &ST) { 3634 const SIInstrInfo *TII = ST.getInstrInfo(); 3635 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3636 MachineFunction *MF = MBB.getParent(); 3637 MachineRegisterInfo &MRI = MF->getRegInfo(); 3638 3639 Register Dst = MI.getOperand(0).getReg(); 3640 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3641 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3642 3643 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3644 3645 unsigned SubReg; 3646 std::tie(SubReg, Offset) 3647 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3648 3649 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3650 3651 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3652 MachineBasicBlock::iterator I(&MI); 3653 const DebugLoc &DL = MI.getDebugLoc(); 3654 3655 if (UseGPRIdxMode) { 3656 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3657 // to avoid interfering with other uses, so probably requires a new 3658 // optimization pass. 3659 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3660 .addReg(SrcReg, 0, SubReg) 3661 .addReg(SrcReg, RegState::Implicit) 3662 .addReg(AMDGPU::M0, RegState::Implicit); 3663 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3664 } else { 3665 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3666 .addReg(SrcReg, 0, SubReg) 3667 .addReg(SrcReg, RegState::Implicit); 3668 } 3669 3670 MI.eraseFromParent(); 3671 3672 return &MBB; 3673 } 3674 3675 const DebugLoc &DL = MI.getDebugLoc(); 3676 MachineBasicBlock::iterator I(&MI); 3677 3678 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3679 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3680 3681 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3682 3683 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3684 Offset, UseGPRIdxMode, true); 3685 MachineBasicBlock *LoopBB = InsPt->getParent(); 3686 3687 if (UseGPRIdxMode) { 3688 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3689 .addReg(SrcReg, 0, SubReg) 3690 .addReg(SrcReg, RegState::Implicit) 3691 .addReg(AMDGPU::M0, RegState::Implicit); 3692 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3693 } else { 3694 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3695 .addReg(SrcReg, 0, SubReg) 3696 .addReg(SrcReg, RegState::Implicit); 3697 } 3698 3699 MI.eraseFromParent(); 3700 3701 return LoopBB; 3702 } 3703 3704 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3705 MachineBasicBlock &MBB, 3706 const GCNSubtarget &ST) { 3707 const SIInstrInfo *TII = ST.getInstrInfo(); 3708 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3709 MachineFunction *MF = MBB.getParent(); 3710 MachineRegisterInfo &MRI = MF->getRegInfo(); 3711 3712 Register Dst = MI.getOperand(0).getReg(); 3713 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3714 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3715 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3716 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3717 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3718 3719 // This can be an immediate, but will be folded later. 3720 assert(Val->getReg()); 3721 3722 unsigned SubReg; 3723 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3724 SrcVec->getReg(), 3725 Offset); 3726 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3727 3728 if (Idx->getReg() == AMDGPU::NoRegister) { 3729 MachineBasicBlock::iterator I(&MI); 3730 const DebugLoc &DL = MI.getDebugLoc(); 3731 3732 assert(Offset == 0); 3733 3734 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3735 .add(*SrcVec) 3736 .add(*Val) 3737 .addImm(SubReg); 3738 3739 MI.eraseFromParent(); 3740 return &MBB; 3741 } 3742 3743 const MCInstrDesc &MovRelDesc 3744 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3745 3746 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3747 MachineBasicBlock::iterator I(&MI); 3748 const DebugLoc &DL = MI.getDebugLoc(); 3749 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3750 .addReg(SrcVec->getReg()) 3751 .add(*Val) 3752 .addImm(SubReg); 3753 if (UseGPRIdxMode) 3754 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3755 3756 MI.eraseFromParent(); 3757 return &MBB; 3758 } 3759 3760 if (Val->isReg()) 3761 MRI.clearKillFlags(Val->getReg()); 3762 3763 const DebugLoc &DL = MI.getDebugLoc(); 3764 3765 Register PhiReg = MRI.createVirtualRegister(VecRC); 3766 3767 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3768 Offset, UseGPRIdxMode, false); 3769 MachineBasicBlock *LoopBB = InsPt->getParent(); 3770 3771 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3772 .addReg(PhiReg) 3773 .add(*Val) 3774 .addImm(AMDGPU::sub0); 3775 if (UseGPRIdxMode) 3776 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3777 3778 MI.eraseFromParent(); 3779 return LoopBB; 3780 } 3781 3782 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3783 MachineInstr &MI, MachineBasicBlock *BB) const { 3784 3785 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3786 MachineFunction *MF = BB->getParent(); 3787 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3788 3789 switch (MI.getOpcode()) { 3790 case AMDGPU::S_UADDO_PSEUDO: 3791 case AMDGPU::S_USUBO_PSEUDO: { 3792 const DebugLoc &DL = MI.getDebugLoc(); 3793 MachineOperand &Dest0 = MI.getOperand(0); 3794 MachineOperand &Dest1 = MI.getOperand(1); 3795 MachineOperand &Src0 = MI.getOperand(2); 3796 MachineOperand &Src1 = MI.getOperand(3); 3797 3798 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3799 ? AMDGPU::S_ADD_I32 3800 : AMDGPU::S_SUB_I32; 3801 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3802 3803 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3804 .addImm(1) 3805 .addImm(0); 3806 3807 MI.eraseFromParent(); 3808 return BB; 3809 } 3810 case AMDGPU::S_ADD_U64_PSEUDO: 3811 case AMDGPU::S_SUB_U64_PSEUDO: { 3812 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3813 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3814 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3815 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3816 const DebugLoc &DL = MI.getDebugLoc(); 3817 3818 MachineOperand &Dest = MI.getOperand(0); 3819 MachineOperand &Src0 = MI.getOperand(1); 3820 MachineOperand &Src1 = MI.getOperand(2); 3821 3822 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3823 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3824 3825 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3826 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3827 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3828 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3829 3830 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3831 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3832 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3833 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3834 3835 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3836 3837 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3838 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3839 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3840 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3841 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3842 .addReg(DestSub0) 3843 .addImm(AMDGPU::sub0) 3844 .addReg(DestSub1) 3845 .addImm(AMDGPU::sub1); 3846 MI.eraseFromParent(); 3847 return BB; 3848 } 3849 case AMDGPU::V_ADD_U64_PSEUDO: 3850 case AMDGPU::V_SUB_U64_PSEUDO: { 3851 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3852 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3853 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3854 const DebugLoc &DL = MI.getDebugLoc(); 3855 3856 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3857 3858 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3859 3860 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3861 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3862 3863 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3864 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3865 3866 MachineOperand &Dest = MI.getOperand(0); 3867 MachineOperand &Src0 = MI.getOperand(1); 3868 MachineOperand &Src1 = MI.getOperand(2); 3869 3870 const TargetRegisterClass *Src0RC = Src0.isReg() 3871 ? MRI.getRegClass(Src0.getReg()) 3872 : &AMDGPU::VReg_64RegClass; 3873 const TargetRegisterClass *Src1RC = Src1.isReg() 3874 ? MRI.getRegClass(Src1.getReg()) 3875 : &AMDGPU::VReg_64RegClass; 3876 3877 const TargetRegisterClass *Src0SubRC = 3878 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3879 const TargetRegisterClass *Src1SubRC = 3880 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3881 3882 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3883 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3884 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3885 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3886 3887 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3888 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3889 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3890 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3891 3892 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3893 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3894 .addReg(CarryReg, RegState::Define) 3895 .add(SrcReg0Sub0) 3896 .add(SrcReg1Sub0) 3897 .addImm(0); // clamp bit 3898 3899 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3900 MachineInstr *HiHalf = 3901 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3902 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3903 .add(SrcReg0Sub1) 3904 .add(SrcReg1Sub1) 3905 .addReg(CarryReg, RegState::Kill) 3906 .addImm(0); // clamp bit 3907 3908 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3909 .addReg(DestSub0) 3910 .addImm(AMDGPU::sub0) 3911 .addReg(DestSub1) 3912 .addImm(AMDGPU::sub1); 3913 TII->legalizeOperands(*LoHalf); 3914 TII->legalizeOperands(*HiHalf); 3915 MI.eraseFromParent(); 3916 return BB; 3917 } 3918 case AMDGPU::S_ADD_CO_PSEUDO: 3919 case AMDGPU::S_SUB_CO_PSEUDO: { 3920 // This pseudo has a chance to be selected 3921 // only from uniform add/subcarry node. All the VGPR operands 3922 // therefore assumed to be splat vectors. 3923 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3924 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3925 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3926 MachineBasicBlock::iterator MII = MI; 3927 const DebugLoc &DL = MI.getDebugLoc(); 3928 MachineOperand &Dest = MI.getOperand(0); 3929 MachineOperand &CarryDest = MI.getOperand(1); 3930 MachineOperand &Src0 = MI.getOperand(2); 3931 MachineOperand &Src1 = MI.getOperand(3); 3932 MachineOperand &Src2 = MI.getOperand(4); 3933 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3934 ? AMDGPU::S_ADDC_U32 3935 : AMDGPU::S_SUBB_U32; 3936 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3937 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3938 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3939 .addReg(Src0.getReg()); 3940 Src0.setReg(RegOp0); 3941 } 3942 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3943 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3944 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3945 .addReg(Src1.getReg()); 3946 Src1.setReg(RegOp1); 3947 } 3948 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3949 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3950 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3951 .addReg(Src2.getReg()); 3952 Src2.setReg(RegOp2); 3953 } 3954 3955 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3956 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3957 .addReg(Src2.getReg()) 3958 .addImm(0); 3959 } else { 3960 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3961 .addReg(Src2.getReg()) 3962 .addImm(0); 3963 } 3964 3965 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3966 3967 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 3968 .addReg(AMDGPU::SCC); 3969 MI.eraseFromParent(); 3970 return BB; 3971 } 3972 case AMDGPU::SI_INIT_M0: { 3973 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3974 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3975 .add(MI.getOperand(0)); 3976 MI.eraseFromParent(); 3977 return BB; 3978 } 3979 case AMDGPU::SI_INIT_EXEC: 3980 // This should be before all vector instructions. 3981 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3982 AMDGPU::EXEC) 3983 .addImm(MI.getOperand(0).getImm()); 3984 MI.eraseFromParent(); 3985 return BB; 3986 3987 case AMDGPU::SI_INIT_EXEC_LO: 3988 // This should be before all vector instructions. 3989 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3990 AMDGPU::EXEC_LO) 3991 .addImm(MI.getOperand(0).getImm()); 3992 MI.eraseFromParent(); 3993 return BB; 3994 3995 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3996 // Extract the thread count from an SGPR input and set EXEC accordingly. 3997 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3998 // 3999 // S_BFE_U32 count, input, {shift, 7} 4000 // S_BFM_B64 exec, count, 0 4001 // S_CMP_EQ_U32 count, 64 4002 // S_CMOV_B64 exec, -1 4003 MachineInstr *FirstMI = &*BB->begin(); 4004 MachineRegisterInfo &MRI = MF->getRegInfo(); 4005 Register InputReg = MI.getOperand(0).getReg(); 4006 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4007 bool Found = false; 4008 4009 // Move the COPY of the input reg to the beginning, so that we can use it. 4010 for (auto I = BB->begin(); I != &MI; I++) { 4011 if (I->getOpcode() != TargetOpcode::COPY || 4012 I->getOperand(0).getReg() != InputReg) 4013 continue; 4014 4015 if (I == FirstMI) { 4016 FirstMI = &*++BB->begin(); 4017 } else { 4018 I->removeFromParent(); 4019 BB->insert(FirstMI, &*I); 4020 } 4021 Found = true; 4022 break; 4023 } 4024 assert(Found); 4025 (void)Found; 4026 4027 // This should be before all vector instructions. 4028 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4029 bool isWave32 = getSubtarget()->isWave32(); 4030 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4031 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4032 .addReg(InputReg) 4033 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4034 BuildMI(*BB, FirstMI, DebugLoc(), 4035 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4036 Exec) 4037 .addReg(CountReg) 4038 .addImm(0); 4039 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4040 .addReg(CountReg, RegState::Kill) 4041 .addImm(getSubtarget()->getWavefrontSize()); 4042 BuildMI(*BB, FirstMI, DebugLoc(), 4043 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4044 Exec) 4045 .addImm(-1); 4046 MI.eraseFromParent(); 4047 return BB; 4048 } 4049 4050 case AMDGPU::GET_GROUPSTATICSIZE: { 4051 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4052 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4053 DebugLoc DL = MI.getDebugLoc(); 4054 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4055 .add(MI.getOperand(0)) 4056 .addImm(MFI->getLDSSize()); 4057 MI.eraseFromParent(); 4058 return BB; 4059 } 4060 case AMDGPU::SI_INDIRECT_SRC_V1: 4061 case AMDGPU::SI_INDIRECT_SRC_V2: 4062 case AMDGPU::SI_INDIRECT_SRC_V4: 4063 case AMDGPU::SI_INDIRECT_SRC_V8: 4064 case AMDGPU::SI_INDIRECT_SRC_V16: 4065 case AMDGPU::SI_INDIRECT_SRC_V32: 4066 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4067 case AMDGPU::SI_INDIRECT_DST_V1: 4068 case AMDGPU::SI_INDIRECT_DST_V2: 4069 case AMDGPU::SI_INDIRECT_DST_V4: 4070 case AMDGPU::SI_INDIRECT_DST_V8: 4071 case AMDGPU::SI_INDIRECT_DST_V16: 4072 case AMDGPU::SI_INDIRECT_DST_V32: 4073 return emitIndirectDst(MI, *BB, *getSubtarget()); 4074 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4075 case AMDGPU::SI_KILL_I1_PSEUDO: 4076 return splitKillBlock(MI, BB); 4077 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4078 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4079 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4080 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4081 4082 Register Dst = MI.getOperand(0).getReg(); 4083 Register Src0 = MI.getOperand(1).getReg(); 4084 Register Src1 = MI.getOperand(2).getReg(); 4085 const DebugLoc &DL = MI.getDebugLoc(); 4086 Register SrcCond = MI.getOperand(3).getReg(); 4087 4088 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4089 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4090 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4091 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4092 4093 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4094 .addReg(SrcCond); 4095 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4096 .addImm(0) 4097 .addReg(Src0, 0, AMDGPU::sub0) 4098 .addImm(0) 4099 .addReg(Src1, 0, AMDGPU::sub0) 4100 .addReg(SrcCondCopy); 4101 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4102 .addImm(0) 4103 .addReg(Src0, 0, AMDGPU::sub1) 4104 .addImm(0) 4105 .addReg(Src1, 0, AMDGPU::sub1) 4106 .addReg(SrcCondCopy); 4107 4108 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4109 .addReg(DstLo) 4110 .addImm(AMDGPU::sub0) 4111 .addReg(DstHi) 4112 .addImm(AMDGPU::sub1); 4113 MI.eraseFromParent(); 4114 return BB; 4115 } 4116 case AMDGPU::SI_BR_UNDEF: { 4117 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4118 const DebugLoc &DL = MI.getDebugLoc(); 4119 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4120 .add(MI.getOperand(0)); 4121 Br->getOperand(1).setIsUndef(true); // read undef SCC 4122 MI.eraseFromParent(); 4123 return BB; 4124 } 4125 case AMDGPU::ADJCALLSTACKUP: 4126 case AMDGPU::ADJCALLSTACKDOWN: { 4127 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4128 MachineInstrBuilder MIB(*MF, &MI); 4129 4130 // Add an implicit use of the frame offset reg to prevent the restore copy 4131 // inserted after the call from being reorderd after stack operations in the 4132 // the caller's frame. 4133 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4134 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4135 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4136 return BB; 4137 } 4138 case AMDGPU::SI_CALL_ISEL: { 4139 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4140 const DebugLoc &DL = MI.getDebugLoc(); 4141 4142 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4143 4144 MachineInstrBuilder MIB; 4145 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4146 4147 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4148 MIB.add(MI.getOperand(I)); 4149 4150 MIB.cloneMemRefs(MI); 4151 MI.eraseFromParent(); 4152 return BB; 4153 } 4154 case AMDGPU::V_ADD_CO_U32_e32: 4155 case AMDGPU::V_SUB_CO_U32_e32: 4156 case AMDGPU::V_SUBREV_CO_U32_e32: { 4157 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4158 const DebugLoc &DL = MI.getDebugLoc(); 4159 unsigned Opc = MI.getOpcode(); 4160 4161 bool NeedClampOperand = false; 4162 if (TII->pseudoToMCOpcode(Opc) == -1) { 4163 Opc = AMDGPU::getVOPe64(Opc); 4164 NeedClampOperand = true; 4165 } 4166 4167 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4168 if (TII->isVOP3(*I)) { 4169 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4170 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4171 I.addReg(TRI->getVCC(), RegState::Define); 4172 } 4173 I.add(MI.getOperand(1)) 4174 .add(MI.getOperand(2)); 4175 if (NeedClampOperand) 4176 I.addImm(0); // clamp bit for e64 encoding 4177 4178 TII->legalizeOperands(*I); 4179 4180 MI.eraseFromParent(); 4181 return BB; 4182 } 4183 case AMDGPU::DS_GWS_INIT: 4184 case AMDGPU::DS_GWS_SEMA_V: 4185 case AMDGPU::DS_GWS_SEMA_BR: 4186 case AMDGPU::DS_GWS_SEMA_P: 4187 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4188 case AMDGPU::DS_GWS_BARRIER: 4189 // A s_waitcnt 0 is required to be the instruction immediately following. 4190 if (getSubtarget()->hasGWSAutoReplay()) { 4191 bundleInstWithWaitcnt(MI); 4192 return BB; 4193 } 4194 4195 return emitGWSMemViolTestLoop(MI, BB); 4196 case AMDGPU::S_SETREG_B32: { 4197 if (!getSubtarget()->hasDenormModeInst()) 4198 return BB; 4199 4200 // Try to optimize cases that only set the denormal mode or rounding mode. 4201 // 4202 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4203 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4204 // instead. 4205 // 4206 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4207 // allow you to have a no side effect instruction in the output of a 4208 // sideeffecting pattern. 4209 4210 // TODO: Should also emit a no side effects pseudo if only FP bits are 4211 // touched, even if not all of them or to a variable. 4212 unsigned ID, Offset, Width; 4213 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4214 if (ID != AMDGPU::Hwreg::ID_MODE) 4215 return BB; 4216 4217 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4218 const unsigned SetMask = WidthMask << Offset; 4219 unsigned SetDenormOp = 0; 4220 unsigned SetRoundOp = 0; 4221 4222 // The dedicated instructions can only set the whole denorm or round mode at 4223 // once, not a subset of bits in either. 4224 if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4225 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) { 4226 // If this fully sets both the round and denorm mode, emit the two 4227 // dedicated instructions for these. 4228 assert(Offset == 0); 4229 SetRoundOp = AMDGPU::S_ROUND_MODE; 4230 SetDenormOp = AMDGPU::S_DENORM_MODE; 4231 } else if (Width == 4) { 4232 if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) { 4233 SetRoundOp = AMDGPU::S_ROUND_MODE; 4234 assert(Offset == 0); 4235 } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) { 4236 SetDenormOp = AMDGPU::S_DENORM_MODE; 4237 assert(Offset == 4); 4238 } 4239 } 4240 4241 if (SetRoundOp || SetDenormOp) { 4242 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4243 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4244 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4245 unsigned ImmVal = Def->getOperand(1).getImm(); 4246 if (SetRoundOp) { 4247 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4248 .addImm(ImmVal & 0xf); 4249 4250 // If we also have the denorm mode, get just the denorm mode bits. 4251 ImmVal >>= 4; 4252 } 4253 4254 if (SetDenormOp) { 4255 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4256 .addImm(ImmVal & 0xf); 4257 } 4258 4259 MI.eraseFromParent(); 4260 } 4261 } 4262 4263 return BB; 4264 } 4265 default: 4266 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4267 } 4268 } 4269 4270 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4271 return isTypeLegal(VT.getScalarType()); 4272 } 4273 4274 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4275 // This currently forces unfolding various combinations of fsub into fma with 4276 // free fneg'd operands. As long as we have fast FMA (controlled by 4277 // isFMAFasterThanFMulAndFAdd), we should perform these. 4278 4279 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4280 // most of these combines appear to be cycle neutral but save on instruction 4281 // count / code size. 4282 return true; 4283 } 4284 4285 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4286 EVT VT) const { 4287 if (!VT.isVector()) { 4288 return MVT::i1; 4289 } 4290 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4291 } 4292 4293 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4294 // TODO: Should i16 be used always if legal? For now it would force VALU 4295 // shifts. 4296 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4297 } 4298 4299 // Answering this is somewhat tricky and depends on the specific device which 4300 // have different rates for fma or all f64 operations. 4301 // 4302 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4303 // regardless of which device (although the number of cycles differs between 4304 // devices), so it is always profitable for f64. 4305 // 4306 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4307 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4308 // which we can always do even without fused FP ops since it returns the same 4309 // result as the separate operations and since it is always full 4310 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4311 // however does not support denormals, so we do report fma as faster if we have 4312 // a fast fma device and require denormals. 4313 // 4314 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4315 EVT VT) const { 4316 VT = VT.getScalarType(); 4317 4318 switch (VT.getSimpleVT().SimpleTy) { 4319 case MVT::f32: { 4320 // If mad is not available this depends only on if f32 fma is full rate. 4321 if (!Subtarget->hasMadMacF32Insts()) 4322 return Subtarget->hasFastFMAF32(); 4323 4324 // Otherwise f32 mad is always full rate and returns the same result as 4325 // the separate operations so should be preferred over fma. 4326 // However does not support denomals. 4327 if (hasFP32Denormals(MF)) 4328 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4329 4330 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4331 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4332 } 4333 case MVT::f64: 4334 return true; 4335 case MVT::f16: 4336 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4337 default: 4338 break; 4339 } 4340 4341 return false; 4342 } 4343 4344 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4345 const SDNode *N) const { 4346 // TODO: Check future ftz flag 4347 // v_mad_f32/v_mac_f32 do not support denormals. 4348 EVT VT = N->getValueType(0); 4349 if (VT == MVT::f32) 4350 return Subtarget->hasMadMacF32Insts() && 4351 !hasFP32Denormals(DAG.getMachineFunction()); 4352 if (VT == MVT::f16) { 4353 return Subtarget->hasMadF16() && 4354 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4355 } 4356 4357 return false; 4358 } 4359 4360 //===----------------------------------------------------------------------===// 4361 // Custom DAG Lowering Operations 4362 //===----------------------------------------------------------------------===// 4363 4364 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4365 // wider vector type is legal. 4366 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4367 SelectionDAG &DAG) const { 4368 unsigned Opc = Op.getOpcode(); 4369 EVT VT = Op.getValueType(); 4370 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4371 4372 SDValue Lo, Hi; 4373 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4374 4375 SDLoc SL(Op); 4376 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4377 Op->getFlags()); 4378 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4379 Op->getFlags()); 4380 4381 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4382 } 4383 4384 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4385 // wider vector type is legal. 4386 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4387 SelectionDAG &DAG) const { 4388 unsigned Opc = Op.getOpcode(); 4389 EVT VT = Op.getValueType(); 4390 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4391 4392 SDValue Lo0, Hi0; 4393 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4394 SDValue Lo1, Hi1; 4395 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4396 4397 SDLoc SL(Op); 4398 4399 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4400 Op->getFlags()); 4401 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4402 Op->getFlags()); 4403 4404 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4405 } 4406 4407 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4408 SelectionDAG &DAG) const { 4409 unsigned Opc = Op.getOpcode(); 4410 EVT VT = Op.getValueType(); 4411 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4412 4413 SDValue Lo0, Hi0; 4414 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4415 SDValue Lo1, Hi1; 4416 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4417 SDValue Lo2, Hi2; 4418 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4419 4420 SDLoc SL(Op); 4421 4422 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4423 Op->getFlags()); 4424 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4425 Op->getFlags()); 4426 4427 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4428 } 4429 4430 4431 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4432 switch (Op.getOpcode()) { 4433 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4434 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4435 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4436 case ISD::LOAD: { 4437 SDValue Result = LowerLOAD(Op, DAG); 4438 assert((!Result.getNode() || 4439 Result.getNode()->getNumValues() == 2) && 4440 "Load should return a value and a chain"); 4441 return Result; 4442 } 4443 4444 case ISD::FSIN: 4445 case ISD::FCOS: 4446 return LowerTrig(Op, DAG); 4447 case ISD::SELECT: return LowerSELECT(Op, DAG); 4448 case ISD::FDIV: return LowerFDIV(Op, DAG); 4449 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4450 case ISD::STORE: return LowerSTORE(Op, DAG); 4451 case ISD::GlobalAddress: { 4452 MachineFunction &MF = DAG.getMachineFunction(); 4453 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4454 return LowerGlobalAddress(MFI, Op, DAG); 4455 } 4456 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4457 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4458 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4459 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4460 case ISD::INSERT_SUBVECTOR: 4461 return lowerINSERT_SUBVECTOR(Op, DAG); 4462 case ISD::INSERT_VECTOR_ELT: 4463 return lowerINSERT_VECTOR_ELT(Op, DAG); 4464 case ISD::EXTRACT_VECTOR_ELT: 4465 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4466 case ISD::VECTOR_SHUFFLE: 4467 return lowerVECTOR_SHUFFLE(Op, DAG); 4468 case ISD::BUILD_VECTOR: 4469 return lowerBUILD_VECTOR(Op, DAG); 4470 case ISD::FP_ROUND: 4471 return lowerFP_ROUND(Op, DAG); 4472 case ISD::TRAP: 4473 return lowerTRAP(Op, DAG); 4474 case ISD::DEBUGTRAP: 4475 return lowerDEBUGTRAP(Op, DAG); 4476 case ISD::FABS: 4477 case ISD::FNEG: 4478 case ISD::FCANONICALIZE: 4479 case ISD::BSWAP: 4480 return splitUnaryVectorOp(Op, DAG); 4481 case ISD::FMINNUM: 4482 case ISD::FMAXNUM: 4483 return lowerFMINNUM_FMAXNUM(Op, DAG); 4484 case ISD::FMA: 4485 return splitTernaryVectorOp(Op, DAG); 4486 case ISD::SHL: 4487 case ISD::SRA: 4488 case ISD::SRL: 4489 case ISD::ADD: 4490 case ISD::SUB: 4491 case ISD::MUL: 4492 case ISD::SMIN: 4493 case ISD::SMAX: 4494 case ISD::UMIN: 4495 case ISD::UMAX: 4496 case ISD::FADD: 4497 case ISD::FMUL: 4498 case ISD::FMINNUM_IEEE: 4499 case ISD::FMAXNUM_IEEE: 4500 case ISD::UADDSAT: 4501 case ISD::USUBSAT: 4502 case ISD::SADDSAT: 4503 case ISD::SSUBSAT: 4504 return splitBinaryVectorOp(Op, DAG); 4505 case ISD::SMULO: 4506 case ISD::UMULO: 4507 return lowerXMULO(Op, DAG); 4508 case ISD::DYNAMIC_STACKALLOC: 4509 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4510 } 4511 return SDValue(); 4512 } 4513 4514 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4515 const SDLoc &DL, 4516 SelectionDAG &DAG, bool Unpacked) { 4517 if (!LoadVT.isVector()) 4518 return Result; 4519 4520 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4521 // Truncate to v2i16/v4i16. 4522 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4523 4524 // Workaround legalizer not scalarizing truncate after vector op 4525 // legalization but not creating intermediate vector trunc. 4526 SmallVector<SDValue, 4> Elts; 4527 DAG.ExtractVectorElements(Result, Elts); 4528 for (SDValue &Elt : Elts) 4529 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4530 4531 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4532 4533 // Bitcast to original type (v2f16/v4f16). 4534 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4535 } 4536 4537 // Cast back to the original packed type. 4538 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4539 } 4540 4541 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4542 MemSDNode *M, 4543 SelectionDAG &DAG, 4544 ArrayRef<SDValue> Ops, 4545 bool IsIntrinsic) const { 4546 SDLoc DL(M); 4547 4548 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4549 EVT LoadVT = M->getValueType(0); 4550 4551 EVT EquivLoadVT = LoadVT; 4552 if (Unpacked && LoadVT.isVector()) { 4553 EquivLoadVT = LoadVT.isVector() ? 4554 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4555 LoadVT.getVectorNumElements()) : LoadVT; 4556 } 4557 4558 // Change from v4f16/v2f16 to EquivLoadVT. 4559 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4560 4561 SDValue Load 4562 = DAG.getMemIntrinsicNode( 4563 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4564 VTList, Ops, M->getMemoryVT(), 4565 M->getMemOperand()); 4566 if (!Unpacked) // Just adjusted the opcode. 4567 return Load; 4568 4569 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4570 4571 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4572 } 4573 4574 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4575 SelectionDAG &DAG, 4576 ArrayRef<SDValue> Ops) const { 4577 SDLoc DL(M); 4578 EVT LoadVT = M->getValueType(0); 4579 EVT EltType = LoadVT.getScalarType(); 4580 EVT IntVT = LoadVT.changeTypeToInteger(); 4581 4582 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4583 4584 unsigned Opc = 4585 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4586 4587 if (IsD16) { 4588 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4589 } 4590 4591 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4592 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4593 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4594 4595 if (isTypeLegal(LoadVT)) { 4596 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4597 M->getMemOperand(), DAG); 4598 } 4599 4600 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4601 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4602 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4603 M->getMemOperand(), DAG); 4604 return DAG.getMergeValues( 4605 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4606 DL); 4607 } 4608 4609 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4610 SDNode *N, SelectionDAG &DAG) { 4611 EVT VT = N->getValueType(0); 4612 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4613 unsigned CondCode = CD->getZExtValue(); 4614 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4615 return DAG.getUNDEF(VT); 4616 4617 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4618 4619 SDValue LHS = N->getOperand(1); 4620 SDValue RHS = N->getOperand(2); 4621 4622 SDLoc DL(N); 4623 4624 EVT CmpVT = LHS.getValueType(); 4625 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4626 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4627 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4628 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4629 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4630 } 4631 4632 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4633 4634 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4635 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4636 4637 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4638 DAG.getCondCode(CCOpcode)); 4639 if (VT.bitsEq(CCVT)) 4640 return SetCC; 4641 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4642 } 4643 4644 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4645 SDNode *N, SelectionDAG &DAG) { 4646 EVT VT = N->getValueType(0); 4647 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4648 4649 unsigned CondCode = CD->getZExtValue(); 4650 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4651 return DAG.getUNDEF(VT); 4652 4653 SDValue Src0 = N->getOperand(1); 4654 SDValue Src1 = N->getOperand(2); 4655 EVT CmpVT = Src0.getValueType(); 4656 SDLoc SL(N); 4657 4658 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4659 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4660 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4661 } 4662 4663 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4664 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4665 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4666 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4667 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4668 Src1, DAG.getCondCode(CCOpcode)); 4669 if (VT.bitsEq(CCVT)) 4670 return SetCC; 4671 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4672 } 4673 4674 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4675 SelectionDAG &DAG) { 4676 EVT VT = N->getValueType(0); 4677 SDValue Src = N->getOperand(1); 4678 SDLoc SL(N); 4679 4680 if (Src.getOpcode() == ISD::SETCC) { 4681 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4682 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4683 Src.getOperand(1), Src.getOperand(2)); 4684 } 4685 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4686 // (ballot 0) -> 0 4687 if (Arg->isNullValue()) 4688 return DAG.getConstant(0, SL, VT); 4689 4690 // (ballot 1) -> EXEC/EXEC_LO 4691 if (Arg->isOne()) { 4692 Register Exec; 4693 if (VT.getScalarSizeInBits() == 32) 4694 Exec = AMDGPU::EXEC_LO; 4695 else if (VT.getScalarSizeInBits() == 64) 4696 Exec = AMDGPU::EXEC; 4697 else 4698 return SDValue(); 4699 4700 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4701 } 4702 } 4703 4704 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4705 // ISD::SETNE) 4706 return DAG.getNode( 4707 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4708 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4709 } 4710 4711 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4712 SmallVectorImpl<SDValue> &Results, 4713 SelectionDAG &DAG) const { 4714 switch (N->getOpcode()) { 4715 case ISD::INSERT_VECTOR_ELT: { 4716 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4717 Results.push_back(Res); 4718 return; 4719 } 4720 case ISD::EXTRACT_VECTOR_ELT: { 4721 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4722 Results.push_back(Res); 4723 return; 4724 } 4725 case ISD::INTRINSIC_WO_CHAIN: { 4726 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4727 switch (IID) { 4728 case Intrinsic::amdgcn_cvt_pkrtz: { 4729 SDValue Src0 = N->getOperand(1); 4730 SDValue Src1 = N->getOperand(2); 4731 SDLoc SL(N); 4732 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4733 Src0, Src1); 4734 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4735 return; 4736 } 4737 case Intrinsic::amdgcn_cvt_pknorm_i16: 4738 case Intrinsic::amdgcn_cvt_pknorm_u16: 4739 case Intrinsic::amdgcn_cvt_pk_i16: 4740 case Intrinsic::amdgcn_cvt_pk_u16: { 4741 SDValue Src0 = N->getOperand(1); 4742 SDValue Src1 = N->getOperand(2); 4743 SDLoc SL(N); 4744 unsigned Opcode; 4745 4746 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4747 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4748 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4749 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4750 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4751 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4752 else 4753 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4754 4755 EVT VT = N->getValueType(0); 4756 if (isTypeLegal(VT)) 4757 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4758 else { 4759 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4760 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4761 } 4762 return; 4763 } 4764 } 4765 break; 4766 } 4767 case ISD::INTRINSIC_W_CHAIN: { 4768 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4769 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4770 // FIXME: Hacky 4771 Results.push_back(Res.getOperand(0)); 4772 Results.push_back(Res.getOperand(1)); 4773 } else { 4774 Results.push_back(Res); 4775 Results.push_back(Res.getValue(1)); 4776 } 4777 return; 4778 } 4779 4780 break; 4781 } 4782 case ISD::SELECT: { 4783 SDLoc SL(N); 4784 EVT VT = N->getValueType(0); 4785 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4786 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4787 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4788 4789 EVT SelectVT = NewVT; 4790 if (NewVT.bitsLT(MVT::i32)) { 4791 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4792 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4793 SelectVT = MVT::i32; 4794 } 4795 4796 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4797 N->getOperand(0), LHS, RHS); 4798 4799 if (NewVT != SelectVT) 4800 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4801 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4802 return; 4803 } 4804 case ISD::FNEG: { 4805 if (N->getValueType(0) != MVT::v2f16) 4806 break; 4807 4808 SDLoc SL(N); 4809 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4810 4811 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4812 BC, 4813 DAG.getConstant(0x80008000, SL, MVT::i32)); 4814 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4815 return; 4816 } 4817 case ISD::FABS: { 4818 if (N->getValueType(0) != MVT::v2f16) 4819 break; 4820 4821 SDLoc SL(N); 4822 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4823 4824 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4825 BC, 4826 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4827 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4828 return; 4829 } 4830 default: 4831 break; 4832 } 4833 } 4834 4835 /// Helper function for LowerBRCOND 4836 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4837 4838 SDNode *Parent = Value.getNode(); 4839 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4840 I != E; ++I) { 4841 4842 if (I.getUse().get() != Value) 4843 continue; 4844 4845 if (I->getOpcode() == Opcode) 4846 return *I; 4847 } 4848 return nullptr; 4849 } 4850 4851 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4852 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4853 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4854 case Intrinsic::amdgcn_if: 4855 return AMDGPUISD::IF; 4856 case Intrinsic::amdgcn_else: 4857 return AMDGPUISD::ELSE; 4858 case Intrinsic::amdgcn_loop: 4859 return AMDGPUISD::LOOP; 4860 case Intrinsic::amdgcn_end_cf: 4861 llvm_unreachable("should not occur"); 4862 default: 4863 return 0; 4864 } 4865 } 4866 4867 // break, if_break, else_break are all only used as inputs to loop, not 4868 // directly as branch conditions. 4869 return 0; 4870 } 4871 4872 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4873 const Triple &TT = getTargetMachine().getTargetTriple(); 4874 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4875 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4876 AMDGPU::shouldEmitConstantsToTextSection(TT); 4877 } 4878 4879 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4880 // FIXME: Either avoid relying on address space here or change the default 4881 // address space for functions to avoid the explicit check. 4882 return (GV->getValueType()->isFunctionTy() || 4883 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4884 !shouldEmitFixup(GV) && 4885 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4886 } 4887 4888 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4889 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4890 } 4891 4892 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4893 if (!GV->hasExternalLinkage()) 4894 return true; 4895 4896 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4897 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4898 } 4899 4900 /// This transforms the control flow intrinsics to get the branch destination as 4901 /// last parameter, also switches branch target with BR if the need arise 4902 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4903 SelectionDAG &DAG) const { 4904 SDLoc DL(BRCOND); 4905 4906 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4907 SDValue Target = BRCOND.getOperand(2); 4908 SDNode *BR = nullptr; 4909 SDNode *SetCC = nullptr; 4910 4911 if (Intr->getOpcode() == ISD::SETCC) { 4912 // As long as we negate the condition everything is fine 4913 SetCC = Intr; 4914 Intr = SetCC->getOperand(0).getNode(); 4915 4916 } else { 4917 // Get the target from BR if we don't negate the condition 4918 BR = findUser(BRCOND, ISD::BR); 4919 assert(BR && "brcond missing unconditional branch user"); 4920 Target = BR->getOperand(1); 4921 } 4922 4923 unsigned CFNode = isCFIntrinsic(Intr); 4924 if (CFNode == 0) { 4925 // This is a uniform branch so we don't need to legalize. 4926 return BRCOND; 4927 } 4928 4929 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4930 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4931 4932 assert(!SetCC || 4933 (SetCC->getConstantOperandVal(1) == 1 && 4934 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4935 ISD::SETNE)); 4936 4937 // operands of the new intrinsic call 4938 SmallVector<SDValue, 4> Ops; 4939 if (HaveChain) 4940 Ops.push_back(BRCOND.getOperand(0)); 4941 4942 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4943 Ops.push_back(Target); 4944 4945 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4946 4947 // build the new intrinsic call 4948 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4949 4950 if (!HaveChain) { 4951 SDValue Ops[] = { 4952 SDValue(Result, 0), 4953 BRCOND.getOperand(0) 4954 }; 4955 4956 Result = DAG.getMergeValues(Ops, DL).getNode(); 4957 } 4958 4959 if (BR) { 4960 // Give the branch instruction our target 4961 SDValue Ops[] = { 4962 BR->getOperand(0), 4963 BRCOND.getOperand(2) 4964 }; 4965 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4966 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4967 } 4968 4969 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4970 4971 // Copy the intrinsic results to registers 4972 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4973 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4974 if (!CopyToReg) 4975 continue; 4976 4977 Chain = DAG.getCopyToReg( 4978 Chain, DL, 4979 CopyToReg->getOperand(1), 4980 SDValue(Result, i - 1), 4981 SDValue()); 4982 4983 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4984 } 4985 4986 // Remove the old intrinsic from the chain 4987 DAG.ReplaceAllUsesOfValueWith( 4988 SDValue(Intr, Intr->getNumValues() - 1), 4989 Intr->getOperand(0)); 4990 4991 return Chain; 4992 } 4993 4994 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4995 SelectionDAG &DAG) const { 4996 MVT VT = Op.getSimpleValueType(); 4997 SDLoc DL(Op); 4998 // Checking the depth 4999 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5000 return DAG.getConstant(0, DL, VT); 5001 5002 MachineFunction &MF = DAG.getMachineFunction(); 5003 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5004 // Check for kernel and shader functions 5005 if (Info->isEntryFunction()) 5006 return DAG.getConstant(0, DL, VT); 5007 5008 MachineFrameInfo &MFI = MF.getFrameInfo(); 5009 // There is a call to @llvm.returnaddress in this function 5010 MFI.setReturnAddressIsTaken(true); 5011 5012 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5013 // Get the return address reg and mark it as an implicit live-in 5014 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5015 5016 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5017 } 5018 5019 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5020 SDValue Op, 5021 const SDLoc &DL, 5022 EVT VT) const { 5023 return Op.getValueType().bitsLE(VT) ? 5024 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5025 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5026 DAG.getTargetConstant(0, DL, MVT::i32)); 5027 } 5028 5029 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5030 assert(Op.getValueType() == MVT::f16 && 5031 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5032 5033 SDValue Src = Op.getOperand(0); 5034 EVT SrcVT = Src.getValueType(); 5035 if (SrcVT != MVT::f64) 5036 return Op; 5037 5038 SDLoc DL(Op); 5039 5040 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5041 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5042 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5043 } 5044 5045 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5046 SelectionDAG &DAG) const { 5047 EVT VT = Op.getValueType(); 5048 const MachineFunction &MF = DAG.getMachineFunction(); 5049 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5050 bool IsIEEEMode = Info->getMode().IEEE; 5051 5052 // FIXME: Assert during selection that this is only selected for 5053 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5054 // mode functions, but this happens to be OK since it's only done in cases 5055 // where there is known no sNaN. 5056 if (IsIEEEMode) 5057 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5058 5059 if (VT == MVT::v4f16) 5060 return splitBinaryVectorOp(Op, DAG); 5061 return Op; 5062 } 5063 5064 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5065 EVT VT = Op.getValueType(); 5066 SDLoc SL(Op); 5067 SDValue LHS = Op.getOperand(0); 5068 SDValue RHS = Op.getOperand(1); 5069 bool isSigned = Op.getOpcode() == ISD::SMULO; 5070 5071 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5072 const APInt &C = RHSC->getAPIntValue(); 5073 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5074 if (C.isPowerOf2()) { 5075 // smulo(x, signed_min) is same as umulo(x, signed_min). 5076 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5077 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5078 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5079 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5080 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5081 SL, VT, Result, ShiftAmt), 5082 LHS, ISD::SETNE); 5083 return DAG.getMergeValues({ Result, Overflow }, SL); 5084 } 5085 } 5086 5087 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5088 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5089 SL, VT, LHS, RHS); 5090 5091 SDValue Sign = isSigned 5092 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5093 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5094 : DAG.getConstant(0, SL, VT); 5095 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5096 5097 return DAG.getMergeValues({ Result, Overflow }, SL); 5098 } 5099 5100 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5101 SDLoc SL(Op); 5102 SDValue Chain = Op.getOperand(0); 5103 5104 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5105 !Subtarget->isTrapHandlerEnabled()) 5106 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5107 5108 MachineFunction &MF = DAG.getMachineFunction(); 5109 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5110 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 5111 assert(UserSGPR != AMDGPU::NoRegister); 5112 SDValue QueuePtr = CreateLiveInRegister( 5113 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5114 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5115 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5116 QueuePtr, SDValue()); 5117 SDValue Ops[] = { 5118 ToReg, 5119 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5120 SGPR01, 5121 ToReg.getValue(1) 5122 }; 5123 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5124 } 5125 5126 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5127 SDLoc SL(Op); 5128 SDValue Chain = Op.getOperand(0); 5129 MachineFunction &MF = DAG.getMachineFunction(); 5130 5131 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5132 !Subtarget->isTrapHandlerEnabled()) { 5133 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5134 "debugtrap handler not supported", 5135 Op.getDebugLoc(), 5136 DS_Warning); 5137 LLVMContext &Ctx = MF.getFunction().getContext(); 5138 Ctx.diagnose(NoTrap); 5139 return Chain; 5140 } 5141 5142 SDValue Ops[] = { 5143 Chain, 5144 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5145 }; 5146 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5147 } 5148 5149 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5150 SelectionDAG &DAG) const { 5151 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5152 if (Subtarget->hasApertureRegs()) { 5153 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5154 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5155 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5156 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5157 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5158 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5159 unsigned Encoding = 5160 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5161 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5162 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5163 5164 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5165 SDValue ApertureReg = SDValue( 5166 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5167 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5168 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5169 } 5170 5171 MachineFunction &MF = DAG.getMachineFunction(); 5172 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5173 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5174 assert(UserSGPR != AMDGPU::NoRegister); 5175 5176 SDValue QueuePtr = CreateLiveInRegister( 5177 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5178 5179 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5180 // private_segment_aperture_base_hi. 5181 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5182 5183 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 5184 5185 // TODO: Use custom target PseudoSourceValue. 5186 // TODO: We should use the value from the IR intrinsic call, but it might not 5187 // be available and how do we get it? 5188 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5189 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5190 MinAlign(64, StructOffset), 5191 MachineMemOperand::MODereferenceable | 5192 MachineMemOperand::MOInvariant); 5193 } 5194 5195 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5196 SelectionDAG &DAG) const { 5197 SDLoc SL(Op); 5198 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5199 5200 SDValue Src = ASC->getOperand(0); 5201 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5202 5203 const AMDGPUTargetMachine &TM = 5204 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5205 5206 // flat -> local/private 5207 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5208 unsigned DestAS = ASC->getDestAddressSpace(); 5209 5210 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5211 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5212 unsigned NullVal = TM.getNullPointerValue(DestAS); 5213 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5214 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5215 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5216 5217 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5218 NonNull, Ptr, SegmentNullPtr); 5219 } 5220 } 5221 5222 // local/private -> flat 5223 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5224 unsigned SrcAS = ASC->getSrcAddressSpace(); 5225 5226 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5227 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5228 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5229 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5230 5231 SDValue NonNull 5232 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5233 5234 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5235 SDValue CvtPtr 5236 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5237 5238 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5239 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5240 FlatNullPtr); 5241 } 5242 } 5243 5244 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5245 Src.getValueType() == MVT::i64) 5246 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5247 5248 // global <-> flat are no-ops and never emitted. 5249 5250 const MachineFunction &MF = DAG.getMachineFunction(); 5251 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5252 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5253 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5254 5255 return DAG.getUNDEF(ASC->getValueType(0)); 5256 } 5257 5258 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5259 // the small vector and inserting them into the big vector. That is better than 5260 // the default expansion of doing it via a stack slot. Even though the use of 5261 // the stack slot would be optimized away afterwards, the stack slot itself 5262 // remains. 5263 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5264 SelectionDAG &DAG) const { 5265 SDValue Vec = Op.getOperand(0); 5266 SDValue Ins = Op.getOperand(1); 5267 SDValue Idx = Op.getOperand(2); 5268 EVT VecVT = Vec.getValueType(); 5269 EVT InsVT = Ins.getValueType(); 5270 EVT EltVT = VecVT.getVectorElementType(); 5271 unsigned InsNumElts = InsVT.getVectorNumElements(); 5272 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5273 SDLoc SL(Op); 5274 5275 for (unsigned I = 0; I != InsNumElts; ++I) { 5276 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5277 DAG.getConstant(I, SL, MVT::i32)); 5278 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5279 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5280 } 5281 return Vec; 5282 } 5283 5284 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5285 SelectionDAG &DAG) const { 5286 SDValue Vec = Op.getOperand(0); 5287 SDValue InsVal = Op.getOperand(1); 5288 SDValue Idx = Op.getOperand(2); 5289 EVT VecVT = Vec.getValueType(); 5290 EVT EltVT = VecVT.getVectorElementType(); 5291 unsigned VecSize = VecVT.getSizeInBits(); 5292 unsigned EltSize = EltVT.getSizeInBits(); 5293 5294 5295 assert(VecSize <= 64); 5296 5297 unsigned NumElts = VecVT.getVectorNumElements(); 5298 SDLoc SL(Op); 5299 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5300 5301 if (NumElts == 4 && EltSize == 16 && KIdx) { 5302 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5303 5304 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5305 DAG.getConstant(0, SL, MVT::i32)); 5306 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5307 DAG.getConstant(1, SL, MVT::i32)); 5308 5309 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5310 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5311 5312 unsigned Idx = KIdx->getZExtValue(); 5313 bool InsertLo = Idx < 2; 5314 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5315 InsertLo ? LoVec : HiVec, 5316 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5317 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5318 5319 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5320 5321 SDValue Concat = InsertLo ? 5322 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5323 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5324 5325 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5326 } 5327 5328 if (isa<ConstantSDNode>(Idx)) 5329 return SDValue(); 5330 5331 MVT IntVT = MVT::getIntegerVT(VecSize); 5332 5333 // Avoid stack access for dynamic indexing. 5334 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5335 5336 // Create a congruent vector with the target value in each element so that 5337 // the required element can be masked and ORed into the target vector. 5338 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5339 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5340 5341 assert(isPowerOf2_32(EltSize)); 5342 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5343 5344 // Convert vector index to bit-index. 5345 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5346 5347 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5348 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5349 DAG.getConstant(0xffff, SL, IntVT), 5350 ScaledIdx); 5351 5352 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5353 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5354 DAG.getNOT(SL, BFM, IntVT), BCVec); 5355 5356 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5357 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5358 } 5359 5360 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5361 SelectionDAG &DAG) const { 5362 SDLoc SL(Op); 5363 5364 EVT ResultVT = Op.getValueType(); 5365 SDValue Vec = Op.getOperand(0); 5366 SDValue Idx = Op.getOperand(1); 5367 EVT VecVT = Vec.getValueType(); 5368 unsigned VecSize = VecVT.getSizeInBits(); 5369 EVT EltVT = VecVT.getVectorElementType(); 5370 assert(VecSize <= 64); 5371 5372 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5373 5374 // Make sure we do any optimizations that will make it easier to fold 5375 // source modifiers before obscuring it with bit operations. 5376 5377 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5378 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5379 return Combined; 5380 5381 unsigned EltSize = EltVT.getSizeInBits(); 5382 assert(isPowerOf2_32(EltSize)); 5383 5384 MVT IntVT = MVT::getIntegerVT(VecSize); 5385 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5386 5387 // Convert vector index to bit-index (* EltSize) 5388 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5389 5390 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5391 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5392 5393 if (ResultVT == MVT::f16) { 5394 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5395 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5396 } 5397 5398 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5399 } 5400 5401 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5402 assert(Elt % 2 == 0); 5403 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5404 } 5405 5406 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5407 SelectionDAG &DAG) const { 5408 SDLoc SL(Op); 5409 EVT ResultVT = Op.getValueType(); 5410 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5411 5412 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5413 EVT EltVT = PackVT.getVectorElementType(); 5414 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5415 5416 // vector_shuffle <0,1,6,7> lhs, rhs 5417 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5418 // 5419 // vector_shuffle <6,7,2,3> lhs, rhs 5420 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5421 // 5422 // vector_shuffle <6,7,0,1> lhs, rhs 5423 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5424 5425 // Avoid scalarizing when both halves are reading from consecutive elements. 5426 SmallVector<SDValue, 4> Pieces; 5427 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5428 if (elementPairIsContiguous(SVN->getMask(), I)) { 5429 const int Idx = SVN->getMaskElt(I); 5430 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5431 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5432 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5433 PackVT, SVN->getOperand(VecIdx), 5434 DAG.getConstant(EltIdx, SL, MVT::i32)); 5435 Pieces.push_back(SubVec); 5436 } else { 5437 const int Idx0 = SVN->getMaskElt(I); 5438 const int Idx1 = SVN->getMaskElt(I + 1); 5439 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5440 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5441 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5442 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5443 5444 SDValue Vec0 = SVN->getOperand(VecIdx0); 5445 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5446 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5447 5448 SDValue Vec1 = SVN->getOperand(VecIdx1); 5449 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5450 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5451 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5452 } 5453 } 5454 5455 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5456 } 5457 5458 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5459 SelectionDAG &DAG) const { 5460 SDLoc SL(Op); 5461 EVT VT = Op.getValueType(); 5462 5463 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5464 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5465 5466 // Turn into pair of packed build_vectors. 5467 // TODO: Special case for constants that can be materialized with s_mov_b64. 5468 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5469 { Op.getOperand(0), Op.getOperand(1) }); 5470 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5471 { Op.getOperand(2), Op.getOperand(3) }); 5472 5473 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5474 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5475 5476 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5477 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5478 } 5479 5480 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5481 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5482 5483 SDValue Lo = Op.getOperand(0); 5484 SDValue Hi = Op.getOperand(1); 5485 5486 // Avoid adding defined bits with the zero_extend. 5487 if (Hi.isUndef()) { 5488 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5489 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5490 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5491 } 5492 5493 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5494 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5495 5496 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5497 DAG.getConstant(16, SL, MVT::i32)); 5498 if (Lo.isUndef()) 5499 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5500 5501 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5502 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5503 5504 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5505 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5506 } 5507 5508 bool 5509 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5510 // We can fold offsets for anything that doesn't require a GOT relocation. 5511 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5512 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5513 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5514 !shouldEmitGOTReloc(GA->getGlobal()); 5515 } 5516 5517 static SDValue 5518 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5519 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5520 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5521 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5522 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5523 // lowered to the following code sequence: 5524 // 5525 // For constant address space: 5526 // s_getpc_b64 s[0:1] 5527 // s_add_u32 s0, s0, $symbol 5528 // s_addc_u32 s1, s1, 0 5529 // 5530 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5531 // a fixup or relocation is emitted to replace $symbol with a literal 5532 // constant, which is a pc-relative offset from the encoding of the $symbol 5533 // operand to the global variable. 5534 // 5535 // For global address space: 5536 // s_getpc_b64 s[0:1] 5537 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5538 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5539 // 5540 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5541 // fixups or relocations are emitted to replace $symbol@*@lo and 5542 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5543 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5544 // operand to the global variable. 5545 // 5546 // What we want here is an offset from the value returned by s_getpc 5547 // (which is the address of the s_add_u32 instruction) to the global 5548 // variable, but since the encoding of $symbol starts 4 bytes after the start 5549 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5550 // small. This requires us to add 4 to the global variable offset in order to 5551 // compute the correct address. 5552 SDValue PtrLo = 5553 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5554 SDValue PtrHi; 5555 if (GAFlags == SIInstrInfo::MO_NONE) { 5556 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5557 } else { 5558 PtrHi = 5559 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5560 } 5561 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5562 } 5563 5564 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5565 SDValue Op, 5566 SelectionDAG &DAG) const { 5567 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5568 const GlobalValue *GV = GSD->getGlobal(); 5569 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5570 shouldUseLDSConstAddress(GV)) || 5571 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5572 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5573 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5574 5575 SDLoc DL(GSD); 5576 EVT PtrVT = Op.getValueType(); 5577 5578 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5579 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5580 SIInstrInfo::MO_ABS32_LO); 5581 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5582 } 5583 5584 if (shouldEmitFixup(GV)) 5585 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5586 else if (shouldEmitPCReloc(GV)) 5587 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5588 SIInstrInfo::MO_REL32); 5589 5590 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5591 SIInstrInfo::MO_GOTPCREL32); 5592 5593 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5594 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5595 const DataLayout &DataLayout = DAG.getDataLayout(); 5596 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5597 MachinePointerInfo PtrInfo 5598 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5599 5600 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5601 MachineMemOperand::MODereferenceable | 5602 MachineMemOperand::MOInvariant); 5603 } 5604 5605 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5606 const SDLoc &DL, SDValue V) const { 5607 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5608 // the destination register. 5609 // 5610 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5611 // so we will end up with redundant moves to m0. 5612 // 5613 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5614 5615 // A Null SDValue creates a glue result. 5616 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5617 V, Chain); 5618 return SDValue(M0, 0); 5619 } 5620 5621 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5622 SDValue Op, 5623 MVT VT, 5624 unsigned Offset) const { 5625 SDLoc SL(Op); 5626 SDValue Param = lowerKernargMemParameter( 5627 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5628 // The local size values will have the hi 16-bits as zero. 5629 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5630 DAG.getValueType(VT)); 5631 } 5632 5633 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5634 EVT VT) { 5635 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5636 "non-hsa intrinsic with hsa target", 5637 DL.getDebugLoc()); 5638 DAG.getContext()->diagnose(BadIntrin); 5639 return DAG.getUNDEF(VT); 5640 } 5641 5642 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5643 EVT VT) { 5644 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5645 "intrinsic not supported on subtarget", 5646 DL.getDebugLoc()); 5647 DAG.getContext()->diagnose(BadIntrin); 5648 return DAG.getUNDEF(VT); 5649 } 5650 5651 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5652 ArrayRef<SDValue> Elts) { 5653 assert(!Elts.empty()); 5654 MVT Type; 5655 unsigned NumElts; 5656 5657 if (Elts.size() == 1) { 5658 Type = MVT::f32; 5659 NumElts = 1; 5660 } else if (Elts.size() == 2) { 5661 Type = MVT::v2f32; 5662 NumElts = 2; 5663 } else if (Elts.size() == 3) { 5664 Type = MVT::v3f32; 5665 NumElts = 3; 5666 } else if (Elts.size() <= 4) { 5667 Type = MVT::v4f32; 5668 NumElts = 4; 5669 } else if (Elts.size() <= 8) { 5670 Type = MVT::v8f32; 5671 NumElts = 8; 5672 } else { 5673 assert(Elts.size() <= 16); 5674 Type = MVT::v16f32; 5675 NumElts = 16; 5676 } 5677 5678 SmallVector<SDValue, 16> VecElts(NumElts); 5679 for (unsigned i = 0; i < Elts.size(); ++i) { 5680 SDValue Elt = Elts[i]; 5681 if (Elt.getValueType() != MVT::f32) 5682 Elt = DAG.getBitcast(MVT::f32, Elt); 5683 VecElts[i] = Elt; 5684 } 5685 for (unsigned i = Elts.size(); i < NumElts; ++i) 5686 VecElts[i] = DAG.getUNDEF(MVT::f32); 5687 5688 if (NumElts == 1) 5689 return VecElts[0]; 5690 return DAG.getBuildVector(Type, DL, VecElts); 5691 } 5692 5693 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5694 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5695 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5696 5697 uint64_t Value = CachePolicyConst->getZExtValue(); 5698 SDLoc DL(CachePolicy); 5699 if (GLC) { 5700 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5701 Value &= ~(uint64_t)0x1; 5702 } 5703 if (SLC) { 5704 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5705 Value &= ~(uint64_t)0x2; 5706 } 5707 if (DLC) { 5708 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5709 Value &= ~(uint64_t)0x4; 5710 } 5711 5712 return Value == 0; 5713 } 5714 5715 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5716 SDValue Src, int ExtraElts) { 5717 EVT SrcVT = Src.getValueType(); 5718 5719 SmallVector<SDValue, 8> Elts; 5720 5721 if (SrcVT.isVector()) 5722 DAG.ExtractVectorElements(Src, Elts); 5723 else 5724 Elts.push_back(Src); 5725 5726 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5727 while (ExtraElts--) 5728 Elts.push_back(Undef); 5729 5730 return DAG.getBuildVector(CastVT, DL, Elts); 5731 } 5732 5733 // Re-construct the required return value for a image load intrinsic. 5734 // This is more complicated due to the optional use TexFailCtrl which means the required 5735 // return type is an aggregate 5736 static SDValue constructRetValue(SelectionDAG &DAG, 5737 MachineSDNode *Result, 5738 ArrayRef<EVT> ResultTypes, 5739 bool IsTexFail, bool Unpacked, bool IsD16, 5740 int DMaskPop, int NumVDataDwords, 5741 const SDLoc &DL, LLVMContext &Context) { 5742 // Determine the required return type. This is the same regardless of IsTexFail flag 5743 EVT ReqRetVT = ResultTypes[0]; 5744 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5745 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5746 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5747 5748 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5749 DMaskPop : (DMaskPop + 1) / 2; 5750 5751 MVT DataDwordVT = NumDataDwords == 1 ? 5752 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5753 5754 MVT MaskPopVT = MaskPopDwords == 1 ? 5755 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5756 5757 SDValue Data(Result, 0); 5758 SDValue TexFail; 5759 5760 if (IsTexFail) { 5761 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5762 if (MaskPopVT.isVector()) { 5763 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5764 SDValue(Result, 0), ZeroIdx); 5765 } else { 5766 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5767 SDValue(Result, 0), ZeroIdx); 5768 } 5769 5770 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5771 SDValue(Result, 0), 5772 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5773 } 5774 5775 if (DataDwordVT.isVector()) 5776 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5777 NumDataDwords - MaskPopDwords); 5778 5779 if (IsD16) 5780 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5781 5782 if (!ReqRetVT.isVector()) 5783 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5784 5785 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5786 5787 if (TexFail) 5788 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5789 5790 if (Result->getNumValues() == 1) 5791 return Data; 5792 5793 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5794 } 5795 5796 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5797 SDValue *LWE, bool &IsTexFail) { 5798 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5799 5800 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5801 if (Value) { 5802 IsTexFail = true; 5803 } 5804 5805 SDLoc DL(TexFailCtrlConst); 5806 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5807 Value &= ~(uint64_t)0x1; 5808 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5809 Value &= ~(uint64_t)0x2; 5810 5811 return Value == 0; 5812 } 5813 5814 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5815 MVT PackVectorVT, 5816 SmallVectorImpl<SDValue> &PackedAddrs, 5817 unsigned DimIdx, unsigned EndIdx, 5818 unsigned NumGradients) { 5819 SDLoc DL(Op); 5820 for (unsigned I = DimIdx; I < EndIdx; I++) { 5821 SDValue Addr = Op.getOperand(I); 5822 5823 // Gradients are packed with undef for each coordinate. 5824 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5825 // 1D: undef,dx/dh; undef,dx/dv 5826 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5827 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5828 if (((I + 1) >= EndIdx) || 5829 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5830 I == DimIdx + NumGradients - 1))) { 5831 if (Addr.getValueType() != MVT::i16) 5832 Addr = DAG.getBitcast(MVT::i16, Addr); 5833 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5834 } else { 5835 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5836 I++; 5837 } 5838 Addr = DAG.getBitcast(MVT::f32, Addr); 5839 PackedAddrs.push_back(Addr); 5840 } 5841 } 5842 5843 SDValue SITargetLowering::lowerImage(SDValue Op, 5844 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5845 SelectionDAG &DAG) const { 5846 SDLoc DL(Op); 5847 MachineFunction &MF = DAG.getMachineFunction(); 5848 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5849 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5850 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5851 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5852 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5853 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5854 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5855 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5856 unsigned IntrOpcode = Intr->BaseOpcode; 5857 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5858 5859 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5860 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5861 bool IsD16 = false; 5862 bool IsG16 = false; 5863 bool IsA16 = false; 5864 SDValue VData; 5865 int NumVDataDwords; 5866 bool AdjustRetType = false; 5867 5868 unsigned AddrIdx; // Index of first address argument 5869 unsigned DMask; 5870 unsigned DMaskLanes = 0; 5871 5872 if (BaseOpcode->Atomic) { 5873 VData = Op.getOperand(2); 5874 5875 bool Is64Bit = VData.getValueType() == MVT::i64; 5876 if (BaseOpcode->AtomicX2) { 5877 SDValue VData2 = Op.getOperand(3); 5878 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5879 {VData, VData2}); 5880 if (Is64Bit) 5881 VData = DAG.getBitcast(MVT::v4i32, VData); 5882 5883 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5884 DMask = Is64Bit ? 0xf : 0x3; 5885 NumVDataDwords = Is64Bit ? 4 : 2; 5886 AddrIdx = 4; 5887 } else { 5888 DMask = Is64Bit ? 0x3 : 0x1; 5889 NumVDataDwords = Is64Bit ? 2 : 1; 5890 AddrIdx = 3; 5891 } 5892 } else { 5893 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5894 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5895 DMask = DMaskConst->getZExtValue(); 5896 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5897 5898 if (BaseOpcode->Store) { 5899 VData = Op.getOperand(2); 5900 5901 MVT StoreVT = VData.getSimpleValueType(); 5902 if (StoreVT.getScalarType() == MVT::f16) { 5903 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5904 return Op; // D16 is unsupported for this instruction 5905 5906 IsD16 = true; 5907 VData = handleD16VData(VData, DAG); 5908 } 5909 5910 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5911 } else { 5912 // Work out the num dwords based on the dmask popcount and underlying type 5913 // and whether packing is supported. 5914 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5915 if (LoadVT.getScalarType() == MVT::f16) { 5916 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5917 return Op; // D16 is unsupported for this instruction 5918 5919 IsD16 = true; 5920 } 5921 5922 // Confirm that the return type is large enough for the dmask specified 5923 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5924 (!LoadVT.isVector() && DMaskLanes > 1)) 5925 return Op; 5926 5927 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5928 NumVDataDwords = (DMaskLanes + 1) / 2; 5929 else 5930 NumVDataDwords = DMaskLanes; 5931 5932 AdjustRetType = true; 5933 } 5934 5935 AddrIdx = DMaskIdx + 1; 5936 } 5937 5938 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5939 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5940 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5941 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5942 NumCoords + NumLCM; 5943 unsigned NumMIVAddrs = NumVAddrs; 5944 5945 SmallVector<SDValue, 4> VAddrs; 5946 5947 // Optimize _L to _LZ when _L is zero 5948 if (LZMappingInfo) { 5949 if (auto ConstantLod = 5950 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5951 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5952 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5953 NumMIVAddrs--; // remove 'lod' 5954 } 5955 } 5956 } 5957 5958 // Optimize _mip away, when 'lod' is zero 5959 if (MIPMappingInfo) { 5960 if (auto ConstantLod = 5961 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5962 if (ConstantLod->isNullValue()) { 5963 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5964 NumMIVAddrs--; // remove 'lod' 5965 } 5966 } 5967 } 5968 5969 // Push back extra arguments. 5970 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 5971 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 5972 5973 // Check for 16 bit addresses or derivatives and pack if true. 5974 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5975 unsigned CoordIdx = DimIdx + NumGradients; 5976 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 5977 5978 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5979 MVT VAddrScalarVT = VAddrVT.getScalarType(); 5980 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5981 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5982 5983 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 5984 VAddrScalarVT = VAddrVT.getScalarType(); 5985 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5986 if (IsA16 || IsG16) { 5987 if (IsA16) { 5988 if (!ST->hasA16()) { 5989 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5990 "support 16 bit addresses\n"); 5991 return Op; 5992 } 5993 if (!IsG16) { 5994 LLVM_DEBUG( 5995 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 5996 "need 16 bit derivatives but got 32 bit derivatives\n"); 5997 return Op; 5998 } 5999 } else if (!ST->hasG16()) { 6000 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6001 "support 16 bit derivatives\n"); 6002 return Op; 6003 } 6004 6005 if (BaseOpcode->Gradients && !IsA16) { 6006 if (!ST->hasG16()) { 6007 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6008 "support 16 bit derivatives\n"); 6009 return Op; 6010 } 6011 // Activate g16 6012 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6013 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6014 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6015 } 6016 6017 // Don't compress addresses for G16 6018 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 6019 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 6020 PackEndIdx, NumGradients); 6021 6022 if (!IsA16) { 6023 // Add uncompressed address 6024 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 6025 VAddrs.push_back(Op.getOperand(I)); 6026 } 6027 } else { 6028 for (unsigned I = DimIdx; I < CoordsEnd; I++) 6029 VAddrs.push_back(Op.getOperand(I)); 6030 } 6031 6032 // If the register allocator cannot place the address registers contiguously 6033 // without introducing moves, then using the non-sequential address encoding 6034 // is always preferable, since it saves VALU instructions and is usually a 6035 // wash in terms of code size or even better. 6036 // 6037 // However, we currently have no way of hinting to the register allocator that 6038 // MIMG addresses should be placed contiguously when it is possible to do so, 6039 // so force non-NSA for the common 2-address case as a heuristic. 6040 // 6041 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6042 // allocation when possible. 6043 bool UseNSA = 6044 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6045 SDValue VAddr; 6046 if (!UseNSA) 6047 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6048 6049 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6050 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6051 unsigned CtrlIdx; // Index of texfailctrl argument 6052 SDValue Unorm; 6053 if (!BaseOpcode->Sampler) { 6054 Unorm = True; 6055 CtrlIdx = AddrIdx + NumVAddrs + 1; 6056 } else { 6057 auto UnormConst = 6058 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6059 6060 Unorm = UnormConst->getZExtValue() ? True : False; 6061 CtrlIdx = AddrIdx + NumVAddrs + 3; 6062 } 6063 6064 SDValue TFE; 6065 SDValue LWE; 6066 SDValue TexFail = Op.getOperand(CtrlIdx); 6067 bool IsTexFail = false; 6068 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6069 return Op; 6070 6071 if (IsTexFail) { 6072 if (!DMaskLanes) { 6073 // Expecting to get an error flag since TFC is on - and dmask is 0 6074 // Force dmask to be at least 1 otherwise the instruction will fail 6075 DMask = 0x1; 6076 DMaskLanes = 1; 6077 NumVDataDwords = 1; 6078 } 6079 NumVDataDwords += 1; 6080 AdjustRetType = true; 6081 } 6082 6083 // Has something earlier tagged that the return type needs adjusting 6084 // This happens if the instruction is a load or has set TexFailCtrl flags 6085 if (AdjustRetType) { 6086 // NumVDataDwords reflects the true number of dwords required in the return type 6087 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6088 // This is a no-op load. This can be eliminated 6089 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6090 if (isa<MemSDNode>(Op)) 6091 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6092 return Undef; 6093 } 6094 6095 EVT NewVT = NumVDataDwords > 1 ? 6096 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6097 : MVT::i32; 6098 6099 ResultTypes[0] = NewVT; 6100 if (ResultTypes.size() == 3) { 6101 // Original result was aggregate type used for TexFailCtrl results 6102 // The actual instruction returns as a vector type which has now been 6103 // created. Remove the aggregate result. 6104 ResultTypes.erase(&ResultTypes[1]); 6105 } 6106 } 6107 6108 SDValue GLC; 6109 SDValue SLC; 6110 SDValue DLC; 6111 if (BaseOpcode->Atomic) { 6112 GLC = True; // TODO no-return optimization 6113 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6114 IsGFX10 ? &DLC : nullptr)) 6115 return Op; 6116 } else { 6117 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6118 IsGFX10 ? &DLC : nullptr)) 6119 return Op; 6120 } 6121 6122 SmallVector<SDValue, 26> Ops; 6123 if (BaseOpcode->Store || BaseOpcode->Atomic) 6124 Ops.push_back(VData); // vdata 6125 if (UseNSA) { 6126 for (const SDValue &Addr : VAddrs) 6127 Ops.push_back(Addr); 6128 } else { 6129 Ops.push_back(VAddr); 6130 } 6131 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6132 if (BaseOpcode->Sampler) 6133 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6134 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6135 if (IsGFX10) 6136 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6137 Ops.push_back(Unorm); 6138 if (IsGFX10) 6139 Ops.push_back(DLC); 6140 Ops.push_back(GLC); 6141 Ops.push_back(SLC); 6142 Ops.push_back(IsA16 && // r128, a16 for gfx9 6143 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6144 if (IsGFX10) 6145 Ops.push_back(IsA16 ? True : False); 6146 Ops.push_back(TFE); 6147 Ops.push_back(LWE); 6148 if (!IsGFX10) 6149 Ops.push_back(DimInfo->DA ? True : False); 6150 if (BaseOpcode->HasD16) 6151 Ops.push_back(IsD16 ? True : False); 6152 if (isa<MemSDNode>(Op)) 6153 Ops.push_back(Op.getOperand(0)); // chain 6154 6155 int NumVAddrDwords = 6156 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6157 int Opcode = -1; 6158 6159 if (IsGFX10) { 6160 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6161 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6162 : AMDGPU::MIMGEncGfx10Default, 6163 NumVDataDwords, NumVAddrDwords); 6164 } else { 6165 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6166 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6167 NumVDataDwords, NumVAddrDwords); 6168 if (Opcode == -1) 6169 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6170 NumVDataDwords, NumVAddrDwords); 6171 } 6172 assert(Opcode != -1); 6173 6174 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6175 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6176 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6177 DAG.setNodeMemRefs(NewNode, {MemRef}); 6178 } 6179 6180 if (BaseOpcode->AtomicX2) { 6181 SmallVector<SDValue, 1> Elt; 6182 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6183 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6184 } else if (!BaseOpcode->Store) { 6185 return constructRetValue(DAG, NewNode, 6186 OrigResultTypes, IsTexFail, 6187 Subtarget->hasUnpackedD16VMem(), IsD16, 6188 DMaskLanes, NumVDataDwords, DL, 6189 *DAG.getContext()); 6190 } 6191 6192 return SDValue(NewNode, 0); 6193 } 6194 6195 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6196 SDValue Offset, SDValue CachePolicy, 6197 SelectionDAG &DAG) const { 6198 MachineFunction &MF = DAG.getMachineFunction(); 6199 6200 const DataLayout &DataLayout = DAG.getDataLayout(); 6201 Align Alignment = 6202 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6203 6204 MachineMemOperand *MMO = MF.getMachineMemOperand( 6205 MachinePointerInfo(), 6206 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6207 MachineMemOperand::MOInvariant, 6208 VT.getStoreSize(), Alignment); 6209 6210 if (!Offset->isDivergent()) { 6211 SDValue Ops[] = { 6212 Rsrc, 6213 Offset, // Offset 6214 CachePolicy 6215 }; 6216 6217 // Widen vec3 load to vec4. 6218 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6219 EVT WidenedVT = 6220 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6221 auto WidenedOp = DAG.getMemIntrinsicNode( 6222 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6223 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6224 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6225 DAG.getVectorIdxConstant(0, DL)); 6226 return Subvector; 6227 } 6228 6229 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6230 DAG.getVTList(VT), Ops, VT, MMO); 6231 } 6232 6233 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6234 // assume that the buffer is unswizzled. 6235 SmallVector<SDValue, 4> Loads; 6236 unsigned NumLoads = 1; 6237 MVT LoadVT = VT.getSimpleVT(); 6238 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6239 assert((LoadVT.getScalarType() == MVT::i32 || 6240 LoadVT.getScalarType() == MVT::f32)); 6241 6242 if (NumElts == 8 || NumElts == 16) { 6243 NumLoads = NumElts / 4; 6244 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6245 } 6246 6247 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6248 SDValue Ops[] = { 6249 DAG.getEntryNode(), // Chain 6250 Rsrc, // rsrc 6251 DAG.getConstant(0, DL, MVT::i32), // vindex 6252 {}, // voffset 6253 {}, // soffset 6254 {}, // offset 6255 CachePolicy, // cachepolicy 6256 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6257 }; 6258 6259 // Use the alignment to ensure that the required offsets will fit into the 6260 // immediate offsets. 6261 setBufferOffsets(Offset, DAG, &Ops[3], 6262 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6263 6264 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6265 for (unsigned i = 0; i < NumLoads; ++i) { 6266 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6267 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6268 LoadVT, MMO, DAG)); 6269 } 6270 6271 if (NumElts == 8 || NumElts == 16) 6272 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6273 6274 return Loads[0]; 6275 } 6276 6277 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6278 SelectionDAG &DAG) const { 6279 MachineFunction &MF = DAG.getMachineFunction(); 6280 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6281 6282 EVT VT = Op.getValueType(); 6283 SDLoc DL(Op); 6284 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6285 6286 // TODO: Should this propagate fast-math-flags? 6287 6288 switch (IntrinsicID) { 6289 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6290 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6291 return emitNonHSAIntrinsicError(DAG, DL, VT); 6292 return getPreloadedValue(DAG, *MFI, VT, 6293 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6294 } 6295 case Intrinsic::amdgcn_dispatch_ptr: 6296 case Intrinsic::amdgcn_queue_ptr: { 6297 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6298 DiagnosticInfoUnsupported BadIntrin( 6299 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6300 DL.getDebugLoc()); 6301 DAG.getContext()->diagnose(BadIntrin); 6302 return DAG.getUNDEF(VT); 6303 } 6304 6305 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6306 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6307 return getPreloadedValue(DAG, *MFI, VT, RegID); 6308 } 6309 case Intrinsic::amdgcn_implicitarg_ptr: { 6310 if (MFI->isEntryFunction()) 6311 return getImplicitArgPtr(DAG, DL); 6312 return getPreloadedValue(DAG, *MFI, VT, 6313 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6314 } 6315 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6316 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6317 // This only makes sense to call in a kernel, so just lower to null. 6318 return DAG.getConstant(0, DL, VT); 6319 } 6320 6321 return getPreloadedValue(DAG, *MFI, VT, 6322 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6323 } 6324 case Intrinsic::amdgcn_dispatch_id: { 6325 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6326 } 6327 case Intrinsic::amdgcn_rcp: 6328 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6329 case Intrinsic::amdgcn_rsq: 6330 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6331 case Intrinsic::amdgcn_rsq_legacy: 6332 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6333 return emitRemovedIntrinsicError(DAG, DL, VT); 6334 return SDValue(); 6335 case Intrinsic::amdgcn_rcp_legacy: 6336 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6337 return emitRemovedIntrinsicError(DAG, DL, VT); 6338 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6339 case Intrinsic::amdgcn_rsq_clamp: { 6340 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6341 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6342 6343 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6344 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6345 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6346 6347 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6348 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6349 DAG.getConstantFP(Max, DL, VT)); 6350 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6351 DAG.getConstantFP(Min, DL, VT)); 6352 } 6353 case Intrinsic::r600_read_ngroups_x: 6354 if (Subtarget->isAmdHsaOS()) 6355 return emitNonHSAIntrinsicError(DAG, DL, VT); 6356 6357 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6358 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6359 false); 6360 case Intrinsic::r600_read_ngroups_y: 6361 if (Subtarget->isAmdHsaOS()) 6362 return emitNonHSAIntrinsicError(DAG, DL, VT); 6363 6364 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6365 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6366 false); 6367 case Intrinsic::r600_read_ngroups_z: 6368 if (Subtarget->isAmdHsaOS()) 6369 return emitNonHSAIntrinsicError(DAG, DL, VT); 6370 6371 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6372 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6373 false); 6374 case Intrinsic::r600_read_global_size_x: 6375 if (Subtarget->isAmdHsaOS()) 6376 return emitNonHSAIntrinsicError(DAG, DL, VT); 6377 6378 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6379 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6380 Align(4), false); 6381 case Intrinsic::r600_read_global_size_y: 6382 if (Subtarget->isAmdHsaOS()) 6383 return emitNonHSAIntrinsicError(DAG, DL, VT); 6384 6385 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6386 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6387 Align(4), false); 6388 case Intrinsic::r600_read_global_size_z: 6389 if (Subtarget->isAmdHsaOS()) 6390 return emitNonHSAIntrinsicError(DAG, DL, VT); 6391 6392 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6393 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6394 Align(4), false); 6395 case Intrinsic::r600_read_local_size_x: 6396 if (Subtarget->isAmdHsaOS()) 6397 return emitNonHSAIntrinsicError(DAG, DL, VT); 6398 6399 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6400 SI::KernelInputOffsets::LOCAL_SIZE_X); 6401 case Intrinsic::r600_read_local_size_y: 6402 if (Subtarget->isAmdHsaOS()) 6403 return emitNonHSAIntrinsicError(DAG, DL, VT); 6404 6405 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6406 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6407 case Intrinsic::r600_read_local_size_z: 6408 if (Subtarget->isAmdHsaOS()) 6409 return emitNonHSAIntrinsicError(DAG, DL, VT); 6410 6411 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6412 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6413 case Intrinsic::amdgcn_workgroup_id_x: 6414 return getPreloadedValue(DAG, *MFI, VT, 6415 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6416 case Intrinsic::amdgcn_workgroup_id_y: 6417 return getPreloadedValue(DAG, *MFI, VT, 6418 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6419 case Intrinsic::amdgcn_workgroup_id_z: 6420 return getPreloadedValue(DAG, *MFI, VT, 6421 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6422 case Intrinsic::amdgcn_workitem_id_x: 6423 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6424 SDLoc(DAG.getEntryNode()), 6425 MFI->getArgInfo().WorkItemIDX); 6426 case Intrinsic::amdgcn_workitem_id_y: 6427 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6428 SDLoc(DAG.getEntryNode()), 6429 MFI->getArgInfo().WorkItemIDY); 6430 case Intrinsic::amdgcn_workitem_id_z: 6431 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6432 SDLoc(DAG.getEntryNode()), 6433 MFI->getArgInfo().WorkItemIDZ); 6434 case Intrinsic::amdgcn_wavefrontsize: 6435 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6436 SDLoc(Op), MVT::i32); 6437 case Intrinsic::amdgcn_s_buffer_load: { 6438 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6439 SDValue GLC; 6440 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6441 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6442 IsGFX10 ? &DLC : nullptr)) 6443 return Op; 6444 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6445 DAG); 6446 } 6447 case Intrinsic::amdgcn_fdiv_fast: 6448 return lowerFDIV_FAST(Op, DAG); 6449 case Intrinsic::amdgcn_sin: 6450 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6451 6452 case Intrinsic::amdgcn_cos: 6453 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6454 6455 case Intrinsic::amdgcn_mul_u24: 6456 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6457 case Intrinsic::amdgcn_mul_i24: 6458 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6459 6460 case Intrinsic::amdgcn_log_clamp: { 6461 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6462 return SDValue(); 6463 6464 DiagnosticInfoUnsupported BadIntrin( 6465 MF.getFunction(), "intrinsic not supported on subtarget", 6466 DL.getDebugLoc()); 6467 DAG.getContext()->diagnose(BadIntrin); 6468 return DAG.getUNDEF(VT); 6469 } 6470 case Intrinsic::amdgcn_ldexp: 6471 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6472 Op.getOperand(1), Op.getOperand(2)); 6473 6474 case Intrinsic::amdgcn_fract: 6475 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6476 6477 case Intrinsic::amdgcn_class: 6478 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6479 Op.getOperand(1), Op.getOperand(2)); 6480 case Intrinsic::amdgcn_div_fmas: 6481 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6482 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6483 Op.getOperand(4)); 6484 6485 case Intrinsic::amdgcn_div_fixup: 6486 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6487 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6488 6489 case Intrinsic::amdgcn_div_scale: { 6490 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6491 6492 // Translate to the operands expected by the machine instruction. The 6493 // first parameter must be the same as the first instruction. 6494 SDValue Numerator = Op.getOperand(1); 6495 SDValue Denominator = Op.getOperand(2); 6496 6497 // Note this order is opposite of the machine instruction's operations, 6498 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6499 // intrinsic has the numerator as the first operand to match a normal 6500 // division operation. 6501 6502 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6503 6504 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6505 Denominator, Numerator); 6506 } 6507 case Intrinsic::amdgcn_icmp: { 6508 // There is a Pat that handles this variant, so return it as-is. 6509 if (Op.getOperand(1).getValueType() == MVT::i1 && 6510 Op.getConstantOperandVal(2) == 0 && 6511 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6512 return Op; 6513 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6514 } 6515 case Intrinsic::amdgcn_fcmp: { 6516 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6517 } 6518 case Intrinsic::amdgcn_ballot: 6519 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6520 case Intrinsic::amdgcn_fmed3: 6521 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6522 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6523 case Intrinsic::amdgcn_fdot2: 6524 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6525 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6526 Op.getOperand(4)); 6527 case Intrinsic::amdgcn_fmul_legacy: 6528 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6529 Op.getOperand(1), Op.getOperand(2)); 6530 case Intrinsic::amdgcn_sffbh: 6531 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6532 case Intrinsic::amdgcn_sbfe: 6533 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6534 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6535 case Intrinsic::amdgcn_ubfe: 6536 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6537 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6538 case Intrinsic::amdgcn_cvt_pkrtz: 6539 case Intrinsic::amdgcn_cvt_pknorm_i16: 6540 case Intrinsic::amdgcn_cvt_pknorm_u16: 6541 case Intrinsic::amdgcn_cvt_pk_i16: 6542 case Intrinsic::amdgcn_cvt_pk_u16: { 6543 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6544 EVT VT = Op.getValueType(); 6545 unsigned Opcode; 6546 6547 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6548 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6549 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6550 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6551 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6552 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6553 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6554 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6555 else 6556 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6557 6558 if (isTypeLegal(VT)) 6559 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6560 6561 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6562 Op.getOperand(1), Op.getOperand(2)); 6563 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6564 } 6565 case Intrinsic::amdgcn_fmad_ftz: 6566 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6567 Op.getOperand(2), Op.getOperand(3)); 6568 6569 case Intrinsic::amdgcn_if_break: 6570 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6571 Op->getOperand(1), Op->getOperand(2)), 0); 6572 6573 case Intrinsic::amdgcn_groupstaticsize: { 6574 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6575 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6576 return Op; 6577 6578 const Module *M = MF.getFunction().getParent(); 6579 const GlobalValue *GV = 6580 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6581 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6582 SIInstrInfo::MO_ABS32_LO); 6583 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6584 } 6585 case Intrinsic::amdgcn_is_shared: 6586 case Intrinsic::amdgcn_is_private: { 6587 SDLoc SL(Op); 6588 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6589 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6590 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6591 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6592 Op.getOperand(1)); 6593 6594 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6595 DAG.getConstant(1, SL, MVT::i32)); 6596 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6597 } 6598 case Intrinsic::amdgcn_alignbit: 6599 return DAG.getNode(ISD::FSHR, DL, VT, 6600 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6601 case Intrinsic::amdgcn_reloc_constant: { 6602 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6603 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6604 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6605 auto RelocSymbol = cast<GlobalVariable>( 6606 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6607 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6608 SIInstrInfo::MO_ABS32_LO); 6609 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6610 } 6611 default: 6612 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6613 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6614 return lowerImage(Op, ImageDimIntr, DAG); 6615 6616 return Op; 6617 } 6618 } 6619 6620 // This function computes an appropriate offset to pass to 6621 // MachineMemOperand::setOffset() based on the offset inputs to 6622 // an intrinsic. If any of the offsets are non-contstant or 6623 // if VIndex is non-zero then this function returns 0. Otherwise, 6624 // it returns the sum of VOffset, SOffset, and Offset. 6625 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6626 SDValue SOffset, 6627 SDValue Offset, 6628 SDValue VIndex = SDValue()) { 6629 6630 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6631 !isa<ConstantSDNode>(Offset)) 6632 return 0; 6633 6634 if (VIndex) { 6635 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6636 return 0; 6637 } 6638 6639 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6640 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6641 cast<ConstantSDNode>(Offset)->getSExtValue(); 6642 } 6643 6644 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6645 switch (MF.getFunction().getCallingConv()) { 6646 case CallingConv::AMDGPU_PS: 6647 return 1; 6648 case CallingConv::AMDGPU_VS: 6649 return 2; 6650 case CallingConv::AMDGPU_GS: 6651 return 3; 6652 case CallingConv::AMDGPU_HS: 6653 case CallingConv::AMDGPU_LS: 6654 case CallingConv::AMDGPU_ES: 6655 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6656 case CallingConv::AMDGPU_CS: 6657 case CallingConv::AMDGPU_KERNEL: 6658 case CallingConv::C: 6659 case CallingConv::Fast: 6660 default: 6661 // Assume other calling conventions are various compute callable functions 6662 return 0; 6663 } 6664 } 6665 6666 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6667 SelectionDAG &DAG) const { 6668 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6669 SDLoc DL(Op); 6670 6671 switch (IntrID) { 6672 case Intrinsic::amdgcn_ds_ordered_add: 6673 case Intrinsic::amdgcn_ds_ordered_swap: { 6674 MemSDNode *M = cast<MemSDNode>(Op); 6675 SDValue Chain = M->getOperand(0); 6676 SDValue M0 = M->getOperand(2); 6677 SDValue Value = M->getOperand(3); 6678 unsigned IndexOperand = M->getConstantOperandVal(7); 6679 unsigned WaveRelease = M->getConstantOperandVal(8); 6680 unsigned WaveDone = M->getConstantOperandVal(9); 6681 6682 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6683 IndexOperand &= ~0x3f; 6684 unsigned CountDw = 0; 6685 6686 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6687 CountDw = (IndexOperand >> 24) & 0xf; 6688 IndexOperand &= ~(0xf << 24); 6689 6690 if (CountDw < 1 || CountDw > 4) { 6691 report_fatal_error( 6692 "ds_ordered_count: dword count must be between 1 and 4"); 6693 } 6694 } 6695 6696 if (IndexOperand) 6697 report_fatal_error("ds_ordered_count: bad index operand"); 6698 6699 if (WaveDone && !WaveRelease) 6700 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6701 6702 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6703 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6704 unsigned Offset0 = OrderedCountIndex << 2; 6705 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6706 (Instruction << 4); 6707 6708 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6709 Offset1 |= (CountDw - 1) << 6; 6710 6711 unsigned Offset = Offset0 | (Offset1 << 8); 6712 6713 SDValue Ops[] = { 6714 Chain, 6715 Value, 6716 DAG.getTargetConstant(Offset, DL, MVT::i16), 6717 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6718 }; 6719 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6720 M->getVTList(), Ops, M->getMemoryVT(), 6721 M->getMemOperand()); 6722 } 6723 case Intrinsic::amdgcn_ds_fadd: { 6724 MemSDNode *M = cast<MemSDNode>(Op); 6725 unsigned Opc; 6726 switch (IntrID) { 6727 case Intrinsic::amdgcn_ds_fadd: 6728 Opc = ISD::ATOMIC_LOAD_FADD; 6729 break; 6730 } 6731 6732 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6733 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6734 M->getMemOperand()); 6735 } 6736 case Intrinsic::amdgcn_atomic_inc: 6737 case Intrinsic::amdgcn_atomic_dec: 6738 case Intrinsic::amdgcn_ds_fmin: 6739 case Intrinsic::amdgcn_ds_fmax: { 6740 MemSDNode *M = cast<MemSDNode>(Op); 6741 unsigned Opc; 6742 switch (IntrID) { 6743 case Intrinsic::amdgcn_atomic_inc: 6744 Opc = AMDGPUISD::ATOMIC_INC; 6745 break; 6746 case Intrinsic::amdgcn_atomic_dec: 6747 Opc = AMDGPUISD::ATOMIC_DEC; 6748 break; 6749 case Intrinsic::amdgcn_ds_fmin: 6750 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6751 break; 6752 case Intrinsic::amdgcn_ds_fmax: 6753 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6754 break; 6755 default: 6756 llvm_unreachable("Unknown intrinsic!"); 6757 } 6758 SDValue Ops[] = { 6759 M->getOperand(0), // Chain 6760 M->getOperand(2), // Ptr 6761 M->getOperand(3) // Value 6762 }; 6763 6764 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6765 M->getMemoryVT(), M->getMemOperand()); 6766 } 6767 case Intrinsic::amdgcn_buffer_load: 6768 case Intrinsic::amdgcn_buffer_load_format: { 6769 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6770 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6771 unsigned IdxEn = 1; 6772 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6773 IdxEn = Idx->getZExtValue() != 0; 6774 SDValue Ops[] = { 6775 Op.getOperand(0), // Chain 6776 Op.getOperand(2), // rsrc 6777 Op.getOperand(3), // vindex 6778 SDValue(), // voffset -- will be set by setBufferOffsets 6779 SDValue(), // soffset -- will be set by setBufferOffsets 6780 SDValue(), // offset -- will be set by setBufferOffsets 6781 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6782 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6783 }; 6784 6785 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6786 // We don't know the offset if vindex is non-zero, so clear it. 6787 if (IdxEn) 6788 Offset = 0; 6789 6790 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6791 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6792 6793 EVT VT = Op.getValueType(); 6794 EVT IntVT = VT.changeTypeToInteger(); 6795 auto *M = cast<MemSDNode>(Op); 6796 M->getMemOperand()->setOffset(Offset); 6797 EVT LoadVT = Op.getValueType(); 6798 6799 if (LoadVT.getScalarType() == MVT::f16) 6800 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6801 M, DAG, Ops); 6802 6803 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6804 if (LoadVT.getScalarType() == MVT::i8 || 6805 LoadVT.getScalarType() == MVT::i16) 6806 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6807 6808 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6809 M->getMemOperand(), DAG); 6810 } 6811 case Intrinsic::amdgcn_raw_buffer_load: 6812 case Intrinsic::amdgcn_raw_buffer_load_format: { 6813 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6814 6815 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6816 SDValue Ops[] = { 6817 Op.getOperand(0), // Chain 6818 Op.getOperand(2), // rsrc 6819 DAG.getConstant(0, DL, MVT::i32), // vindex 6820 Offsets.first, // voffset 6821 Op.getOperand(4), // soffset 6822 Offsets.second, // offset 6823 Op.getOperand(5), // cachepolicy, swizzled buffer 6824 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6825 }; 6826 6827 auto *M = cast<MemSDNode>(Op); 6828 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6829 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6830 } 6831 case Intrinsic::amdgcn_struct_buffer_load: 6832 case Intrinsic::amdgcn_struct_buffer_load_format: { 6833 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6834 6835 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6836 SDValue Ops[] = { 6837 Op.getOperand(0), // Chain 6838 Op.getOperand(2), // rsrc 6839 Op.getOperand(3), // vindex 6840 Offsets.first, // voffset 6841 Op.getOperand(5), // soffset 6842 Offsets.second, // offset 6843 Op.getOperand(6), // cachepolicy, swizzled buffer 6844 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6845 }; 6846 6847 auto *M = cast<MemSDNode>(Op); 6848 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6849 Ops[2])); 6850 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6851 } 6852 case Intrinsic::amdgcn_tbuffer_load: { 6853 MemSDNode *M = cast<MemSDNode>(Op); 6854 EVT LoadVT = Op.getValueType(); 6855 6856 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6857 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6858 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6859 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6860 unsigned IdxEn = 1; 6861 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6862 IdxEn = Idx->getZExtValue() != 0; 6863 SDValue Ops[] = { 6864 Op.getOperand(0), // Chain 6865 Op.getOperand(2), // rsrc 6866 Op.getOperand(3), // vindex 6867 Op.getOperand(4), // voffset 6868 Op.getOperand(5), // soffset 6869 Op.getOperand(6), // offset 6870 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6871 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6872 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6873 }; 6874 6875 if (LoadVT.getScalarType() == MVT::f16) 6876 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6877 M, DAG, Ops); 6878 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6879 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6880 DAG); 6881 } 6882 case Intrinsic::amdgcn_raw_tbuffer_load: { 6883 MemSDNode *M = cast<MemSDNode>(Op); 6884 EVT LoadVT = Op.getValueType(); 6885 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6886 6887 SDValue Ops[] = { 6888 Op.getOperand(0), // Chain 6889 Op.getOperand(2), // rsrc 6890 DAG.getConstant(0, DL, MVT::i32), // vindex 6891 Offsets.first, // voffset 6892 Op.getOperand(4), // soffset 6893 Offsets.second, // offset 6894 Op.getOperand(5), // format 6895 Op.getOperand(6), // cachepolicy, swizzled buffer 6896 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6897 }; 6898 6899 if (LoadVT.getScalarType() == MVT::f16) 6900 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6901 M, DAG, Ops); 6902 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6903 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6904 DAG); 6905 } 6906 case Intrinsic::amdgcn_struct_tbuffer_load: { 6907 MemSDNode *M = cast<MemSDNode>(Op); 6908 EVT LoadVT = Op.getValueType(); 6909 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6910 6911 SDValue Ops[] = { 6912 Op.getOperand(0), // Chain 6913 Op.getOperand(2), // rsrc 6914 Op.getOperand(3), // vindex 6915 Offsets.first, // voffset 6916 Op.getOperand(5), // soffset 6917 Offsets.second, // offset 6918 Op.getOperand(6), // format 6919 Op.getOperand(7), // cachepolicy, swizzled buffer 6920 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6921 }; 6922 6923 if (LoadVT.getScalarType() == MVT::f16) 6924 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6925 M, DAG, Ops); 6926 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6927 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6928 DAG); 6929 } 6930 case Intrinsic::amdgcn_buffer_atomic_swap: 6931 case Intrinsic::amdgcn_buffer_atomic_add: 6932 case Intrinsic::amdgcn_buffer_atomic_sub: 6933 case Intrinsic::amdgcn_buffer_atomic_csub: 6934 case Intrinsic::amdgcn_buffer_atomic_smin: 6935 case Intrinsic::amdgcn_buffer_atomic_umin: 6936 case Intrinsic::amdgcn_buffer_atomic_smax: 6937 case Intrinsic::amdgcn_buffer_atomic_umax: 6938 case Intrinsic::amdgcn_buffer_atomic_and: 6939 case Intrinsic::amdgcn_buffer_atomic_or: 6940 case Intrinsic::amdgcn_buffer_atomic_xor: { 6941 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6942 unsigned IdxEn = 1; 6943 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6944 IdxEn = Idx->getZExtValue() != 0; 6945 SDValue Ops[] = { 6946 Op.getOperand(0), // Chain 6947 Op.getOperand(2), // vdata 6948 Op.getOperand(3), // rsrc 6949 Op.getOperand(4), // vindex 6950 SDValue(), // voffset -- will be set by setBufferOffsets 6951 SDValue(), // soffset -- will be set by setBufferOffsets 6952 SDValue(), // offset -- will be set by setBufferOffsets 6953 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6954 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6955 }; 6956 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6957 // We don't know the offset if vindex is non-zero, so clear it. 6958 if (IdxEn) 6959 Offset = 0; 6960 EVT VT = Op.getValueType(); 6961 6962 auto *M = cast<MemSDNode>(Op); 6963 M->getMemOperand()->setOffset(Offset); 6964 unsigned Opcode = 0; 6965 6966 switch (IntrID) { 6967 case Intrinsic::amdgcn_buffer_atomic_swap: 6968 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6969 break; 6970 case Intrinsic::amdgcn_buffer_atomic_add: 6971 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6972 break; 6973 case Intrinsic::amdgcn_buffer_atomic_sub: 6974 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6975 break; 6976 case Intrinsic::amdgcn_buffer_atomic_csub: 6977 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 6978 break; 6979 case Intrinsic::amdgcn_buffer_atomic_smin: 6980 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6981 break; 6982 case Intrinsic::amdgcn_buffer_atomic_umin: 6983 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6984 break; 6985 case Intrinsic::amdgcn_buffer_atomic_smax: 6986 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6987 break; 6988 case Intrinsic::amdgcn_buffer_atomic_umax: 6989 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6990 break; 6991 case Intrinsic::amdgcn_buffer_atomic_and: 6992 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6993 break; 6994 case Intrinsic::amdgcn_buffer_atomic_or: 6995 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6996 break; 6997 case Intrinsic::amdgcn_buffer_atomic_xor: 6998 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6999 break; 7000 default: 7001 llvm_unreachable("unhandled atomic opcode"); 7002 } 7003 7004 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7005 M->getMemOperand()); 7006 } 7007 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7008 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7009 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7010 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7011 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7012 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7013 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7014 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7015 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7016 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7017 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7018 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 7019 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7020 SDValue Ops[] = { 7021 Op.getOperand(0), // Chain 7022 Op.getOperand(2), // vdata 7023 Op.getOperand(3), // rsrc 7024 DAG.getConstant(0, DL, MVT::i32), // vindex 7025 Offsets.first, // voffset 7026 Op.getOperand(5), // soffset 7027 Offsets.second, // offset 7028 Op.getOperand(6), // cachepolicy 7029 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7030 }; 7031 EVT VT = Op.getValueType(); 7032 7033 auto *M = cast<MemSDNode>(Op); 7034 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7035 unsigned Opcode = 0; 7036 7037 switch (IntrID) { 7038 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7039 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7040 break; 7041 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7042 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7043 break; 7044 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7045 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7046 break; 7047 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7048 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7049 break; 7050 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7051 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7052 break; 7053 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7054 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7055 break; 7056 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7057 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7058 break; 7059 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7060 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7061 break; 7062 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7063 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7064 break; 7065 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7066 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7067 break; 7068 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7069 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7070 break; 7071 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7072 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7073 break; 7074 default: 7075 llvm_unreachable("unhandled atomic opcode"); 7076 } 7077 7078 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7079 M->getMemOperand()); 7080 } 7081 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7082 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7083 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7084 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7085 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7086 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7087 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7088 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7089 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7090 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7091 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7092 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 7093 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7094 SDValue Ops[] = { 7095 Op.getOperand(0), // Chain 7096 Op.getOperand(2), // vdata 7097 Op.getOperand(3), // rsrc 7098 Op.getOperand(4), // vindex 7099 Offsets.first, // voffset 7100 Op.getOperand(6), // soffset 7101 Offsets.second, // offset 7102 Op.getOperand(7), // cachepolicy 7103 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7104 }; 7105 EVT VT = Op.getValueType(); 7106 7107 auto *M = cast<MemSDNode>(Op); 7108 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7109 Ops[3])); 7110 unsigned Opcode = 0; 7111 7112 switch (IntrID) { 7113 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7114 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7115 break; 7116 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7117 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7118 break; 7119 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7120 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7121 break; 7122 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7123 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7124 break; 7125 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7126 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7127 break; 7128 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7129 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7130 break; 7131 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7132 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7133 break; 7134 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7135 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7136 break; 7137 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7138 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7139 break; 7140 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7141 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7142 break; 7143 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7144 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7145 break; 7146 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7147 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7148 break; 7149 default: 7150 llvm_unreachable("unhandled atomic opcode"); 7151 } 7152 7153 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7154 M->getMemOperand()); 7155 } 7156 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7157 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7158 unsigned IdxEn = 1; 7159 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7160 IdxEn = Idx->getZExtValue() != 0; 7161 SDValue Ops[] = { 7162 Op.getOperand(0), // Chain 7163 Op.getOperand(2), // src 7164 Op.getOperand(3), // cmp 7165 Op.getOperand(4), // rsrc 7166 Op.getOperand(5), // vindex 7167 SDValue(), // voffset -- will be set by setBufferOffsets 7168 SDValue(), // soffset -- will be set by setBufferOffsets 7169 SDValue(), // offset -- will be set by setBufferOffsets 7170 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7171 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7172 }; 7173 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7174 // We don't know the offset if vindex is non-zero, so clear it. 7175 if (IdxEn) 7176 Offset = 0; 7177 EVT VT = Op.getValueType(); 7178 auto *M = cast<MemSDNode>(Op); 7179 M->getMemOperand()->setOffset(Offset); 7180 7181 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7182 Op->getVTList(), Ops, VT, M->getMemOperand()); 7183 } 7184 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7185 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7186 SDValue Ops[] = { 7187 Op.getOperand(0), // Chain 7188 Op.getOperand(2), // src 7189 Op.getOperand(3), // cmp 7190 Op.getOperand(4), // rsrc 7191 DAG.getConstant(0, DL, MVT::i32), // vindex 7192 Offsets.first, // voffset 7193 Op.getOperand(6), // soffset 7194 Offsets.second, // offset 7195 Op.getOperand(7), // cachepolicy 7196 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7197 }; 7198 EVT VT = Op.getValueType(); 7199 auto *M = cast<MemSDNode>(Op); 7200 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7201 7202 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7203 Op->getVTList(), Ops, VT, M->getMemOperand()); 7204 } 7205 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7206 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7207 SDValue Ops[] = { 7208 Op.getOperand(0), // Chain 7209 Op.getOperand(2), // src 7210 Op.getOperand(3), // cmp 7211 Op.getOperand(4), // rsrc 7212 Op.getOperand(5), // vindex 7213 Offsets.first, // voffset 7214 Op.getOperand(7), // soffset 7215 Offsets.second, // offset 7216 Op.getOperand(8), // cachepolicy 7217 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7218 }; 7219 EVT VT = Op.getValueType(); 7220 auto *M = cast<MemSDNode>(Op); 7221 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7222 Ops[4])); 7223 7224 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7225 Op->getVTList(), Ops, VT, M->getMemOperand()); 7226 } 7227 default: 7228 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7229 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7230 return lowerImage(Op, ImageDimIntr, DAG); 7231 7232 return SDValue(); 7233 } 7234 } 7235 7236 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7237 // dwordx4 if on SI. 7238 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7239 SDVTList VTList, 7240 ArrayRef<SDValue> Ops, EVT MemVT, 7241 MachineMemOperand *MMO, 7242 SelectionDAG &DAG) const { 7243 EVT VT = VTList.VTs[0]; 7244 EVT WidenedVT = VT; 7245 EVT WidenedMemVT = MemVT; 7246 if (!Subtarget->hasDwordx3LoadStores() && 7247 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7248 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7249 WidenedVT.getVectorElementType(), 4); 7250 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7251 WidenedMemVT.getVectorElementType(), 4); 7252 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7253 } 7254 7255 assert(VTList.NumVTs == 2); 7256 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7257 7258 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7259 WidenedMemVT, MMO); 7260 if (WidenedVT != VT) { 7261 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7262 DAG.getVectorIdxConstant(0, DL)); 7263 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7264 } 7265 return NewOp; 7266 } 7267 7268 SDValue SITargetLowering::handleD16VData(SDValue VData, 7269 SelectionDAG &DAG) const { 7270 EVT StoreVT = VData.getValueType(); 7271 7272 // No change for f16 and legal vector D16 types. 7273 if (!StoreVT.isVector()) 7274 return VData; 7275 7276 SDLoc DL(VData); 7277 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7278 7279 if (Subtarget->hasUnpackedD16VMem()) { 7280 // We need to unpack the packed data to store. 7281 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7282 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7283 7284 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7285 StoreVT.getVectorNumElements()); 7286 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7287 return DAG.UnrollVectorOp(ZExt.getNode()); 7288 } 7289 7290 assert(isTypeLegal(StoreVT)); 7291 return VData; 7292 } 7293 7294 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7295 SelectionDAG &DAG) const { 7296 SDLoc DL(Op); 7297 SDValue Chain = Op.getOperand(0); 7298 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7299 MachineFunction &MF = DAG.getMachineFunction(); 7300 7301 switch (IntrinsicID) { 7302 case Intrinsic::amdgcn_exp_compr: { 7303 SDValue Src0 = Op.getOperand(4); 7304 SDValue Src1 = Op.getOperand(5); 7305 // Hack around illegal type on SI by directly selecting it. 7306 if (isTypeLegal(Src0.getValueType())) 7307 return SDValue(); 7308 7309 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7310 SDValue Undef = DAG.getUNDEF(MVT::f32); 7311 const SDValue Ops[] = { 7312 Op.getOperand(2), // tgt 7313 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7314 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7315 Undef, // src2 7316 Undef, // src3 7317 Op.getOperand(7), // vm 7318 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7319 Op.getOperand(3), // en 7320 Op.getOperand(0) // Chain 7321 }; 7322 7323 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7324 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7325 } 7326 case Intrinsic::amdgcn_s_barrier: { 7327 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7328 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7329 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7330 if (WGSize <= ST.getWavefrontSize()) 7331 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7332 Op.getOperand(0)), 0); 7333 } 7334 return SDValue(); 7335 }; 7336 case Intrinsic::amdgcn_tbuffer_store: { 7337 SDValue VData = Op.getOperand(2); 7338 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7339 if (IsD16) 7340 VData = handleD16VData(VData, DAG); 7341 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7342 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7343 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7344 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7345 unsigned IdxEn = 1; 7346 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7347 IdxEn = Idx->getZExtValue() != 0; 7348 SDValue Ops[] = { 7349 Chain, 7350 VData, // vdata 7351 Op.getOperand(3), // rsrc 7352 Op.getOperand(4), // vindex 7353 Op.getOperand(5), // voffset 7354 Op.getOperand(6), // soffset 7355 Op.getOperand(7), // offset 7356 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7357 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7358 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7359 }; 7360 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7361 AMDGPUISD::TBUFFER_STORE_FORMAT; 7362 MemSDNode *M = cast<MemSDNode>(Op); 7363 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7364 M->getMemoryVT(), M->getMemOperand()); 7365 } 7366 7367 case Intrinsic::amdgcn_struct_tbuffer_store: { 7368 SDValue VData = Op.getOperand(2); 7369 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7370 if (IsD16) 7371 VData = handleD16VData(VData, DAG); 7372 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7373 SDValue Ops[] = { 7374 Chain, 7375 VData, // vdata 7376 Op.getOperand(3), // rsrc 7377 Op.getOperand(4), // vindex 7378 Offsets.first, // voffset 7379 Op.getOperand(6), // soffset 7380 Offsets.second, // offset 7381 Op.getOperand(7), // format 7382 Op.getOperand(8), // cachepolicy, swizzled buffer 7383 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7384 }; 7385 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7386 AMDGPUISD::TBUFFER_STORE_FORMAT; 7387 MemSDNode *M = cast<MemSDNode>(Op); 7388 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7389 M->getMemoryVT(), M->getMemOperand()); 7390 } 7391 7392 case Intrinsic::amdgcn_raw_tbuffer_store: { 7393 SDValue VData = Op.getOperand(2); 7394 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7395 if (IsD16) 7396 VData = handleD16VData(VData, DAG); 7397 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7398 SDValue Ops[] = { 7399 Chain, 7400 VData, // vdata 7401 Op.getOperand(3), // rsrc 7402 DAG.getConstant(0, DL, MVT::i32), // vindex 7403 Offsets.first, // voffset 7404 Op.getOperand(5), // soffset 7405 Offsets.second, // offset 7406 Op.getOperand(6), // format 7407 Op.getOperand(7), // cachepolicy, swizzled buffer 7408 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7409 }; 7410 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7411 AMDGPUISD::TBUFFER_STORE_FORMAT; 7412 MemSDNode *M = cast<MemSDNode>(Op); 7413 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7414 M->getMemoryVT(), M->getMemOperand()); 7415 } 7416 7417 case Intrinsic::amdgcn_buffer_store: 7418 case Intrinsic::amdgcn_buffer_store_format: { 7419 SDValue VData = Op.getOperand(2); 7420 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7421 if (IsD16) 7422 VData = handleD16VData(VData, DAG); 7423 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7424 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7425 unsigned IdxEn = 1; 7426 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7427 IdxEn = Idx->getZExtValue() != 0; 7428 SDValue Ops[] = { 7429 Chain, 7430 VData, 7431 Op.getOperand(3), // rsrc 7432 Op.getOperand(4), // vindex 7433 SDValue(), // voffset -- will be set by setBufferOffsets 7434 SDValue(), // soffset -- will be set by setBufferOffsets 7435 SDValue(), // offset -- will be set by setBufferOffsets 7436 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7437 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7438 }; 7439 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7440 // We don't know the offset if vindex is non-zero, so clear it. 7441 if (IdxEn) 7442 Offset = 0; 7443 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7444 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7445 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7446 MemSDNode *M = cast<MemSDNode>(Op); 7447 M->getMemOperand()->setOffset(Offset); 7448 7449 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7450 EVT VDataType = VData.getValueType().getScalarType(); 7451 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7452 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7453 7454 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7455 M->getMemoryVT(), M->getMemOperand()); 7456 } 7457 7458 case Intrinsic::amdgcn_raw_buffer_store: 7459 case Intrinsic::amdgcn_raw_buffer_store_format: { 7460 const bool IsFormat = 7461 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7462 7463 SDValue VData = Op.getOperand(2); 7464 EVT VDataVT = VData.getValueType(); 7465 EVT EltType = VDataVT.getScalarType(); 7466 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7467 if (IsD16) 7468 VData = handleD16VData(VData, DAG); 7469 7470 if (!isTypeLegal(VDataVT)) { 7471 VData = 7472 DAG.getNode(ISD::BITCAST, DL, 7473 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7474 } 7475 7476 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7477 SDValue Ops[] = { 7478 Chain, 7479 VData, 7480 Op.getOperand(3), // rsrc 7481 DAG.getConstant(0, DL, MVT::i32), // vindex 7482 Offsets.first, // voffset 7483 Op.getOperand(5), // soffset 7484 Offsets.second, // offset 7485 Op.getOperand(6), // cachepolicy, swizzled buffer 7486 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7487 }; 7488 unsigned Opc = 7489 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7490 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7491 MemSDNode *M = cast<MemSDNode>(Op); 7492 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7493 7494 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7495 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7496 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7497 7498 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7499 M->getMemoryVT(), M->getMemOperand()); 7500 } 7501 7502 case Intrinsic::amdgcn_struct_buffer_store: 7503 case Intrinsic::amdgcn_struct_buffer_store_format: { 7504 const bool IsFormat = 7505 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7506 7507 SDValue VData = Op.getOperand(2); 7508 EVT VDataVT = VData.getValueType(); 7509 EVT EltType = VDataVT.getScalarType(); 7510 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7511 7512 if (IsD16) 7513 VData = handleD16VData(VData, DAG); 7514 7515 if (!isTypeLegal(VDataVT)) { 7516 VData = 7517 DAG.getNode(ISD::BITCAST, DL, 7518 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7519 } 7520 7521 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7522 SDValue Ops[] = { 7523 Chain, 7524 VData, 7525 Op.getOperand(3), // rsrc 7526 Op.getOperand(4), // vindex 7527 Offsets.first, // voffset 7528 Op.getOperand(6), // soffset 7529 Offsets.second, // offset 7530 Op.getOperand(7), // cachepolicy, swizzled buffer 7531 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7532 }; 7533 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7534 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7535 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7536 MemSDNode *M = cast<MemSDNode>(Op); 7537 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7538 Ops[3])); 7539 7540 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7541 EVT VDataType = VData.getValueType().getScalarType(); 7542 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7543 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7544 7545 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7546 M->getMemoryVT(), M->getMemOperand()); 7547 } 7548 7549 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7550 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7551 unsigned IdxEn = 1; 7552 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7553 IdxEn = Idx->getZExtValue() != 0; 7554 SDValue Ops[] = { 7555 Chain, 7556 Op.getOperand(2), // vdata 7557 Op.getOperand(3), // rsrc 7558 Op.getOperand(4), // vindex 7559 SDValue(), // voffset -- will be set by setBufferOffsets 7560 SDValue(), // soffset -- will be set by setBufferOffsets 7561 SDValue(), // offset -- will be set by setBufferOffsets 7562 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7563 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7564 }; 7565 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7566 // We don't know the offset if vindex is non-zero, so clear it. 7567 if (IdxEn) 7568 Offset = 0; 7569 EVT VT = Op.getOperand(2).getValueType(); 7570 7571 auto *M = cast<MemSDNode>(Op); 7572 M->getMemOperand()->setOffset(Offset); 7573 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7574 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7575 7576 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7577 M->getMemOperand()); 7578 } 7579 7580 case Intrinsic::amdgcn_global_atomic_fadd: { 7581 SDValue Ops[] = { 7582 Chain, 7583 Op.getOperand(2), // ptr 7584 Op.getOperand(3) // vdata 7585 }; 7586 EVT VT = Op.getOperand(3).getValueType(); 7587 7588 auto *M = cast<MemSDNode>(Op); 7589 if (VT.isVector()) { 7590 return DAG.getMemIntrinsicNode( 7591 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7592 M->getMemOperand()); 7593 } 7594 7595 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7596 DAG.getVTList(VT, MVT::Other), Ops, 7597 M->getMemOperand()).getValue(1); 7598 } 7599 case Intrinsic::amdgcn_end_cf: 7600 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7601 Op->getOperand(2), Chain), 0); 7602 7603 default: { 7604 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7605 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7606 return lowerImage(Op, ImageDimIntr, DAG); 7607 7608 return Op; 7609 } 7610 } 7611 } 7612 7613 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7614 // offset (the offset that is included in bounds checking and swizzling, to be 7615 // split between the instruction's voffset and immoffset fields) and soffset 7616 // (the offset that is excluded from bounds checking and swizzling, to go in 7617 // the instruction's soffset field). This function takes the first kind of 7618 // offset and figures out how to split it between voffset and immoffset. 7619 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7620 SDValue Offset, SelectionDAG &DAG) const { 7621 SDLoc DL(Offset); 7622 const unsigned MaxImm = 4095; 7623 SDValue N0 = Offset; 7624 ConstantSDNode *C1 = nullptr; 7625 7626 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7627 N0 = SDValue(); 7628 else if (DAG.isBaseWithConstantOffset(N0)) { 7629 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7630 N0 = N0.getOperand(0); 7631 } 7632 7633 if (C1) { 7634 unsigned ImmOffset = C1->getZExtValue(); 7635 // If the immediate value is too big for the immoffset field, put the value 7636 // and -4096 into the immoffset field so that the value that is copied/added 7637 // for the voffset field is a multiple of 4096, and it stands more chance 7638 // of being CSEd with the copy/add for another similar load/store. 7639 // However, do not do that rounding down to a multiple of 4096 if that is a 7640 // negative number, as it appears to be illegal to have a negative offset 7641 // in the vgpr, even if adding the immediate offset makes it positive. 7642 unsigned Overflow = ImmOffset & ~MaxImm; 7643 ImmOffset -= Overflow; 7644 if ((int32_t)Overflow < 0) { 7645 Overflow += ImmOffset; 7646 ImmOffset = 0; 7647 } 7648 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7649 if (Overflow) { 7650 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7651 if (!N0) 7652 N0 = OverflowVal; 7653 else { 7654 SDValue Ops[] = { N0, OverflowVal }; 7655 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7656 } 7657 } 7658 } 7659 if (!N0) 7660 N0 = DAG.getConstant(0, DL, MVT::i32); 7661 if (!C1) 7662 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7663 return {N0, SDValue(C1, 0)}; 7664 } 7665 7666 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7667 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7668 // pointed to by Offsets. 7669 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7670 SelectionDAG &DAG, SDValue *Offsets, 7671 Align Alignment) const { 7672 SDLoc DL(CombinedOffset); 7673 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7674 uint32_t Imm = C->getZExtValue(); 7675 uint32_t SOffset, ImmOffset; 7676 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7677 Alignment)) { 7678 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7679 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7680 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7681 return SOffset + ImmOffset; 7682 } 7683 } 7684 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7685 SDValue N0 = CombinedOffset.getOperand(0); 7686 SDValue N1 = CombinedOffset.getOperand(1); 7687 uint32_t SOffset, ImmOffset; 7688 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7689 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7690 Subtarget, Alignment)) { 7691 Offsets[0] = N0; 7692 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7693 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7694 return 0; 7695 } 7696 } 7697 Offsets[0] = CombinedOffset; 7698 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7699 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7700 return 0; 7701 } 7702 7703 // Handle 8 bit and 16 bit buffer loads 7704 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7705 EVT LoadVT, SDLoc DL, 7706 ArrayRef<SDValue> Ops, 7707 MemSDNode *M) const { 7708 EVT IntVT = LoadVT.changeTypeToInteger(); 7709 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7710 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7711 7712 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7713 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7714 Ops, IntVT, 7715 M->getMemOperand()); 7716 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7717 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7718 7719 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7720 } 7721 7722 // Handle 8 bit and 16 bit buffer stores 7723 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7724 EVT VDataType, SDLoc DL, 7725 SDValue Ops[], 7726 MemSDNode *M) const { 7727 if (VDataType == MVT::f16) 7728 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7729 7730 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7731 Ops[1] = BufferStoreExt; 7732 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7733 AMDGPUISD::BUFFER_STORE_SHORT; 7734 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7735 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7736 M->getMemOperand()); 7737 } 7738 7739 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7740 ISD::LoadExtType ExtType, SDValue Op, 7741 const SDLoc &SL, EVT VT) { 7742 if (VT.bitsLT(Op.getValueType())) 7743 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7744 7745 switch (ExtType) { 7746 case ISD::SEXTLOAD: 7747 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7748 case ISD::ZEXTLOAD: 7749 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7750 case ISD::EXTLOAD: 7751 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7752 case ISD::NON_EXTLOAD: 7753 return Op; 7754 } 7755 7756 llvm_unreachable("invalid ext type"); 7757 } 7758 7759 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7760 SelectionDAG &DAG = DCI.DAG; 7761 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7762 return SDValue(); 7763 7764 // FIXME: Constant loads should all be marked invariant. 7765 unsigned AS = Ld->getAddressSpace(); 7766 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7767 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7768 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7769 return SDValue(); 7770 7771 // Don't do this early, since it may interfere with adjacent load merging for 7772 // illegal types. We can avoid losing alignment information for exotic types 7773 // pre-legalize. 7774 EVT MemVT = Ld->getMemoryVT(); 7775 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7776 MemVT.getSizeInBits() >= 32) 7777 return SDValue(); 7778 7779 SDLoc SL(Ld); 7780 7781 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7782 "unexpected vector extload"); 7783 7784 // TODO: Drop only high part of range. 7785 SDValue Ptr = Ld->getBasePtr(); 7786 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7787 MVT::i32, SL, Ld->getChain(), Ptr, 7788 Ld->getOffset(), 7789 Ld->getPointerInfo(), MVT::i32, 7790 Ld->getAlignment(), 7791 Ld->getMemOperand()->getFlags(), 7792 Ld->getAAInfo(), 7793 nullptr); // Drop ranges 7794 7795 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7796 if (MemVT.isFloatingPoint()) { 7797 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7798 "unexpected fp extload"); 7799 TruncVT = MemVT.changeTypeToInteger(); 7800 } 7801 7802 SDValue Cvt = NewLoad; 7803 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7804 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7805 DAG.getValueType(TruncVT)); 7806 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7807 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7808 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7809 } else { 7810 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7811 } 7812 7813 EVT VT = Ld->getValueType(0); 7814 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7815 7816 DCI.AddToWorklist(Cvt.getNode()); 7817 7818 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7819 // the appropriate extension from the 32-bit load. 7820 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7821 DCI.AddToWorklist(Cvt.getNode()); 7822 7823 // Handle conversion back to floating point if necessary. 7824 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7825 7826 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7827 } 7828 7829 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7830 SDLoc DL(Op); 7831 LoadSDNode *Load = cast<LoadSDNode>(Op); 7832 ISD::LoadExtType ExtType = Load->getExtensionType(); 7833 EVT MemVT = Load->getMemoryVT(); 7834 7835 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7836 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7837 return SDValue(); 7838 7839 // FIXME: Copied from PPC 7840 // First, load into 32 bits, then truncate to 1 bit. 7841 7842 SDValue Chain = Load->getChain(); 7843 SDValue BasePtr = Load->getBasePtr(); 7844 MachineMemOperand *MMO = Load->getMemOperand(); 7845 7846 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7847 7848 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7849 BasePtr, RealMemVT, MMO); 7850 7851 if (!MemVT.isVector()) { 7852 SDValue Ops[] = { 7853 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7854 NewLD.getValue(1) 7855 }; 7856 7857 return DAG.getMergeValues(Ops, DL); 7858 } 7859 7860 SmallVector<SDValue, 3> Elts; 7861 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7862 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7863 DAG.getConstant(I, DL, MVT::i32)); 7864 7865 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7866 } 7867 7868 SDValue Ops[] = { 7869 DAG.getBuildVector(MemVT, DL, Elts), 7870 NewLD.getValue(1) 7871 }; 7872 7873 return DAG.getMergeValues(Ops, DL); 7874 } 7875 7876 if (!MemVT.isVector()) 7877 return SDValue(); 7878 7879 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7880 "Custom lowering for non-i32 vectors hasn't been implemented."); 7881 7882 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7883 MemVT, *Load->getMemOperand())) { 7884 SDValue Ops[2]; 7885 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7886 return DAG.getMergeValues(Ops, DL); 7887 } 7888 7889 unsigned Alignment = Load->getAlignment(); 7890 unsigned AS = Load->getAddressSpace(); 7891 if (Subtarget->hasLDSMisalignedBug() && 7892 AS == AMDGPUAS::FLAT_ADDRESS && 7893 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7894 return SplitVectorLoad(Op, DAG); 7895 } 7896 7897 MachineFunction &MF = DAG.getMachineFunction(); 7898 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7899 // If there is a possibilty that flat instruction access scratch memory 7900 // then we need to use the same legalization rules we use for private. 7901 if (AS == AMDGPUAS::FLAT_ADDRESS && 7902 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7903 AS = MFI->hasFlatScratchInit() ? 7904 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7905 7906 unsigned NumElements = MemVT.getVectorNumElements(); 7907 7908 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7909 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7910 if (!Op->isDivergent() && 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 7923 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7924 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7925 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7926 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7927 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7928 Alignment >= 4 && NumElements < 32) { 7929 if (MemVT.isPow2VectorType()) 7930 return SDValue(); 7931 if (NumElements == 3) 7932 return WidenVectorLoad(Op, DAG); 7933 return SplitVectorLoad(Op, DAG); 7934 } 7935 // Non-uniform loads will be selected to MUBUF instructions, so they 7936 // have the same legalization requirements as global and private 7937 // loads. 7938 // 7939 } 7940 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7941 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7942 AS == AMDGPUAS::GLOBAL_ADDRESS || 7943 AS == AMDGPUAS::FLAT_ADDRESS) { 7944 if (NumElements > 4) 7945 return SplitVectorLoad(Op, DAG); 7946 // v3 loads not supported on SI. 7947 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7948 return WidenVectorLoad(Op, DAG); 7949 // v3 and v4 loads are supported for private and global memory. 7950 return SDValue(); 7951 } 7952 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7953 // Depending on the setting of the private_element_size field in the 7954 // resource descriptor, we can only make private accesses up to a certain 7955 // size. 7956 switch (Subtarget->getMaxPrivateElementSize()) { 7957 case 4: { 7958 SDValue Ops[2]; 7959 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7960 return DAG.getMergeValues(Ops, DL); 7961 } 7962 case 8: 7963 if (NumElements > 2) 7964 return SplitVectorLoad(Op, DAG); 7965 return SDValue(); 7966 case 16: 7967 // Same as global/flat 7968 if (NumElements > 4) 7969 return SplitVectorLoad(Op, DAG); 7970 // v3 loads not supported on SI. 7971 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7972 return WidenVectorLoad(Op, DAG); 7973 return SDValue(); 7974 default: 7975 llvm_unreachable("unsupported private_element_size"); 7976 } 7977 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7978 // Use ds_read_b128 if possible. 7979 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7980 MemVT.getStoreSize() == 16) 7981 return SDValue(); 7982 7983 if (NumElements > 2) 7984 return SplitVectorLoad(Op, DAG); 7985 7986 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7987 // address is negative, then the instruction is incorrectly treated as 7988 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7989 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7990 // load later in the SILoadStoreOptimizer. 7991 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7992 NumElements == 2 && MemVT.getStoreSize() == 8 && 7993 Load->getAlignment() < 8) { 7994 return SplitVectorLoad(Op, DAG); 7995 } 7996 } 7997 return SDValue(); 7998 } 7999 8000 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8001 EVT VT = Op.getValueType(); 8002 assert(VT.getSizeInBits() == 64); 8003 8004 SDLoc DL(Op); 8005 SDValue Cond = Op.getOperand(0); 8006 8007 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8008 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8009 8010 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8011 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8012 8013 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8014 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8015 8016 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8017 8018 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8019 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8020 8021 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8022 8023 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8024 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8025 } 8026 8027 // Catch division cases where we can use shortcuts with rcp and rsq 8028 // instructions. 8029 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8030 SelectionDAG &DAG) const { 8031 SDLoc SL(Op); 8032 SDValue LHS = Op.getOperand(0); 8033 SDValue RHS = Op.getOperand(1); 8034 EVT VT = Op.getValueType(); 8035 const SDNodeFlags Flags = Op->getFlags(); 8036 8037 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8038 Flags.hasApproximateFuncs(); 8039 8040 // Without !fpmath accuracy information, we can't do more because we don't 8041 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8042 if (!AllowInaccurateRcp) 8043 return SDValue(); 8044 8045 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8046 if (CLHS->isExactlyValue(1.0)) { 8047 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8048 // the CI documentation has a worst case error of 1 ulp. 8049 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8050 // use it as long as we aren't trying to use denormals. 8051 // 8052 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8053 8054 // 1.0 / sqrt(x) -> rsq(x) 8055 8056 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8057 // error seems really high at 2^29 ULP. 8058 if (RHS.getOpcode() == ISD::FSQRT) 8059 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8060 8061 // 1.0 / x -> rcp(x) 8062 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8063 } 8064 8065 // Same as for 1.0, but expand the sign out of the constant. 8066 if (CLHS->isExactlyValue(-1.0)) { 8067 // -1.0 / x -> rcp (fneg x) 8068 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8069 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8070 } 8071 } 8072 8073 // Turn into multiply by the reciprocal. 8074 // x / y -> x * (1.0 / y) 8075 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8076 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8077 } 8078 8079 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8080 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8081 SDNodeFlags Flags) { 8082 if (GlueChain->getNumValues() <= 1) { 8083 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8084 } 8085 8086 assert(GlueChain->getNumValues() == 3); 8087 8088 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8089 switch (Opcode) { 8090 default: llvm_unreachable("no chain equivalent for opcode"); 8091 case ISD::FMUL: 8092 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8093 break; 8094 } 8095 8096 return DAG.getNode(Opcode, SL, VTList, 8097 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8098 Flags); 8099 } 8100 8101 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8102 EVT VT, SDValue A, SDValue B, SDValue C, 8103 SDValue GlueChain, SDNodeFlags Flags) { 8104 if (GlueChain->getNumValues() <= 1) { 8105 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8106 } 8107 8108 assert(GlueChain->getNumValues() == 3); 8109 8110 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8111 switch (Opcode) { 8112 default: llvm_unreachable("no chain equivalent for opcode"); 8113 case ISD::FMA: 8114 Opcode = AMDGPUISD::FMA_W_CHAIN; 8115 break; 8116 } 8117 8118 return DAG.getNode(Opcode, SL, VTList, 8119 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8120 Flags); 8121 } 8122 8123 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8124 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8125 return FastLowered; 8126 8127 SDLoc SL(Op); 8128 SDValue Src0 = Op.getOperand(0); 8129 SDValue Src1 = Op.getOperand(1); 8130 8131 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8132 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8133 8134 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8135 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8136 8137 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8138 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8139 8140 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8141 } 8142 8143 // Faster 2.5 ULP division that does not support denormals. 8144 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8145 SDLoc SL(Op); 8146 SDValue LHS = Op.getOperand(1); 8147 SDValue RHS = Op.getOperand(2); 8148 8149 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8150 8151 const APFloat K0Val(BitsToFloat(0x6f800000)); 8152 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8153 8154 const APFloat K1Val(BitsToFloat(0x2f800000)); 8155 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8156 8157 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8158 8159 EVT SetCCVT = 8160 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8161 8162 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8163 8164 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8165 8166 // TODO: Should this propagate fast-math-flags? 8167 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8168 8169 // rcp does not support denormals. 8170 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8171 8172 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8173 8174 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8175 } 8176 8177 // Returns immediate value for setting the F32 denorm mode when using the 8178 // S_DENORM_MODE instruction. 8179 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8180 const SDLoc &SL, const GCNSubtarget *ST) { 8181 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8182 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8183 ? FP_DENORM_FLUSH_NONE 8184 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8185 8186 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8187 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8188 } 8189 8190 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8191 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8192 return FastLowered; 8193 8194 // The selection matcher assumes anything with a chain selecting to a 8195 // mayRaiseFPException machine instruction. Since we're introducing a chain 8196 // here, we need to explicitly report nofpexcept for the regular fdiv 8197 // lowering. 8198 SDNodeFlags Flags = Op->getFlags(); 8199 Flags.setNoFPExcept(true); 8200 8201 SDLoc SL(Op); 8202 SDValue LHS = Op.getOperand(0); 8203 SDValue RHS = Op.getOperand(1); 8204 8205 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8206 8207 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8208 8209 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8210 {RHS, RHS, LHS}, Flags); 8211 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8212 {LHS, RHS, LHS}, Flags); 8213 8214 // Denominator is scaled to not be denormal, so using rcp is ok. 8215 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8216 DenominatorScaled, Flags); 8217 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8218 DenominatorScaled, Flags); 8219 8220 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8221 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8222 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8223 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8224 8225 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8226 8227 if (!HasFP32Denormals) { 8228 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8229 // lowering. The chain dependence is insufficient, and we need glue. We do 8230 // not need the glue variants in a strictfp function. 8231 8232 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8233 8234 SDNode *EnableDenorm; 8235 if (Subtarget->hasDenormModeInst()) { 8236 const SDValue EnableDenormValue = 8237 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8238 8239 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8240 DAG.getEntryNode(), EnableDenormValue).getNode(); 8241 } else { 8242 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8243 SL, MVT::i32); 8244 EnableDenorm = 8245 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8246 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8247 } 8248 8249 SDValue Ops[3] = { 8250 NegDivScale0, 8251 SDValue(EnableDenorm, 0), 8252 SDValue(EnableDenorm, 1) 8253 }; 8254 8255 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8256 } 8257 8258 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8259 ApproxRcp, One, NegDivScale0, Flags); 8260 8261 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8262 ApproxRcp, Fma0, Flags); 8263 8264 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8265 Fma1, Fma1, Flags); 8266 8267 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8268 NumeratorScaled, Mul, Flags); 8269 8270 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8271 Fma2, Fma1, Mul, Fma2, Flags); 8272 8273 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8274 NumeratorScaled, Fma3, Flags); 8275 8276 if (!HasFP32Denormals) { 8277 SDNode *DisableDenorm; 8278 if (Subtarget->hasDenormModeInst()) { 8279 const SDValue DisableDenormValue = 8280 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8281 8282 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8283 Fma4.getValue(1), DisableDenormValue, 8284 Fma4.getValue(2)).getNode(); 8285 } else { 8286 const SDValue DisableDenormValue = 8287 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8288 8289 DisableDenorm = DAG.getMachineNode( 8290 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8291 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8292 } 8293 8294 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8295 SDValue(DisableDenorm, 0), DAG.getRoot()); 8296 DAG.setRoot(OutputChain); 8297 } 8298 8299 SDValue Scale = NumeratorScaled.getValue(1); 8300 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8301 {Fma4, Fma1, Fma3, Scale}, Flags); 8302 8303 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8304 } 8305 8306 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8307 if (DAG.getTarget().Options.UnsafeFPMath) 8308 return lowerFastUnsafeFDIV(Op, DAG); 8309 8310 SDLoc SL(Op); 8311 SDValue X = Op.getOperand(0); 8312 SDValue Y = Op.getOperand(1); 8313 8314 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8315 8316 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8317 8318 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8319 8320 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8321 8322 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8323 8324 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8325 8326 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8327 8328 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8329 8330 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8331 8332 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8333 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8334 8335 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8336 NegDivScale0, Mul, DivScale1); 8337 8338 SDValue Scale; 8339 8340 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8341 // Workaround a hardware bug on SI where the condition output from div_scale 8342 // is not usable. 8343 8344 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8345 8346 // Figure out if the scale to use for div_fmas. 8347 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8348 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8349 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8350 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8351 8352 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8353 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8354 8355 SDValue Scale0Hi 8356 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8357 SDValue Scale1Hi 8358 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8359 8360 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8361 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8362 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8363 } else { 8364 Scale = DivScale1.getValue(1); 8365 } 8366 8367 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8368 Fma4, Fma3, Mul, Scale); 8369 8370 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8371 } 8372 8373 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8374 EVT VT = Op.getValueType(); 8375 8376 if (VT == MVT::f32) 8377 return LowerFDIV32(Op, DAG); 8378 8379 if (VT == MVT::f64) 8380 return LowerFDIV64(Op, DAG); 8381 8382 if (VT == MVT::f16) 8383 return LowerFDIV16(Op, DAG); 8384 8385 llvm_unreachable("Unexpected type for fdiv"); 8386 } 8387 8388 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8389 SDLoc DL(Op); 8390 StoreSDNode *Store = cast<StoreSDNode>(Op); 8391 EVT VT = Store->getMemoryVT(); 8392 8393 if (VT == MVT::i1) { 8394 return DAG.getTruncStore(Store->getChain(), DL, 8395 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8396 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8397 } 8398 8399 assert(VT.isVector() && 8400 Store->getValue().getValueType().getScalarType() == MVT::i32); 8401 8402 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8403 VT, *Store->getMemOperand())) { 8404 return expandUnalignedStore(Store, DAG); 8405 } 8406 8407 unsigned AS = Store->getAddressSpace(); 8408 if (Subtarget->hasLDSMisalignedBug() && 8409 AS == AMDGPUAS::FLAT_ADDRESS && 8410 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8411 return SplitVectorStore(Op, DAG); 8412 } 8413 8414 MachineFunction &MF = DAG.getMachineFunction(); 8415 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8416 // If there is a possibilty that flat instruction access scratch memory 8417 // then we need to use the same legalization rules we use for private. 8418 if (AS == AMDGPUAS::FLAT_ADDRESS && 8419 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8420 AS = MFI->hasFlatScratchInit() ? 8421 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8422 8423 unsigned NumElements = VT.getVectorNumElements(); 8424 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8425 AS == AMDGPUAS::FLAT_ADDRESS) { 8426 if (NumElements > 4) 8427 return SplitVectorStore(Op, DAG); 8428 // v3 stores not supported on SI. 8429 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8430 return SplitVectorStore(Op, DAG); 8431 return SDValue(); 8432 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8433 switch (Subtarget->getMaxPrivateElementSize()) { 8434 case 4: 8435 return scalarizeVectorStore(Store, DAG); 8436 case 8: 8437 if (NumElements > 2) 8438 return SplitVectorStore(Op, DAG); 8439 return SDValue(); 8440 case 16: 8441 if (NumElements > 4 || NumElements == 3) 8442 return SplitVectorStore(Op, DAG); 8443 return SDValue(); 8444 default: 8445 llvm_unreachable("unsupported private_element_size"); 8446 } 8447 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8448 // Use ds_write_b128 if possible. 8449 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8450 VT.getStoreSize() == 16 && NumElements != 3) 8451 return SDValue(); 8452 8453 if (NumElements > 2) 8454 return SplitVectorStore(Op, DAG); 8455 8456 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8457 // address is negative, then the instruction is incorrectly treated as 8458 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8459 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8460 // store later in the SILoadStoreOptimizer. 8461 if (!Subtarget->hasUsableDSOffset() && 8462 NumElements == 2 && VT.getStoreSize() == 8 && 8463 Store->getAlignment() < 8) { 8464 return SplitVectorStore(Op, DAG); 8465 } 8466 8467 return SDValue(); 8468 } else { 8469 llvm_unreachable("unhandled address space"); 8470 } 8471 } 8472 8473 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8474 SDLoc DL(Op); 8475 EVT VT = Op.getValueType(); 8476 SDValue Arg = Op.getOperand(0); 8477 SDValue TrigVal; 8478 8479 // Propagate fast-math flags so that the multiply we introduce can be folded 8480 // if Arg is already the result of a multiply by constant. 8481 auto Flags = Op->getFlags(); 8482 8483 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8484 8485 if (Subtarget->hasTrigReducedRange()) { 8486 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8487 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8488 } else { 8489 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8490 } 8491 8492 switch (Op.getOpcode()) { 8493 case ISD::FCOS: 8494 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8495 case ISD::FSIN: 8496 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8497 default: 8498 llvm_unreachable("Wrong trig opcode"); 8499 } 8500 } 8501 8502 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8503 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8504 assert(AtomicNode->isCompareAndSwap()); 8505 unsigned AS = AtomicNode->getAddressSpace(); 8506 8507 // No custom lowering required for local address space 8508 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8509 return Op; 8510 8511 // Non-local address space requires custom lowering for atomic compare 8512 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8513 SDLoc DL(Op); 8514 SDValue ChainIn = Op.getOperand(0); 8515 SDValue Addr = Op.getOperand(1); 8516 SDValue Old = Op.getOperand(2); 8517 SDValue New = Op.getOperand(3); 8518 EVT VT = Op.getValueType(); 8519 MVT SimpleVT = VT.getSimpleVT(); 8520 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8521 8522 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8523 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8524 8525 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8526 Ops, VT, AtomicNode->getMemOperand()); 8527 } 8528 8529 //===----------------------------------------------------------------------===// 8530 // Custom DAG optimizations 8531 //===----------------------------------------------------------------------===// 8532 8533 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8534 DAGCombinerInfo &DCI) const { 8535 EVT VT = N->getValueType(0); 8536 EVT ScalarVT = VT.getScalarType(); 8537 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8538 return SDValue(); 8539 8540 SelectionDAG &DAG = DCI.DAG; 8541 SDLoc DL(N); 8542 8543 SDValue Src = N->getOperand(0); 8544 EVT SrcVT = Src.getValueType(); 8545 8546 // TODO: We could try to match extracting the higher bytes, which would be 8547 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8548 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8549 // about in practice. 8550 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8551 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8552 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8553 DCI.AddToWorklist(Cvt.getNode()); 8554 8555 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8556 if (ScalarVT != MVT::f32) { 8557 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8558 DAG.getTargetConstant(0, DL, MVT::i32)); 8559 } 8560 return Cvt; 8561 } 8562 } 8563 8564 return SDValue(); 8565 } 8566 8567 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8568 8569 // This is a variant of 8570 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8571 // 8572 // The normal DAG combiner will do this, but only if the add has one use since 8573 // that would increase the number of instructions. 8574 // 8575 // This prevents us from seeing a constant offset that can be folded into a 8576 // memory instruction's addressing mode. If we know the resulting add offset of 8577 // a pointer can be folded into an addressing offset, we can replace the pointer 8578 // operand with the add of new constant offset. This eliminates one of the uses, 8579 // and may allow the remaining use to also be simplified. 8580 // 8581 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8582 unsigned AddrSpace, 8583 EVT MemVT, 8584 DAGCombinerInfo &DCI) const { 8585 SDValue N0 = N->getOperand(0); 8586 SDValue N1 = N->getOperand(1); 8587 8588 // We only do this to handle cases where it's profitable when there are 8589 // multiple uses of the add, so defer to the standard combine. 8590 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8591 N0->hasOneUse()) 8592 return SDValue(); 8593 8594 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8595 if (!CN1) 8596 return SDValue(); 8597 8598 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8599 if (!CAdd) 8600 return SDValue(); 8601 8602 // If the resulting offset is too large, we can't fold it into the addressing 8603 // mode offset. 8604 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8605 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8606 8607 AddrMode AM; 8608 AM.HasBaseReg = true; 8609 AM.BaseOffs = Offset.getSExtValue(); 8610 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8611 return SDValue(); 8612 8613 SelectionDAG &DAG = DCI.DAG; 8614 SDLoc SL(N); 8615 EVT VT = N->getValueType(0); 8616 8617 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8618 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8619 8620 SDNodeFlags Flags; 8621 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8622 (N0.getOpcode() == ISD::OR || 8623 N0->getFlags().hasNoUnsignedWrap())); 8624 8625 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8626 } 8627 8628 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8629 DAGCombinerInfo &DCI) const { 8630 SDValue Ptr = N->getBasePtr(); 8631 SelectionDAG &DAG = DCI.DAG; 8632 SDLoc SL(N); 8633 8634 // TODO: We could also do this for multiplies. 8635 if (Ptr.getOpcode() == ISD::SHL) { 8636 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8637 N->getMemoryVT(), DCI); 8638 if (NewPtr) { 8639 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8640 8641 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8642 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8643 } 8644 } 8645 8646 return SDValue(); 8647 } 8648 8649 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8650 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8651 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8652 (Opc == ISD::XOR && Val == 0); 8653 } 8654 8655 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8656 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8657 // integer combine opportunities since most 64-bit operations are decomposed 8658 // this way. TODO: We won't want this for SALU especially if it is an inline 8659 // immediate. 8660 SDValue SITargetLowering::splitBinaryBitConstantOp( 8661 DAGCombinerInfo &DCI, 8662 const SDLoc &SL, 8663 unsigned Opc, SDValue LHS, 8664 const ConstantSDNode *CRHS) const { 8665 uint64_t Val = CRHS->getZExtValue(); 8666 uint32_t ValLo = Lo_32(Val); 8667 uint32_t ValHi = Hi_32(Val); 8668 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8669 8670 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8671 bitOpWithConstantIsReducible(Opc, ValHi)) || 8672 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8673 // If we need to materialize a 64-bit immediate, it will be split up later 8674 // anyway. Avoid creating the harder to understand 64-bit immediate 8675 // materialization. 8676 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8677 } 8678 8679 return SDValue(); 8680 } 8681 8682 // Returns true if argument is a boolean value which is not serialized into 8683 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8684 static bool isBoolSGPR(SDValue V) { 8685 if (V.getValueType() != MVT::i1) 8686 return false; 8687 switch (V.getOpcode()) { 8688 default: break; 8689 case ISD::SETCC: 8690 case ISD::AND: 8691 case ISD::OR: 8692 case ISD::XOR: 8693 case AMDGPUISD::FP_CLASS: 8694 return true; 8695 } 8696 return false; 8697 } 8698 8699 // If a constant has all zeroes or all ones within each byte return it. 8700 // Otherwise return 0. 8701 static uint32_t getConstantPermuteMask(uint32_t C) { 8702 // 0xff for any zero byte in the mask 8703 uint32_t ZeroByteMask = 0; 8704 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8705 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8706 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8707 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8708 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8709 if ((NonZeroByteMask & C) != NonZeroByteMask) 8710 return 0; // Partial bytes selected. 8711 return C; 8712 } 8713 8714 // Check if a node selects whole bytes from its operand 0 starting at a byte 8715 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8716 // or -1 if not succeeded. 8717 // Note byte select encoding: 8718 // value 0-3 selects corresponding source byte; 8719 // value 0xc selects zero; 8720 // value 0xff selects 0xff. 8721 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8722 assert(V.getValueSizeInBits() == 32); 8723 8724 if (V.getNumOperands() != 2) 8725 return ~0; 8726 8727 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8728 if (!N1) 8729 return ~0; 8730 8731 uint32_t C = N1->getZExtValue(); 8732 8733 switch (V.getOpcode()) { 8734 default: 8735 break; 8736 case ISD::AND: 8737 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8738 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8739 } 8740 break; 8741 8742 case ISD::OR: 8743 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8744 return (0x03020100 & ~ConstMask) | ConstMask; 8745 } 8746 break; 8747 8748 case ISD::SHL: 8749 if (C % 8) 8750 return ~0; 8751 8752 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8753 8754 case ISD::SRL: 8755 if (C % 8) 8756 return ~0; 8757 8758 return uint32_t(0x0c0c0c0c03020100ull >> C); 8759 } 8760 8761 return ~0; 8762 } 8763 8764 SDValue SITargetLowering::performAndCombine(SDNode *N, 8765 DAGCombinerInfo &DCI) const { 8766 if (DCI.isBeforeLegalize()) 8767 return SDValue(); 8768 8769 SelectionDAG &DAG = DCI.DAG; 8770 EVT VT = N->getValueType(0); 8771 SDValue LHS = N->getOperand(0); 8772 SDValue RHS = N->getOperand(1); 8773 8774 8775 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8776 if (VT == MVT::i64 && CRHS) { 8777 if (SDValue Split 8778 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8779 return Split; 8780 } 8781 8782 if (CRHS && VT == MVT::i32) { 8783 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8784 // nb = number of trailing zeroes in mask 8785 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8786 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8787 uint64_t Mask = CRHS->getZExtValue(); 8788 unsigned Bits = countPopulation(Mask); 8789 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8790 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8791 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8792 unsigned Shift = CShift->getZExtValue(); 8793 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8794 unsigned Offset = NB + Shift; 8795 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8796 SDLoc SL(N); 8797 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8798 LHS->getOperand(0), 8799 DAG.getConstant(Offset, SL, MVT::i32), 8800 DAG.getConstant(Bits, SL, MVT::i32)); 8801 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8802 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8803 DAG.getValueType(NarrowVT)); 8804 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8805 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8806 return Shl; 8807 } 8808 } 8809 } 8810 8811 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8812 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8813 isa<ConstantSDNode>(LHS.getOperand(2))) { 8814 uint32_t Sel = getConstantPermuteMask(Mask); 8815 if (!Sel) 8816 return SDValue(); 8817 8818 // Select 0xc for all zero bytes 8819 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8820 SDLoc DL(N); 8821 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8822 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8823 } 8824 } 8825 8826 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8827 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8828 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8829 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8830 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8831 8832 SDValue X = LHS.getOperand(0); 8833 SDValue Y = RHS.getOperand(0); 8834 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8835 return SDValue(); 8836 8837 if (LCC == ISD::SETO) { 8838 if (X != LHS.getOperand(1)) 8839 return SDValue(); 8840 8841 if (RCC == ISD::SETUNE) { 8842 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8843 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8844 return SDValue(); 8845 8846 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8847 SIInstrFlags::N_SUBNORMAL | 8848 SIInstrFlags::N_ZERO | 8849 SIInstrFlags::P_ZERO | 8850 SIInstrFlags::P_SUBNORMAL | 8851 SIInstrFlags::P_NORMAL; 8852 8853 static_assert(((~(SIInstrFlags::S_NAN | 8854 SIInstrFlags::Q_NAN | 8855 SIInstrFlags::N_INFINITY | 8856 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8857 "mask not equal"); 8858 8859 SDLoc DL(N); 8860 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8861 X, DAG.getConstant(Mask, DL, MVT::i32)); 8862 } 8863 } 8864 } 8865 8866 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8867 std::swap(LHS, RHS); 8868 8869 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8870 RHS.hasOneUse()) { 8871 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8872 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8873 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8874 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8875 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8876 (RHS.getOperand(0) == LHS.getOperand(0) && 8877 LHS.getOperand(0) == LHS.getOperand(1))) { 8878 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8879 unsigned NewMask = LCC == ISD::SETO ? 8880 Mask->getZExtValue() & ~OrdMask : 8881 Mask->getZExtValue() & OrdMask; 8882 8883 SDLoc DL(N); 8884 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8885 DAG.getConstant(NewMask, DL, MVT::i32)); 8886 } 8887 } 8888 8889 if (VT == MVT::i32 && 8890 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8891 // and x, (sext cc from i1) => select cc, x, 0 8892 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8893 std::swap(LHS, RHS); 8894 if (isBoolSGPR(RHS.getOperand(0))) 8895 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8896 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8897 } 8898 8899 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8900 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8901 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8902 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8903 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8904 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8905 if (LHSMask != ~0u && RHSMask != ~0u) { 8906 // Canonicalize the expression in an attempt to have fewer unique masks 8907 // and therefore fewer registers used to hold the masks. 8908 if (LHSMask > RHSMask) { 8909 std::swap(LHSMask, RHSMask); 8910 std::swap(LHS, RHS); 8911 } 8912 8913 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8914 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8915 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8916 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8917 8918 // Check of we need to combine values from two sources within a byte. 8919 if (!(LHSUsedLanes & RHSUsedLanes) && 8920 // If we select high and lower word keep it for SDWA. 8921 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8922 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8923 // Each byte in each mask is either selector mask 0-3, or has higher 8924 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8925 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8926 // mask which is not 0xff wins. By anding both masks we have a correct 8927 // result except that 0x0c shall be corrected to give 0x0c only. 8928 uint32_t Mask = LHSMask & RHSMask; 8929 for (unsigned I = 0; I < 32; I += 8) { 8930 uint32_t ByteSel = 0xff << I; 8931 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8932 Mask &= (0x0c << I) & 0xffffffff; 8933 } 8934 8935 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8936 // or 0x0c. 8937 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8938 SDLoc DL(N); 8939 8940 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8941 LHS.getOperand(0), RHS.getOperand(0), 8942 DAG.getConstant(Sel, DL, MVT::i32)); 8943 } 8944 } 8945 } 8946 8947 return SDValue(); 8948 } 8949 8950 SDValue SITargetLowering::performOrCombine(SDNode *N, 8951 DAGCombinerInfo &DCI) const { 8952 SelectionDAG &DAG = DCI.DAG; 8953 SDValue LHS = N->getOperand(0); 8954 SDValue RHS = N->getOperand(1); 8955 8956 EVT VT = N->getValueType(0); 8957 if (VT == MVT::i1) { 8958 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8959 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8960 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8961 SDValue Src = LHS.getOperand(0); 8962 if (Src != RHS.getOperand(0)) 8963 return SDValue(); 8964 8965 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8966 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8967 if (!CLHS || !CRHS) 8968 return SDValue(); 8969 8970 // Only 10 bits are used. 8971 static const uint32_t MaxMask = 0x3ff; 8972 8973 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8974 SDLoc DL(N); 8975 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8976 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8977 } 8978 8979 return SDValue(); 8980 } 8981 8982 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8983 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8984 LHS.getOpcode() == AMDGPUISD::PERM && 8985 isa<ConstantSDNode>(LHS.getOperand(2))) { 8986 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8987 if (!Sel) 8988 return SDValue(); 8989 8990 Sel |= LHS.getConstantOperandVal(2); 8991 SDLoc DL(N); 8992 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8993 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8994 } 8995 8996 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8997 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8998 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8999 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9000 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9001 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9002 if (LHSMask != ~0u && RHSMask != ~0u) { 9003 // Canonicalize the expression in an attempt to have fewer unique masks 9004 // and therefore fewer registers used to hold the masks. 9005 if (LHSMask > RHSMask) { 9006 std::swap(LHSMask, RHSMask); 9007 std::swap(LHS, RHS); 9008 } 9009 9010 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9011 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9012 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9013 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9014 9015 // Check of we need to combine values from two sources within a byte. 9016 if (!(LHSUsedLanes & RHSUsedLanes) && 9017 // If we select high and lower word keep it for SDWA. 9018 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9019 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9020 // Kill zero bytes selected by other mask. Zero value is 0xc. 9021 LHSMask &= ~RHSUsedLanes; 9022 RHSMask &= ~LHSUsedLanes; 9023 // Add 4 to each active LHS lane 9024 LHSMask |= LHSUsedLanes & 0x04040404; 9025 // Combine masks 9026 uint32_t Sel = LHSMask | RHSMask; 9027 SDLoc DL(N); 9028 9029 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9030 LHS.getOperand(0), RHS.getOperand(0), 9031 DAG.getConstant(Sel, DL, MVT::i32)); 9032 } 9033 } 9034 } 9035 9036 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9037 return SDValue(); 9038 9039 // TODO: This could be a generic combine with a predicate for extracting the 9040 // high half of an integer being free. 9041 9042 // (or i64:x, (zero_extend i32:y)) -> 9043 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9044 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9045 RHS.getOpcode() != ISD::ZERO_EXTEND) 9046 std::swap(LHS, RHS); 9047 9048 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9049 SDValue ExtSrc = RHS.getOperand(0); 9050 EVT SrcVT = ExtSrc.getValueType(); 9051 if (SrcVT == MVT::i32) { 9052 SDLoc SL(N); 9053 SDValue LowLHS, HiBits; 9054 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9055 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9056 9057 DCI.AddToWorklist(LowOr.getNode()); 9058 DCI.AddToWorklist(HiBits.getNode()); 9059 9060 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9061 LowOr, HiBits); 9062 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9063 } 9064 } 9065 9066 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9067 if (CRHS) { 9068 if (SDValue Split 9069 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9070 return Split; 9071 } 9072 9073 return SDValue(); 9074 } 9075 9076 SDValue SITargetLowering::performXorCombine(SDNode *N, 9077 DAGCombinerInfo &DCI) const { 9078 EVT VT = N->getValueType(0); 9079 if (VT != MVT::i64) 9080 return SDValue(); 9081 9082 SDValue LHS = N->getOperand(0); 9083 SDValue RHS = N->getOperand(1); 9084 9085 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9086 if (CRHS) { 9087 if (SDValue Split 9088 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9089 return Split; 9090 } 9091 9092 return SDValue(); 9093 } 9094 9095 // Instructions that will be lowered with a final instruction that zeros the 9096 // high result bits. 9097 // XXX - probably only need to list legal operations. 9098 static bool fp16SrcZerosHighBits(unsigned Opc) { 9099 switch (Opc) { 9100 case ISD::FADD: 9101 case ISD::FSUB: 9102 case ISD::FMUL: 9103 case ISD::FDIV: 9104 case ISD::FREM: 9105 case ISD::FMA: 9106 case ISD::FMAD: 9107 case ISD::FCANONICALIZE: 9108 case ISD::FP_ROUND: 9109 case ISD::UINT_TO_FP: 9110 case ISD::SINT_TO_FP: 9111 case ISD::FABS: 9112 // Fabs is lowered to a bit operation, but it's an and which will clear the 9113 // high bits anyway. 9114 case ISD::FSQRT: 9115 case ISD::FSIN: 9116 case ISD::FCOS: 9117 case ISD::FPOWI: 9118 case ISD::FPOW: 9119 case ISD::FLOG: 9120 case ISD::FLOG2: 9121 case ISD::FLOG10: 9122 case ISD::FEXP: 9123 case ISD::FEXP2: 9124 case ISD::FCEIL: 9125 case ISD::FTRUNC: 9126 case ISD::FRINT: 9127 case ISD::FNEARBYINT: 9128 case ISD::FROUND: 9129 case ISD::FFLOOR: 9130 case ISD::FMINNUM: 9131 case ISD::FMAXNUM: 9132 case AMDGPUISD::FRACT: 9133 case AMDGPUISD::CLAMP: 9134 case AMDGPUISD::COS_HW: 9135 case AMDGPUISD::SIN_HW: 9136 case AMDGPUISD::FMIN3: 9137 case AMDGPUISD::FMAX3: 9138 case AMDGPUISD::FMED3: 9139 case AMDGPUISD::FMAD_FTZ: 9140 case AMDGPUISD::RCP: 9141 case AMDGPUISD::RSQ: 9142 case AMDGPUISD::RCP_IFLAG: 9143 case AMDGPUISD::LDEXP: 9144 return true; 9145 default: 9146 // fcopysign, select and others may be lowered to 32-bit bit operations 9147 // which don't zero the high bits. 9148 return false; 9149 } 9150 } 9151 9152 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9153 DAGCombinerInfo &DCI) const { 9154 if (!Subtarget->has16BitInsts() || 9155 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9156 return SDValue(); 9157 9158 EVT VT = N->getValueType(0); 9159 if (VT != MVT::i32) 9160 return SDValue(); 9161 9162 SDValue Src = N->getOperand(0); 9163 if (Src.getValueType() != MVT::i16) 9164 return SDValue(); 9165 9166 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9167 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9168 if (Src.getOpcode() == ISD::BITCAST) { 9169 SDValue BCSrc = Src.getOperand(0); 9170 if (BCSrc.getValueType() == MVT::f16 && 9171 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9172 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9173 } 9174 9175 return SDValue(); 9176 } 9177 9178 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9179 DAGCombinerInfo &DCI) 9180 const { 9181 SDValue Src = N->getOperand(0); 9182 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9183 9184 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9185 VTSign->getVT() == MVT::i8) || 9186 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9187 VTSign->getVT() == MVT::i16)) && 9188 Src.hasOneUse()) { 9189 auto *M = cast<MemSDNode>(Src); 9190 SDValue Ops[] = { 9191 Src.getOperand(0), // Chain 9192 Src.getOperand(1), // rsrc 9193 Src.getOperand(2), // vindex 9194 Src.getOperand(3), // voffset 9195 Src.getOperand(4), // soffset 9196 Src.getOperand(5), // offset 9197 Src.getOperand(6), 9198 Src.getOperand(7) 9199 }; 9200 // replace with BUFFER_LOAD_BYTE/SHORT 9201 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9202 Src.getOperand(0).getValueType()); 9203 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9204 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9205 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9206 ResList, 9207 Ops, M->getMemoryVT(), 9208 M->getMemOperand()); 9209 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9210 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9211 } 9212 return SDValue(); 9213 } 9214 9215 SDValue SITargetLowering::performClassCombine(SDNode *N, 9216 DAGCombinerInfo &DCI) const { 9217 SelectionDAG &DAG = DCI.DAG; 9218 SDValue Mask = N->getOperand(1); 9219 9220 // fp_class x, 0 -> false 9221 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9222 if (CMask->isNullValue()) 9223 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9224 } 9225 9226 if (N->getOperand(0).isUndef()) 9227 return DAG.getUNDEF(MVT::i1); 9228 9229 return SDValue(); 9230 } 9231 9232 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9233 DAGCombinerInfo &DCI) const { 9234 EVT VT = N->getValueType(0); 9235 SDValue N0 = N->getOperand(0); 9236 9237 if (N0.isUndef()) 9238 return N0; 9239 9240 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9241 N0.getOpcode() == ISD::SINT_TO_FP)) { 9242 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9243 N->getFlags()); 9244 } 9245 9246 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9247 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9248 N0.getOperand(0), N->getFlags()); 9249 } 9250 9251 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9252 } 9253 9254 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9255 unsigned MaxDepth) const { 9256 unsigned Opcode = Op.getOpcode(); 9257 if (Opcode == ISD::FCANONICALIZE) 9258 return true; 9259 9260 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9261 auto F = CFP->getValueAPF(); 9262 if (F.isNaN() && F.isSignaling()) 9263 return false; 9264 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9265 } 9266 9267 // If source is a result of another standard FP operation it is already in 9268 // canonical form. 9269 if (MaxDepth == 0) 9270 return false; 9271 9272 switch (Opcode) { 9273 // These will flush denorms if required. 9274 case ISD::FADD: 9275 case ISD::FSUB: 9276 case ISD::FMUL: 9277 case ISD::FCEIL: 9278 case ISD::FFLOOR: 9279 case ISD::FMA: 9280 case ISD::FMAD: 9281 case ISD::FSQRT: 9282 case ISD::FDIV: 9283 case ISD::FREM: 9284 case ISD::FP_ROUND: 9285 case ISD::FP_EXTEND: 9286 case AMDGPUISD::FMUL_LEGACY: 9287 case AMDGPUISD::FMAD_FTZ: 9288 case AMDGPUISD::RCP: 9289 case AMDGPUISD::RSQ: 9290 case AMDGPUISD::RSQ_CLAMP: 9291 case AMDGPUISD::RCP_LEGACY: 9292 case AMDGPUISD::RCP_IFLAG: 9293 case AMDGPUISD::DIV_SCALE: 9294 case AMDGPUISD::DIV_FMAS: 9295 case AMDGPUISD::DIV_FIXUP: 9296 case AMDGPUISD::FRACT: 9297 case AMDGPUISD::LDEXP: 9298 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9299 case AMDGPUISD::CVT_F32_UBYTE0: 9300 case AMDGPUISD::CVT_F32_UBYTE1: 9301 case AMDGPUISD::CVT_F32_UBYTE2: 9302 case AMDGPUISD::CVT_F32_UBYTE3: 9303 return true; 9304 9305 // It can/will be lowered or combined as a bit operation. 9306 // Need to check their input recursively to handle. 9307 case ISD::FNEG: 9308 case ISD::FABS: 9309 case ISD::FCOPYSIGN: 9310 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9311 9312 case ISD::FSIN: 9313 case ISD::FCOS: 9314 case ISD::FSINCOS: 9315 return Op.getValueType().getScalarType() != MVT::f16; 9316 9317 case ISD::FMINNUM: 9318 case ISD::FMAXNUM: 9319 case ISD::FMINNUM_IEEE: 9320 case ISD::FMAXNUM_IEEE: 9321 case AMDGPUISD::CLAMP: 9322 case AMDGPUISD::FMED3: 9323 case AMDGPUISD::FMAX3: 9324 case AMDGPUISD::FMIN3: { 9325 // FIXME: Shouldn't treat the generic operations different based these. 9326 // However, we aren't really required to flush the result from 9327 // minnum/maxnum.. 9328 9329 // snans will be quieted, so we only need to worry about denormals. 9330 if (Subtarget->supportsMinMaxDenormModes() || 9331 denormalsEnabledForType(DAG, Op.getValueType())) 9332 return true; 9333 9334 // Flushing may be required. 9335 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9336 // targets need to check their input recursively. 9337 9338 // FIXME: Does this apply with clamp? It's implemented with max. 9339 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9340 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9341 return false; 9342 } 9343 9344 return true; 9345 } 9346 case ISD::SELECT: { 9347 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9348 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9349 } 9350 case ISD::BUILD_VECTOR: { 9351 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9352 SDValue SrcOp = Op.getOperand(i); 9353 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9354 return false; 9355 } 9356 9357 return true; 9358 } 9359 case ISD::EXTRACT_VECTOR_ELT: 9360 case ISD::EXTRACT_SUBVECTOR: { 9361 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9362 } 9363 case ISD::INSERT_VECTOR_ELT: { 9364 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9365 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9366 } 9367 case ISD::UNDEF: 9368 // Could be anything. 9369 return false; 9370 9371 case ISD::BITCAST: { 9372 // Hack round the mess we make when legalizing extract_vector_elt 9373 SDValue Src = Op.getOperand(0); 9374 if (Src.getValueType() == MVT::i16 && 9375 Src.getOpcode() == ISD::TRUNCATE) { 9376 SDValue TruncSrc = Src.getOperand(0); 9377 if (TruncSrc.getValueType() == MVT::i32 && 9378 TruncSrc.getOpcode() == ISD::BITCAST && 9379 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9380 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9381 } 9382 } 9383 9384 return false; 9385 } 9386 case ISD::INTRINSIC_WO_CHAIN: { 9387 unsigned IntrinsicID 9388 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9389 // TODO: Handle more intrinsics 9390 switch (IntrinsicID) { 9391 case Intrinsic::amdgcn_cvt_pkrtz: 9392 case Intrinsic::amdgcn_cubeid: 9393 case Intrinsic::amdgcn_frexp_mant: 9394 case Intrinsic::amdgcn_fdot2: 9395 case Intrinsic::amdgcn_rcp: 9396 case Intrinsic::amdgcn_rsq: 9397 case Intrinsic::amdgcn_rsq_clamp: 9398 case Intrinsic::amdgcn_rcp_legacy: 9399 case Intrinsic::amdgcn_rsq_legacy: 9400 case Intrinsic::amdgcn_trig_preop: 9401 return true; 9402 default: 9403 break; 9404 } 9405 9406 LLVM_FALLTHROUGH; 9407 } 9408 default: 9409 return denormalsEnabledForType(DAG, Op.getValueType()) && 9410 DAG.isKnownNeverSNaN(Op); 9411 } 9412 9413 llvm_unreachable("invalid operation"); 9414 } 9415 9416 // Constant fold canonicalize. 9417 SDValue SITargetLowering::getCanonicalConstantFP( 9418 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9419 // Flush denormals to 0 if not enabled. 9420 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9421 return DAG.getConstantFP(0.0, SL, VT); 9422 9423 if (C.isNaN()) { 9424 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9425 if (C.isSignaling()) { 9426 // Quiet a signaling NaN. 9427 // FIXME: Is this supposed to preserve payload bits? 9428 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9429 } 9430 9431 // Make sure it is the canonical NaN bitpattern. 9432 // 9433 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9434 // immediate? 9435 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9436 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9437 } 9438 9439 // Already canonical. 9440 return DAG.getConstantFP(C, SL, VT); 9441 } 9442 9443 static bool vectorEltWillFoldAway(SDValue Op) { 9444 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9445 } 9446 9447 SDValue SITargetLowering::performFCanonicalizeCombine( 9448 SDNode *N, 9449 DAGCombinerInfo &DCI) const { 9450 SelectionDAG &DAG = DCI.DAG; 9451 SDValue N0 = N->getOperand(0); 9452 EVT VT = N->getValueType(0); 9453 9454 // fcanonicalize undef -> qnan 9455 if (N0.isUndef()) { 9456 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9457 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9458 } 9459 9460 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9461 EVT VT = N->getValueType(0); 9462 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9463 } 9464 9465 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9466 // (fcanonicalize k) 9467 // 9468 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9469 9470 // TODO: This could be better with wider vectors that will be split to v2f16, 9471 // and to consider uses since there aren't that many packed operations. 9472 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9473 isTypeLegal(MVT::v2f16)) { 9474 SDLoc SL(N); 9475 SDValue NewElts[2]; 9476 SDValue Lo = N0.getOperand(0); 9477 SDValue Hi = N0.getOperand(1); 9478 EVT EltVT = Lo.getValueType(); 9479 9480 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9481 for (unsigned I = 0; I != 2; ++I) { 9482 SDValue Op = N0.getOperand(I); 9483 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9484 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9485 CFP->getValueAPF()); 9486 } else if (Op.isUndef()) { 9487 // Handled below based on what the other operand is. 9488 NewElts[I] = Op; 9489 } else { 9490 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9491 } 9492 } 9493 9494 // If one half is undef, and one is constant, perfer a splat vector rather 9495 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9496 // cheaper to use and may be free with a packed operation. 9497 if (NewElts[0].isUndef()) { 9498 if (isa<ConstantFPSDNode>(NewElts[1])) 9499 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9500 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9501 } 9502 9503 if (NewElts[1].isUndef()) { 9504 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9505 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9506 } 9507 9508 return DAG.getBuildVector(VT, SL, NewElts); 9509 } 9510 } 9511 9512 unsigned SrcOpc = N0.getOpcode(); 9513 9514 // If it's free to do so, push canonicalizes further up the source, which may 9515 // find a canonical source. 9516 // 9517 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9518 // sNaNs. 9519 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9520 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9521 if (CRHS && N0.hasOneUse()) { 9522 SDLoc SL(N); 9523 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9524 N0.getOperand(0)); 9525 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9526 DCI.AddToWorklist(Canon0.getNode()); 9527 9528 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9529 } 9530 } 9531 9532 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9533 } 9534 9535 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9536 switch (Opc) { 9537 case ISD::FMAXNUM: 9538 case ISD::FMAXNUM_IEEE: 9539 return AMDGPUISD::FMAX3; 9540 case ISD::SMAX: 9541 return AMDGPUISD::SMAX3; 9542 case ISD::UMAX: 9543 return AMDGPUISD::UMAX3; 9544 case ISD::FMINNUM: 9545 case ISD::FMINNUM_IEEE: 9546 return AMDGPUISD::FMIN3; 9547 case ISD::SMIN: 9548 return AMDGPUISD::SMIN3; 9549 case ISD::UMIN: 9550 return AMDGPUISD::UMIN3; 9551 default: 9552 llvm_unreachable("Not a min/max opcode"); 9553 } 9554 } 9555 9556 SDValue SITargetLowering::performIntMed3ImmCombine( 9557 SelectionDAG &DAG, const SDLoc &SL, 9558 SDValue Op0, SDValue Op1, bool Signed) const { 9559 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9560 if (!K1) 9561 return SDValue(); 9562 9563 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9564 if (!K0) 9565 return SDValue(); 9566 9567 if (Signed) { 9568 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9569 return SDValue(); 9570 } else { 9571 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9572 return SDValue(); 9573 } 9574 9575 EVT VT = K0->getValueType(0); 9576 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9577 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9578 return DAG.getNode(Med3Opc, SL, VT, 9579 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9580 } 9581 9582 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9583 MVT NVT = MVT::i32; 9584 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9585 9586 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9587 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9588 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9589 9590 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9591 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9592 } 9593 9594 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9595 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9596 return C; 9597 9598 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9599 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9600 return C; 9601 } 9602 9603 return nullptr; 9604 } 9605 9606 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9607 const SDLoc &SL, 9608 SDValue Op0, 9609 SDValue Op1) const { 9610 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9611 if (!K1) 9612 return SDValue(); 9613 9614 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9615 if (!K0) 9616 return SDValue(); 9617 9618 // Ordered >= (although NaN inputs should have folded away by now). 9619 if (K0->getValueAPF() > K1->getValueAPF()) 9620 return SDValue(); 9621 9622 const MachineFunction &MF = DAG.getMachineFunction(); 9623 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9624 9625 // TODO: Check IEEE bit enabled? 9626 EVT VT = Op0.getValueType(); 9627 if (Info->getMode().DX10Clamp) { 9628 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9629 // hardware fmed3 behavior converting to a min. 9630 // FIXME: Should this be allowing -0.0? 9631 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9632 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9633 } 9634 9635 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9636 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9637 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9638 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9639 // then give the other result, which is different from med3 with a NaN 9640 // input. 9641 SDValue Var = Op0.getOperand(0); 9642 if (!DAG.isKnownNeverSNaN(Var)) 9643 return SDValue(); 9644 9645 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9646 9647 if ((!K0->hasOneUse() || 9648 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9649 (!K1->hasOneUse() || 9650 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9651 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9652 Var, SDValue(K0, 0), SDValue(K1, 0)); 9653 } 9654 } 9655 9656 return SDValue(); 9657 } 9658 9659 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9660 DAGCombinerInfo &DCI) const { 9661 SelectionDAG &DAG = DCI.DAG; 9662 9663 EVT VT = N->getValueType(0); 9664 unsigned Opc = N->getOpcode(); 9665 SDValue Op0 = N->getOperand(0); 9666 SDValue Op1 = N->getOperand(1); 9667 9668 // Only do this if the inner op has one use since this will just increases 9669 // register pressure for no benefit. 9670 9671 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9672 !VT.isVector() && 9673 (VT == MVT::i32 || VT == MVT::f32 || 9674 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9675 // max(max(a, b), c) -> max3(a, b, c) 9676 // min(min(a, b), c) -> min3(a, b, c) 9677 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9678 SDLoc DL(N); 9679 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9680 DL, 9681 N->getValueType(0), 9682 Op0.getOperand(0), 9683 Op0.getOperand(1), 9684 Op1); 9685 } 9686 9687 // Try commuted. 9688 // max(a, max(b, c)) -> max3(a, b, c) 9689 // min(a, min(b, c)) -> min3(a, b, c) 9690 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9691 SDLoc DL(N); 9692 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9693 DL, 9694 N->getValueType(0), 9695 Op0, 9696 Op1.getOperand(0), 9697 Op1.getOperand(1)); 9698 } 9699 } 9700 9701 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9702 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9703 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9704 return Med3; 9705 } 9706 9707 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9708 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9709 return Med3; 9710 } 9711 9712 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9713 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9714 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9715 (Opc == AMDGPUISD::FMIN_LEGACY && 9716 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9717 (VT == MVT::f32 || VT == MVT::f64 || 9718 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9719 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9720 Op0.hasOneUse()) { 9721 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9722 return Res; 9723 } 9724 9725 return SDValue(); 9726 } 9727 9728 static bool isClampZeroToOne(SDValue A, SDValue B) { 9729 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9730 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9731 // FIXME: Should this be allowing -0.0? 9732 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9733 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9734 } 9735 } 9736 9737 return false; 9738 } 9739 9740 // FIXME: Should only worry about snans for version with chain. 9741 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9742 DAGCombinerInfo &DCI) const { 9743 EVT VT = N->getValueType(0); 9744 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9745 // NaNs. With a NaN input, the order of the operands may change the result. 9746 9747 SelectionDAG &DAG = DCI.DAG; 9748 SDLoc SL(N); 9749 9750 SDValue Src0 = N->getOperand(0); 9751 SDValue Src1 = N->getOperand(1); 9752 SDValue Src2 = N->getOperand(2); 9753 9754 if (isClampZeroToOne(Src0, Src1)) { 9755 // const_a, const_b, x -> clamp is safe in all cases including signaling 9756 // nans. 9757 // FIXME: Should this be allowing -0.0? 9758 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9759 } 9760 9761 const MachineFunction &MF = DAG.getMachineFunction(); 9762 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9763 9764 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9765 // handling no dx10-clamp? 9766 if (Info->getMode().DX10Clamp) { 9767 // If NaNs is clamped to 0, we are free to reorder the inputs. 9768 9769 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9770 std::swap(Src0, Src1); 9771 9772 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9773 std::swap(Src1, Src2); 9774 9775 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9776 std::swap(Src0, Src1); 9777 9778 if (isClampZeroToOne(Src1, Src2)) 9779 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9780 } 9781 9782 return SDValue(); 9783 } 9784 9785 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9786 DAGCombinerInfo &DCI) const { 9787 SDValue Src0 = N->getOperand(0); 9788 SDValue Src1 = N->getOperand(1); 9789 if (Src0.isUndef() && Src1.isUndef()) 9790 return DCI.DAG.getUNDEF(N->getValueType(0)); 9791 return SDValue(); 9792 } 9793 9794 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9795 // expanded into a set of cmp/select instructions. 9796 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9797 unsigned NumElem, 9798 bool IsDivergentIdx) { 9799 if (UseDivergentRegisterIndexing) 9800 return false; 9801 9802 unsigned VecSize = EltSize * NumElem; 9803 9804 // Sub-dword vectors of size 2 dword or less have better implementation. 9805 if (VecSize <= 64 && EltSize < 32) 9806 return false; 9807 9808 // Always expand the rest of sub-dword instructions, otherwise it will be 9809 // lowered via memory. 9810 if (EltSize < 32) 9811 return true; 9812 9813 // Always do this if var-idx is divergent, otherwise it will become a loop. 9814 if (IsDivergentIdx) 9815 return true; 9816 9817 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9818 unsigned NumInsts = NumElem /* Number of compares */ + 9819 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9820 return NumInsts <= 16; 9821 } 9822 9823 static bool shouldExpandVectorDynExt(SDNode *N) { 9824 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9825 if (isa<ConstantSDNode>(Idx)) 9826 return false; 9827 9828 SDValue Vec = N->getOperand(0); 9829 EVT VecVT = Vec.getValueType(); 9830 EVT EltVT = VecVT.getVectorElementType(); 9831 unsigned EltSize = EltVT.getSizeInBits(); 9832 unsigned NumElem = VecVT.getVectorNumElements(); 9833 9834 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9835 Idx->isDivergent()); 9836 } 9837 9838 SDValue SITargetLowering::performExtractVectorEltCombine( 9839 SDNode *N, DAGCombinerInfo &DCI) const { 9840 SDValue Vec = N->getOperand(0); 9841 SelectionDAG &DAG = DCI.DAG; 9842 9843 EVT VecVT = Vec.getValueType(); 9844 EVT EltVT = VecVT.getVectorElementType(); 9845 9846 if ((Vec.getOpcode() == ISD::FNEG || 9847 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9848 SDLoc SL(N); 9849 EVT EltVT = N->getValueType(0); 9850 SDValue Idx = N->getOperand(1); 9851 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9852 Vec.getOperand(0), Idx); 9853 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9854 } 9855 9856 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9857 // => 9858 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9859 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9860 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9861 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9862 SDLoc SL(N); 9863 EVT EltVT = N->getValueType(0); 9864 SDValue Idx = N->getOperand(1); 9865 unsigned Opc = Vec.getOpcode(); 9866 9867 switch(Opc) { 9868 default: 9869 break; 9870 // TODO: Support other binary operations. 9871 case ISD::FADD: 9872 case ISD::FSUB: 9873 case ISD::FMUL: 9874 case ISD::ADD: 9875 case ISD::UMIN: 9876 case ISD::UMAX: 9877 case ISD::SMIN: 9878 case ISD::SMAX: 9879 case ISD::FMAXNUM: 9880 case ISD::FMINNUM: 9881 case ISD::FMAXNUM_IEEE: 9882 case ISD::FMINNUM_IEEE: { 9883 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9884 Vec.getOperand(0), Idx); 9885 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9886 Vec.getOperand(1), Idx); 9887 9888 DCI.AddToWorklist(Elt0.getNode()); 9889 DCI.AddToWorklist(Elt1.getNode()); 9890 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9891 } 9892 } 9893 } 9894 9895 unsigned VecSize = VecVT.getSizeInBits(); 9896 unsigned EltSize = EltVT.getSizeInBits(); 9897 9898 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9899 if (::shouldExpandVectorDynExt(N)) { 9900 SDLoc SL(N); 9901 SDValue Idx = N->getOperand(1); 9902 SDValue V; 9903 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9904 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9905 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9906 if (I == 0) 9907 V = Elt; 9908 else 9909 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9910 } 9911 return V; 9912 } 9913 9914 if (!DCI.isBeforeLegalize()) 9915 return SDValue(); 9916 9917 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9918 // elements. This exposes more load reduction opportunities by replacing 9919 // multiple small extract_vector_elements with a single 32-bit extract. 9920 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9921 if (isa<MemSDNode>(Vec) && 9922 EltSize <= 16 && 9923 EltVT.isByteSized() && 9924 VecSize > 32 && 9925 VecSize % 32 == 0 && 9926 Idx) { 9927 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9928 9929 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9930 unsigned EltIdx = BitIndex / 32; 9931 unsigned LeftoverBitIdx = BitIndex % 32; 9932 SDLoc SL(N); 9933 9934 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9935 DCI.AddToWorklist(Cast.getNode()); 9936 9937 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9938 DAG.getConstant(EltIdx, SL, MVT::i32)); 9939 DCI.AddToWorklist(Elt.getNode()); 9940 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9941 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9942 DCI.AddToWorklist(Srl.getNode()); 9943 9944 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9945 DCI.AddToWorklist(Trunc.getNode()); 9946 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9947 } 9948 9949 return SDValue(); 9950 } 9951 9952 SDValue 9953 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9954 DAGCombinerInfo &DCI) const { 9955 SDValue Vec = N->getOperand(0); 9956 SDValue Idx = N->getOperand(2); 9957 EVT VecVT = Vec.getValueType(); 9958 EVT EltVT = VecVT.getVectorElementType(); 9959 9960 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9961 // => BUILD_VECTOR n x select (e, const-idx) 9962 if (!::shouldExpandVectorDynExt(N)) 9963 return SDValue(); 9964 9965 SelectionDAG &DAG = DCI.DAG; 9966 SDLoc SL(N); 9967 SDValue Ins = N->getOperand(1); 9968 EVT IdxVT = Idx.getValueType(); 9969 9970 SmallVector<SDValue, 16> Ops; 9971 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9972 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9973 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9974 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9975 Ops.push_back(V); 9976 } 9977 9978 return DAG.getBuildVector(VecVT, SL, Ops); 9979 } 9980 9981 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9982 const SDNode *N0, 9983 const SDNode *N1) const { 9984 EVT VT = N0->getValueType(0); 9985 9986 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9987 // support denormals ever. 9988 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9989 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9990 getSubtarget()->hasMadF16())) && 9991 isOperationLegal(ISD::FMAD, VT)) 9992 return ISD::FMAD; 9993 9994 const TargetOptions &Options = DAG.getTarget().Options; 9995 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9996 (N0->getFlags().hasAllowContract() && 9997 N1->getFlags().hasAllowContract())) && 9998 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9999 return ISD::FMA; 10000 } 10001 10002 return 0; 10003 } 10004 10005 // For a reassociatable opcode perform: 10006 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10007 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10008 SelectionDAG &DAG) const { 10009 EVT VT = N->getValueType(0); 10010 if (VT != MVT::i32 && VT != MVT::i64) 10011 return SDValue(); 10012 10013 unsigned Opc = N->getOpcode(); 10014 SDValue Op0 = N->getOperand(0); 10015 SDValue Op1 = N->getOperand(1); 10016 10017 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10018 return SDValue(); 10019 10020 if (Op0->isDivergent()) 10021 std::swap(Op0, Op1); 10022 10023 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10024 return SDValue(); 10025 10026 SDValue Op2 = Op1.getOperand(1); 10027 Op1 = Op1.getOperand(0); 10028 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10029 return SDValue(); 10030 10031 if (Op1->isDivergent()) 10032 std::swap(Op1, Op2); 10033 10034 // If either operand is constant this will conflict with 10035 // DAGCombiner::ReassociateOps(). 10036 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10037 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10038 return SDValue(); 10039 10040 SDLoc SL(N); 10041 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10042 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10043 } 10044 10045 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10046 EVT VT, 10047 SDValue N0, SDValue N1, SDValue N2, 10048 bool Signed) { 10049 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10050 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10051 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10052 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10053 } 10054 10055 SDValue SITargetLowering::performAddCombine(SDNode *N, 10056 DAGCombinerInfo &DCI) const { 10057 SelectionDAG &DAG = DCI.DAG; 10058 EVT VT = N->getValueType(0); 10059 SDLoc SL(N); 10060 SDValue LHS = N->getOperand(0); 10061 SDValue RHS = N->getOperand(1); 10062 10063 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10064 && Subtarget->hasMad64_32() && 10065 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10066 VT.getScalarSizeInBits() <= 64) { 10067 if (LHS.getOpcode() != ISD::MUL) 10068 std::swap(LHS, RHS); 10069 10070 SDValue MulLHS = LHS.getOperand(0); 10071 SDValue MulRHS = LHS.getOperand(1); 10072 SDValue AddRHS = RHS; 10073 10074 // TODO: Maybe restrict if SGPR inputs. 10075 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10076 numBitsUnsigned(MulRHS, DAG) <= 32) { 10077 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10078 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10079 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10080 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10081 } 10082 10083 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10084 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10085 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10086 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10087 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10088 } 10089 10090 return SDValue(); 10091 } 10092 10093 if (SDValue V = reassociateScalarOps(N, DAG)) { 10094 return V; 10095 } 10096 10097 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10098 return SDValue(); 10099 10100 // add x, zext (setcc) => addcarry x, 0, setcc 10101 // add x, sext (setcc) => subcarry x, 0, setcc 10102 unsigned Opc = LHS.getOpcode(); 10103 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10104 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10105 std::swap(RHS, LHS); 10106 10107 Opc = RHS.getOpcode(); 10108 switch (Opc) { 10109 default: break; 10110 case ISD::ZERO_EXTEND: 10111 case ISD::SIGN_EXTEND: 10112 case ISD::ANY_EXTEND: { 10113 auto Cond = RHS.getOperand(0); 10114 // If this won't be a real VOPC output, we would still need to insert an 10115 // extra instruction anyway. 10116 if (!isBoolSGPR(Cond)) 10117 break; 10118 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10119 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10120 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10121 return DAG.getNode(Opc, SL, VTList, Args); 10122 } 10123 case ISD::ADDCARRY: { 10124 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10125 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10126 if (!C || C->getZExtValue() != 0) break; 10127 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10128 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10129 } 10130 } 10131 return SDValue(); 10132 } 10133 10134 SDValue SITargetLowering::performSubCombine(SDNode *N, 10135 DAGCombinerInfo &DCI) const { 10136 SelectionDAG &DAG = DCI.DAG; 10137 EVT VT = N->getValueType(0); 10138 10139 if (VT != MVT::i32) 10140 return SDValue(); 10141 10142 SDLoc SL(N); 10143 SDValue LHS = N->getOperand(0); 10144 SDValue RHS = N->getOperand(1); 10145 10146 // sub x, zext (setcc) => subcarry x, 0, setcc 10147 // sub x, sext (setcc) => addcarry x, 0, setcc 10148 unsigned Opc = RHS.getOpcode(); 10149 switch (Opc) { 10150 default: break; 10151 case ISD::ZERO_EXTEND: 10152 case ISD::SIGN_EXTEND: 10153 case ISD::ANY_EXTEND: { 10154 auto Cond = RHS.getOperand(0); 10155 // If this won't be a real VOPC output, we would still need to insert an 10156 // extra instruction anyway. 10157 if (!isBoolSGPR(Cond)) 10158 break; 10159 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10160 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10161 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10162 return DAG.getNode(Opc, SL, VTList, Args); 10163 } 10164 } 10165 10166 if (LHS.getOpcode() == ISD::SUBCARRY) { 10167 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10168 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10169 if (!C || !C->isNullValue()) 10170 return SDValue(); 10171 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10172 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10173 } 10174 return SDValue(); 10175 } 10176 10177 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10178 DAGCombinerInfo &DCI) const { 10179 10180 if (N->getValueType(0) != MVT::i32) 10181 return SDValue(); 10182 10183 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10184 if (!C || C->getZExtValue() != 0) 10185 return SDValue(); 10186 10187 SelectionDAG &DAG = DCI.DAG; 10188 SDValue LHS = N->getOperand(0); 10189 10190 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10191 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10192 unsigned LHSOpc = LHS.getOpcode(); 10193 unsigned Opc = N->getOpcode(); 10194 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10195 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10196 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10197 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10198 } 10199 return SDValue(); 10200 } 10201 10202 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10203 DAGCombinerInfo &DCI) const { 10204 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10205 return SDValue(); 10206 10207 SelectionDAG &DAG = DCI.DAG; 10208 EVT VT = N->getValueType(0); 10209 10210 SDLoc SL(N); 10211 SDValue LHS = N->getOperand(0); 10212 SDValue RHS = N->getOperand(1); 10213 10214 // These should really be instruction patterns, but writing patterns with 10215 // source modiifiers is a pain. 10216 10217 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10218 if (LHS.getOpcode() == ISD::FADD) { 10219 SDValue A = LHS.getOperand(0); 10220 if (A == LHS.getOperand(1)) { 10221 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10222 if (FusedOp != 0) { 10223 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10224 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10225 } 10226 } 10227 } 10228 10229 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10230 if (RHS.getOpcode() == ISD::FADD) { 10231 SDValue A = RHS.getOperand(0); 10232 if (A == RHS.getOperand(1)) { 10233 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10234 if (FusedOp != 0) { 10235 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10236 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10237 } 10238 } 10239 } 10240 10241 return SDValue(); 10242 } 10243 10244 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10245 DAGCombinerInfo &DCI) const { 10246 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10247 return SDValue(); 10248 10249 SelectionDAG &DAG = DCI.DAG; 10250 SDLoc SL(N); 10251 EVT VT = N->getValueType(0); 10252 assert(!VT.isVector()); 10253 10254 // Try to get the fneg to fold into the source modifier. This undoes generic 10255 // DAG combines and folds them into the mad. 10256 // 10257 // Only do this if we are not trying to support denormals. v_mad_f32 does 10258 // not support denormals ever. 10259 SDValue LHS = N->getOperand(0); 10260 SDValue RHS = N->getOperand(1); 10261 if (LHS.getOpcode() == ISD::FADD) { 10262 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10263 SDValue A = LHS.getOperand(0); 10264 if (A == LHS.getOperand(1)) { 10265 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10266 if (FusedOp != 0){ 10267 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10268 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10269 10270 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10271 } 10272 } 10273 } 10274 10275 if (RHS.getOpcode() == ISD::FADD) { 10276 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10277 10278 SDValue A = RHS.getOperand(0); 10279 if (A == RHS.getOperand(1)) { 10280 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10281 if (FusedOp != 0){ 10282 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10283 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10284 } 10285 } 10286 } 10287 10288 return SDValue(); 10289 } 10290 10291 SDValue SITargetLowering::performFMACombine(SDNode *N, 10292 DAGCombinerInfo &DCI) const { 10293 SelectionDAG &DAG = DCI.DAG; 10294 EVT VT = N->getValueType(0); 10295 SDLoc SL(N); 10296 10297 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10298 return SDValue(); 10299 10300 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10301 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10302 SDValue Op1 = N->getOperand(0); 10303 SDValue Op2 = N->getOperand(1); 10304 SDValue FMA = N->getOperand(2); 10305 10306 if (FMA.getOpcode() != ISD::FMA || 10307 Op1.getOpcode() != ISD::FP_EXTEND || 10308 Op2.getOpcode() != ISD::FP_EXTEND) 10309 return SDValue(); 10310 10311 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10312 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10313 // is sufficient to allow generaing fdot2. 10314 const TargetOptions &Options = DAG.getTarget().Options; 10315 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10316 (N->getFlags().hasAllowContract() && 10317 FMA->getFlags().hasAllowContract())) { 10318 Op1 = Op1.getOperand(0); 10319 Op2 = Op2.getOperand(0); 10320 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10321 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10322 return SDValue(); 10323 10324 SDValue Vec1 = Op1.getOperand(0); 10325 SDValue Idx1 = Op1.getOperand(1); 10326 SDValue Vec2 = Op2.getOperand(0); 10327 10328 SDValue FMAOp1 = FMA.getOperand(0); 10329 SDValue FMAOp2 = FMA.getOperand(1); 10330 SDValue FMAAcc = FMA.getOperand(2); 10331 10332 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10333 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10334 return SDValue(); 10335 10336 FMAOp1 = FMAOp1.getOperand(0); 10337 FMAOp2 = FMAOp2.getOperand(0); 10338 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10339 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10340 return SDValue(); 10341 10342 SDValue Vec3 = FMAOp1.getOperand(0); 10343 SDValue Vec4 = FMAOp2.getOperand(0); 10344 SDValue Idx2 = FMAOp1.getOperand(1); 10345 10346 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10347 // Idx1 and Idx2 cannot be the same. 10348 Idx1 == Idx2) 10349 return SDValue(); 10350 10351 if (Vec1 == Vec2 || Vec3 == Vec4) 10352 return SDValue(); 10353 10354 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10355 return SDValue(); 10356 10357 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10358 (Vec1 == Vec4 && Vec2 == Vec3)) { 10359 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10360 DAG.getTargetConstant(0, SL, MVT::i1)); 10361 } 10362 } 10363 return SDValue(); 10364 } 10365 10366 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10367 DAGCombinerInfo &DCI) const { 10368 SelectionDAG &DAG = DCI.DAG; 10369 SDLoc SL(N); 10370 10371 SDValue LHS = N->getOperand(0); 10372 SDValue RHS = N->getOperand(1); 10373 EVT VT = LHS.getValueType(); 10374 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10375 10376 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10377 if (!CRHS) { 10378 CRHS = dyn_cast<ConstantSDNode>(LHS); 10379 if (CRHS) { 10380 std::swap(LHS, RHS); 10381 CC = getSetCCSwappedOperands(CC); 10382 } 10383 } 10384 10385 if (CRHS) { 10386 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10387 isBoolSGPR(LHS.getOperand(0))) { 10388 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10389 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10390 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10391 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10392 if ((CRHS->isAllOnesValue() && 10393 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10394 (CRHS->isNullValue() && 10395 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10396 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10397 DAG.getConstant(-1, SL, MVT::i1)); 10398 if ((CRHS->isAllOnesValue() && 10399 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10400 (CRHS->isNullValue() && 10401 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10402 return LHS.getOperand(0); 10403 } 10404 10405 uint64_t CRHSVal = CRHS->getZExtValue(); 10406 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10407 LHS.getOpcode() == ISD::SELECT && 10408 isa<ConstantSDNode>(LHS.getOperand(1)) && 10409 isa<ConstantSDNode>(LHS.getOperand(2)) && 10410 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10411 isBoolSGPR(LHS.getOperand(0))) { 10412 // Given CT != FT: 10413 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10414 // setcc (select cc, CT, CF), CF, ne => cc 10415 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10416 // setcc (select cc, CT, CF), CT, eq => cc 10417 uint64_t CT = LHS.getConstantOperandVal(1); 10418 uint64_t CF = LHS.getConstantOperandVal(2); 10419 10420 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10421 (CT == CRHSVal && CC == ISD::SETNE)) 10422 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10423 DAG.getConstant(-1, SL, MVT::i1)); 10424 if ((CF == CRHSVal && CC == ISD::SETNE) || 10425 (CT == CRHSVal && CC == ISD::SETEQ)) 10426 return LHS.getOperand(0); 10427 } 10428 } 10429 10430 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10431 VT != MVT::f16)) 10432 return SDValue(); 10433 10434 // Match isinf/isfinite pattern 10435 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10436 // (fcmp one (fabs x), inf) -> (fp_class x, 10437 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10438 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10439 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10440 if (!CRHS) 10441 return SDValue(); 10442 10443 const APFloat &APF = CRHS->getValueAPF(); 10444 if (APF.isInfinity() && !APF.isNegative()) { 10445 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10446 SIInstrFlags::N_INFINITY; 10447 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10448 SIInstrFlags::P_ZERO | 10449 SIInstrFlags::N_NORMAL | 10450 SIInstrFlags::P_NORMAL | 10451 SIInstrFlags::N_SUBNORMAL | 10452 SIInstrFlags::P_SUBNORMAL; 10453 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10454 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10455 DAG.getConstant(Mask, SL, MVT::i32)); 10456 } 10457 } 10458 10459 return SDValue(); 10460 } 10461 10462 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10463 DAGCombinerInfo &DCI) const { 10464 SelectionDAG &DAG = DCI.DAG; 10465 SDLoc SL(N); 10466 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10467 10468 SDValue Src = N->getOperand(0); 10469 SDValue Shift = N->getOperand(0); 10470 10471 // TODO: Extend type shouldn't matter (assuming legal types). 10472 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10473 Shift = Shift.getOperand(0); 10474 10475 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10476 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10477 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10478 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10479 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10480 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10481 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10482 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10483 SDLoc(Shift.getOperand(0)), MVT::i32); 10484 10485 unsigned ShiftOffset = 8 * Offset; 10486 if (Shift.getOpcode() == ISD::SHL) 10487 ShiftOffset -= C->getZExtValue(); 10488 else 10489 ShiftOffset += C->getZExtValue(); 10490 10491 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10492 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10493 MVT::f32, Shift); 10494 } 10495 } 10496 } 10497 10498 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10499 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10500 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10501 // We simplified Src. If this node is not dead, visit it again so it is 10502 // folded properly. 10503 if (N->getOpcode() != ISD::DELETED_NODE) 10504 DCI.AddToWorklist(N); 10505 return SDValue(N, 0); 10506 } 10507 10508 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10509 if (SDValue DemandedSrc = 10510 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10511 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10512 10513 return SDValue(); 10514 } 10515 10516 SDValue SITargetLowering::performClampCombine(SDNode *N, 10517 DAGCombinerInfo &DCI) const { 10518 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10519 if (!CSrc) 10520 return SDValue(); 10521 10522 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10523 const APFloat &F = CSrc->getValueAPF(); 10524 APFloat Zero = APFloat::getZero(F.getSemantics()); 10525 if (F < Zero || 10526 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10527 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10528 } 10529 10530 APFloat One(F.getSemantics(), "1.0"); 10531 if (F > One) 10532 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10533 10534 return SDValue(CSrc, 0); 10535 } 10536 10537 10538 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10539 DAGCombinerInfo &DCI) const { 10540 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10541 return SDValue(); 10542 switch (N->getOpcode()) { 10543 default: 10544 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10545 case ISD::ADD: 10546 return performAddCombine(N, DCI); 10547 case ISD::SUB: 10548 return performSubCombine(N, DCI); 10549 case ISD::ADDCARRY: 10550 case ISD::SUBCARRY: 10551 return performAddCarrySubCarryCombine(N, DCI); 10552 case ISD::FADD: 10553 return performFAddCombine(N, DCI); 10554 case ISD::FSUB: 10555 return performFSubCombine(N, DCI); 10556 case ISD::SETCC: 10557 return performSetCCCombine(N, DCI); 10558 case ISD::FMAXNUM: 10559 case ISD::FMINNUM: 10560 case ISD::FMAXNUM_IEEE: 10561 case ISD::FMINNUM_IEEE: 10562 case ISD::SMAX: 10563 case ISD::SMIN: 10564 case ISD::UMAX: 10565 case ISD::UMIN: 10566 case AMDGPUISD::FMIN_LEGACY: 10567 case AMDGPUISD::FMAX_LEGACY: 10568 return performMinMaxCombine(N, DCI); 10569 case ISD::FMA: 10570 return performFMACombine(N, DCI); 10571 case ISD::LOAD: { 10572 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10573 return Widended; 10574 LLVM_FALLTHROUGH; 10575 } 10576 case ISD::STORE: 10577 case ISD::ATOMIC_LOAD: 10578 case ISD::ATOMIC_STORE: 10579 case ISD::ATOMIC_CMP_SWAP: 10580 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10581 case ISD::ATOMIC_SWAP: 10582 case ISD::ATOMIC_LOAD_ADD: 10583 case ISD::ATOMIC_LOAD_SUB: 10584 case ISD::ATOMIC_LOAD_AND: 10585 case ISD::ATOMIC_LOAD_OR: 10586 case ISD::ATOMIC_LOAD_XOR: 10587 case ISD::ATOMIC_LOAD_NAND: 10588 case ISD::ATOMIC_LOAD_MIN: 10589 case ISD::ATOMIC_LOAD_MAX: 10590 case ISD::ATOMIC_LOAD_UMIN: 10591 case ISD::ATOMIC_LOAD_UMAX: 10592 case ISD::ATOMIC_LOAD_FADD: 10593 case AMDGPUISD::ATOMIC_INC: 10594 case AMDGPUISD::ATOMIC_DEC: 10595 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10596 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10597 if (DCI.isBeforeLegalize()) 10598 break; 10599 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10600 case ISD::AND: 10601 return performAndCombine(N, DCI); 10602 case ISD::OR: 10603 return performOrCombine(N, DCI); 10604 case ISD::XOR: 10605 return performXorCombine(N, DCI); 10606 case ISD::ZERO_EXTEND: 10607 return performZeroExtendCombine(N, DCI); 10608 case ISD::SIGN_EXTEND_INREG: 10609 return performSignExtendInRegCombine(N , DCI); 10610 case AMDGPUISD::FP_CLASS: 10611 return performClassCombine(N, DCI); 10612 case ISD::FCANONICALIZE: 10613 return performFCanonicalizeCombine(N, DCI); 10614 case AMDGPUISD::RCP: 10615 return performRcpCombine(N, DCI); 10616 case AMDGPUISD::FRACT: 10617 case AMDGPUISD::RSQ: 10618 case AMDGPUISD::RCP_LEGACY: 10619 case AMDGPUISD::RCP_IFLAG: 10620 case AMDGPUISD::RSQ_CLAMP: 10621 case AMDGPUISD::LDEXP: { 10622 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10623 SDValue Src = N->getOperand(0); 10624 if (Src.isUndef()) 10625 return Src; 10626 break; 10627 } 10628 case ISD::SINT_TO_FP: 10629 case ISD::UINT_TO_FP: 10630 return performUCharToFloatCombine(N, DCI); 10631 case AMDGPUISD::CVT_F32_UBYTE0: 10632 case AMDGPUISD::CVT_F32_UBYTE1: 10633 case AMDGPUISD::CVT_F32_UBYTE2: 10634 case AMDGPUISD::CVT_F32_UBYTE3: 10635 return performCvtF32UByteNCombine(N, DCI); 10636 case AMDGPUISD::FMED3: 10637 return performFMed3Combine(N, DCI); 10638 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10639 return performCvtPkRTZCombine(N, DCI); 10640 case AMDGPUISD::CLAMP: 10641 return performClampCombine(N, DCI); 10642 case ISD::SCALAR_TO_VECTOR: { 10643 SelectionDAG &DAG = DCI.DAG; 10644 EVT VT = N->getValueType(0); 10645 10646 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10647 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10648 SDLoc SL(N); 10649 SDValue Src = N->getOperand(0); 10650 EVT EltVT = Src.getValueType(); 10651 if (EltVT == MVT::f16) 10652 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10653 10654 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10655 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10656 } 10657 10658 break; 10659 } 10660 case ISD::EXTRACT_VECTOR_ELT: 10661 return performExtractVectorEltCombine(N, DCI); 10662 case ISD::INSERT_VECTOR_ELT: 10663 return performInsertVectorEltCombine(N, DCI); 10664 } 10665 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10666 } 10667 10668 /// Helper function for adjustWritemask 10669 static unsigned SubIdx2Lane(unsigned Idx) { 10670 switch (Idx) { 10671 default: return 0; 10672 case AMDGPU::sub0: return 0; 10673 case AMDGPU::sub1: return 1; 10674 case AMDGPU::sub2: return 2; 10675 case AMDGPU::sub3: return 3; 10676 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10677 } 10678 } 10679 10680 /// Adjust the writemask of MIMG instructions 10681 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10682 SelectionDAG &DAG) const { 10683 unsigned Opcode = Node->getMachineOpcode(); 10684 10685 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10686 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10687 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10688 return Node; // not implemented for D16 10689 10690 SDNode *Users[5] = { nullptr }; 10691 unsigned Lane = 0; 10692 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10693 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10694 unsigned NewDmask = 0; 10695 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10696 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10697 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10698 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10699 unsigned TFCLane = 0; 10700 bool HasChain = Node->getNumValues() > 1; 10701 10702 if (OldDmask == 0) { 10703 // These are folded out, but on the chance it happens don't assert. 10704 return Node; 10705 } 10706 10707 unsigned OldBitsSet = countPopulation(OldDmask); 10708 // Work out which is the TFE/LWE lane if that is enabled. 10709 if (UsesTFC) { 10710 TFCLane = OldBitsSet; 10711 } 10712 10713 // Try to figure out the used register components 10714 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10715 I != E; ++I) { 10716 10717 // Don't look at users of the chain. 10718 if (I.getUse().getResNo() != 0) 10719 continue; 10720 10721 // Abort if we can't understand the usage 10722 if (!I->isMachineOpcode() || 10723 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10724 return Node; 10725 10726 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10727 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10728 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10729 // set, etc. 10730 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10731 10732 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10733 if (UsesTFC && Lane == TFCLane) { 10734 Users[Lane] = *I; 10735 } else { 10736 // Set which texture component corresponds to the lane. 10737 unsigned Comp; 10738 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10739 Comp = countTrailingZeros(Dmask); 10740 Dmask &= ~(1 << Comp); 10741 } 10742 10743 // Abort if we have more than one user per component. 10744 if (Users[Lane]) 10745 return Node; 10746 10747 Users[Lane] = *I; 10748 NewDmask |= 1 << Comp; 10749 } 10750 } 10751 10752 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10753 bool NoChannels = !NewDmask; 10754 if (NoChannels) { 10755 if (!UsesTFC) { 10756 // No uses of the result and not using TFC. Then do nothing. 10757 return Node; 10758 } 10759 // If the original dmask has one channel - then nothing to do 10760 if (OldBitsSet == 1) 10761 return Node; 10762 // Use an arbitrary dmask - required for the instruction to work 10763 NewDmask = 1; 10764 } 10765 // Abort if there's no change 10766 if (NewDmask == OldDmask) 10767 return Node; 10768 10769 unsigned BitsSet = countPopulation(NewDmask); 10770 10771 // Check for TFE or LWE - increase the number of channels by one to account 10772 // for the extra return value 10773 // This will need adjustment for D16 if this is also included in 10774 // adjustWriteMask (this function) but at present D16 are excluded. 10775 unsigned NewChannels = BitsSet + UsesTFC; 10776 10777 int NewOpcode = 10778 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10779 assert(NewOpcode != -1 && 10780 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10781 "failed to find equivalent MIMG op"); 10782 10783 // Adjust the writemask in the node 10784 SmallVector<SDValue, 12> Ops; 10785 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10786 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10787 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10788 10789 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10790 10791 MVT ResultVT = NewChannels == 1 ? 10792 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10793 NewChannels == 5 ? 8 : NewChannels); 10794 SDVTList NewVTList = HasChain ? 10795 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10796 10797 10798 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10799 NewVTList, Ops); 10800 10801 if (HasChain) { 10802 // Update chain. 10803 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10804 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10805 } 10806 10807 if (NewChannels == 1) { 10808 assert(Node->hasNUsesOfValue(1, 0)); 10809 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10810 SDLoc(Node), Users[Lane]->getValueType(0), 10811 SDValue(NewNode, 0)); 10812 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10813 return nullptr; 10814 } 10815 10816 // Update the users of the node with the new indices 10817 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10818 SDNode *User = Users[i]; 10819 if (!User) { 10820 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10821 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10822 if (i || !NoChannels) 10823 continue; 10824 } else { 10825 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10826 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10827 } 10828 10829 switch (Idx) { 10830 default: break; 10831 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10832 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10833 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10834 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10835 } 10836 } 10837 10838 DAG.RemoveDeadNode(Node); 10839 return nullptr; 10840 } 10841 10842 static bool isFrameIndexOp(SDValue Op) { 10843 if (Op.getOpcode() == ISD::AssertZext) 10844 Op = Op.getOperand(0); 10845 10846 return isa<FrameIndexSDNode>(Op); 10847 } 10848 10849 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10850 /// with frame index operands. 10851 /// LLVM assumes that inputs are to these instructions are registers. 10852 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10853 SelectionDAG &DAG) const { 10854 if (Node->getOpcode() == ISD::CopyToReg) { 10855 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10856 SDValue SrcVal = Node->getOperand(2); 10857 10858 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10859 // to try understanding copies to physical registers. 10860 if (SrcVal.getValueType() == MVT::i1 && 10861 Register::isPhysicalRegister(DestReg->getReg())) { 10862 SDLoc SL(Node); 10863 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10864 SDValue VReg = DAG.getRegister( 10865 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10866 10867 SDNode *Glued = Node->getGluedNode(); 10868 SDValue ToVReg 10869 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10870 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10871 SDValue ToResultReg 10872 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10873 VReg, ToVReg.getValue(1)); 10874 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10875 DAG.RemoveDeadNode(Node); 10876 return ToResultReg.getNode(); 10877 } 10878 } 10879 10880 SmallVector<SDValue, 8> Ops; 10881 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10882 if (!isFrameIndexOp(Node->getOperand(i))) { 10883 Ops.push_back(Node->getOperand(i)); 10884 continue; 10885 } 10886 10887 SDLoc DL(Node); 10888 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10889 Node->getOperand(i).getValueType(), 10890 Node->getOperand(i)), 0)); 10891 } 10892 10893 return DAG.UpdateNodeOperands(Node, Ops); 10894 } 10895 10896 /// Fold the instructions after selecting them. 10897 /// Returns null if users were already updated. 10898 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10899 SelectionDAG &DAG) const { 10900 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10901 unsigned Opcode = Node->getMachineOpcode(); 10902 10903 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10904 !TII->isGather4(Opcode)) { 10905 return adjustWritemask(Node, DAG); 10906 } 10907 10908 if (Opcode == AMDGPU::INSERT_SUBREG || 10909 Opcode == AMDGPU::REG_SEQUENCE) { 10910 legalizeTargetIndependentNode(Node, DAG); 10911 return Node; 10912 } 10913 10914 switch (Opcode) { 10915 case AMDGPU::V_DIV_SCALE_F32: 10916 case AMDGPU::V_DIV_SCALE_F64: { 10917 // Satisfy the operand register constraint when one of the inputs is 10918 // undefined. Ordinarily each undef value will have its own implicit_def of 10919 // a vreg, so force these to use a single register. 10920 SDValue Src0 = Node->getOperand(0); 10921 SDValue Src1 = Node->getOperand(1); 10922 SDValue Src2 = Node->getOperand(2); 10923 10924 if ((Src0.isMachineOpcode() && 10925 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10926 (Src0 == Src1 || Src0 == Src2)) 10927 break; 10928 10929 MVT VT = Src0.getValueType().getSimpleVT(); 10930 const TargetRegisterClass *RC = 10931 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10932 10933 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10934 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10935 10936 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10937 UndefReg, Src0, SDValue()); 10938 10939 // src0 must be the same register as src1 or src2, even if the value is 10940 // undefined, so make sure we don't violate this constraint. 10941 if (Src0.isMachineOpcode() && 10942 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10943 if (Src1.isMachineOpcode() && 10944 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10945 Src0 = Src1; 10946 else if (Src2.isMachineOpcode() && 10947 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10948 Src0 = Src2; 10949 else { 10950 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10951 Src0 = UndefReg; 10952 Src1 = UndefReg; 10953 } 10954 } else 10955 break; 10956 10957 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10958 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10959 Ops.push_back(Node->getOperand(I)); 10960 10961 Ops.push_back(ImpDef.getValue(1)); 10962 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10963 } 10964 default: 10965 break; 10966 } 10967 10968 return Node; 10969 } 10970 10971 /// Assign the register class depending on the number of 10972 /// bits set in the writemask 10973 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10974 SDNode *Node) const { 10975 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10976 10977 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10978 10979 if (TII->isVOP3(MI.getOpcode())) { 10980 // Make sure constant bus requirements are respected. 10981 TII->legalizeOperandsVOP3(MRI, MI); 10982 10983 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10984 // This saves a chain-copy of registers and better ballance register 10985 // use between vgpr and agpr as agpr tuples tend to be big. 10986 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10987 unsigned Opc = MI.getOpcode(); 10988 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10989 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10990 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10991 if (I == -1) 10992 break; 10993 MachineOperand &Op = MI.getOperand(I); 10994 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10995 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10996 !Register::isVirtualRegister(Op.getReg()) || 10997 !TRI->isAGPR(MRI, Op.getReg())) 10998 continue; 10999 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11000 if (!Src || !Src->isCopy() || 11001 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11002 continue; 11003 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11004 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11005 // All uses of agpr64 and agpr32 can also accept vgpr except for 11006 // v_accvgpr_read, but we do not produce agpr reads during selection, 11007 // so no use checks are needed. 11008 MRI.setRegClass(Op.getReg(), NewRC); 11009 } 11010 } 11011 11012 return; 11013 } 11014 11015 // Replace unused atomics with the no return version. 11016 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11017 if (NoRetAtomicOp != -1) { 11018 if (!Node->hasAnyUseOfValue(0)) { 11019 MI.setDesc(TII->get(NoRetAtomicOp)); 11020 MI.RemoveOperand(0); 11021 return; 11022 } 11023 11024 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11025 // instruction, because the return type of these instructions is a vec2 of 11026 // the memory type, so it can be tied to the input operand. 11027 // This means these instructions always have a use, so we need to add a 11028 // special case to check if the atomic has only one extract_subreg use, 11029 // which itself has no uses. 11030 if ((Node->hasNUsesOfValue(1, 0) && 11031 Node->use_begin()->isMachineOpcode() && 11032 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11033 !Node->use_begin()->hasAnyUseOfValue(0))) { 11034 Register Def = MI.getOperand(0).getReg(); 11035 11036 // Change this into a noret atomic. 11037 MI.setDesc(TII->get(NoRetAtomicOp)); 11038 MI.RemoveOperand(0); 11039 11040 // If we only remove the def operand from the atomic instruction, the 11041 // extract_subreg will be left with a use of a vreg without a def. 11042 // So we need to insert an implicit_def to avoid machine verifier 11043 // errors. 11044 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11045 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11046 } 11047 return; 11048 } 11049 } 11050 11051 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11052 uint64_t Val) { 11053 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11054 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11055 } 11056 11057 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11058 const SDLoc &DL, 11059 SDValue Ptr) const { 11060 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11061 11062 // Build the half of the subregister with the constants before building the 11063 // full 128-bit register. If we are building multiple resource descriptors, 11064 // this will allow CSEing of the 2-component register. 11065 const SDValue Ops0[] = { 11066 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11067 buildSMovImm32(DAG, DL, 0), 11068 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11069 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11070 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11071 }; 11072 11073 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11074 MVT::v2i32, Ops0), 0); 11075 11076 // Combine the constants and the pointer. 11077 const SDValue Ops1[] = { 11078 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11079 Ptr, 11080 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11081 SubRegHi, 11082 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11083 }; 11084 11085 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11086 } 11087 11088 /// Return a resource descriptor with the 'Add TID' bit enabled 11089 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11090 /// of the resource descriptor) to create an offset, which is added to 11091 /// the resource pointer. 11092 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11093 SDValue Ptr, uint32_t RsrcDword1, 11094 uint64_t RsrcDword2And3) const { 11095 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11096 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11097 if (RsrcDword1) { 11098 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11099 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11100 0); 11101 } 11102 11103 SDValue DataLo = buildSMovImm32(DAG, DL, 11104 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11105 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11106 11107 const SDValue Ops[] = { 11108 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11109 PtrLo, 11110 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11111 PtrHi, 11112 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11113 DataLo, 11114 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11115 DataHi, 11116 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11117 }; 11118 11119 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11120 } 11121 11122 //===----------------------------------------------------------------------===// 11123 // SI Inline Assembly Support 11124 //===----------------------------------------------------------------------===// 11125 11126 std::pair<unsigned, const TargetRegisterClass *> 11127 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11128 StringRef Constraint, 11129 MVT VT) const { 11130 const TargetRegisterClass *RC = nullptr; 11131 if (Constraint.size() == 1) { 11132 const unsigned BitWidth = VT.getSizeInBits(); 11133 switch (Constraint[0]) { 11134 default: 11135 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11136 case 's': 11137 case 'r': 11138 switch (BitWidth) { 11139 case 16: 11140 RC = &AMDGPU::SReg_32RegClass; 11141 break; 11142 case 64: 11143 RC = &AMDGPU::SGPR_64RegClass; 11144 break; 11145 default: 11146 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11147 if (!RC) 11148 return std::make_pair(0U, nullptr); 11149 break; 11150 } 11151 break; 11152 case 'v': 11153 switch (BitWidth) { 11154 case 16: 11155 RC = &AMDGPU::VGPR_32RegClass; 11156 break; 11157 default: 11158 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11159 if (!RC) 11160 return std::make_pair(0U, nullptr); 11161 break; 11162 } 11163 break; 11164 case 'a': 11165 if (!Subtarget->hasMAIInsts()) 11166 break; 11167 switch (BitWidth) { 11168 case 16: 11169 RC = &AMDGPU::AGPR_32RegClass; 11170 break; 11171 default: 11172 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11173 if (!RC) 11174 return std::make_pair(0U, nullptr); 11175 break; 11176 } 11177 break; 11178 } 11179 // We actually support i128, i16 and f16 as inline parameters 11180 // even if they are not reported as legal 11181 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11182 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11183 return std::make_pair(0U, RC); 11184 } 11185 11186 if (Constraint.size() > 1) { 11187 if (Constraint[1] == 'v') { 11188 RC = &AMDGPU::VGPR_32RegClass; 11189 } else if (Constraint[1] == 's') { 11190 RC = &AMDGPU::SGPR_32RegClass; 11191 } else if (Constraint[1] == 'a') { 11192 RC = &AMDGPU::AGPR_32RegClass; 11193 } 11194 11195 if (RC) { 11196 uint32_t Idx; 11197 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11198 if (!Failed && Idx < RC->getNumRegs()) 11199 return std::make_pair(RC->getRegister(Idx), RC); 11200 } 11201 } 11202 11203 // FIXME: Returns VS_32 for physical SGPR constraints 11204 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11205 } 11206 11207 static bool isImmConstraint(StringRef Constraint) { 11208 if (Constraint.size() == 1) { 11209 switch (Constraint[0]) { 11210 default: break; 11211 case 'I': 11212 case 'J': 11213 case 'A': 11214 case 'B': 11215 case 'C': 11216 return true; 11217 } 11218 } else if (Constraint == "DA" || 11219 Constraint == "DB") { 11220 return true; 11221 } 11222 return false; 11223 } 11224 11225 SITargetLowering::ConstraintType 11226 SITargetLowering::getConstraintType(StringRef Constraint) const { 11227 if (Constraint.size() == 1) { 11228 switch (Constraint[0]) { 11229 default: break; 11230 case 's': 11231 case 'v': 11232 case 'a': 11233 return C_RegisterClass; 11234 } 11235 } 11236 if (isImmConstraint(Constraint)) { 11237 return C_Other; 11238 } 11239 return TargetLowering::getConstraintType(Constraint); 11240 } 11241 11242 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11243 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11244 Val = Val & maskTrailingOnes<uint64_t>(Size); 11245 } 11246 return Val; 11247 } 11248 11249 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11250 std::string &Constraint, 11251 std::vector<SDValue> &Ops, 11252 SelectionDAG &DAG) const { 11253 if (isImmConstraint(Constraint)) { 11254 uint64_t Val; 11255 if (getAsmOperandConstVal(Op, Val) && 11256 checkAsmConstraintVal(Op, Constraint, Val)) { 11257 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11258 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11259 } 11260 } else { 11261 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11262 } 11263 } 11264 11265 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11266 unsigned Size = Op.getScalarValueSizeInBits(); 11267 if (Size > 64) 11268 return false; 11269 11270 if (Size == 16 && !Subtarget->has16BitInsts()) 11271 return false; 11272 11273 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11274 Val = C->getSExtValue(); 11275 return true; 11276 } 11277 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11278 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11279 return true; 11280 } 11281 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11282 if (Size != 16 || Op.getNumOperands() != 2) 11283 return false; 11284 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11285 return false; 11286 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11287 Val = C->getSExtValue(); 11288 return true; 11289 } 11290 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11291 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11292 return true; 11293 } 11294 } 11295 11296 return false; 11297 } 11298 11299 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11300 const std::string &Constraint, 11301 uint64_t Val) const { 11302 if (Constraint.size() == 1) { 11303 switch (Constraint[0]) { 11304 case 'I': 11305 return AMDGPU::isInlinableIntLiteral(Val); 11306 case 'J': 11307 return isInt<16>(Val); 11308 case 'A': 11309 return checkAsmConstraintValA(Op, Val); 11310 case 'B': 11311 return isInt<32>(Val); 11312 case 'C': 11313 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11314 AMDGPU::isInlinableIntLiteral(Val); 11315 default: 11316 break; 11317 } 11318 } else if (Constraint.size() == 2) { 11319 if (Constraint == "DA") { 11320 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11321 int64_t LoBits = static_cast<int32_t>(Val); 11322 return checkAsmConstraintValA(Op, HiBits, 32) && 11323 checkAsmConstraintValA(Op, LoBits, 32); 11324 } 11325 if (Constraint == "DB") { 11326 return true; 11327 } 11328 } 11329 llvm_unreachable("Invalid asm constraint"); 11330 } 11331 11332 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11333 uint64_t Val, 11334 unsigned MaxSize) const { 11335 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11336 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11337 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11338 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11339 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11340 return true; 11341 } 11342 return false; 11343 } 11344 11345 // Figure out which registers should be reserved for stack access. Only after 11346 // the function is legalized do we know all of the non-spill stack objects or if 11347 // calls are present. 11348 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11349 MachineRegisterInfo &MRI = MF.getRegInfo(); 11350 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11351 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11352 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11353 11354 if (Info->isEntryFunction()) { 11355 // Callable functions have fixed registers used for stack access. 11356 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11357 } 11358 11359 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11360 Info->getStackPtrOffsetReg())); 11361 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11362 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11363 11364 // We need to worry about replacing the default register with itself in case 11365 // of MIR testcases missing the MFI. 11366 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11367 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11368 11369 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11370 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11371 11372 Info->limitOccupancy(MF); 11373 11374 if (ST.isWave32() && !MF.empty()) { 11375 // Add VCC_HI def because many instructions marked as imp-use VCC where 11376 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11377 // having a use of undef. 11378 11379 const SIInstrInfo *TII = ST.getInstrInfo(); 11380 DebugLoc DL; 11381 11382 MachineBasicBlock &MBB = MF.front(); 11383 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11384 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11385 11386 for (auto &MBB : MF) { 11387 for (auto &MI : MBB) { 11388 TII->fixImplicitOperands(MI); 11389 } 11390 } 11391 } 11392 11393 TargetLoweringBase::finalizeLowering(MF); 11394 11395 // Allocate a VGPR for future SGPR Spill if 11396 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11397 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11398 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11399 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11400 Info->reserveVGPRforSGPRSpills(MF); 11401 } 11402 11403 void SITargetLowering::computeKnownBitsForFrameIndex( 11404 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11405 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11406 11407 // Set the high bits to zero based on the maximum allowed scratch size per 11408 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11409 // calculation won't overflow, so assume the sign bit is never set. 11410 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11411 } 11412 11413 Align SITargetLowering::computeKnownAlignForTargetInstr( 11414 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11415 unsigned Depth) const { 11416 const MachineInstr *MI = MRI.getVRegDef(R); 11417 switch (MI->getOpcode()) { 11418 case AMDGPU::G_INTRINSIC: 11419 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11420 // FIXME: Can this move to generic code? What about the case where the call 11421 // site specifies a lower alignment? 11422 Intrinsic::ID IID = MI->getIntrinsicID(); 11423 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11424 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11425 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11426 return *RetAlign; 11427 return Align(1); 11428 } 11429 default: 11430 return Align(1); 11431 } 11432 } 11433 11434 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11435 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11436 const Align CacheLineAlign = Align(64); 11437 11438 // Pre-GFX10 target did not benefit from loop alignment 11439 if (!ML || DisableLoopAlignment || 11440 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11441 getSubtarget()->hasInstFwdPrefetchBug()) 11442 return PrefAlign; 11443 11444 // On GFX10 I$ is 4 x 64 bytes cache lines. 11445 // By default prefetcher keeps one cache line behind and reads two ahead. 11446 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11447 // behind and one ahead. 11448 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11449 // If loop fits 64 bytes it always spans no more than two cache lines and 11450 // does not need an alignment. 11451 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11452 // Else if loop is less or equal 192 bytes we need two lines behind. 11453 11454 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11455 const MachineBasicBlock *Header = ML->getHeader(); 11456 if (Header->getAlignment() != PrefAlign) 11457 return Header->getAlignment(); // Already processed. 11458 11459 unsigned LoopSize = 0; 11460 for (const MachineBasicBlock *MBB : ML->blocks()) { 11461 // If inner loop block is aligned assume in average half of the alignment 11462 // size to be added as nops. 11463 if (MBB != Header) 11464 LoopSize += MBB->getAlignment().value() / 2; 11465 11466 for (const MachineInstr &MI : *MBB) { 11467 LoopSize += TII->getInstSizeInBytes(MI); 11468 if (LoopSize > 192) 11469 return PrefAlign; 11470 } 11471 } 11472 11473 if (LoopSize <= 64) 11474 return PrefAlign; 11475 11476 if (LoopSize <= 128) 11477 return CacheLineAlign; 11478 11479 // If any of parent loops is surrounded by prefetch instructions do not 11480 // insert new for inner loop, which would reset parent's settings. 11481 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11482 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11483 auto I = Exit->getFirstNonDebugInstr(); 11484 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11485 return CacheLineAlign; 11486 } 11487 } 11488 11489 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11490 MachineBasicBlock *Exit = ML->getExitBlock(); 11491 11492 if (Pre && Exit) { 11493 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11494 TII->get(AMDGPU::S_INST_PREFETCH)) 11495 .addImm(1); // prefetch 2 lines behind PC 11496 11497 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11498 TII->get(AMDGPU::S_INST_PREFETCH)) 11499 .addImm(2); // prefetch 1 line behind PC 11500 } 11501 11502 return CacheLineAlign; 11503 } 11504 11505 LLVM_ATTRIBUTE_UNUSED 11506 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11507 assert(N->getOpcode() == ISD::CopyFromReg); 11508 do { 11509 // Follow the chain until we find an INLINEASM node. 11510 N = N->getOperand(0).getNode(); 11511 if (N->getOpcode() == ISD::INLINEASM || 11512 N->getOpcode() == ISD::INLINEASM_BR) 11513 return true; 11514 } while (N->getOpcode() == ISD::CopyFromReg); 11515 return false; 11516 } 11517 11518 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11519 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11520 { 11521 switch (N->getOpcode()) { 11522 case ISD::CopyFromReg: 11523 { 11524 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11525 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11526 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11527 Register Reg = R->getReg(); 11528 11529 // FIXME: Why does this need to consider isLiveIn? 11530 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11531 return !TRI->isSGPRReg(MRI, Reg); 11532 11533 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11534 return KDA->isDivergent(V); 11535 11536 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11537 return !TRI->isSGPRReg(MRI, Reg); 11538 } 11539 break; 11540 case ISD::LOAD: { 11541 const LoadSDNode *L = cast<LoadSDNode>(N); 11542 unsigned AS = L->getAddressSpace(); 11543 // A flat load may access private memory. 11544 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11545 } break; 11546 case ISD::CALLSEQ_END: 11547 return true; 11548 break; 11549 case ISD::INTRINSIC_WO_CHAIN: 11550 { 11551 11552 } 11553 return AMDGPU::isIntrinsicSourceOfDivergence( 11554 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11555 case ISD::INTRINSIC_W_CHAIN: 11556 return AMDGPU::isIntrinsicSourceOfDivergence( 11557 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11558 } 11559 return false; 11560 } 11561 11562 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11563 EVT VT) const { 11564 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11565 case MVT::f32: 11566 return hasFP32Denormals(DAG.getMachineFunction()); 11567 case MVT::f64: 11568 case MVT::f16: 11569 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11570 default: 11571 return false; 11572 } 11573 } 11574 11575 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11576 const SelectionDAG &DAG, 11577 bool SNaN, 11578 unsigned Depth) const { 11579 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11580 const MachineFunction &MF = DAG.getMachineFunction(); 11581 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11582 11583 if (Info->getMode().DX10Clamp) 11584 return true; // Clamped to 0. 11585 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11586 } 11587 11588 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11589 SNaN, Depth); 11590 } 11591 11592 TargetLowering::AtomicExpansionKind 11593 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11594 switch (RMW->getOperation()) { 11595 case AtomicRMWInst::FAdd: { 11596 Type *Ty = RMW->getType(); 11597 11598 // We don't have a way to support 16-bit atomics now, so just leave them 11599 // as-is. 11600 if (Ty->isHalfTy()) 11601 return AtomicExpansionKind::None; 11602 11603 if (!Ty->isFloatTy()) 11604 return AtomicExpansionKind::CmpXChg; 11605 11606 // TODO: Do have these for flat. Older targets also had them for buffers. 11607 unsigned AS = RMW->getPointerAddressSpace(); 11608 11609 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11610 return RMW->use_empty() ? AtomicExpansionKind::None : 11611 AtomicExpansionKind::CmpXChg; 11612 } 11613 11614 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11615 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11616 } 11617 default: 11618 break; 11619 } 11620 11621 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11622 } 11623 11624 const TargetRegisterClass * 11625 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11626 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11627 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11628 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11629 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11630 : &AMDGPU::SReg_32RegClass; 11631 if (!TRI->isSGPRClass(RC) && !isDivergent) 11632 return TRI->getEquivalentSGPRClass(RC); 11633 else if (TRI->isSGPRClass(RC) && isDivergent) 11634 return TRI->getEquivalentVGPRClass(RC); 11635 11636 return RC; 11637 } 11638 11639 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11640 // uniform values (as produced by the mask results of control flow intrinsics) 11641 // used outside of divergent blocks. The phi users need to also be treated as 11642 // always uniform. 11643 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11644 unsigned WaveSize) { 11645 // FIXME: We asssume we never cast the mask results of a control flow 11646 // intrinsic. 11647 // Early exit if the type won't be consistent as a compile time hack. 11648 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11649 if (!IT || IT->getBitWidth() != WaveSize) 11650 return false; 11651 11652 if (!isa<Instruction>(V)) 11653 return false; 11654 if (!Visited.insert(V).second) 11655 return false; 11656 bool Result = false; 11657 for (auto U : V->users()) { 11658 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11659 if (V == U->getOperand(1)) { 11660 switch (Intrinsic->getIntrinsicID()) { 11661 default: 11662 Result = false; 11663 break; 11664 case Intrinsic::amdgcn_if_break: 11665 case Intrinsic::amdgcn_if: 11666 case Intrinsic::amdgcn_else: 11667 Result = true; 11668 break; 11669 } 11670 } 11671 if (V == U->getOperand(0)) { 11672 switch (Intrinsic->getIntrinsicID()) { 11673 default: 11674 Result = false; 11675 break; 11676 case Intrinsic::amdgcn_end_cf: 11677 case Intrinsic::amdgcn_loop: 11678 Result = true; 11679 break; 11680 } 11681 } 11682 } else { 11683 Result = hasCFUser(U, Visited, WaveSize); 11684 } 11685 if (Result) 11686 break; 11687 } 11688 return Result; 11689 } 11690 11691 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11692 const Value *V) const { 11693 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11694 if (CI->isInlineAsm()) { 11695 // FIXME: This cannot give a correct answer. This should only trigger in 11696 // the case where inline asm returns mixed SGPR and VGPR results, used 11697 // outside the defining block. We don't have a specific result to 11698 // consider, so this assumes if any value is SGPR, the overall register 11699 // also needs to be SGPR. 11700 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11701 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11702 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11703 for (auto &TC : TargetConstraints) { 11704 if (TC.Type == InlineAsm::isOutput) { 11705 ComputeConstraintToUse(TC, SDValue()); 11706 unsigned AssignedReg; 11707 const TargetRegisterClass *RC; 11708 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11709 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11710 if (RC) { 11711 MachineRegisterInfo &MRI = MF.getRegInfo(); 11712 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11713 return true; 11714 else if (SIRI->isSGPRClass(RC)) 11715 return true; 11716 } 11717 } 11718 } 11719 } 11720 } 11721 SmallPtrSet<const Value *, 16> Visited; 11722 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11723 } 11724 11725 std::pair<int, MVT> 11726 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11727 Type *Ty) const { 11728 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11729 auto Size = DL.getTypeSizeInBits(Ty); 11730 // Maximum load or store can handle 8 dwords for scalar and 4 for 11731 // vector ALU. Let's assume anything above 8 dwords is expensive 11732 // even if legal. 11733 if (Size <= 256) 11734 return Cost; 11735 11736 Cost.first = (Size + 255) / 256; 11737 return Cost; 11738 } 11739