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/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstr.h" 42 #include "llvm/CodeGen/MachineInstrBuilder.h" 43 #include "llvm/CodeGen/MachineLoopInfo.h" 44 #include "llvm/CodeGen/MachineMemOperand.h" 45 #include "llvm/CodeGen/MachineModuleInfo.h" 46 #include "llvm/CodeGen/MachineOperand.h" 47 #include "llvm/CodeGen/MachineRegisterInfo.h" 48 #include "llvm/CodeGen/SelectionDAG.h" 49 #include "llvm/CodeGen/SelectionDAGNodes.h" 50 #include "llvm/CodeGen/TargetCallingConv.h" 51 #include "llvm/CodeGen/TargetRegisterInfo.h" 52 #include "llvm/CodeGen/ValueTypes.h" 53 #include "llvm/IR/Constants.h" 54 #include "llvm/IR/DataLayout.h" 55 #include "llvm/IR/DebugLoc.h" 56 #include "llvm/IR/DerivedTypes.h" 57 #include "llvm/IR/DiagnosticInfo.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/GlobalValue.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/IntrinsicInst.h" 64 #include "llvm/IR/Type.h" 65 #include "llvm/Support/Casting.h" 66 #include "llvm/Support/CodeGen.h" 67 #include "llvm/Support/CommandLine.h" 68 #include "llvm/Support/Compiler.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/KnownBits.h" 71 #include "llvm/Support/MachineValueType.h" 72 #include "llvm/Support/MathExtras.h" 73 #include "llvm/Target/TargetOptions.h" 74 #include <cassert> 75 #include <cmath> 76 #include <cstdint> 77 #include <iterator> 78 #include <tuple> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 #define DEBUG_TYPE "si-lower" 85 86 STATISTIC(NumTailCalls, "Number of tail calls"); 87 88 static cl::opt<bool> DisableLoopAlignment( 89 "amdgpu-disable-loop-alignment", 90 cl::desc("Do not align and prefetch loops"), 91 cl::init(false)); 92 93 static cl::opt<bool> VGPRReserveforSGPRSpill( 94 "amdgpu-reserve-vgpr-for-sgpr-spill", 95 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 96 97 static cl::opt<bool> UseDivergentRegisterIndexing( 98 "amdgpu-use-divergent-register-indexing", 99 cl::Hidden, 100 cl::desc("Use indirect register addressing for divergent indexes"), 101 cl::init(false)); 102 103 static bool hasFP32Denormals(const MachineFunction &MF) { 104 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 105 return Info->getMode().allFP32Denormals(); 106 } 107 108 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 110 return Info->getMode().allFP64FP16Denormals(); 111 } 112 113 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 114 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 115 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 116 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 117 return AMDGPU::SGPR0 + Reg; 118 } 119 } 120 llvm_unreachable("Cannot allocate sgpr"); 121 } 122 123 SITargetLowering::SITargetLowering(const TargetMachine &TM, 124 const GCNSubtarget &STI) 125 : AMDGPUTargetLowering(TM, STI), 126 Subtarget(&STI) { 127 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 128 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 129 130 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 131 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 132 133 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 134 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 135 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 136 137 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 138 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 139 140 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 141 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 142 143 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 144 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 145 146 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 147 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 148 149 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 150 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 151 152 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 153 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 154 155 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 156 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 157 158 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 159 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 160 161 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 162 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 163 164 if (Subtarget->has16BitInsts()) { 165 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 166 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 167 168 // Unless there are also VOP3P operations, not operations are really legal. 169 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 170 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 171 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 172 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 173 } 174 175 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 176 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 177 178 computeRegisterProperties(Subtarget->getRegisterInfo()); 179 180 // The boolean content concept here is too inflexible. Compares only ever 181 // really produce a 1-bit result. Any copy/extend from these will turn into a 182 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 183 // it's what most targets use. 184 setBooleanContents(ZeroOrOneBooleanContent); 185 setBooleanVectorContents(ZeroOrOneBooleanContent); 186 187 // We need to custom lower vector stores from local memory 188 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 189 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 190 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::i1, Custom); 195 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 196 197 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 198 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 199 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 203 setOperationAction(ISD::STORE, MVT::i1, Custom); 204 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 205 206 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 207 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 208 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 209 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 210 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 211 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 212 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 213 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 214 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 215 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 216 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 217 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 218 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 219 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 220 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 221 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 222 223 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 224 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 225 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 227 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 228 229 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 230 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 231 232 setOperationAction(ISD::SELECT, MVT::i1, Promote); 233 setOperationAction(ISD::SELECT, MVT::i64, Custom); 234 setOperationAction(ISD::SELECT, MVT::f64, Promote); 235 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 236 237 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 238 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 239 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 242 243 setOperationAction(ISD::SETCC, MVT::i1, Promote); 244 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 245 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 246 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 247 248 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 249 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 250 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 251 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 252 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 253 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 254 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 255 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 256 257 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 258 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 265 266 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 267 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 268 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 269 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 270 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 271 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 272 273 setOperationAction(ISD::UADDO, MVT::i32, Legal); 274 setOperationAction(ISD::USUBO, MVT::i32, Legal); 275 276 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 277 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 278 279 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 280 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 281 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 282 283 #if 0 284 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 285 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 286 #endif 287 288 // We only support LOAD/STORE and vector manipulation ops for vectors 289 // with > 4 elements. 290 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 291 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 292 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 293 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 294 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 295 switch (Op) { 296 case ISD::LOAD: 297 case ISD::STORE: 298 case ISD::BUILD_VECTOR: 299 case ISD::BITCAST: 300 case ISD::EXTRACT_VECTOR_ELT: 301 case ISD::INSERT_VECTOR_ELT: 302 case ISD::INSERT_SUBVECTOR: 303 case ISD::EXTRACT_SUBVECTOR: 304 case ISD::SCALAR_TO_VECTOR: 305 break; 306 case ISD::CONCAT_VECTORS: 307 setOperationAction(Op, VT, Custom); 308 break; 309 default: 310 setOperationAction(Op, VT, Expand); 311 break; 312 } 313 } 314 } 315 316 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 317 318 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 319 // is expanded to avoid having two separate loops in case the index is a VGPR. 320 321 // Most operations are naturally 32-bit vector operations. We only support 322 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 323 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 324 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 325 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 326 327 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 328 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 329 330 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 331 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 332 333 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 334 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 335 } 336 337 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 338 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 339 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 340 341 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 342 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 343 344 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 345 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 346 347 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 348 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 349 } 350 351 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 352 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 353 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 354 355 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 356 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 357 358 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 359 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 360 361 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 362 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 363 } 364 365 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 366 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 367 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 368 369 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 370 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 371 372 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 373 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 374 375 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 376 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 377 } 378 379 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 383 384 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 385 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 386 387 // Avoid stack access for these. 388 // TODO: Generalize to more vector types. 389 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 393 394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 399 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 403 404 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 405 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 406 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 407 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 408 409 // Deal with vec3 vector operations when widened to vec4. 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 414 415 // Deal with vec5 vector operations when widened to vec8. 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 420 421 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 422 // and output demarshalling 423 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 424 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 425 426 // We can't return success/failure, only the old value, 427 // let LLVM add the comparison 428 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 429 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 430 431 if (Subtarget->hasFlatAddressSpace()) { 432 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 433 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 434 } 435 436 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 437 438 // FIXME: This should be narrowed to i32, but that only happens if i64 is 439 // illegal. 440 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 441 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 442 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 443 444 // On SI this is s_memtime and s_memrealtime on VI. 445 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 446 setOperationAction(ISD::TRAP, MVT::Other, Custom); 447 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 448 449 if (Subtarget->has16BitInsts()) { 450 setOperationAction(ISD::FPOW, MVT::f16, Promote); 451 setOperationAction(ISD::FLOG, MVT::f16, Custom); 452 setOperationAction(ISD::FEXP, MVT::f16, Custom); 453 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 454 } 455 456 if (Subtarget->hasMadMacF32Insts()) 457 setOperationAction(ISD::FMAD, MVT::f32, Legal); 458 459 if (!Subtarget->hasBFI()) { 460 // fcopysign can be done in a single instruction with BFI. 461 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 462 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 463 } 464 465 if (!Subtarget->hasBCNT(32)) 466 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 467 468 if (!Subtarget->hasBCNT(64)) 469 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 470 471 if (Subtarget->hasFFBH()) 472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 473 474 if (Subtarget->hasFFBL()) 475 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 476 477 // We only really have 32-bit BFE instructions (and 16-bit on VI). 478 // 479 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 480 // effort to match them now. We want this to be false for i64 cases when the 481 // extraction isn't restricted to the upper or lower half. Ideally we would 482 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 483 // span the midpoint are probably relatively rare, so don't worry about them 484 // for now. 485 if (Subtarget->hasBFE()) 486 setHasExtractBitsInsn(true); 487 488 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 489 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 490 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 491 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 492 493 494 // These are really only legal for ieee_mode functions. We should be avoiding 495 // them for functions that don't have ieee_mode enabled, so just say they are 496 // legal. 497 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 498 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 499 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 500 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 501 502 503 if (Subtarget->haveRoundOpsF64()) { 504 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 505 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 506 setOperationAction(ISD::FRINT, MVT::f64, Legal); 507 } else { 508 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 509 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 510 setOperationAction(ISD::FRINT, MVT::f64, Custom); 511 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 512 } 513 514 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 515 516 setOperationAction(ISD::FSIN, MVT::f32, Custom); 517 setOperationAction(ISD::FCOS, MVT::f32, Custom); 518 setOperationAction(ISD::FDIV, MVT::f32, Custom); 519 setOperationAction(ISD::FDIV, MVT::f64, Custom); 520 521 if (Subtarget->has16BitInsts()) { 522 setOperationAction(ISD::Constant, MVT::i16, Legal); 523 524 setOperationAction(ISD::SMIN, MVT::i16, Legal); 525 setOperationAction(ISD::SMAX, MVT::i16, Legal); 526 527 setOperationAction(ISD::UMIN, MVT::i16, Legal); 528 setOperationAction(ISD::UMAX, MVT::i16, Legal); 529 530 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 531 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 532 533 setOperationAction(ISD::ROTR, MVT::i16, Promote); 534 setOperationAction(ISD::ROTL, MVT::i16, Promote); 535 536 setOperationAction(ISD::SDIV, MVT::i16, Promote); 537 setOperationAction(ISD::UDIV, MVT::i16, Promote); 538 setOperationAction(ISD::SREM, MVT::i16, Promote); 539 setOperationAction(ISD::UREM, MVT::i16, Promote); 540 541 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 542 543 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 544 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 545 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 546 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 547 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 548 549 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 550 551 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 552 553 setOperationAction(ISD::LOAD, MVT::i16, Custom); 554 555 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 556 557 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 558 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 559 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 560 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 561 562 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 563 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 564 565 // F16 - Constant Actions. 566 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 567 568 // F16 - Load/Store Actions. 569 setOperationAction(ISD::LOAD, MVT::f16, Promote); 570 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 571 setOperationAction(ISD::STORE, MVT::f16, Promote); 572 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 573 574 // F16 - VOP1 Actions. 575 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 576 setOperationAction(ISD::FCOS, MVT::f16, Custom); 577 setOperationAction(ISD::FSIN, MVT::f16, Custom); 578 579 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 580 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 581 582 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 583 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 584 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 585 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 586 setOperationAction(ISD::FROUND, MVT::f16, Custom); 587 588 // F16 - VOP2 Actions. 589 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 590 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 591 592 setOperationAction(ISD::FDIV, MVT::f16, Custom); 593 594 // F16 - VOP3 Actions. 595 setOperationAction(ISD::FMA, MVT::f16, Legal); 596 if (STI.hasMadF16()) 597 setOperationAction(ISD::FMAD, MVT::f16, Legal); 598 599 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 600 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 601 switch (Op) { 602 case ISD::LOAD: 603 case ISD::STORE: 604 case ISD::BUILD_VECTOR: 605 case ISD::BITCAST: 606 case ISD::EXTRACT_VECTOR_ELT: 607 case ISD::INSERT_VECTOR_ELT: 608 case ISD::INSERT_SUBVECTOR: 609 case ISD::EXTRACT_SUBVECTOR: 610 case ISD::SCALAR_TO_VECTOR: 611 break; 612 case ISD::CONCAT_VECTORS: 613 setOperationAction(Op, VT, Custom); 614 break; 615 default: 616 setOperationAction(Op, VT, Expand); 617 break; 618 } 619 } 620 } 621 622 // v_perm_b32 can handle either of these. 623 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 624 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 625 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 626 627 // XXX - Do these do anything? Vector constants turn into build_vector. 628 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 629 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 630 631 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 632 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 633 634 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 635 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 636 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 637 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 638 639 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 640 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 641 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 642 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 643 644 setOperationAction(ISD::AND, MVT::v2i16, Promote); 645 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 646 setOperationAction(ISD::OR, MVT::v2i16, Promote); 647 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 648 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 649 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 650 651 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 652 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 653 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 654 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 655 656 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 657 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 658 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 659 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 660 661 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 662 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 663 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 664 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 665 666 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 667 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 668 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 669 670 if (!Subtarget->hasVOP3PInsts()) { 671 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 672 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 673 } 674 675 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 676 // This isn't really legal, but this avoids the legalizer unrolling it (and 677 // allows matching fneg (fabs x) patterns) 678 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 679 680 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 681 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 682 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 683 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 684 685 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 686 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 687 688 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 689 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 690 } 691 692 if (Subtarget->hasVOP3PInsts()) { 693 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 694 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 695 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 696 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 697 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 698 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 699 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 700 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 701 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 702 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 703 704 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 705 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 706 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 707 708 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 709 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 710 711 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 712 713 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 715 716 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 717 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 718 719 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 720 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 721 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 722 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 723 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 724 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 725 726 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 727 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 728 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 729 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 730 731 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 732 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 733 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 734 735 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 736 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 737 738 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 739 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 740 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 741 742 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 743 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 744 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 745 } 746 747 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 748 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 749 750 if (Subtarget->has16BitInsts()) { 751 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 752 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 753 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 754 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 755 } else { 756 // Legalization hack. 757 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 758 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 759 760 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 761 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 762 } 763 764 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 765 setOperationAction(ISD::SELECT, VT, Custom); 766 } 767 768 setOperationAction(ISD::SMULO, MVT::i64, Custom); 769 setOperationAction(ISD::UMULO, MVT::i64, Custom); 770 771 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 772 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 773 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 774 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 775 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 776 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 777 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 778 779 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 785 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 786 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 787 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 788 789 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 790 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 795 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 796 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 797 798 setTargetDAGCombine(ISD::ADD); 799 setTargetDAGCombine(ISD::ADDCARRY); 800 setTargetDAGCombine(ISD::SUB); 801 setTargetDAGCombine(ISD::SUBCARRY); 802 setTargetDAGCombine(ISD::FADD); 803 setTargetDAGCombine(ISD::FSUB); 804 setTargetDAGCombine(ISD::FMINNUM); 805 setTargetDAGCombine(ISD::FMAXNUM); 806 setTargetDAGCombine(ISD::FMINNUM_IEEE); 807 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 808 setTargetDAGCombine(ISD::FMA); 809 setTargetDAGCombine(ISD::SMIN); 810 setTargetDAGCombine(ISD::SMAX); 811 setTargetDAGCombine(ISD::UMIN); 812 setTargetDAGCombine(ISD::UMAX); 813 setTargetDAGCombine(ISD::SETCC); 814 setTargetDAGCombine(ISD::AND); 815 setTargetDAGCombine(ISD::OR); 816 setTargetDAGCombine(ISD::XOR); 817 setTargetDAGCombine(ISD::SINT_TO_FP); 818 setTargetDAGCombine(ISD::UINT_TO_FP); 819 setTargetDAGCombine(ISD::FCANONICALIZE); 820 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 821 setTargetDAGCombine(ISD::ZERO_EXTEND); 822 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 823 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 824 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 825 826 // All memory operations. Some folding on the pointer operand is done to help 827 // matching the constant offsets in the addressing modes. 828 setTargetDAGCombine(ISD::LOAD); 829 setTargetDAGCombine(ISD::STORE); 830 setTargetDAGCombine(ISD::ATOMIC_LOAD); 831 setTargetDAGCombine(ISD::ATOMIC_STORE); 832 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 833 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 834 setTargetDAGCombine(ISD::ATOMIC_SWAP); 835 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 844 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 845 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 846 847 // FIXME: In other contexts we pretend this is a per-function property. 848 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 849 850 setSchedulingPreference(Sched::RegPressure); 851 } 852 853 const GCNSubtarget *SITargetLowering::getSubtarget() const { 854 return Subtarget; 855 } 856 857 //===----------------------------------------------------------------------===// 858 // TargetLowering queries 859 //===----------------------------------------------------------------------===// 860 861 // v_mad_mix* support a conversion from f16 to f32. 862 // 863 // There is only one special case when denormals are enabled we don't currently, 864 // where this is OK to use. 865 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 866 EVT DestVT, EVT SrcVT) const { 867 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 868 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 869 DestVT.getScalarType() == MVT::f32 && 870 SrcVT.getScalarType() == MVT::f16 && 871 // TODO: This probably only requires no input flushing? 872 !hasFP32Denormals(DAG.getMachineFunction()); 873 } 874 875 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 876 // SI has some legal vector types, but no legal vector operations. Say no 877 // shuffles are legal in order to prefer scalarizing some vector operations. 878 return false; 879 } 880 881 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 882 CallingConv::ID CC, 883 EVT VT) const { 884 if (CC == CallingConv::AMDGPU_KERNEL) 885 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 886 887 if (VT.isVector()) { 888 EVT ScalarVT = VT.getScalarType(); 889 unsigned Size = ScalarVT.getSizeInBits(); 890 if (Size == 32) 891 return ScalarVT.getSimpleVT(); 892 893 if (Size > 32) 894 return MVT::i32; 895 896 if (Size == 16 && Subtarget->has16BitInsts()) 897 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 898 } else if (VT.getSizeInBits() > 32) 899 return MVT::i32; 900 901 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 902 } 903 904 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 905 CallingConv::ID CC, 906 EVT VT) const { 907 if (CC == CallingConv::AMDGPU_KERNEL) 908 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 909 910 if (VT.isVector()) { 911 unsigned NumElts = VT.getVectorNumElements(); 912 EVT ScalarVT = VT.getScalarType(); 913 unsigned Size = ScalarVT.getSizeInBits(); 914 915 if (Size == 32) 916 return NumElts; 917 918 if (Size > 32) 919 return NumElts * ((Size + 31) / 32); 920 921 if (Size == 16 && Subtarget->has16BitInsts()) 922 return (NumElts + 1) / 2; 923 } else if (VT.getSizeInBits() > 32) 924 return (VT.getSizeInBits() + 31) / 32; 925 926 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 927 } 928 929 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 930 LLVMContext &Context, CallingConv::ID CC, 931 EVT VT, EVT &IntermediateVT, 932 unsigned &NumIntermediates, MVT &RegisterVT) const { 933 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 934 unsigned NumElts = VT.getVectorNumElements(); 935 EVT ScalarVT = VT.getScalarType(); 936 unsigned Size = ScalarVT.getSizeInBits(); 937 if (Size == 32) { 938 RegisterVT = ScalarVT.getSimpleVT(); 939 IntermediateVT = RegisterVT; 940 NumIntermediates = NumElts; 941 return NumIntermediates; 942 } 943 944 if (Size > 32) { 945 RegisterVT = MVT::i32; 946 IntermediateVT = RegisterVT; 947 NumIntermediates = NumElts * ((Size + 31) / 32); 948 return NumIntermediates; 949 } 950 951 // FIXME: We should fix the ABI to be the same on targets without 16-bit 952 // support, but unless we can properly handle 3-vectors, it will be still be 953 // inconsistent. 954 if (Size == 16 && Subtarget->has16BitInsts()) { 955 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 956 IntermediateVT = RegisterVT; 957 NumIntermediates = (NumElts + 1) / 2; 958 return NumIntermediates; 959 } 960 } 961 962 return TargetLowering::getVectorTypeBreakdownForCallingConv( 963 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 964 } 965 966 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 967 assert(DMaskLanes != 0); 968 969 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 970 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 971 return EVT::getVectorVT(Ty->getContext(), 972 EVT::getEVT(VT->getElementType()), 973 NumElts); 974 } 975 976 return EVT::getEVT(Ty); 977 } 978 979 // Peek through TFE struct returns to only use the data size. 980 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 981 auto *ST = dyn_cast<StructType>(Ty); 982 if (!ST) 983 return memVTFromImageData(Ty, DMaskLanes); 984 985 // Some intrinsics return an aggregate type - special case to work out the 986 // correct memVT. 987 // 988 // Only limited forms of aggregate type currently expected. 989 if (ST->getNumContainedTypes() != 2 || 990 !ST->getContainedType(1)->isIntegerTy(32)) 991 return EVT(); 992 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 993 } 994 995 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 996 const CallInst &CI, 997 MachineFunction &MF, 998 unsigned IntrID) const { 999 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1000 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1001 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1002 (Intrinsic::ID)IntrID); 1003 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1004 return false; 1005 1006 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1007 1008 if (RsrcIntr->IsImage) { 1009 Info.ptrVal = MFI->getImagePSV( 1010 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1011 CI.getArgOperand(RsrcIntr->RsrcArg)); 1012 Info.align.reset(); 1013 } else { 1014 Info.ptrVal = MFI->getBufferPSV( 1015 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1016 CI.getArgOperand(RsrcIntr->RsrcArg)); 1017 } 1018 1019 Info.flags = MachineMemOperand::MODereferenceable; 1020 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1021 unsigned DMaskLanes = 4; 1022 1023 if (RsrcIntr->IsImage) { 1024 const AMDGPU::ImageDimIntrinsicInfo *Intr 1025 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1026 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1027 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1028 1029 if (!BaseOpcode->Gather4) { 1030 // If this isn't a gather, we may have excess loaded elements in the 1031 // IR type. Check the dmask for the real number of elements loaded. 1032 unsigned DMask 1033 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1034 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1035 } 1036 1037 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1038 } else 1039 Info.memVT = EVT::getEVT(CI.getType()); 1040 1041 // FIXME: What does alignment mean for an image? 1042 Info.opc = ISD::INTRINSIC_W_CHAIN; 1043 Info.flags |= MachineMemOperand::MOLoad; 1044 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1045 Info.opc = ISD::INTRINSIC_VOID; 1046 1047 Type *DataTy = CI.getArgOperand(0)->getType(); 1048 if (RsrcIntr->IsImage) { 1049 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1050 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1051 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1052 } else 1053 Info.memVT = EVT::getEVT(DataTy); 1054 1055 Info.flags |= MachineMemOperand::MOStore; 1056 } else { 1057 // Atomic 1058 Info.opc = ISD::INTRINSIC_W_CHAIN; 1059 Info.memVT = MVT::getVT(CI.getType()); 1060 Info.flags = MachineMemOperand::MOLoad | 1061 MachineMemOperand::MOStore | 1062 MachineMemOperand::MODereferenceable; 1063 1064 // XXX - Should this be volatile without known ordering? 1065 Info.flags |= MachineMemOperand::MOVolatile; 1066 } 1067 return true; 1068 } 1069 1070 switch (IntrID) { 1071 case Intrinsic::amdgcn_atomic_inc: 1072 case Intrinsic::amdgcn_atomic_dec: 1073 case Intrinsic::amdgcn_ds_ordered_add: 1074 case Intrinsic::amdgcn_ds_ordered_swap: 1075 case Intrinsic::amdgcn_ds_fadd: 1076 case Intrinsic::amdgcn_ds_fmin: 1077 case Intrinsic::amdgcn_ds_fmax: { 1078 Info.opc = ISD::INTRINSIC_W_CHAIN; 1079 Info.memVT = MVT::getVT(CI.getType()); 1080 Info.ptrVal = CI.getOperand(0); 1081 Info.align.reset(); 1082 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1083 1084 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1085 if (!Vol->isZero()) 1086 Info.flags |= MachineMemOperand::MOVolatile; 1087 1088 return true; 1089 } 1090 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1091 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1092 1093 Info.opc = ISD::INTRINSIC_VOID; 1094 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1095 Info.ptrVal = MFI->getBufferPSV( 1096 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1097 CI.getArgOperand(1)); 1098 Info.align.reset(); 1099 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1100 1101 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1102 if (!Vol || !Vol->isZero()) 1103 Info.flags |= MachineMemOperand::MOVolatile; 1104 1105 return true; 1106 } 1107 case Intrinsic::amdgcn_global_atomic_fadd: { 1108 Info.opc = ISD::INTRINSIC_VOID; 1109 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1110 ->getPointerElementType()); 1111 Info.ptrVal = CI.getOperand(0); 1112 Info.align.reset(); 1113 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1114 1115 return true; 1116 } 1117 case Intrinsic::amdgcn_ds_append: 1118 case Intrinsic::amdgcn_ds_consume: { 1119 Info.opc = ISD::INTRINSIC_W_CHAIN; 1120 Info.memVT = MVT::getVT(CI.getType()); 1121 Info.ptrVal = CI.getOperand(0); 1122 Info.align.reset(); 1123 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1124 1125 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1126 if (!Vol->isZero()) 1127 Info.flags |= MachineMemOperand::MOVolatile; 1128 1129 return true; 1130 } 1131 case Intrinsic::amdgcn_global_atomic_csub: { 1132 Info.opc = ISD::INTRINSIC_W_CHAIN; 1133 Info.memVT = MVT::getVT(CI.getType()); 1134 Info.ptrVal = CI.getOperand(0); 1135 Info.align.reset(); 1136 Info.flags = MachineMemOperand::MOLoad | 1137 MachineMemOperand::MOStore | 1138 MachineMemOperand::MODereferenceable | 1139 MachineMemOperand::MOVolatile; 1140 return true; 1141 } 1142 case Intrinsic::amdgcn_ds_gws_init: 1143 case Intrinsic::amdgcn_ds_gws_barrier: 1144 case Intrinsic::amdgcn_ds_gws_sema_v: 1145 case Intrinsic::amdgcn_ds_gws_sema_br: 1146 case Intrinsic::amdgcn_ds_gws_sema_p: 1147 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1148 Info.opc = ISD::INTRINSIC_VOID; 1149 1150 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1151 Info.ptrVal = 1152 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1153 1154 // This is an abstract access, but we need to specify a type and size. 1155 Info.memVT = MVT::i32; 1156 Info.size = 4; 1157 Info.align = Align(4); 1158 1159 Info.flags = MachineMemOperand::MOStore; 1160 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1161 Info.flags = MachineMemOperand::MOLoad; 1162 return true; 1163 } 1164 default: 1165 return false; 1166 } 1167 } 1168 1169 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1170 SmallVectorImpl<Value*> &Ops, 1171 Type *&AccessTy) const { 1172 switch (II->getIntrinsicID()) { 1173 case Intrinsic::amdgcn_atomic_inc: 1174 case Intrinsic::amdgcn_atomic_dec: 1175 case Intrinsic::amdgcn_ds_ordered_add: 1176 case Intrinsic::amdgcn_ds_ordered_swap: 1177 case Intrinsic::amdgcn_ds_fadd: 1178 case Intrinsic::amdgcn_ds_fmin: 1179 case Intrinsic::amdgcn_ds_fmax: { 1180 Value *Ptr = II->getArgOperand(0); 1181 AccessTy = II->getType(); 1182 Ops.push_back(Ptr); 1183 return true; 1184 } 1185 default: 1186 return false; 1187 } 1188 } 1189 1190 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1191 if (!Subtarget->hasFlatInstOffsets()) { 1192 // Flat instructions do not have offsets, and only have the register 1193 // address. 1194 return AM.BaseOffs == 0 && AM.Scale == 0; 1195 } 1196 1197 return AM.Scale == 0 && 1198 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1199 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1200 /*Signed=*/false)); 1201 } 1202 1203 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1204 if (Subtarget->hasFlatGlobalInsts()) 1205 return AM.Scale == 0 && 1206 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1207 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1208 /*Signed=*/true)); 1209 1210 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1211 // Assume the we will use FLAT for all global memory accesses 1212 // on VI. 1213 // FIXME: This assumption is currently wrong. On VI we still use 1214 // MUBUF instructions for the r + i addressing mode. As currently 1215 // implemented, the MUBUF instructions only work on buffer < 4GB. 1216 // It may be possible to support > 4GB buffers with MUBUF instructions, 1217 // by setting the stride value in the resource descriptor which would 1218 // increase the size limit to (stride * 4GB). However, this is risky, 1219 // because it has never been validated. 1220 return isLegalFlatAddressingMode(AM); 1221 } 1222 1223 return isLegalMUBUFAddressingMode(AM); 1224 } 1225 1226 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1227 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1228 // additionally can do r + r + i with addr64. 32-bit has more addressing 1229 // mode options. Depending on the resource constant, it can also do 1230 // (i64 r0) + (i32 r1) * (i14 i). 1231 // 1232 // Private arrays end up using a scratch buffer most of the time, so also 1233 // assume those use MUBUF instructions. Scratch loads / stores are currently 1234 // implemented as mubuf instructions with offen bit set, so slightly 1235 // different than the normal addr64. 1236 if (!isUInt<12>(AM.BaseOffs)) 1237 return false; 1238 1239 // FIXME: Since we can split immediate into soffset and immediate offset, 1240 // would it make sense to allow any immediate? 1241 1242 switch (AM.Scale) { 1243 case 0: // r + i or just i, depending on HasBaseReg. 1244 return true; 1245 case 1: 1246 return true; // We have r + r or r + i. 1247 case 2: 1248 if (AM.HasBaseReg) { 1249 // Reject 2 * r + r. 1250 return false; 1251 } 1252 1253 // Allow 2 * r as r + r 1254 // Or 2 * r + i is allowed as r + r + i. 1255 return true; 1256 default: // Don't allow n * r 1257 return false; 1258 } 1259 } 1260 1261 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1262 const AddrMode &AM, Type *Ty, 1263 unsigned AS, Instruction *I) const { 1264 // No global is ever allowed as a base. 1265 if (AM.BaseGV) 1266 return false; 1267 1268 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1269 return isLegalGlobalAddressingMode(AM); 1270 1271 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1272 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1273 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1274 // If the offset isn't a multiple of 4, it probably isn't going to be 1275 // correctly aligned. 1276 // FIXME: Can we get the real alignment here? 1277 if (AM.BaseOffs % 4 != 0) 1278 return isLegalMUBUFAddressingMode(AM); 1279 1280 // There are no SMRD extloads, so if we have to do a small type access we 1281 // will use a MUBUF load. 1282 // FIXME?: We also need to do this if unaligned, but we don't know the 1283 // alignment here. 1284 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1285 return isLegalGlobalAddressingMode(AM); 1286 1287 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1288 // SMRD instructions have an 8-bit, dword offset on SI. 1289 if (!isUInt<8>(AM.BaseOffs / 4)) 1290 return false; 1291 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1292 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1293 // in 8-bits, it can use a smaller encoding. 1294 if (!isUInt<32>(AM.BaseOffs / 4)) 1295 return false; 1296 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1297 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1298 if (!isUInt<20>(AM.BaseOffs)) 1299 return false; 1300 } else 1301 llvm_unreachable("unhandled generation"); 1302 1303 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1304 return true; 1305 1306 if (AM.Scale == 1 && AM.HasBaseReg) 1307 return true; 1308 1309 return false; 1310 1311 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1312 return isLegalMUBUFAddressingMode(AM); 1313 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1314 AS == AMDGPUAS::REGION_ADDRESS) { 1315 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1316 // field. 1317 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1318 // an 8-bit dword offset but we don't know the alignment here. 1319 if (!isUInt<16>(AM.BaseOffs)) 1320 return false; 1321 1322 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1323 return true; 1324 1325 if (AM.Scale == 1 && AM.HasBaseReg) 1326 return true; 1327 1328 return false; 1329 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1330 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1331 // For an unknown address space, this usually means that this is for some 1332 // reason being used for pure arithmetic, and not based on some addressing 1333 // computation. We don't have instructions that compute pointers with any 1334 // addressing modes, so treat them as having no offset like flat 1335 // instructions. 1336 return isLegalFlatAddressingMode(AM); 1337 } 1338 1339 // Assume a user alias of global for unknown address spaces. 1340 return isLegalGlobalAddressingMode(AM); 1341 } 1342 1343 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1344 const SelectionDAG &DAG) const { 1345 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1346 return (MemVT.getSizeInBits() <= 4 * 32); 1347 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1348 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1349 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1350 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1351 return (MemVT.getSizeInBits() <= 2 * 32); 1352 } 1353 return true; 1354 } 1355 1356 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1357 unsigned Size, unsigned AddrSpace, unsigned Align, 1358 MachineMemOperand::Flags Flags, bool *IsFast) const { 1359 if (IsFast) 1360 *IsFast = false; 1361 1362 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1363 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1364 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1365 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1366 // with adjacent offsets. 1367 bool AlignedBy4 = (Align % 4 == 0); 1368 if (IsFast) 1369 *IsFast = AlignedBy4; 1370 1371 return AlignedBy4; 1372 } 1373 1374 // FIXME: We have to be conservative here and assume that flat operations 1375 // will access scratch. If we had access to the IR function, then we 1376 // could determine if any private memory was used in the function. 1377 if (!Subtarget->hasUnalignedScratchAccess() && 1378 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1379 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1380 bool AlignedBy4 = Align >= 4; 1381 if (IsFast) 1382 *IsFast = AlignedBy4; 1383 1384 return AlignedBy4; 1385 } 1386 1387 if (Subtarget->hasUnalignedBufferAccess()) { 1388 // If we have an uniform constant load, it still requires using a slow 1389 // buffer instruction if unaligned. 1390 if (IsFast) { 1391 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1392 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1393 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1394 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1395 Align >= 4 : Align != 2; 1396 } 1397 1398 return true; 1399 } 1400 1401 // Smaller than dword value must be aligned. 1402 if (Size < 32) 1403 return false; 1404 1405 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1406 // byte-address are ignored, thus forcing Dword alignment. 1407 // This applies to private, global, and constant memory. 1408 if (IsFast) 1409 *IsFast = true; 1410 1411 return Size >= 32 && Align >= 4; 1412 } 1413 1414 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1415 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1416 bool *IsFast) const { 1417 if (IsFast) 1418 *IsFast = false; 1419 1420 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1421 // which isn't a simple VT. 1422 // Until MVT is extended to handle this, simply check for the size and 1423 // rely on the condition below: allow accesses if the size is a multiple of 4. 1424 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1425 VT.getStoreSize() > 16)) { 1426 return false; 1427 } 1428 1429 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1430 Align, Flags, IsFast); 1431 } 1432 1433 EVT SITargetLowering::getOptimalMemOpType( 1434 const MemOp &Op, const AttributeList &FuncAttributes) const { 1435 // FIXME: Should account for address space here. 1436 1437 // The default fallback uses the private pointer size as a guess for a type to 1438 // use. Make sure we switch these to 64-bit accesses. 1439 1440 if (Op.size() >= 16 && 1441 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1442 return MVT::v4i32; 1443 1444 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1445 return MVT::v2i32; 1446 1447 // Use the default. 1448 return MVT::Other; 1449 } 1450 1451 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1452 unsigned DestAS) const { 1453 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1454 } 1455 1456 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1457 const MemSDNode *MemNode = cast<MemSDNode>(N); 1458 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1459 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1460 return I && I->getMetadata("amdgpu.noclobber"); 1461 } 1462 1463 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1464 unsigned DestAS) const { 1465 // Flat -> private/local is a simple truncate. 1466 // Flat -> global is no-op 1467 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1468 return true; 1469 1470 return isNoopAddrSpaceCast(SrcAS, DestAS); 1471 } 1472 1473 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1474 const MemSDNode *MemNode = cast<MemSDNode>(N); 1475 1476 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1477 } 1478 1479 TargetLoweringBase::LegalizeTypeAction 1480 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1481 int NumElts = VT.getVectorNumElements(); 1482 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1483 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1484 return TargetLoweringBase::getPreferredVectorAction(VT); 1485 } 1486 1487 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1488 Type *Ty) const { 1489 // FIXME: Could be smarter if called for vector constants. 1490 return true; 1491 } 1492 1493 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1494 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1495 switch (Op) { 1496 case ISD::LOAD: 1497 case ISD::STORE: 1498 1499 // These operations are done with 32-bit instructions anyway. 1500 case ISD::AND: 1501 case ISD::OR: 1502 case ISD::XOR: 1503 case ISD::SELECT: 1504 // TODO: Extensions? 1505 return true; 1506 default: 1507 return false; 1508 } 1509 } 1510 1511 // SimplifySetCC uses this function to determine whether or not it should 1512 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1513 if (VT == MVT::i1 && Op == ISD::SETCC) 1514 return false; 1515 1516 return TargetLowering::isTypeDesirableForOp(Op, VT); 1517 } 1518 1519 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1520 const SDLoc &SL, 1521 SDValue Chain, 1522 uint64_t Offset) const { 1523 const DataLayout &DL = DAG.getDataLayout(); 1524 MachineFunction &MF = DAG.getMachineFunction(); 1525 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1526 1527 const ArgDescriptor *InputPtrReg; 1528 const TargetRegisterClass *RC; 1529 1530 std::tie(InputPtrReg, RC) 1531 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1532 1533 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1534 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1535 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1536 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1537 1538 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1539 } 1540 1541 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1542 const SDLoc &SL) const { 1543 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1544 FIRST_IMPLICIT); 1545 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1546 } 1547 1548 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1549 const SDLoc &SL, SDValue Val, 1550 bool Signed, 1551 const ISD::InputArg *Arg) const { 1552 // First, if it is a widened vector, narrow it. 1553 if (VT.isVector() && 1554 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1555 EVT NarrowedVT = 1556 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1557 VT.getVectorNumElements()); 1558 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1559 DAG.getConstant(0, SL, MVT::i32)); 1560 } 1561 1562 // Then convert the vector elements or scalar value. 1563 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1564 VT.bitsLT(MemVT)) { 1565 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1566 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1567 } 1568 1569 if (MemVT.isFloatingPoint()) 1570 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1571 else if (Signed) 1572 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1573 else 1574 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1575 1576 return Val; 1577 } 1578 1579 SDValue SITargetLowering::lowerKernargMemParameter( 1580 SelectionDAG &DAG, EVT VT, EVT MemVT, 1581 const SDLoc &SL, SDValue Chain, 1582 uint64_t Offset, unsigned Align, bool Signed, 1583 const ISD::InputArg *Arg) const { 1584 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1585 1586 // Try to avoid using an extload by loading earlier than the argument address, 1587 // and extracting the relevant bits. The load should hopefully be merged with 1588 // the previous argument. 1589 if (MemVT.getStoreSize() < 4 && Align < 4) { 1590 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1591 int64_t AlignDownOffset = alignDown(Offset, 4); 1592 int64_t OffsetDiff = Offset - AlignDownOffset; 1593 1594 EVT IntVT = MemVT.changeTypeToInteger(); 1595 1596 // TODO: If we passed in the base kernel offset we could have a better 1597 // alignment than 4, but we don't really need it. 1598 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1599 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1600 MachineMemOperand::MODereferenceable | 1601 MachineMemOperand::MOInvariant); 1602 1603 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1604 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1605 1606 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1607 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1608 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1609 1610 1611 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1612 } 1613 1614 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1615 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1616 MachineMemOperand::MODereferenceable | 1617 MachineMemOperand::MOInvariant); 1618 1619 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1620 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1621 } 1622 1623 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1624 const SDLoc &SL, SDValue Chain, 1625 const ISD::InputArg &Arg) const { 1626 MachineFunction &MF = DAG.getMachineFunction(); 1627 MachineFrameInfo &MFI = MF.getFrameInfo(); 1628 1629 if (Arg.Flags.isByVal()) { 1630 unsigned Size = Arg.Flags.getByValSize(); 1631 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1632 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1633 } 1634 1635 unsigned ArgOffset = VA.getLocMemOffset(); 1636 unsigned ArgSize = VA.getValVT().getStoreSize(); 1637 1638 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1639 1640 // Create load nodes to retrieve arguments from the stack. 1641 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1642 SDValue ArgValue; 1643 1644 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1645 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1646 MVT MemVT = VA.getValVT(); 1647 1648 switch (VA.getLocInfo()) { 1649 default: 1650 break; 1651 case CCValAssign::BCvt: 1652 MemVT = VA.getLocVT(); 1653 break; 1654 case CCValAssign::SExt: 1655 ExtType = ISD::SEXTLOAD; 1656 break; 1657 case CCValAssign::ZExt: 1658 ExtType = ISD::ZEXTLOAD; 1659 break; 1660 case CCValAssign::AExt: 1661 ExtType = ISD::EXTLOAD; 1662 break; 1663 } 1664 1665 ArgValue = DAG.getExtLoad( 1666 ExtType, SL, VA.getLocVT(), Chain, FIN, 1667 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1668 MemVT); 1669 return ArgValue; 1670 } 1671 1672 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1673 const SIMachineFunctionInfo &MFI, 1674 EVT VT, 1675 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1676 const ArgDescriptor *Reg; 1677 const TargetRegisterClass *RC; 1678 1679 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1680 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1681 } 1682 1683 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1684 CallingConv::ID CallConv, 1685 ArrayRef<ISD::InputArg> Ins, 1686 BitVector &Skipped, 1687 FunctionType *FType, 1688 SIMachineFunctionInfo *Info) { 1689 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1690 const ISD::InputArg *Arg = &Ins[I]; 1691 1692 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1693 "vector type argument should have been split"); 1694 1695 // First check if it's a PS input addr. 1696 if (CallConv == CallingConv::AMDGPU_PS && 1697 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1698 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1699 1700 // Inconveniently only the first part of the split is marked as isSplit, 1701 // so skip to the end. We only want to increment PSInputNum once for the 1702 // entire split argument. 1703 if (Arg->Flags.isSplit()) { 1704 while (!Arg->Flags.isSplitEnd()) { 1705 assert((!Arg->VT.isVector() || 1706 Arg->VT.getScalarSizeInBits() == 16) && 1707 "unexpected vector split in ps argument type"); 1708 if (!SkipArg) 1709 Splits.push_back(*Arg); 1710 Arg = &Ins[++I]; 1711 } 1712 } 1713 1714 if (SkipArg) { 1715 // We can safely skip PS inputs. 1716 Skipped.set(Arg->getOrigArgIndex()); 1717 ++PSInputNum; 1718 continue; 1719 } 1720 1721 Info->markPSInputAllocated(PSInputNum); 1722 if (Arg->Used) 1723 Info->markPSInputEnabled(PSInputNum); 1724 1725 ++PSInputNum; 1726 } 1727 1728 Splits.push_back(*Arg); 1729 } 1730 } 1731 1732 // Allocate special inputs passed in VGPRs. 1733 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1734 MachineFunction &MF, 1735 const SIRegisterInfo &TRI, 1736 SIMachineFunctionInfo &Info) const { 1737 const LLT S32 = LLT::scalar(32); 1738 MachineRegisterInfo &MRI = MF.getRegInfo(); 1739 1740 if (Info.hasWorkItemIDX()) { 1741 Register Reg = AMDGPU::VGPR0; 1742 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1743 1744 CCInfo.AllocateReg(Reg); 1745 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1746 } 1747 1748 if (Info.hasWorkItemIDY()) { 1749 Register Reg = AMDGPU::VGPR1; 1750 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1751 1752 CCInfo.AllocateReg(Reg); 1753 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1754 } 1755 1756 if (Info.hasWorkItemIDZ()) { 1757 Register Reg = AMDGPU::VGPR2; 1758 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1759 1760 CCInfo.AllocateReg(Reg); 1761 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1762 } 1763 } 1764 1765 // Try to allocate a VGPR at the end of the argument list, or if no argument 1766 // VGPRs are left allocating a stack slot. 1767 // If \p Mask is is given it indicates bitfield position in the register. 1768 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1769 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1770 ArgDescriptor Arg = ArgDescriptor()) { 1771 if (Arg.isSet()) 1772 return ArgDescriptor::createArg(Arg, Mask); 1773 1774 ArrayRef<MCPhysReg> ArgVGPRs 1775 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1776 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1777 if (RegIdx == ArgVGPRs.size()) { 1778 // Spill to stack required. 1779 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1780 1781 return ArgDescriptor::createStack(Offset, Mask); 1782 } 1783 1784 unsigned Reg = ArgVGPRs[RegIdx]; 1785 Reg = CCInfo.AllocateReg(Reg); 1786 assert(Reg != AMDGPU::NoRegister); 1787 1788 MachineFunction &MF = CCInfo.getMachineFunction(); 1789 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1790 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1791 return ArgDescriptor::createRegister(Reg, Mask); 1792 } 1793 1794 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1795 const TargetRegisterClass *RC, 1796 unsigned NumArgRegs) { 1797 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1798 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1799 if (RegIdx == ArgSGPRs.size()) 1800 report_fatal_error("ran out of SGPRs for arguments"); 1801 1802 unsigned Reg = ArgSGPRs[RegIdx]; 1803 Reg = CCInfo.AllocateReg(Reg); 1804 assert(Reg != AMDGPU::NoRegister); 1805 1806 MachineFunction &MF = CCInfo.getMachineFunction(); 1807 MF.addLiveIn(Reg, RC); 1808 return ArgDescriptor::createRegister(Reg); 1809 } 1810 1811 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1812 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1813 } 1814 1815 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1816 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1817 } 1818 1819 /// Allocate implicit function VGPR arguments at the end of allocated user 1820 /// arguments. 1821 void SITargetLowering::allocateSpecialInputVGPRs( 1822 CCState &CCInfo, MachineFunction &MF, 1823 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1824 const unsigned Mask = 0x3ff; 1825 ArgDescriptor Arg; 1826 1827 if (Info.hasWorkItemIDX()) { 1828 Arg = allocateVGPR32Input(CCInfo, Mask); 1829 Info.setWorkItemIDX(Arg); 1830 } 1831 1832 if (Info.hasWorkItemIDY()) { 1833 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1834 Info.setWorkItemIDY(Arg); 1835 } 1836 1837 if (Info.hasWorkItemIDZ()) 1838 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1839 } 1840 1841 /// Allocate implicit function VGPR arguments in fixed registers. 1842 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1843 CCState &CCInfo, MachineFunction &MF, 1844 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1845 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1846 if (!Reg) 1847 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1848 1849 const unsigned Mask = 0x3ff; 1850 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1851 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1852 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1853 } 1854 1855 void SITargetLowering::allocateSpecialInputSGPRs( 1856 CCState &CCInfo, 1857 MachineFunction &MF, 1858 const SIRegisterInfo &TRI, 1859 SIMachineFunctionInfo &Info) const { 1860 auto &ArgInfo = Info.getArgInfo(); 1861 1862 // TODO: Unify handling with private memory pointers. 1863 1864 if (Info.hasDispatchPtr()) 1865 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1866 1867 if (Info.hasQueuePtr()) 1868 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1869 1870 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1871 // constant offset from the kernarg segment. 1872 if (Info.hasImplicitArgPtr()) 1873 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1874 1875 if (Info.hasDispatchID()) 1876 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1877 1878 // flat_scratch_init is not applicable for non-kernel functions. 1879 1880 if (Info.hasWorkGroupIDX()) 1881 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1882 1883 if (Info.hasWorkGroupIDY()) 1884 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1885 1886 if (Info.hasWorkGroupIDZ()) 1887 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1888 } 1889 1890 // Allocate special inputs passed in user SGPRs. 1891 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1892 MachineFunction &MF, 1893 const SIRegisterInfo &TRI, 1894 SIMachineFunctionInfo &Info) const { 1895 if (Info.hasImplicitBufferPtr()) { 1896 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1897 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1898 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1899 } 1900 1901 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1902 if (Info.hasPrivateSegmentBuffer()) { 1903 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1904 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1905 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1906 } 1907 1908 if (Info.hasDispatchPtr()) { 1909 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1910 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1911 CCInfo.AllocateReg(DispatchPtrReg); 1912 } 1913 1914 if (Info.hasQueuePtr()) { 1915 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1916 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1917 CCInfo.AllocateReg(QueuePtrReg); 1918 } 1919 1920 if (Info.hasKernargSegmentPtr()) { 1921 MachineRegisterInfo &MRI = MF.getRegInfo(); 1922 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1923 CCInfo.AllocateReg(InputPtrReg); 1924 1925 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1926 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1927 } 1928 1929 if (Info.hasDispatchID()) { 1930 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1931 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1932 CCInfo.AllocateReg(DispatchIDReg); 1933 } 1934 1935 if (Info.hasFlatScratchInit()) { 1936 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1937 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1938 CCInfo.AllocateReg(FlatScratchInitReg); 1939 } 1940 1941 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1942 // these from the dispatch pointer. 1943 } 1944 1945 // Allocate special input registers that are initialized per-wave. 1946 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1947 MachineFunction &MF, 1948 SIMachineFunctionInfo &Info, 1949 CallingConv::ID CallConv, 1950 bool IsShader) const { 1951 if (Info.hasWorkGroupIDX()) { 1952 unsigned Reg = Info.addWorkGroupIDX(); 1953 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1954 CCInfo.AllocateReg(Reg); 1955 } 1956 1957 if (Info.hasWorkGroupIDY()) { 1958 unsigned Reg = Info.addWorkGroupIDY(); 1959 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1960 CCInfo.AllocateReg(Reg); 1961 } 1962 1963 if (Info.hasWorkGroupIDZ()) { 1964 unsigned Reg = Info.addWorkGroupIDZ(); 1965 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1966 CCInfo.AllocateReg(Reg); 1967 } 1968 1969 if (Info.hasWorkGroupInfo()) { 1970 unsigned Reg = Info.addWorkGroupInfo(); 1971 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1972 CCInfo.AllocateReg(Reg); 1973 } 1974 1975 if (Info.hasPrivateSegmentWaveByteOffset()) { 1976 // Scratch wave offset passed in system SGPR. 1977 unsigned PrivateSegmentWaveByteOffsetReg; 1978 1979 if (IsShader) { 1980 PrivateSegmentWaveByteOffsetReg = 1981 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1982 1983 // This is true if the scratch wave byte offset doesn't have a fixed 1984 // location. 1985 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1986 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1987 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1988 } 1989 } else 1990 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1991 1992 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1993 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1994 } 1995 } 1996 1997 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1998 MachineFunction &MF, 1999 const SIRegisterInfo &TRI, 2000 SIMachineFunctionInfo &Info) { 2001 // Now that we've figured out where the scratch register inputs are, see if 2002 // should reserve the arguments and use them directly. 2003 MachineFrameInfo &MFI = MF.getFrameInfo(); 2004 bool HasStackObjects = MFI.hasStackObjects(); 2005 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2006 2007 // Record that we know we have non-spill stack objects so we don't need to 2008 // check all stack objects later. 2009 if (HasStackObjects) 2010 Info.setHasNonSpillStackObjects(true); 2011 2012 // Everything live out of a block is spilled with fast regalloc, so it's 2013 // almost certain that spilling will be required. 2014 if (TM.getOptLevel() == CodeGenOpt::None) 2015 HasStackObjects = true; 2016 2017 // For now assume stack access is needed in any callee functions, so we need 2018 // the scratch registers to pass in. 2019 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2020 2021 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2022 // If we have stack objects, we unquestionably need the private buffer 2023 // resource. For the Code Object V2 ABI, this will be the first 4 user 2024 // SGPR inputs. We can reserve those and use them directly. 2025 2026 Register PrivateSegmentBufferReg = 2027 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2028 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2029 } else { 2030 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2031 // We tentatively reserve the last registers (skipping the last registers 2032 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2033 // we'll replace these with the ones immediately after those which were 2034 // really allocated. In the prologue copies will be inserted from the 2035 // argument to these reserved registers. 2036 2037 // Without HSA, relocations are used for the scratch pointer and the 2038 // buffer resource setup is always inserted in the prologue. Scratch wave 2039 // offset is still in an input SGPR. 2040 Info.setScratchRSrcReg(ReservedBufferReg); 2041 } 2042 2043 MachineRegisterInfo &MRI = MF.getRegInfo(); 2044 2045 // For entry functions we have to set up the stack pointer if we use it, 2046 // whereas non-entry functions get this "for free". This means there is no 2047 // intrinsic advantage to using S32 over S34 in cases where we do not have 2048 // calls but do need a frame pointer (i.e. if we are requested to have one 2049 // because frame pointer elimination is disabled). To keep things simple we 2050 // only ever use S32 as the call ABI stack pointer, and so using it does not 2051 // imply we need a separate frame pointer. 2052 // 2053 // Try to use s32 as the SP, but move it if it would interfere with input 2054 // arguments. This won't work with calls though. 2055 // 2056 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2057 // registers. 2058 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2059 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2060 } else { 2061 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2062 2063 if (MFI.hasCalls()) 2064 report_fatal_error("call in graphics shader with too many input SGPRs"); 2065 2066 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2067 if (!MRI.isLiveIn(Reg)) { 2068 Info.setStackPtrOffsetReg(Reg); 2069 break; 2070 } 2071 } 2072 2073 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2074 report_fatal_error("failed to find register for SP"); 2075 } 2076 2077 // hasFP should be accurate for entry functions even before the frame is 2078 // finalized, because it does not rely on the known stack size, only 2079 // properties like whether variable sized objects are present. 2080 if (ST.getFrameLowering()->hasFP(MF)) { 2081 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2082 } 2083 } 2084 2085 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2086 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2087 return !Info->isEntryFunction(); 2088 } 2089 2090 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2091 2092 } 2093 2094 void SITargetLowering::insertCopiesSplitCSR( 2095 MachineBasicBlock *Entry, 2096 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2097 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2098 2099 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2100 if (!IStart) 2101 return; 2102 2103 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2104 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2105 MachineBasicBlock::iterator MBBI = Entry->begin(); 2106 for (const MCPhysReg *I = IStart; *I; ++I) { 2107 const TargetRegisterClass *RC = nullptr; 2108 if (AMDGPU::SReg_64RegClass.contains(*I)) 2109 RC = &AMDGPU::SGPR_64RegClass; 2110 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2111 RC = &AMDGPU::SGPR_32RegClass; 2112 else 2113 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2114 2115 Register NewVR = MRI->createVirtualRegister(RC); 2116 // Create copy from CSR to a virtual register. 2117 Entry->addLiveIn(*I); 2118 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2119 .addReg(*I); 2120 2121 // Insert the copy-back instructions right before the terminator. 2122 for (auto *Exit : Exits) 2123 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2124 TII->get(TargetOpcode::COPY), *I) 2125 .addReg(NewVR); 2126 } 2127 } 2128 2129 SDValue SITargetLowering::LowerFormalArguments( 2130 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2131 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2132 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2133 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2134 2135 MachineFunction &MF = DAG.getMachineFunction(); 2136 const Function &Fn = MF.getFunction(); 2137 FunctionType *FType = MF.getFunction().getFunctionType(); 2138 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2139 2140 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2141 DiagnosticInfoUnsupported NoGraphicsHSA( 2142 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2143 DAG.getContext()->diagnose(NoGraphicsHSA); 2144 return DAG.getEntryNode(); 2145 } 2146 2147 SmallVector<ISD::InputArg, 16> Splits; 2148 SmallVector<CCValAssign, 16> ArgLocs; 2149 BitVector Skipped(Ins.size()); 2150 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2151 *DAG.getContext()); 2152 2153 bool IsShader = AMDGPU::isShader(CallConv); 2154 bool IsKernel = AMDGPU::isKernel(CallConv); 2155 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2156 2157 if (IsShader) { 2158 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2159 2160 // At least one interpolation mode must be enabled or else the GPU will 2161 // hang. 2162 // 2163 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2164 // set PSInputAddr, the user wants to enable some bits after the compilation 2165 // based on run-time states. Since we can't know what the final PSInputEna 2166 // will look like, so we shouldn't do anything here and the user should take 2167 // responsibility for the correct programming. 2168 // 2169 // Otherwise, the following restrictions apply: 2170 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2171 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2172 // enabled too. 2173 if (CallConv == CallingConv::AMDGPU_PS) { 2174 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2175 ((Info->getPSInputAddr() & 0xF) == 0 && 2176 Info->isPSInputAllocated(11))) { 2177 CCInfo.AllocateReg(AMDGPU::VGPR0); 2178 CCInfo.AllocateReg(AMDGPU::VGPR1); 2179 Info->markPSInputAllocated(0); 2180 Info->markPSInputEnabled(0); 2181 } 2182 if (Subtarget->isAmdPalOS()) { 2183 // For isAmdPalOS, the user does not enable some bits after compilation 2184 // based on run-time states; the register values being generated here are 2185 // the final ones set in hardware. Therefore we need to apply the 2186 // workaround to PSInputAddr and PSInputEnable together. (The case where 2187 // a bit is set in PSInputAddr but not PSInputEnable is where the 2188 // frontend set up an input arg for a particular interpolation mode, but 2189 // nothing uses that input arg. Really we should have an earlier pass 2190 // that removes such an arg.) 2191 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2192 if ((PsInputBits & 0x7F) == 0 || 2193 ((PsInputBits & 0xF) == 0 && 2194 (PsInputBits >> 11 & 1))) 2195 Info->markPSInputEnabled( 2196 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2197 } 2198 } 2199 2200 assert(!Info->hasDispatchPtr() && 2201 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2202 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2203 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2204 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2205 !Info->hasWorkItemIDZ()); 2206 } else if (IsKernel) { 2207 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2208 } else { 2209 Splits.append(Ins.begin(), Ins.end()); 2210 } 2211 2212 if (IsEntryFunc) { 2213 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2214 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2215 } else { 2216 // For the fixed ABI, pass workitem IDs in the last argument register. 2217 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2218 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2219 } 2220 2221 if (IsKernel) { 2222 analyzeFormalArgumentsCompute(CCInfo, Ins); 2223 } else { 2224 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2225 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2226 } 2227 2228 SmallVector<SDValue, 16> Chains; 2229 2230 // FIXME: This is the minimum kernel argument alignment. We should improve 2231 // this to the maximum alignment of the arguments. 2232 // 2233 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2234 // kern arg offset. 2235 const unsigned KernelArgBaseAlign = 16; 2236 2237 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2238 const ISD::InputArg &Arg = Ins[i]; 2239 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2240 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2241 continue; 2242 } 2243 2244 CCValAssign &VA = ArgLocs[ArgIdx++]; 2245 MVT VT = VA.getLocVT(); 2246 2247 if (IsEntryFunc && VA.isMemLoc()) { 2248 VT = Ins[i].VT; 2249 EVT MemVT = VA.getLocVT(); 2250 2251 const uint64_t Offset = VA.getLocMemOffset(); 2252 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2253 2254 SDValue Arg = lowerKernargMemParameter( 2255 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2256 Chains.push_back(Arg.getValue(1)); 2257 2258 auto *ParamTy = 2259 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2260 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2261 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2262 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2263 // On SI local pointers are just offsets into LDS, so they are always 2264 // less than 16-bits. On CI and newer they could potentially be 2265 // real pointers, so we can't guarantee their size. 2266 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2267 DAG.getValueType(MVT::i16)); 2268 } 2269 2270 InVals.push_back(Arg); 2271 continue; 2272 } else if (!IsEntryFunc && VA.isMemLoc()) { 2273 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2274 InVals.push_back(Val); 2275 if (!Arg.Flags.isByVal()) 2276 Chains.push_back(Val.getValue(1)); 2277 continue; 2278 } 2279 2280 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2281 2282 Register Reg = VA.getLocReg(); 2283 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2284 EVT ValVT = VA.getValVT(); 2285 2286 Reg = MF.addLiveIn(Reg, RC); 2287 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2288 2289 if (Arg.Flags.isSRet()) { 2290 // The return object should be reasonably addressable. 2291 2292 // FIXME: This helps when the return is a real sret. If it is a 2293 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2294 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2295 unsigned NumBits 2296 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2297 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2298 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2299 } 2300 2301 // If this is an 8 or 16-bit value, it is really passed promoted 2302 // to 32 bits. Insert an assert[sz]ext to capture this, then 2303 // truncate to the right size. 2304 switch (VA.getLocInfo()) { 2305 case CCValAssign::Full: 2306 break; 2307 case CCValAssign::BCvt: 2308 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2309 break; 2310 case CCValAssign::SExt: 2311 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2312 DAG.getValueType(ValVT)); 2313 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2314 break; 2315 case CCValAssign::ZExt: 2316 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2317 DAG.getValueType(ValVT)); 2318 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2319 break; 2320 case CCValAssign::AExt: 2321 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2322 break; 2323 default: 2324 llvm_unreachable("Unknown loc info!"); 2325 } 2326 2327 InVals.push_back(Val); 2328 } 2329 2330 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2331 // Special inputs come after user arguments. 2332 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2333 } 2334 2335 // Start adding system SGPRs. 2336 if (IsEntryFunc) { 2337 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2338 } else { 2339 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2340 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2341 } 2342 2343 auto &ArgUsageInfo = 2344 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2345 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2346 2347 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2348 Info->setBytesInStackArgArea(StackArgSize); 2349 2350 return Chains.empty() ? Chain : 2351 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2352 } 2353 2354 // TODO: If return values can't fit in registers, we should return as many as 2355 // possible in registers before passing on stack. 2356 bool SITargetLowering::CanLowerReturn( 2357 CallingConv::ID CallConv, 2358 MachineFunction &MF, bool IsVarArg, 2359 const SmallVectorImpl<ISD::OutputArg> &Outs, 2360 LLVMContext &Context) const { 2361 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2362 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2363 // for shaders. Vector types should be explicitly handled by CC. 2364 if (AMDGPU::isEntryFunctionCC(CallConv)) 2365 return true; 2366 2367 SmallVector<CCValAssign, 16> RVLocs; 2368 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2369 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2370 } 2371 2372 SDValue 2373 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2374 bool isVarArg, 2375 const SmallVectorImpl<ISD::OutputArg> &Outs, 2376 const SmallVectorImpl<SDValue> &OutVals, 2377 const SDLoc &DL, SelectionDAG &DAG) const { 2378 MachineFunction &MF = DAG.getMachineFunction(); 2379 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2380 2381 if (AMDGPU::isKernel(CallConv)) { 2382 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2383 OutVals, DL, DAG); 2384 } 2385 2386 bool IsShader = AMDGPU::isShader(CallConv); 2387 2388 Info->setIfReturnsVoid(Outs.empty()); 2389 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2390 2391 // CCValAssign - represent the assignment of the return value to a location. 2392 SmallVector<CCValAssign, 48> RVLocs; 2393 SmallVector<ISD::OutputArg, 48> Splits; 2394 2395 // CCState - Info about the registers and stack slots. 2396 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2397 *DAG.getContext()); 2398 2399 // Analyze outgoing return values. 2400 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2401 2402 SDValue Flag; 2403 SmallVector<SDValue, 48> RetOps; 2404 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2405 2406 // Add return address for callable functions. 2407 if (!Info->isEntryFunction()) { 2408 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2409 SDValue ReturnAddrReg = CreateLiveInRegister( 2410 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2411 2412 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2413 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2414 MVT::i64); 2415 Chain = 2416 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2417 Flag = Chain.getValue(1); 2418 RetOps.push_back(ReturnAddrVirtualReg); 2419 } 2420 2421 // Copy the result values into the output registers. 2422 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2423 ++I, ++RealRVLocIdx) { 2424 CCValAssign &VA = RVLocs[I]; 2425 assert(VA.isRegLoc() && "Can only return in registers!"); 2426 // TODO: Partially return in registers if return values don't fit. 2427 SDValue Arg = OutVals[RealRVLocIdx]; 2428 2429 // Copied from other backends. 2430 switch (VA.getLocInfo()) { 2431 case CCValAssign::Full: 2432 break; 2433 case CCValAssign::BCvt: 2434 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2435 break; 2436 case CCValAssign::SExt: 2437 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2438 break; 2439 case CCValAssign::ZExt: 2440 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2441 break; 2442 case CCValAssign::AExt: 2443 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2444 break; 2445 default: 2446 llvm_unreachable("Unknown loc info!"); 2447 } 2448 2449 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2450 Flag = Chain.getValue(1); 2451 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2452 } 2453 2454 // FIXME: Does sret work properly? 2455 if (!Info->isEntryFunction()) { 2456 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2457 const MCPhysReg *I = 2458 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2459 if (I) { 2460 for (; *I; ++I) { 2461 if (AMDGPU::SReg_64RegClass.contains(*I)) 2462 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2463 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2464 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2465 else 2466 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2467 } 2468 } 2469 } 2470 2471 // Update chain and glue. 2472 RetOps[0] = Chain; 2473 if (Flag.getNode()) 2474 RetOps.push_back(Flag); 2475 2476 unsigned Opc = AMDGPUISD::ENDPGM; 2477 if (!IsWaveEnd) 2478 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2479 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2480 } 2481 2482 SDValue SITargetLowering::LowerCallResult( 2483 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2484 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2485 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2486 SDValue ThisVal) const { 2487 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2488 2489 // Assign locations to each value returned by this call. 2490 SmallVector<CCValAssign, 16> RVLocs; 2491 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2492 *DAG.getContext()); 2493 CCInfo.AnalyzeCallResult(Ins, RetCC); 2494 2495 // Copy all of the result registers out of their specified physreg. 2496 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2497 CCValAssign VA = RVLocs[i]; 2498 SDValue Val; 2499 2500 if (VA.isRegLoc()) { 2501 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2502 Chain = Val.getValue(1); 2503 InFlag = Val.getValue(2); 2504 } else if (VA.isMemLoc()) { 2505 report_fatal_error("TODO: return values in memory"); 2506 } else 2507 llvm_unreachable("unknown argument location type"); 2508 2509 switch (VA.getLocInfo()) { 2510 case CCValAssign::Full: 2511 break; 2512 case CCValAssign::BCvt: 2513 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2514 break; 2515 case CCValAssign::ZExt: 2516 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2517 DAG.getValueType(VA.getValVT())); 2518 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2519 break; 2520 case CCValAssign::SExt: 2521 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2522 DAG.getValueType(VA.getValVT())); 2523 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2524 break; 2525 case CCValAssign::AExt: 2526 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2527 break; 2528 default: 2529 llvm_unreachable("Unknown loc info!"); 2530 } 2531 2532 InVals.push_back(Val); 2533 } 2534 2535 return Chain; 2536 } 2537 2538 // Add code to pass special inputs required depending on used features separate 2539 // from the explicit user arguments present in the IR. 2540 void SITargetLowering::passSpecialInputs( 2541 CallLoweringInfo &CLI, 2542 CCState &CCInfo, 2543 const SIMachineFunctionInfo &Info, 2544 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2545 SmallVectorImpl<SDValue> &MemOpChains, 2546 SDValue Chain) const { 2547 // If we don't have a call site, this was a call inserted by 2548 // legalization. These can never use special inputs. 2549 if (!CLI.CB) 2550 return; 2551 2552 SelectionDAG &DAG = CLI.DAG; 2553 const SDLoc &DL = CLI.DL; 2554 2555 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2556 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2557 2558 const AMDGPUFunctionArgInfo *CalleeArgInfo 2559 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2560 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2561 auto &ArgUsageInfo = 2562 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2563 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2564 } 2565 2566 // TODO: Unify with private memory register handling. This is complicated by 2567 // the fact that at least in kernels, the input argument is not necessarily 2568 // in the same location as the input. 2569 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2570 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2571 AMDGPUFunctionArgInfo::QUEUE_PTR, 2572 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2573 AMDGPUFunctionArgInfo::DISPATCH_ID, 2574 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2575 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2576 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2577 }; 2578 2579 for (auto InputID : InputRegs) { 2580 const ArgDescriptor *OutgoingArg; 2581 const TargetRegisterClass *ArgRC; 2582 2583 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2584 if (!OutgoingArg) 2585 continue; 2586 2587 const ArgDescriptor *IncomingArg; 2588 const TargetRegisterClass *IncomingArgRC; 2589 std::tie(IncomingArg, IncomingArgRC) 2590 = CallerArgInfo.getPreloadedValue(InputID); 2591 assert(IncomingArgRC == ArgRC); 2592 2593 // All special arguments are ints for now. 2594 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2595 SDValue InputReg; 2596 2597 if (IncomingArg) { 2598 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2599 } else { 2600 // The implicit arg ptr is special because it doesn't have a corresponding 2601 // input for kernels, and is computed from the kernarg segment pointer. 2602 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2603 InputReg = getImplicitArgPtr(DAG, DL); 2604 } 2605 2606 if (OutgoingArg->isRegister()) { 2607 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2608 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2609 report_fatal_error("failed to allocate implicit input argument"); 2610 } else { 2611 unsigned SpecialArgOffset = 2612 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2613 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2614 SpecialArgOffset); 2615 MemOpChains.push_back(ArgStore); 2616 } 2617 } 2618 2619 // Pack workitem IDs into a single register or pass it as is if already 2620 // packed. 2621 const ArgDescriptor *OutgoingArg; 2622 const TargetRegisterClass *ArgRC; 2623 2624 std::tie(OutgoingArg, ArgRC) = 2625 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2626 if (!OutgoingArg) 2627 std::tie(OutgoingArg, ArgRC) = 2628 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2629 if (!OutgoingArg) 2630 std::tie(OutgoingArg, ArgRC) = 2631 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2632 if (!OutgoingArg) 2633 return; 2634 2635 const ArgDescriptor *IncomingArgX 2636 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2637 const ArgDescriptor *IncomingArgY 2638 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2639 const ArgDescriptor *IncomingArgZ 2640 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2641 2642 SDValue InputReg; 2643 SDLoc SL; 2644 2645 // If incoming ids are not packed we need to pack them. 2646 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2647 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2648 2649 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2650 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2651 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2652 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2653 InputReg = InputReg.getNode() ? 2654 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2655 } 2656 2657 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2658 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2659 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2660 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2661 InputReg = InputReg.getNode() ? 2662 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2663 } 2664 2665 if (!InputReg.getNode()) { 2666 // Workitem ids are already packed, any of present incoming arguments 2667 // will carry all required fields. 2668 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2669 IncomingArgX ? *IncomingArgX : 2670 IncomingArgY ? *IncomingArgY : 2671 *IncomingArgZ, ~0u); 2672 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2673 } 2674 2675 if (OutgoingArg->isRegister()) { 2676 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2677 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2678 } else { 2679 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2680 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2681 SpecialArgOffset); 2682 MemOpChains.push_back(ArgStore); 2683 } 2684 } 2685 2686 static bool canGuaranteeTCO(CallingConv::ID CC) { 2687 return CC == CallingConv::Fast; 2688 } 2689 2690 /// Return true if we might ever do TCO for calls with this calling convention. 2691 static bool mayTailCallThisCC(CallingConv::ID CC) { 2692 switch (CC) { 2693 case CallingConv::C: 2694 return true; 2695 default: 2696 return canGuaranteeTCO(CC); 2697 } 2698 } 2699 2700 bool SITargetLowering::isEligibleForTailCallOptimization( 2701 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2702 const SmallVectorImpl<ISD::OutputArg> &Outs, 2703 const SmallVectorImpl<SDValue> &OutVals, 2704 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2705 if (!mayTailCallThisCC(CalleeCC)) 2706 return false; 2707 2708 MachineFunction &MF = DAG.getMachineFunction(); 2709 const Function &CallerF = MF.getFunction(); 2710 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2711 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2712 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2713 2714 // Kernels aren't callable, and don't have a live in return address so it 2715 // doesn't make sense to do a tail call with entry functions. 2716 if (!CallerPreserved) 2717 return false; 2718 2719 bool CCMatch = CallerCC == CalleeCC; 2720 2721 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2722 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2723 return true; 2724 return false; 2725 } 2726 2727 // TODO: Can we handle var args? 2728 if (IsVarArg) 2729 return false; 2730 2731 for (const Argument &Arg : CallerF.args()) { 2732 if (Arg.hasByValAttr()) 2733 return false; 2734 } 2735 2736 LLVMContext &Ctx = *DAG.getContext(); 2737 2738 // Check that the call results are passed in the same way. 2739 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2740 CCAssignFnForCall(CalleeCC, IsVarArg), 2741 CCAssignFnForCall(CallerCC, IsVarArg))) 2742 return false; 2743 2744 // The callee has to preserve all registers the caller needs to preserve. 2745 if (!CCMatch) { 2746 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2747 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2748 return false; 2749 } 2750 2751 // Nothing more to check if the callee is taking no arguments. 2752 if (Outs.empty()) 2753 return true; 2754 2755 SmallVector<CCValAssign, 16> ArgLocs; 2756 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2757 2758 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2759 2760 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2761 // If the stack arguments for this call do not fit into our own save area then 2762 // the call cannot be made tail. 2763 // TODO: Is this really necessary? 2764 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2765 return false; 2766 2767 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2768 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2769 } 2770 2771 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2772 if (!CI->isTailCall()) 2773 return false; 2774 2775 const Function *ParentFn = CI->getParent()->getParent(); 2776 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2777 return false; 2778 return true; 2779 } 2780 2781 // The wave scratch offset register is used as the global base pointer. 2782 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2783 SmallVectorImpl<SDValue> &InVals) const { 2784 SelectionDAG &DAG = CLI.DAG; 2785 const SDLoc &DL = CLI.DL; 2786 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2787 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2788 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2789 SDValue Chain = CLI.Chain; 2790 SDValue Callee = CLI.Callee; 2791 bool &IsTailCall = CLI.IsTailCall; 2792 CallingConv::ID CallConv = CLI.CallConv; 2793 bool IsVarArg = CLI.IsVarArg; 2794 bool IsSibCall = false; 2795 bool IsThisReturn = false; 2796 MachineFunction &MF = DAG.getMachineFunction(); 2797 2798 if (Callee.isUndef() || isNullConstant(Callee)) { 2799 if (!CLI.IsTailCall) { 2800 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2801 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2802 } 2803 2804 return Chain; 2805 } 2806 2807 if (IsVarArg) { 2808 return lowerUnhandledCall(CLI, InVals, 2809 "unsupported call to variadic function "); 2810 } 2811 2812 if (!CLI.CB) 2813 report_fatal_error("unsupported libcall legalization"); 2814 2815 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2816 !CLI.CB->getCalledFunction()) { 2817 return lowerUnhandledCall(CLI, InVals, 2818 "unsupported indirect call to function "); 2819 } 2820 2821 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2822 return lowerUnhandledCall(CLI, InVals, 2823 "unsupported required tail call to function "); 2824 } 2825 2826 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2827 // Note the issue is with the CC of the calling function, not of the call 2828 // itself. 2829 return lowerUnhandledCall(CLI, InVals, 2830 "unsupported call from graphics shader of function "); 2831 } 2832 2833 if (IsTailCall) { 2834 IsTailCall = isEligibleForTailCallOptimization( 2835 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2836 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2837 report_fatal_error("failed to perform tail call elimination on a call " 2838 "site marked musttail"); 2839 } 2840 2841 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2842 2843 // A sibling call is one where we're under the usual C ABI and not planning 2844 // to change that but can still do a tail call: 2845 if (!TailCallOpt && IsTailCall) 2846 IsSibCall = true; 2847 2848 if (IsTailCall) 2849 ++NumTailCalls; 2850 } 2851 2852 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2853 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2854 SmallVector<SDValue, 8> MemOpChains; 2855 2856 // Analyze operands of the call, assigning locations to each operand. 2857 SmallVector<CCValAssign, 16> ArgLocs; 2858 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2859 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2860 2861 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2862 // With a fixed ABI, allocate fixed registers before user arguments. 2863 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2864 } 2865 2866 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2867 2868 // Get a count of how many bytes are to be pushed on the stack. 2869 unsigned NumBytes = CCInfo.getNextStackOffset(); 2870 2871 if (IsSibCall) { 2872 // Since we're not changing the ABI to make this a tail call, the memory 2873 // operands are already available in the caller's incoming argument space. 2874 NumBytes = 0; 2875 } 2876 2877 // FPDiff is the byte offset of the call's argument area from the callee's. 2878 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2879 // by this amount for a tail call. In a sibling call it must be 0 because the 2880 // caller will deallocate the entire stack and the callee still expects its 2881 // arguments to begin at SP+0. Completely unused for non-tail calls. 2882 int32_t FPDiff = 0; 2883 MachineFrameInfo &MFI = MF.getFrameInfo(); 2884 2885 // Adjust the stack pointer for the new arguments... 2886 // These operations are automatically eliminated by the prolog/epilog pass 2887 if (!IsSibCall) { 2888 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2889 2890 SmallVector<SDValue, 4> CopyFromChains; 2891 2892 // In the HSA case, this should be an identity copy. 2893 SDValue ScratchRSrcReg 2894 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2895 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2896 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2897 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2898 } 2899 2900 MVT PtrVT = MVT::i32; 2901 2902 // Walk the register/memloc assignments, inserting copies/loads. 2903 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2904 CCValAssign &VA = ArgLocs[i]; 2905 SDValue Arg = OutVals[i]; 2906 2907 // Promote the value if needed. 2908 switch (VA.getLocInfo()) { 2909 case CCValAssign::Full: 2910 break; 2911 case CCValAssign::BCvt: 2912 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2913 break; 2914 case CCValAssign::ZExt: 2915 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2916 break; 2917 case CCValAssign::SExt: 2918 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2919 break; 2920 case CCValAssign::AExt: 2921 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2922 break; 2923 case CCValAssign::FPExt: 2924 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2925 break; 2926 default: 2927 llvm_unreachable("Unknown loc info!"); 2928 } 2929 2930 if (VA.isRegLoc()) { 2931 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2932 } else { 2933 assert(VA.isMemLoc()); 2934 2935 SDValue DstAddr; 2936 MachinePointerInfo DstInfo; 2937 2938 unsigned LocMemOffset = VA.getLocMemOffset(); 2939 int32_t Offset = LocMemOffset; 2940 2941 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2942 MaybeAlign Alignment; 2943 2944 if (IsTailCall) { 2945 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2946 unsigned OpSize = Flags.isByVal() ? 2947 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2948 2949 // FIXME: We can have better than the minimum byval required alignment. 2950 Alignment = 2951 Flags.isByVal() 2952 ? Flags.getNonZeroByValAlign() 2953 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2954 2955 Offset = Offset + FPDiff; 2956 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2957 2958 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2959 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2960 2961 // Make sure any stack arguments overlapping with where we're storing 2962 // are loaded before this eventual operation. Otherwise they'll be 2963 // clobbered. 2964 2965 // FIXME: Why is this really necessary? This seems to just result in a 2966 // lot of code to copy the stack and write them back to the same 2967 // locations, which are supposed to be immutable? 2968 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2969 } else { 2970 DstAddr = PtrOff; 2971 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2972 Alignment = 2973 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2974 } 2975 2976 if (Outs[i].Flags.isByVal()) { 2977 SDValue SizeNode = 2978 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2979 SDValue Cpy = 2980 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2981 Outs[i].Flags.getNonZeroByValAlign(), 2982 /*isVol = */ false, /*AlwaysInline = */ true, 2983 /*isTailCall = */ false, DstInfo, 2984 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2985 2986 MemOpChains.push_back(Cpy); 2987 } else { 2988 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2989 Alignment ? Alignment->value() : 0); 2990 MemOpChains.push_back(Store); 2991 } 2992 } 2993 } 2994 2995 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2996 // Copy special input registers after user input arguments. 2997 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2998 } 2999 3000 if (!MemOpChains.empty()) 3001 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3002 3003 // Build a sequence of copy-to-reg nodes chained together with token chain 3004 // and flag operands which copy the outgoing args into the appropriate regs. 3005 SDValue InFlag; 3006 for (auto &RegToPass : RegsToPass) { 3007 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3008 RegToPass.second, InFlag); 3009 InFlag = Chain.getValue(1); 3010 } 3011 3012 3013 SDValue PhysReturnAddrReg; 3014 if (IsTailCall) { 3015 // Since the return is being combined with the call, we need to pass on the 3016 // return address. 3017 3018 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3019 SDValue ReturnAddrReg = CreateLiveInRegister( 3020 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3021 3022 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3023 MVT::i64); 3024 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3025 InFlag = Chain.getValue(1); 3026 } 3027 3028 // We don't usually want to end the call-sequence here because we would tidy 3029 // the frame up *after* the call, however in the ABI-changing tail-call case 3030 // we've carefully laid out the parameters so that when sp is reset they'll be 3031 // in the correct location. 3032 if (IsTailCall && !IsSibCall) { 3033 Chain = DAG.getCALLSEQ_END(Chain, 3034 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3035 DAG.getTargetConstant(0, DL, MVT::i32), 3036 InFlag, DL); 3037 InFlag = Chain.getValue(1); 3038 } 3039 3040 std::vector<SDValue> Ops; 3041 Ops.push_back(Chain); 3042 Ops.push_back(Callee); 3043 // Add a redundant copy of the callee global which will not be legalized, as 3044 // we need direct access to the callee later. 3045 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3046 const GlobalValue *GV = GSD->getGlobal(); 3047 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3048 } else { 3049 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3050 } 3051 3052 if (IsTailCall) { 3053 // Each tail call may have to adjust the stack by a different amount, so 3054 // this information must travel along with the operation for eventual 3055 // consumption by emitEpilogue. 3056 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3057 3058 Ops.push_back(PhysReturnAddrReg); 3059 } 3060 3061 // Add argument registers to the end of the list so that they are known live 3062 // into the call. 3063 for (auto &RegToPass : RegsToPass) { 3064 Ops.push_back(DAG.getRegister(RegToPass.first, 3065 RegToPass.second.getValueType())); 3066 } 3067 3068 // Add a register mask operand representing the call-preserved registers. 3069 3070 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3071 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3072 assert(Mask && "Missing call preserved mask for calling convention"); 3073 Ops.push_back(DAG.getRegisterMask(Mask)); 3074 3075 if (InFlag.getNode()) 3076 Ops.push_back(InFlag); 3077 3078 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3079 3080 // If we're doing a tall call, use a TC_RETURN here rather than an 3081 // actual call instruction. 3082 if (IsTailCall) { 3083 MFI.setHasTailCall(); 3084 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3085 } 3086 3087 // Returns a chain and a flag for retval copy to use. 3088 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3089 Chain = Call.getValue(0); 3090 InFlag = Call.getValue(1); 3091 3092 uint64_t CalleePopBytes = NumBytes; 3093 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3094 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3095 InFlag, DL); 3096 if (!Ins.empty()) 3097 InFlag = Chain.getValue(1); 3098 3099 // Handle result values, copying them out of physregs into vregs that we 3100 // return. 3101 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3102 InVals, IsThisReturn, 3103 IsThisReturn ? OutVals[0] : SDValue()); 3104 } 3105 3106 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3107 // except for applying the wave size scale to the increment amount. 3108 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3109 SDValue Op, SelectionDAG &DAG) const { 3110 const MachineFunction &MF = DAG.getMachineFunction(); 3111 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3112 3113 SDLoc dl(Op); 3114 EVT VT = Op.getValueType(); 3115 SDValue Tmp1 = Op; 3116 SDValue Tmp2 = Op.getValue(1); 3117 SDValue Tmp3 = Op.getOperand(2); 3118 SDValue Chain = Tmp1.getOperand(0); 3119 3120 Register SPReg = Info->getStackPtrOffsetReg(); 3121 3122 // Chain the dynamic stack allocation so that it doesn't modify the stack 3123 // pointer when other instructions are using the stack. 3124 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3125 3126 SDValue Size = Tmp2.getOperand(1); 3127 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3128 Chain = SP.getValue(1); 3129 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue(); 3130 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3131 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3132 unsigned Opc = 3133 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3134 ISD::ADD : ISD::SUB; 3135 3136 SDValue ScaledSize = DAG.getNode( 3137 ISD::SHL, dl, VT, Size, 3138 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3139 3140 unsigned StackAlign = TFL->getStackAlignment(); 3141 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3142 if (Align > StackAlign) { 3143 Tmp1 = DAG.getNode( 3144 ISD::AND, dl, VT, Tmp1, 3145 DAG.getConstant(-(uint64_t)Align << ST.getWavefrontSizeLog2(), dl, VT)); 3146 } 3147 3148 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3149 Tmp2 = DAG.getCALLSEQ_END( 3150 Chain, DAG.getIntPtrConstant(0, dl, true), 3151 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3152 3153 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3154 } 3155 3156 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3157 SelectionDAG &DAG) const { 3158 // We only handle constant sizes here to allow non-entry block, static sized 3159 // allocas. A truly dynamic value is more difficult to support because we 3160 // don't know if the size value is uniform or not. If the size isn't uniform, 3161 // we would need to do a wave reduction to get the maximum size to know how 3162 // much to increment the uniform stack pointer. 3163 SDValue Size = Op.getOperand(1); 3164 if (isa<ConstantSDNode>(Size)) 3165 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3166 3167 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3168 } 3169 3170 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3171 const MachineFunction &MF) const { 3172 Register Reg = StringSwitch<Register>(RegName) 3173 .Case("m0", AMDGPU::M0) 3174 .Case("exec", AMDGPU::EXEC) 3175 .Case("exec_lo", AMDGPU::EXEC_LO) 3176 .Case("exec_hi", AMDGPU::EXEC_HI) 3177 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3178 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3179 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3180 .Default(Register()); 3181 3182 if (Reg == AMDGPU::NoRegister) { 3183 report_fatal_error(Twine("invalid register name \"" 3184 + StringRef(RegName) + "\".")); 3185 3186 } 3187 3188 if (!Subtarget->hasFlatScrRegister() && 3189 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3190 report_fatal_error(Twine("invalid register \"" 3191 + StringRef(RegName) + "\" for subtarget.")); 3192 } 3193 3194 switch (Reg) { 3195 case AMDGPU::M0: 3196 case AMDGPU::EXEC_LO: 3197 case AMDGPU::EXEC_HI: 3198 case AMDGPU::FLAT_SCR_LO: 3199 case AMDGPU::FLAT_SCR_HI: 3200 if (VT.getSizeInBits() == 32) 3201 return Reg; 3202 break; 3203 case AMDGPU::EXEC: 3204 case AMDGPU::FLAT_SCR: 3205 if (VT.getSizeInBits() == 64) 3206 return Reg; 3207 break; 3208 default: 3209 llvm_unreachable("missing register type checking"); 3210 } 3211 3212 report_fatal_error(Twine("invalid type for register \"" 3213 + StringRef(RegName) + "\".")); 3214 } 3215 3216 // If kill is not the last instruction, split the block so kill is always a 3217 // proper terminator. 3218 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3219 MachineBasicBlock *BB) const { 3220 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3221 3222 MachineBasicBlock::iterator SplitPoint(&MI); 3223 ++SplitPoint; 3224 3225 if (SplitPoint == BB->end()) { 3226 // Don't bother with a new block. 3227 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3228 return BB; 3229 } 3230 3231 MachineFunction *MF = BB->getParent(); 3232 MachineBasicBlock *SplitBB 3233 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3234 3235 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3236 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3237 3238 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3239 BB->addSuccessor(SplitBB); 3240 3241 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3242 return SplitBB; 3243 } 3244 3245 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3246 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3247 // be the first instruction in the remainder block. 3248 // 3249 /// \returns { LoopBody, Remainder } 3250 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3251 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3252 MachineFunction *MF = MBB.getParent(); 3253 MachineBasicBlock::iterator I(&MI); 3254 3255 // To insert the loop we need to split the block. Move everything after this 3256 // point to a new block, and insert a new empty block between the two. 3257 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3258 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3259 MachineFunction::iterator MBBI(MBB); 3260 ++MBBI; 3261 3262 MF->insert(MBBI, LoopBB); 3263 MF->insert(MBBI, RemainderBB); 3264 3265 LoopBB->addSuccessor(LoopBB); 3266 LoopBB->addSuccessor(RemainderBB); 3267 3268 // Move the rest of the block into a new block. 3269 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3270 3271 if (InstInLoop) { 3272 auto Next = std::next(I); 3273 3274 // Move instruction to loop body. 3275 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3276 3277 // Move the rest of the block. 3278 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3279 } else { 3280 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3281 } 3282 3283 MBB.addSuccessor(LoopBB); 3284 3285 return std::make_pair(LoopBB, RemainderBB); 3286 } 3287 3288 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3289 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3290 MachineBasicBlock *MBB = MI.getParent(); 3291 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3292 auto I = MI.getIterator(); 3293 auto E = std::next(I); 3294 3295 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3296 .addImm(0); 3297 3298 MIBundleBuilder Bundler(*MBB, I, E); 3299 finalizeBundle(*MBB, Bundler.begin()); 3300 } 3301 3302 MachineBasicBlock * 3303 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3304 MachineBasicBlock *BB) const { 3305 const DebugLoc &DL = MI.getDebugLoc(); 3306 3307 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3308 3309 MachineBasicBlock *LoopBB; 3310 MachineBasicBlock *RemainderBB; 3311 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3312 3313 // Apparently kill flags are only valid if the def is in the same block? 3314 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3315 Src->setIsKill(false); 3316 3317 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3318 3319 MachineBasicBlock::iterator I = LoopBB->end(); 3320 3321 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3322 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3323 3324 // Clear TRAP_STS.MEM_VIOL 3325 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3326 .addImm(0) 3327 .addImm(EncodedReg); 3328 3329 bundleInstWithWaitcnt(MI); 3330 3331 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3332 3333 // Load and check TRAP_STS.MEM_VIOL 3334 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3335 .addImm(EncodedReg); 3336 3337 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3338 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3339 .addReg(Reg, RegState::Kill) 3340 .addImm(0); 3341 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3342 .addMBB(LoopBB); 3343 3344 return RemainderBB; 3345 } 3346 3347 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3348 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3349 // will only do one iteration. In the worst case, this will loop 64 times. 3350 // 3351 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3352 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3353 const SIInstrInfo *TII, 3354 MachineRegisterInfo &MRI, 3355 MachineBasicBlock &OrigBB, 3356 MachineBasicBlock &LoopBB, 3357 const DebugLoc &DL, 3358 const MachineOperand &IdxReg, 3359 unsigned InitReg, 3360 unsigned ResultReg, 3361 unsigned PhiReg, 3362 unsigned InitSaveExecReg, 3363 int Offset, 3364 bool UseGPRIdxMode, 3365 bool IsIndirectSrc) { 3366 MachineFunction *MF = OrigBB.getParent(); 3367 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3368 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3369 MachineBasicBlock::iterator I = LoopBB.begin(); 3370 3371 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3372 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3373 Register NewExec = MRI.createVirtualRegister(BoolRC); 3374 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3375 Register CondReg = MRI.createVirtualRegister(BoolRC); 3376 3377 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3378 .addReg(InitReg) 3379 .addMBB(&OrigBB) 3380 .addReg(ResultReg) 3381 .addMBB(&LoopBB); 3382 3383 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3384 .addReg(InitSaveExecReg) 3385 .addMBB(&OrigBB) 3386 .addReg(NewExec) 3387 .addMBB(&LoopBB); 3388 3389 // Read the next variant <- also loop target. 3390 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3391 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3392 3393 // Compare the just read M0 value to all possible Idx values. 3394 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3395 .addReg(CurrentIdxReg) 3396 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3397 3398 // Update EXEC, save the original EXEC value to VCC. 3399 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3400 : AMDGPU::S_AND_SAVEEXEC_B64), 3401 NewExec) 3402 .addReg(CondReg, RegState::Kill); 3403 3404 MRI.setSimpleHint(NewExec, CondReg); 3405 3406 if (UseGPRIdxMode) { 3407 unsigned IdxReg; 3408 if (Offset == 0) { 3409 IdxReg = CurrentIdxReg; 3410 } else { 3411 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3412 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3413 .addReg(CurrentIdxReg, RegState::Kill) 3414 .addImm(Offset); 3415 } 3416 unsigned IdxMode = IsIndirectSrc ? 3417 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3418 MachineInstr *SetOn = 3419 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3420 .addReg(IdxReg, RegState::Kill) 3421 .addImm(IdxMode); 3422 SetOn->getOperand(3).setIsUndef(); 3423 } else { 3424 // Move index from VCC into M0 3425 if (Offset == 0) { 3426 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3427 .addReg(CurrentIdxReg, RegState::Kill); 3428 } else { 3429 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3430 .addReg(CurrentIdxReg, RegState::Kill) 3431 .addImm(Offset); 3432 } 3433 } 3434 3435 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3436 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3437 MachineInstr *InsertPt = 3438 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3439 : AMDGPU::S_XOR_B64_term), Exec) 3440 .addReg(Exec) 3441 .addReg(NewExec); 3442 3443 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3444 // s_cbranch_scc0? 3445 3446 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3447 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3448 .addMBB(&LoopBB); 3449 3450 return InsertPt->getIterator(); 3451 } 3452 3453 // This has slightly sub-optimal regalloc when the source vector is killed by 3454 // the read. The register allocator does not understand that the kill is 3455 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3456 // subregister from it, using 1 more VGPR than necessary. This was saved when 3457 // this was expanded after register allocation. 3458 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3459 MachineBasicBlock &MBB, 3460 MachineInstr &MI, 3461 unsigned InitResultReg, 3462 unsigned PhiReg, 3463 int Offset, 3464 bool UseGPRIdxMode, 3465 bool IsIndirectSrc) { 3466 MachineFunction *MF = MBB.getParent(); 3467 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3468 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3469 MachineRegisterInfo &MRI = MF->getRegInfo(); 3470 const DebugLoc &DL = MI.getDebugLoc(); 3471 MachineBasicBlock::iterator I(&MI); 3472 3473 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3474 Register DstReg = MI.getOperand(0).getReg(); 3475 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3476 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3477 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3478 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3479 3480 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3481 3482 // Save the EXEC mask 3483 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3484 .addReg(Exec); 3485 3486 MachineBasicBlock *LoopBB; 3487 MachineBasicBlock *RemainderBB; 3488 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3489 3490 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3491 3492 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3493 InitResultReg, DstReg, PhiReg, TmpExec, 3494 Offset, UseGPRIdxMode, IsIndirectSrc); 3495 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3496 MachineFunction::iterator MBBI(LoopBB); 3497 ++MBBI; 3498 MF->insert(MBBI, LandingPad); 3499 LoopBB->removeSuccessor(RemainderBB); 3500 LandingPad->addSuccessor(RemainderBB); 3501 LoopBB->addSuccessor(LandingPad); 3502 MachineBasicBlock::iterator First = LandingPad->begin(); 3503 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3504 .addReg(SaveExec); 3505 3506 return InsPt; 3507 } 3508 3509 // Returns subreg index, offset 3510 static std::pair<unsigned, int> 3511 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3512 const TargetRegisterClass *SuperRC, 3513 unsigned VecReg, 3514 int Offset) { 3515 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3516 3517 // Skip out of bounds offsets, or else we would end up using an undefined 3518 // register. 3519 if (Offset >= NumElts || Offset < 0) 3520 return std::make_pair(AMDGPU::sub0, Offset); 3521 3522 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3523 } 3524 3525 // Return true if the index is an SGPR and was set. 3526 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3527 MachineRegisterInfo &MRI, 3528 MachineInstr &MI, 3529 int Offset, 3530 bool UseGPRIdxMode, 3531 bool IsIndirectSrc) { 3532 MachineBasicBlock *MBB = MI.getParent(); 3533 const DebugLoc &DL = MI.getDebugLoc(); 3534 MachineBasicBlock::iterator I(&MI); 3535 3536 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3537 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3538 3539 assert(Idx->getReg() != AMDGPU::NoRegister); 3540 3541 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3542 return false; 3543 3544 if (UseGPRIdxMode) { 3545 unsigned IdxMode = IsIndirectSrc ? 3546 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3547 if (Offset == 0) { 3548 MachineInstr *SetOn = 3549 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3550 .add(*Idx) 3551 .addImm(IdxMode); 3552 3553 SetOn->getOperand(3).setIsUndef(); 3554 } else { 3555 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3556 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3557 .add(*Idx) 3558 .addImm(Offset); 3559 MachineInstr *SetOn = 3560 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3561 .addReg(Tmp, RegState::Kill) 3562 .addImm(IdxMode); 3563 3564 SetOn->getOperand(3).setIsUndef(); 3565 } 3566 3567 return true; 3568 } 3569 3570 if (Offset == 0) { 3571 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3572 .add(*Idx); 3573 } else { 3574 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3575 .add(*Idx) 3576 .addImm(Offset); 3577 } 3578 3579 return true; 3580 } 3581 3582 // Control flow needs to be inserted if indexing with a VGPR. 3583 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3584 MachineBasicBlock &MBB, 3585 const GCNSubtarget &ST) { 3586 const SIInstrInfo *TII = ST.getInstrInfo(); 3587 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3588 MachineFunction *MF = MBB.getParent(); 3589 MachineRegisterInfo &MRI = MF->getRegInfo(); 3590 3591 Register Dst = MI.getOperand(0).getReg(); 3592 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3593 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3594 3595 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3596 3597 unsigned SubReg; 3598 std::tie(SubReg, Offset) 3599 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3600 3601 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3602 3603 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3604 MachineBasicBlock::iterator I(&MI); 3605 const DebugLoc &DL = MI.getDebugLoc(); 3606 3607 if (UseGPRIdxMode) { 3608 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3609 // to avoid interfering with other uses, so probably requires a new 3610 // optimization pass. 3611 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3612 .addReg(SrcReg, RegState::Undef, SubReg) 3613 .addReg(SrcReg, RegState::Implicit) 3614 .addReg(AMDGPU::M0, RegState::Implicit); 3615 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3616 } else { 3617 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3618 .addReg(SrcReg, RegState::Undef, SubReg) 3619 .addReg(SrcReg, RegState::Implicit); 3620 } 3621 3622 MI.eraseFromParent(); 3623 3624 return &MBB; 3625 } 3626 3627 const DebugLoc &DL = MI.getDebugLoc(); 3628 MachineBasicBlock::iterator I(&MI); 3629 3630 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3631 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3632 3633 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3634 3635 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3636 Offset, UseGPRIdxMode, true); 3637 MachineBasicBlock *LoopBB = InsPt->getParent(); 3638 3639 if (UseGPRIdxMode) { 3640 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3641 .addReg(SrcReg, RegState::Undef, SubReg) 3642 .addReg(SrcReg, RegState::Implicit) 3643 .addReg(AMDGPU::M0, RegState::Implicit); 3644 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3645 } else { 3646 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3647 .addReg(SrcReg, RegState::Undef, SubReg) 3648 .addReg(SrcReg, RegState::Implicit); 3649 } 3650 3651 MI.eraseFromParent(); 3652 3653 return LoopBB; 3654 } 3655 3656 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3657 MachineBasicBlock &MBB, 3658 const GCNSubtarget &ST) { 3659 const SIInstrInfo *TII = ST.getInstrInfo(); 3660 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3661 MachineFunction *MF = MBB.getParent(); 3662 MachineRegisterInfo &MRI = MF->getRegInfo(); 3663 3664 Register Dst = MI.getOperand(0).getReg(); 3665 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3666 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3667 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3668 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3669 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3670 3671 // This can be an immediate, but will be folded later. 3672 assert(Val->getReg()); 3673 3674 unsigned SubReg; 3675 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3676 SrcVec->getReg(), 3677 Offset); 3678 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3679 3680 if (Idx->getReg() == AMDGPU::NoRegister) { 3681 MachineBasicBlock::iterator I(&MI); 3682 const DebugLoc &DL = MI.getDebugLoc(); 3683 3684 assert(Offset == 0); 3685 3686 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3687 .add(*SrcVec) 3688 .add(*Val) 3689 .addImm(SubReg); 3690 3691 MI.eraseFromParent(); 3692 return &MBB; 3693 } 3694 3695 const MCInstrDesc &MovRelDesc 3696 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3697 3698 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3699 MachineBasicBlock::iterator I(&MI); 3700 const DebugLoc &DL = MI.getDebugLoc(); 3701 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3702 .addReg(SrcVec->getReg()) 3703 .add(*Val) 3704 .addImm(SubReg); 3705 if (UseGPRIdxMode) 3706 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3707 3708 MI.eraseFromParent(); 3709 return &MBB; 3710 } 3711 3712 if (Val->isReg()) 3713 MRI.clearKillFlags(Val->getReg()); 3714 3715 const DebugLoc &DL = MI.getDebugLoc(); 3716 3717 Register PhiReg = MRI.createVirtualRegister(VecRC); 3718 3719 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3720 Offset, UseGPRIdxMode, false); 3721 MachineBasicBlock *LoopBB = InsPt->getParent(); 3722 3723 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3724 .addReg(PhiReg) 3725 .add(*Val) 3726 .addImm(AMDGPU::sub0); 3727 if (UseGPRIdxMode) 3728 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3729 3730 MI.eraseFromParent(); 3731 return LoopBB; 3732 } 3733 3734 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3735 MachineInstr &MI, MachineBasicBlock *BB) const { 3736 3737 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3738 MachineFunction *MF = BB->getParent(); 3739 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3740 3741 switch (MI.getOpcode()) { 3742 case AMDGPU::S_UADDO_PSEUDO: 3743 case AMDGPU::S_USUBO_PSEUDO: { 3744 const DebugLoc &DL = MI.getDebugLoc(); 3745 MachineOperand &Dest0 = MI.getOperand(0); 3746 MachineOperand &Dest1 = MI.getOperand(1); 3747 MachineOperand &Src0 = MI.getOperand(2); 3748 MachineOperand &Src1 = MI.getOperand(3); 3749 3750 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3751 ? AMDGPU::S_ADD_I32 3752 : AMDGPU::S_SUB_I32; 3753 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3754 3755 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3756 .addImm(1) 3757 .addImm(0); 3758 3759 MI.eraseFromParent(); 3760 return BB; 3761 } 3762 case AMDGPU::S_ADD_U64_PSEUDO: 3763 case AMDGPU::S_SUB_U64_PSEUDO: { 3764 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3765 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3766 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3767 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3768 const DebugLoc &DL = MI.getDebugLoc(); 3769 3770 MachineOperand &Dest = MI.getOperand(0); 3771 MachineOperand &Src0 = MI.getOperand(1); 3772 MachineOperand &Src1 = MI.getOperand(2); 3773 3774 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3775 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3776 3777 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3778 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3779 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3780 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3781 3782 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3783 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3784 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3785 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3786 3787 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3788 3789 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3790 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3791 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3792 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3793 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3794 .addReg(DestSub0) 3795 .addImm(AMDGPU::sub0) 3796 .addReg(DestSub1) 3797 .addImm(AMDGPU::sub1); 3798 MI.eraseFromParent(); 3799 return BB; 3800 } 3801 case AMDGPU::V_ADD_U64_PSEUDO: 3802 case AMDGPU::V_SUB_U64_PSEUDO: { 3803 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3804 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3805 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3806 const DebugLoc &DL = MI.getDebugLoc(); 3807 3808 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3809 3810 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3811 3812 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3813 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3814 3815 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3816 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3817 3818 MachineOperand &Dest = MI.getOperand(0); 3819 MachineOperand &Src0 = MI.getOperand(1); 3820 MachineOperand &Src1 = MI.getOperand(2); 3821 3822 const TargetRegisterClass *Src0RC = Src0.isReg() 3823 ? MRI.getRegClass(Src0.getReg()) 3824 : &AMDGPU::VReg_64RegClass; 3825 const TargetRegisterClass *Src1RC = Src1.isReg() 3826 ? MRI.getRegClass(Src1.getReg()) 3827 : &AMDGPU::VReg_64RegClass; 3828 3829 const TargetRegisterClass *Src0SubRC = 3830 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3831 const TargetRegisterClass *Src1SubRC = 3832 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3833 3834 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3835 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3836 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3837 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3838 3839 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3840 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3841 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3842 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3843 3844 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3845 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3846 .addReg(CarryReg, RegState::Define) 3847 .add(SrcReg0Sub0) 3848 .add(SrcReg1Sub0) 3849 .addImm(0); // clamp bit 3850 3851 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3852 MachineInstr *HiHalf = 3853 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3854 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3855 .add(SrcReg0Sub1) 3856 .add(SrcReg1Sub1) 3857 .addReg(CarryReg, RegState::Kill) 3858 .addImm(0); // clamp bit 3859 3860 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3861 .addReg(DestSub0) 3862 .addImm(AMDGPU::sub0) 3863 .addReg(DestSub1) 3864 .addImm(AMDGPU::sub1); 3865 TII->legalizeOperands(*LoHalf); 3866 TII->legalizeOperands(*HiHalf); 3867 MI.eraseFromParent(); 3868 return BB; 3869 } 3870 case AMDGPU::S_ADD_CO_PSEUDO: 3871 case AMDGPU::S_SUB_CO_PSEUDO: { 3872 // This pseudo has a chance to be selected 3873 // only from uniform add/subcarry node. All the VGPR operands 3874 // therefore assumed to be splat vectors. 3875 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3876 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3877 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3878 MachineBasicBlock::iterator MII = MI; 3879 const DebugLoc &DL = MI.getDebugLoc(); 3880 MachineOperand &Dest = MI.getOperand(0); 3881 MachineOperand &Src0 = MI.getOperand(2); 3882 MachineOperand &Src1 = MI.getOperand(3); 3883 MachineOperand &Src2 = MI.getOperand(4); 3884 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3885 ? AMDGPU::S_ADDC_U32 3886 : AMDGPU::S_SUBB_U32; 3887 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3888 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3889 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3890 .addReg(Src0.getReg()); 3891 Src0.setReg(RegOp0); 3892 } 3893 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3894 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3895 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3896 .addReg(Src1.getReg()); 3897 Src1.setReg(RegOp1); 3898 } 3899 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3900 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3901 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3902 .addReg(Src2.getReg()); 3903 Src2.setReg(RegOp2); 3904 } 3905 3906 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3907 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3908 .addReg(Src2.getReg()) 3909 .addImm(0); 3910 } else { 3911 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3912 .addReg(Src2.getReg()) 3913 .addImm(0); 3914 } 3915 3916 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3917 MI.eraseFromParent(); 3918 return BB; 3919 } 3920 case AMDGPU::SI_INIT_M0: { 3921 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3922 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3923 .add(MI.getOperand(0)); 3924 MI.eraseFromParent(); 3925 return BB; 3926 } 3927 case AMDGPU::SI_INIT_EXEC: 3928 // This should be before all vector instructions. 3929 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3930 AMDGPU::EXEC) 3931 .addImm(MI.getOperand(0).getImm()); 3932 MI.eraseFromParent(); 3933 return BB; 3934 3935 case AMDGPU::SI_INIT_EXEC_LO: 3936 // This should be before all vector instructions. 3937 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3938 AMDGPU::EXEC_LO) 3939 .addImm(MI.getOperand(0).getImm()); 3940 MI.eraseFromParent(); 3941 return BB; 3942 3943 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3944 // Extract the thread count from an SGPR input and set EXEC accordingly. 3945 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3946 // 3947 // S_BFE_U32 count, input, {shift, 7} 3948 // S_BFM_B64 exec, count, 0 3949 // S_CMP_EQ_U32 count, 64 3950 // S_CMOV_B64 exec, -1 3951 MachineInstr *FirstMI = &*BB->begin(); 3952 MachineRegisterInfo &MRI = MF->getRegInfo(); 3953 Register InputReg = MI.getOperand(0).getReg(); 3954 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3955 bool Found = false; 3956 3957 // Move the COPY of the input reg to the beginning, so that we can use it. 3958 for (auto I = BB->begin(); I != &MI; I++) { 3959 if (I->getOpcode() != TargetOpcode::COPY || 3960 I->getOperand(0).getReg() != InputReg) 3961 continue; 3962 3963 if (I == FirstMI) { 3964 FirstMI = &*++BB->begin(); 3965 } else { 3966 I->removeFromParent(); 3967 BB->insert(FirstMI, &*I); 3968 } 3969 Found = true; 3970 break; 3971 } 3972 assert(Found); 3973 (void)Found; 3974 3975 // This should be before all vector instructions. 3976 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3977 bool isWave32 = getSubtarget()->isWave32(); 3978 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3979 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3980 .addReg(InputReg) 3981 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3982 BuildMI(*BB, FirstMI, DebugLoc(), 3983 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3984 Exec) 3985 .addReg(CountReg) 3986 .addImm(0); 3987 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3988 .addReg(CountReg, RegState::Kill) 3989 .addImm(getSubtarget()->getWavefrontSize()); 3990 BuildMI(*BB, FirstMI, DebugLoc(), 3991 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3992 Exec) 3993 .addImm(-1); 3994 MI.eraseFromParent(); 3995 return BB; 3996 } 3997 3998 case AMDGPU::GET_GROUPSTATICSIZE: { 3999 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4000 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4001 DebugLoc DL = MI.getDebugLoc(); 4002 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4003 .add(MI.getOperand(0)) 4004 .addImm(MFI->getLDSSize()); 4005 MI.eraseFromParent(); 4006 return BB; 4007 } 4008 case AMDGPU::SI_INDIRECT_SRC_V1: 4009 case AMDGPU::SI_INDIRECT_SRC_V2: 4010 case AMDGPU::SI_INDIRECT_SRC_V4: 4011 case AMDGPU::SI_INDIRECT_SRC_V8: 4012 case AMDGPU::SI_INDIRECT_SRC_V16: 4013 case AMDGPU::SI_INDIRECT_SRC_V32: 4014 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4015 case AMDGPU::SI_INDIRECT_DST_V1: 4016 case AMDGPU::SI_INDIRECT_DST_V2: 4017 case AMDGPU::SI_INDIRECT_DST_V4: 4018 case AMDGPU::SI_INDIRECT_DST_V8: 4019 case AMDGPU::SI_INDIRECT_DST_V16: 4020 case AMDGPU::SI_INDIRECT_DST_V32: 4021 return emitIndirectDst(MI, *BB, *getSubtarget()); 4022 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4023 case AMDGPU::SI_KILL_I1_PSEUDO: 4024 return splitKillBlock(MI, BB); 4025 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4026 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4027 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4028 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4029 4030 Register Dst = MI.getOperand(0).getReg(); 4031 Register Src0 = MI.getOperand(1).getReg(); 4032 Register Src1 = MI.getOperand(2).getReg(); 4033 const DebugLoc &DL = MI.getDebugLoc(); 4034 Register SrcCond = MI.getOperand(3).getReg(); 4035 4036 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4037 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4038 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4039 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4040 4041 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4042 .addReg(SrcCond); 4043 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4044 .addImm(0) 4045 .addReg(Src0, 0, AMDGPU::sub0) 4046 .addImm(0) 4047 .addReg(Src1, 0, AMDGPU::sub0) 4048 .addReg(SrcCondCopy); 4049 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4050 .addImm(0) 4051 .addReg(Src0, 0, AMDGPU::sub1) 4052 .addImm(0) 4053 .addReg(Src1, 0, AMDGPU::sub1) 4054 .addReg(SrcCondCopy); 4055 4056 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4057 .addReg(DstLo) 4058 .addImm(AMDGPU::sub0) 4059 .addReg(DstHi) 4060 .addImm(AMDGPU::sub1); 4061 MI.eraseFromParent(); 4062 return BB; 4063 } 4064 case AMDGPU::SI_BR_UNDEF: { 4065 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4066 const DebugLoc &DL = MI.getDebugLoc(); 4067 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4068 .add(MI.getOperand(0)); 4069 Br->getOperand(1).setIsUndef(true); // read undef SCC 4070 MI.eraseFromParent(); 4071 return BB; 4072 } 4073 case AMDGPU::ADJCALLSTACKUP: 4074 case AMDGPU::ADJCALLSTACKDOWN: { 4075 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4076 MachineInstrBuilder MIB(*MF, &MI); 4077 4078 // Add an implicit use of the frame offset reg to prevent the restore copy 4079 // inserted after the call from being reorderd after stack operations in the 4080 // the caller's frame. 4081 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4082 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4083 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4084 return BB; 4085 } 4086 case AMDGPU::SI_CALL_ISEL: { 4087 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4088 const DebugLoc &DL = MI.getDebugLoc(); 4089 4090 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4091 4092 MachineInstrBuilder MIB; 4093 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4094 4095 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4096 MIB.add(MI.getOperand(I)); 4097 4098 MIB.cloneMemRefs(MI); 4099 MI.eraseFromParent(); 4100 return BB; 4101 } 4102 case AMDGPU::V_ADD_I32_e32: 4103 case AMDGPU::V_SUB_I32_e32: 4104 case AMDGPU::V_SUBREV_I32_e32: { 4105 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4106 const DebugLoc &DL = MI.getDebugLoc(); 4107 unsigned Opc = MI.getOpcode(); 4108 4109 bool NeedClampOperand = false; 4110 if (TII->pseudoToMCOpcode(Opc) == -1) { 4111 Opc = AMDGPU::getVOPe64(Opc); 4112 NeedClampOperand = true; 4113 } 4114 4115 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4116 if (TII->isVOP3(*I)) { 4117 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4118 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4119 I.addReg(TRI->getVCC(), RegState::Define); 4120 } 4121 I.add(MI.getOperand(1)) 4122 .add(MI.getOperand(2)); 4123 if (NeedClampOperand) 4124 I.addImm(0); // clamp bit for e64 encoding 4125 4126 TII->legalizeOperands(*I); 4127 4128 MI.eraseFromParent(); 4129 return BB; 4130 } 4131 case AMDGPU::DS_GWS_INIT: 4132 case AMDGPU::DS_GWS_SEMA_V: 4133 case AMDGPU::DS_GWS_SEMA_BR: 4134 case AMDGPU::DS_GWS_SEMA_P: 4135 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4136 case AMDGPU::DS_GWS_BARRIER: 4137 // A s_waitcnt 0 is required to be the instruction immediately following. 4138 if (getSubtarget()->hasGWSAutoReplay()) { 4139 bundleInstWithWaitcnt(MI); 4140 return BB; 4141 } 4142 4143 return emitGWSMemViolTestLoop(MI, BB); 4144 case AMDGPU::S_SETREG_B32: { 4145 if (!getSubtarget()->hasDenormModeInst()) 4146 return BB; 4147 4148 // Try to optimize cases that only set the denormal mode or rounding mode. 4149 // 4150 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4151 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4152 // instead. 4153 // 4154 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4155 // allow you to have a no side effect instruction in the output of a 4156 // sideeffecting pattern. 4157 4158 // TODO: Should also emit a no side effects pseudo if only FP bits are 4159 // touched, even if not all of them or to a variable. 4160 unsigned ID, Offset, Width; 4161 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4162 if (ID != AMDGPU::Hwreg::ID_MODE) 4163 return BB; 4164 4165 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4166 const unsigned SetMask = WidthMask << Offset; 4167 unsigned SetDenormOp = 0; 4168 unsigned SetRoundOp = 0; 4169 4170 // The dedicated instructions can only set the whole denorm or round mode at 4171 // once, not a subset of bits in either. 4172 if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4173 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) { 4174 // If this fully sets both the round and denorm mode, emit the two 4175 // dedicated instructions for these. 4176 assert(Offset == 0); 4177 SetRoundOp = AMDGPU::S_ROUND_MODE; 4178 SetDenormOp = AMDGPU::S_DENORM_MODE; 4179 } else if (Width == 4) { 4180 if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) { 4181 SetRoundOp = AMDGPU::S_ROUND_MODE; 4182 assert(Offset == 0); 4183 } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) { 4184 SetDenormOp = AMDGPU::S_DENORM_MODE; 4185 assert(Offset == 4); 4186 } 4187 } 4188 4189 if (SetRoundOp || SetDenormOp) { 4190 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4191 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4192 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4193 unsigned ImmVal = Def->getOperand(1).getImm(); 4194 if (SetRoundOp) { 4195 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4196 .addImm(ImmVal & 0xf); 4197 4198 // If we also have the denorm mode, get just the denorm mode bits. 4199 ImmVal >>= 4; 4200 } 4201 4202 if (SetDenormOp) { 4203 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4204 .addImm(ImmVal & 0xf); 4205 } 4206 4207 MI.eraseFromParent(); 4208 } 4209 } 4210 4211 return BB; 4212 } 4213 default: 4214 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4215 } 4216 } 4217 4218 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4219 return isTypeLegal(VT.getScalarType()); 4220 } 4221 4222 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4223 // This currently forces unfolding various combinations of fsub into fma with 4224 // free fneg'd operands. As long as we have fast FMA (controlled by 4225 // isFMAFasterThanFMulAndFAdd), we should perform these. 4226 4227 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4228 // most of these combines appear to be cycle neutral but save on instruction 4229 // count / code size. 4230 return true; 4231 } 4232 4233 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4234 EVT VT) const { 4235 if (!VT.isVector()) { 4236 return MVT::i1; 4237 } 4238 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4239 } 4240 4241 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4242 // TODO: Should i16 be used always if legal? For now it would force VALU 4243 // shifts. 4244 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4245 } 4246 4247 // Answering this is somewhat tricky and depends on the specific device which 4248 // have different rates for fma or all f64 operations. 4249 // 4250 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4251 // regardless of which device (although the number of cycles differs between 4252 // devices), so it is always profitable for f64. 4253 // 4254 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4255 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4256 // which we can always do even without fused FP ops since it returns the same 4257 // result as the separate operations and since it is always full 4258 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4259 // however does not support denormals, so we do report fma as faster if we have 4260 // a fast fma device and require denormals. 4261 // 4262 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4263 EVT VT) const { 4264 VT = VT.getScalarType(); 4265 4266 switch (VT.getSimpleVT().SimpleTy) { 4267 case MVT::f32: { 4268 // This is as fast on some subtargets. However, we always have full rate f32 4269 // mad available which returns the same result as the separate operations 4270 // which we should prefer over fma. We can't use this if we want to support 4271 // denormals, so only report this in these cases. 4272 if (hasFP32Denormals(MF)) 4273 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4274 4275 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4276 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4277 } 4278 case MVT::f64: 4279 return true; 4280 case MVT::f16: 4281 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4282 default: 4283 break; 4284 } 4285 4286 return false; 4287 } 4288 4289 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4290 const SDNode *N) const { 4291 // TODO: Check future ftz flag 4292 // v_mad_f32/v_mac_f32 do not support denormals. 4293 EVT VT = N->getValueType(0); 4294 if (VT == MVT::f32) 4295 return Subtarget->hasMadMacF32Insts() && 4296 !hasFP32Denormals(DAG.getMachineFunction()); 4297 if (VT == MVT::f16) { 4298 return Subtarget->hasMadF16() && 4299 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4300 } 4301 4302 return false; 4303 } 4304 4305 //===----------------------------------------------------------------------===// 4306 // Custom DAG Lowering Operations 4307 //===----------------------------------------------------------------------===// 4308 4309 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4310 // wider vector type is legal. 4311 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4312 SelectionDAG &DAG) const { 4313 unsigned Opc = Op.getOpcode(); 4314 EVT VT = Op.getValueType(); 4315 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4316 4317 SDValue Lo, Hi; 4318 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4319 4320 SDLoc SL(Op); 4321 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4322 Op->getFlags()); 4323 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4324 Op->getFlags()); 4325 4326 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4327 } 4328 4329 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4330 // wider vector type is legal. 4331 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4332 SelectionDAG &DAG) const { 4333 unsigned Opc = Op.getOpcode(); 4334 EVT VT = Op.getValueType(); 4335 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4336 4337 SDValue Lo0, Hi0; 4338 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4339 SDValue Lo1, Hi1; 4340 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4341 4342 SDLoc SL(Op); 4343 4344 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4345 Op->getFlags()); 4346 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4347 Op->getFlags()); 4348 4349 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4350 } 4351 4352 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4353 SelectionDAG &DAG) const { 4354 unsigned Opc = Op.getOpcode(); 4355 EVT VT = Op.getValueType(); 4356 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4357 4358 SDValue Lo0, Hi0; 4359 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4360 SDValue Lo1, Hi1; 4361 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4362 SDValue Lo2, Hi2; 4363 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4364 4365 SDLoc SL(Op); 4366 4367 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4368 Op->getFlags()); 4369 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4370 Op->getFlags()); 4371 4372 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4373 } 4374 4375 4376 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4377 switch (Op.getOpcode()) { 4378 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4379 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4380 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4381 case ISD::LOAD: { 4382 SDValue Result = LowerLOAD(Op, DAG); 4383 assert((!Result.getNode() || 4384 Result.getNode()->getNumValues() == 2) && 4385 "Load should return a value and a chain"); 4386 return Result; 4387 } 4388 4389 case ISD::FSIN: 4390 case ISD::FCOS: 4391 return LowerTrig(Op, DAG); 4392 case ISD::SELECT: return LowerSELECT(Op, DAG); 4393 case ISD::FDIV: return LowerFDIV(Op, DAG); 4394 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4395 case ISD::STORE: return LowerSTORE(Op, DAG); 4396 case ISD::GlobalAddress: { 4397 MachineFunction &MF = DAG.getMachineFunction(); 4398 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4399 return LowerGlobalAddress(MFI, Op, DAG); 4400 } 4401 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4402 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4403 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4404 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4405 case ISD::INSERT_SUBVECTOR: 4406 return lowerINSERT_SUBVECTOR(Op, DAG); 4407 case ISD::INSERT_VECTOR_ELT: 4408 return lowerINSERT_VECTOR_ELT(Op, DAG); 4409 case ISD::EXTRACT_VECTOR_ELT: 4410 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4411 case ISD::VECTOR_SHUFFLE: 4412 return lowerVECTOR_SHUFFLE(Op, DAG); 4413 case ISD::BUILD_VECTOR: 4414 return lowerBUILD_VECTOR(Op, DAG); 4415 case ISD::FP_ROUND: 4416 return lowerFP_ROUND(Op, DAG); 4417 case ISD::TRAP: 4418 return lowerTRAP(Op, DAG); 4419 case ISD::DEBUGTRAP: 4420 return lowerDEBUGTRAP(Op, DAG); 4421 case ISD::FABS: 4422 case ISD::FNEG: 4423 case ISD::FCANONICALIZE: 4424 case ISD::BSWAP: 4425 return splitUnaryVectorOp(Op, DAG); 4426 case ISD::FMINNUM: 4427 case ISD::FMAXNUM: 4428 return lowerFMINNUM_FMAXNUM(Op, DAG); 4429 case ISD::FMA: 4430 return splitTernaryVectorOp(Op, DAG); 4431 case ISD::SHL: 4432 case ISD::SRA: 4433 case ISD::SRL: 4434 case ISD::ADD: 4435 case ISD::SUB: 4436 case ISD::MUL: 4437 case ISD::SMIN: 4438 case ISD::SMAX: 4439 case ISD::UMIN: 4440 case ISD::UMAX: 4441 case ISD::FADD: 4442 case ISD::FMUL: 4443 case ISD::FMINNUM_IEEE: 4444 case ISD::FMAXNUM_IEEE: 4445 return splitBinaryVectorOp(Op, DAG); 4446 case ISD::SMULO: 4447 case ISD::UMULO: 4448 return lowerXMULO(Op, DAG); 4449 case ISD::DYNAMIC_STACKALLOC: 4450 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4451 } 4452 return SDValue(); 4453 } 4454 4455 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4456 const SDLoc &DL, 4457 SelectionDAG &DAG, bool Unpacked) { 4458 if (!LoadVT.isVector()) 4459 return Result; 4460 4461 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4462 // Truncate to v2i16/v4i16. 4463 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4464 4465 // Workaround legalizer not scalarizing truncate after vector op 4466 // legalization byt not creating intermediate vector trunc. 4467 SmallVector<SDValue, 4> Elts; 4468 DAG.ExtractVectorElements(Result, Elts); 4469 for (SDValue &Elt : Elts) 4470 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4471 4472 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4473 4474 // Bitcast to original type (v2f16/v4f16). 4475 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4476 } 4477 4478 // Cast back to the original packed type. 4479 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4480 } 4481 4482 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4483 MemSDNode *M, 4484 SelectionDAG &DAG, 4485 ArrayRef<SDValue> Ops, 4486 bool IsIntrinsic) const { 4487 SDLoc DL(M); 4488 4489 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4490 EVT LoadVT = M->getValueType(0); 4491 4492 EVT EquivLoadVT = LoadVT; 4493 if (Unpacked && LoadVT.isVector()) { 4494 EquivLoadVT = LoadVT.isVector() ? 4495 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4496 LoadVT.getVectorNumElements()) : LoadVT; 4497 } 4498 4499 // Change from v4f16/v2f16 to EquivLoadVT. 4500 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4501 4502 SDValue Load 4503 = DAG.getMemIntrinsicNode( 4504 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4505 VTList, Ops, M->getMemoryVT(), 4506 M->getMemOperand()); 4507 if (!Unpacked) // Just adjusted the opcode. 4508 return Load; 4509 4510 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4511 4512 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4513 } 4514 4515 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4516 SelectionDAG &DAG, 4517 ArrayRef<SDValue> Ops) const { 4518 SDLoc DL(M); 4519 EVT LoadVT = M->getValueType(0); 4520 EVT EltType = LoadVT.getScalarType(); 4521 EVT IntVT = LoadVT.changeTypeToInteger(); 4522 4523 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4524 4525 unsigned Opc = 4526 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4527 4528 if (IsD16) { 4529 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4530 } 4531 4532 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4533 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4534 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4535 4536 if (isTypeLegal(LoadVT)) { 4537 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4538 M->getMemOperand(), DAG); 4539 } 4540 4541 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4542 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4543 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4544 M->getMemOperand(), DAG); 4545 return DAG.getMergeValues( 4546 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4547 DL); 4548 } 4549 4550 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4551 SDNode *N, SelectionDAG &DAG) { 4552 EVT VT = N->getValueType(0); 4553 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4554 int CondCode = CD->getSExtValue(); 4555 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4556 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4557 return DAG.getUNDEF(VT); 4558 4559 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4560 4561 SDValue LHS = N->getOperand(1); 4562 SDValue RHS = N->getOperand(2); 4563 4564 SDLoc DL(N); 4565 4566 EVT CmpVT = LHS.getValueType(); 4567 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4568 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4569 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4570 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4571 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4572 } 4573 4574 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4575 4576 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4577 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4578 4579 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4580 DAG.getCondCode(CCOpcode)); 4581 if (VT.bitsEq(CCVT)) 4582 return SetCC; 4583 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4584 } 4585 4586 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4587 SDNode *N, SelectionDAG &DAG) { 4588 EVT VT = N->getValueType(0); 4589 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4590 4591 int CondCode = CD->getSExtValue(); 4592 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4593 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4594 return DAG.getUNDEF(VT); 4595 } 4596 4597 SDValue Src0 = N->getOperand(1); 4598 SDValue Src1 = N->getOperand(2); 4599 EVT CmpVT = Src0.getValueType(); 4600 SDLoc SL(N); 4601 4602 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4603 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4604 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4605 } 4606 4607 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4608 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4609 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4610 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4611 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4612 Src1, DAG.getCondCode(CCOpcode)); 4613 if (VT.bitsEq(CCVT)) 4614 return SetCC; 4615 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4616 } 4617 4618 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4619 SelectionDAG &DAG) { 4620 EVT VT = N->getValueType(0); 4621 SDValue Src = N->getOperand(1); 4622 SDLoc SL(N); 4623 4624 if (Src.getOpcode() == ISD::SETCC) { 4625 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4626 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4627 Src.getOperand(1), Src.getOperand(2)); 4628 } 4629 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4630 // (ballot 0) -> 0 4631 if (Arg->isNullValue()) 4632 return DAG.getConstant(0, SL, VT); 4633 4634 // (ballot 1) -> EXEC/EXEC_LO 4635 if (Arg->isOne()) { 4636 Register Exec; 4637 if (VT.getScalarSizeInBits() == 32) 4638 Exec = AMDGPU::EXEC_LO; 4639 else if (VT.getScalarSizeInBits() == 64) 4640 Exec = AMDGPU::EXEC; 4641 else 4642 return SDValue(); 4643 4644 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4645 } 4646 } 4647 4648 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4649 // ISD::SETNE) 4650 return DAG.getNode( 4651 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4652 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4653 } 4654 4655 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4656 SmallVectorImpl<SDValue> &Results, 4657 SelectionDAG &DAG) const { 4658 switch (N->getOpcode()) { 4659 case ISD::INSERT_VECTOR_ELT: { 4660 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4661 Results.push_back(Res); 4662 return; 4663 } 4664 case ISD::EXTRACT_VECTOR_ELT: { 4665 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4666 Results.push_back(Res); 4667 return; 4668 } 4669 case ISD::INTRINSIC_WO_CHAIN: { 4670 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4671 switch (IID) { 4672 case Intrinsic::amdgcn_cvt_pkrtz: { 4673 SDValue Src0 = N->getOperand(1); 4674 SDValue Src1 = N->getOperand(2); 4675 SDLoc SL(N); 4676 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4677 Src0, Src1); 4678 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4679 return; 4680 } 4681 case Intrinsic::amdgcn_cvt_pknorm_i16: 4682 case Intrinsic::amdgcn_cvt_pknorm_u16: 4683 case Intrinsic::amdgcn_cvt_pk_i16: 4684 case Intrinsic::amdgcn_cvt_pk_u16: { 4685 SDValue Src0 = N->getOperand(1); 4686 SDValue Src1 = N->getOperand(2); 4687 SDLoc SL(N); 4688 unsigned Opcode; 4689 4690 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4691 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4692 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4693 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4694 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4695 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4696 else 4697 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4698 4699 EVT VT = N->getValueType(0); 4700 if (isTypeLegal(VT)) 4701 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4702 else { 4703 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4704 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4705 } 4706 return; 4707 } 4708 } 4709 break; 4710 } 4711 case ISD::INTRINSIC_W_CHAIN: { 4712 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4713 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4714 // FIXME: Hacky 4715 Results.push_back(Res.getOperand(0)); 4716 Results.push_back(Res.getOperand(1)); 4717 } else { 4718 Results.push_back(Res); 4719 Results.push_back(Res.getValue(1)); 4720 } 4721 return; 4722 } 4723 4724 break; 4725 } 4726 case ISD::SELECT: { 4727 SDLoc SL(N); 4728 EVT VT = N->getValueType(0); 4729 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4730 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4731 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4732 4733 EVT SelectVT = NewVT; 4734 if (NewVT.bitsLT(MVT::i32)) { 4735 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4736 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4737 SelectVT = MVT::i32; 4738 } 4739 4740 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4741 N->getOperand(0), LHS, RHS); 4742 4743 if (NewVT != SelectVT) 4744 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4745 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4746 return; 4747 } 4748 case ISD::FNEG: { 4749 if (N->getValueType(0) != MVT::v2f16) 4750 break; 4751 4752 SDLoc SL(N); 4753 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4754 4755 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4756 BC, 4757 DAG.getConstant(0x80008000, SL, MVT::i32)); 4758 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4759 return; 4760 } 4761 case ISD::FABS: { 4762 if (N->getValueType(0) != MVT::v2f16) 4763 break; 4764 4765 SDLoc SL(N); 4766 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4767 4768 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4769 BC, 4770 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4771 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4772 return; 4773 } 4774 default: 4775 break; 4776 } 4777 } 4778 4779 /// Helper function for LowerBRCOND 4780 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4781 4782 SDNode *Parent = Value.getNode(); 4783 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4784 I != E; ++I) { 4785 4786 if (I.getUse().get() != Value) 4787 continue; 4788 4789 if (I->getOpcode() == Opcode) 4790 return *I; 4791 } 4792 return nullptr; 4793 } 4794 4795 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4796 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4797 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4798 case Intrinsic::amdgcn_if: 4799 return AMDGPUISD::IF; 4800 case Intrinsic::amdgcn_else: 4801 return AMDGPUISD::ELSE; 4802 case Intrinsic::amdgcn_loop: 4803 return AMDGPUISD::LOOP; 4804 case Intrinsic::amdgcn_end_cf: 4805 llvm_unreachable("should not occur"); 4806 default: 4807 return 0; 4808 } 4809 } 4810 4811 // break, if_break, else_break are all only used as inputs to loop, not 4812 // directly as branch conditions. 4813 return 0; 4814 } 4815 4816 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4817 const Triple &TT = getTargetMachine().getTargetTriple(); 4818 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4819 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4820 AMDGPU::shouldEmitConstantsToTextSection(TT); 4821 } 4822 4823 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4824 // FIXME: Either avoid relying on address space here or change the default 4825 // address space for functions to avoid the explicit check. 4826 return (GV->getValueType()->isFunctionTy() || 4827 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4828 !shouldEmitFixup(GV) && 4829 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4830 } 4831 4832 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4833 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4834 } 4835 4836 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4837 if (!GV->hasExternalLinkage()) 4838 return true; 4839 4840 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4841 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4842 } 4843 4844 /// This transforms the control flow intrinsics to get the branch destination as 4845 /// last parameter, also switches branch target with BR if the need arise 4846 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4847 SelectionDAG &DAG) const { 4848 SDLoc DL(BRCOND); 4849 4850 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4851 SDValue Target = BRCOND.getOperand(2); 4852 SDNode *BR = nullptr; 4853 SDNode *SetCC = nullptr; 4854 4855 if (Intr->getOpcode() == ISD::SETCC) { 4856 // As long as we negate the condition everything is fine 4857 SetCC = Intr; 4858 Intr = SetCC->getOperand(0).getNode(); 4859 4860 } else { 4861 // Get the target from BR if we don't negate the condition 4862 BR = findUser(BRCOND, ISD::BR); 4863 assert(BR && "brcond missing unconditional branch user"); 4864 Target = BR->getOperand(1); 4865 } 4866 4867 unsigned CFNode = isCFIntrinsic(Intr); 4868 if (CFNode == 0) { 4869 // This is a uniform branch so we don't need to legalize. 4870 return BRCOND; 4871 } 4872 4873 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4874 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4875 4876 assert(!SetCC || 4877 (SetCC->getConstantOperandVal(1) == 1 && 4878 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4879 ISD::SETNE)); 4880 4881 // operands of the new intrinsic call 4882 SmallVector<SDValue, 4> Ops; 4883 if (HaveChain) 4884 Ops.push_back(BRCOND.getOperand(0)); 4885 4886 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4887 Ops.push_back(Target); 4888 4889 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4890 4891 // build the new intrinsic call 4892 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4893 4894 if (!HaveChain) { 4895 SDValue Ops[] = { 4896 SDValue(Result, 0), 4897 BRCOND.getOperand(0) 4898 }; 4899 4900 Result = DAG.getMergeValues(Ops, DL).getNode(); 4901 } 4902 4903 if (BR) { 4904 // Give the branch instruction our target 4905 SDValue Ops[] = { 4906 BR->getOperand(0), 4907 BRCOND.getOperand(2) 4908 }; 4909 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4910 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4911 } 4912 4913 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4914 4915 // Copy the intrinsic results to registers 4916 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4917 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4918 if (!CopyToReg) 4919 continue; 4920 4921 Chain = DAG.getCopyToReg( 4922 Chain, DL, 4923 CopyToReg->getOperand(1), 4924 SDValue(Result, i - 1), 4925 SDValue()); 4926 4927 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4928 } 4929 4930 // Remove the old intrinsic from the chain 4931 DAG.ReplaceAllUsesOfValueWith( 4932 SDValue(Intr, Intr->getNumValues() - 1), 4933 Intr->getOperand(0)); 4934 4935 return Chain; 4936 } 4937 4938 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4939 SelectionDAG &DAG) const { 4940 MVT VT = Op.getSimpleValueType(); 4941 SDLoc DL(Op); 4942 // Checking the depth 4943 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4944 return DAG.getConstant(0, DL, VT); 4945 4946 MachineFunction &MF = DAG.getMachineFunction(); 4947 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4948 // Check for kernel and shader functions 4949 if (Info->isEntryFunction()) 4950 return DAG.getConstant(0, DL, VT); 4951 4952 MachineFrameInfo &MFI = MF.getFrameInfo(); 4953 // There is a call to @llvm.returnaddress in this function 4954 MFI.setReturnAddressIsTaken(true); 4955 4956 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4957 // Get the return address reg and mark it as an implicit live-in 4958 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4959 4960 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4961 } 4962 4963 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4964 SDValue Op, 4965 const SDLoc &DL, 4966 EVT VT) const { 4967 return Op.getValueType().bitsLE(VT) ? 4968 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4969 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4970 DAG.getTargetConstant(0, DL, MVT::i32)); 4971 } 4972 4973 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4974 assert(Op.getValueType() == MVT::f16 && 4975 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4976 4977 SDValue Src = Op.getOperand(0); 4978 EVT SrcVT = Src.getValueType(); 4979 if (SrcVT != MVT::f64) 4980 return Op; 4981 4982 SDLoc DL(Op); 4983 4984 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4985 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4986 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4987 } 4988 4989 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4990 SelectionDAG &DAG) const { 4991 EVT VT = Op.getValueType(); 4992 const MachineFunction &MF = DAG.getMachineFunction(); 4993 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4994 bool IsIEEEMode = Info->getMode().IEEE; 4995 4996 // FIXME: Assert during selection that this is only selected for 4997 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4998 // mode functions, but this happens to be OK since it's only done in cases 4999 // where there is known no sNaN. 5000 if (IsIEEEMode) 5001 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5002 5003 if (VT == MVT::v4f16) 5004 return splitBinaryVectorOp(Op, DAG); 5005 return Op; 5006 } 5007 5008 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5009 EVT VT = Op.getValueType(); 5010 SDLoc SL(Op); 5011 SDValue LHS = Op.getOperand(0); 5012 SDValue RHS = Op.getOperand(1); 5013 bool isSigned = Op.getOpcode() == ISD::SMULO; 5014 5015 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5016 const APInt &C = RHSC->getAPIntValue(); 5017 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5018 if (C.isPowerOf2()) { 5019 // smulo(x, signed_min) is same as umulo(x, signed_min). 5020 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5021 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5022 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5023 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5024 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5025 SL, VT, Result, ShiftAmt), 5026 LHS, ISD::SETNE); 5027 return DAG.getMergeValues({ Result, Overflow }, SL); 5028 } 5029 } 5030 5031 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5032 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5033 SL, VT, LHS, RHS); 5034 5035 SDValue Sign = isSigned 5036 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5037 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5038 : DAG.getConstant(0, SL, VT); 5039 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5040 5041 return DAG.getMergeValues({ Result, Overflow }, SL); 5042 } 5043 5044 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5045 SDLoc SL(Op); 5046 SDValue Chain = Op.getOperand(0); 5047 5048 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5049 !Subtarget->isTrapHandlerEnabled()) 5050 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5051 5052 MachineFunction &MF = DAG.getMachineFunction(); 5053 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5054 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 5055 assert(UserSGPR != AMDGPU::NoRegister); 5056 SDValue QueuePtr = CreateLiveInRegister( 5057 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5058 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5059 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5060 QueuePtr, SDValue()); 5061 SDValue Ops[] = { 5062 ToReg, 5063 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5064 SGPR01, 5065 ToReg.getValue(1) 5066 }; 5067 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5068 } 5069 5070 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5071 SDLoc SL(Op); 5072 SDValue Chain = Op.getOperand(0); 5073 MachineFunction &MF = DAG.getMachineFunction(); 5074 5075 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5076 !Subtarget->isTrapHandlerEnabled()) { 5077 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5078 "debugtrap handler not supported", 5079 Op.getDebugLoc(), 5080 DS_Warning); 5081 LLVMContext &Ctx = MF.getFunction().getContext(); 5082 Ctx.diagnose(NoTrap); 5083 return Chain; 5084 } 5085 5086 SDValue Ops[] = { 5087 Chain, 5088 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5089 }; 5090 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5091 } 5092 5093 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5094 SelectionDAG &DAG) const { 5095 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5096 if (Subtarget->hasApertureRegs()) { 5097 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5098 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5099 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5100 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5101 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5102 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5103 unsigned Encoding = 5104 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5105 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5106 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5107 5108 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5109 SDValue ApertureReg = SDValue( 5110 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5111 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5112 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5113 } 5114 5115 MachineFunction &MF = DAG.getMachineFunction(); 5116 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5117 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5118 assert(UserSGPR != AMDGPU::NoRegister); 5119 5120 SDValue QueuePtr = CreateLiveInRegister( 5121 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5122 5123 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5124 // private_segment_aperture_base_hi. 5125 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5126 5127 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 5128 5129 // TODO: Use custom target PseudoSourceValue. 5130 // TODO: We should use the value from the IR intrinsic call, but it might not 5131 // be available and how do we get it? 5132 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5133 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5134 MinAlign(64, StructOffset), 5135 MachineMemOperand::MODereferenceable | 5136 MachineMemOperand::MOInvariant); 5137 } 5138 5139 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5140 SelectionDAG &DAG) const { 5141 SDLoc SL(Op); 5142 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5143 5144 SDValue Src = ASC->getOperand(0); 5145 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5146 5147 const AMDGPUTargetMachine &TM = 5148 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5149 5150 // flat -> local/private 5151 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5152 unsigned DestAS = ASC->getDestAddressSpace(); 5153 5154 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5155 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5156 unsigned NullVal = TM.getNullPointerValue(DestAS); 5157 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5158 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5159 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5160 5161 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5162 NonNull, Ptr, SegmentNullPtr); 5163 } 5164 } 5165 5166 // local/private -> flat 5167 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5168 unsigned SrcAS = ASC->getSrcAddressSpace(); 5169 5170 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5171 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5172 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5173 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5174 5175 SDValue NonNull 5176 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5177 5178 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5179 SDValue CvtPtr 5180 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5181 5182 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5183 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5184 FlatNullPtr); 5185 } 5186 } 5187 5188 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5189 Src.getValueType() == MVT::i64) 5190 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5191 5192 // global <-> flat are no-ops and never emitted. 5193 5194 const MachineFunction &MF = DAG.getMachineFunction(); 5195 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5196 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5197 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5198 5199 return DAG.getUNDEF(ASC->getValueType(0)); 5200 } 5201 5202 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5203 // the small vector and inserting them into the big vector. That is better than 5204 // the default expansion of doing it via a stack slot. Even though the use of 5205 // the stack slot would be optimized away afterwards, the stack slot itself 5206 // remains. 5207 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5208 SelectionDAG &DAG) const { 5209 SDValue Vec = Op.getOperand(0); 5210 SDValue Ins = Op.getOperand(1); 5211 SDValue Idx = Op.getOperand(2); 5212 EVT VecVT = Vec.getValueType(); 5213 EVT InsVT = Ins.getValueType(); 5214 EVT EltVT = VecVT.getVectorElementType(); 5215 unsigned InsNumElts = InsVT.getVectorNumElements(); 5216 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5217 SDLoc SL(Op); 5218 5219 for (unsigned I = 0; I != InsNumElts; ++I) { 5220 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5221 DAG.getConstant(I, SL, MVT::i32)); 5222 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5223 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5224 } 5225 return Vec; 5226 } 5227 5228 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5229 SelectionDAG &DAG) const { 5230 SDValue Vec = Op.getOperand(0); 5231 SDValue InsVal = Op.getOperand(1); 5232 SDValue Idx = Op.getOperand(2); 5233 EVT VecVT = Vec.getValueType(); 5234 EVT EltVT = VecVT.getVectorElementType(); 5235 unsigned VecSize = VecVT.getSizeInBits(); 5236 unsigned EltSize = EltVT.getSizeInBits(); 5237 5238 5239 assert(VecSize <= 64); 5240 5241 unsigned NumElts = VecVT.getVectorNumElements(); 5242 SDLoc SL(Op); 5243 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5244 5245 if (NumElts == 4 && EltSize == 16 && KIdx) { 5246 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5247 5248 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5249 DAG.getConstant(0, SL, MVT::i32)); 5250 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5251 DAG.getConstant(1, SL, MVT::i32)); 5252 5253 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5254 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5255 5256 unsigned Idx = KIdx->getZExtValue(); 5257 bool InsertLo = Idx < 2; 5258 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5259 InsertLo ? LoVec : HiVec, 5260 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5261 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5262 5263 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5264 5265 SDValue Concat = InsertLo ? 5266 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5267 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5268 5269 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5270 } 5271 5272 if (isa<ConstantSDNode>(Idx)) 5273 return SDValue(); 5274 5275 MVT IntVT = MVT::getIntegerVT(VecSize); 5276 5277 // Avoid stack access for dynamic indexing. 5278 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5279 5280 // Create a congruent vector with the target value in each element so that 5281 // the required element can be masked and ORed into the target vector. 5282 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5283 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5284 5285 assert(isPowerOf2_32(EltSize)); 5286 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5287 5288 // Convert vector index to bit-index. 5289 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5290 5291 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5292 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5293 DAG.getConstant(0xffff, SL, IntVT), 5294 ScaledIdx); 5295 5296 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5297 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5298 DAG.getNOT(SL, BFM, IntVT), BCVec); 5299 5300 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5301 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5302 } 5303 5304 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5305 SelectionDAG &DAG) const { 5306 SDLoc SL(Op); 5307 5308 EVT ResultVT = Op.getValueType(); 5309 SDValue Vec = Op.getOperand(0); 5310 SDValue Idx = Op.getOperand(1); 5311 EVT VecVT = Vec.getValueType(); 5312 unsigned VecSize = VecVT.getSizeInBits(); 5313 EVT EltVT = VecVT.getVectorElementType(); 5314 assert(VecSize <= 64); 5315 5316 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5317 5318 // Make sure we do any optimizations that will make it easier to fold 5319 // source modifiers before obscuring it with bit operations. 5320 5321 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5322 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5323 return Combined; 5324 5325 unsigned EltSize = EltVT.getSizeInBits(); 5326 assert(isPowerOf2_32(EltSize)); 5327 5328 MVT IntVT = MVT::getIntegerVT(VecSize); 5329 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5330 5331 // Convert vector index to bit-index (* EltSize) 5332 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5333 5334 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5335 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5336 5337 if (ResultVT == MVT::f16) { 5338 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5339 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5340 } 5341 5342 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5343 } 5344 5345 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5346 assert(Elt % 2 == 0); 5347 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5348 } 5349 5350 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5351 SelectionDAG &DAG) const { 5352 SDLoc SL(Op); 5353 EVT ResultVT = Op.getValueType(); 5354 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5355 5356 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5357 EVT EltVT = PackVT.getVectorElementType(); 5358 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5359 5360 // vector_shuffle <0,1,6,7> lhs, rhs 5361 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5362 // 5363 // vector_shuffle <6,7,2,3> lhs, rhs 5364 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5365 // 5366 // vector_shuffle <6,7,0,1> lhs, rhs 5367 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5368 5369 // Avoid scalarizing when both halves are reading from consecutive elements. 5370 SmallVector<SDValue, 4> Pieces; 5371 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5372 if (elementPairIsContiguous(SVN->getMask(), I)) { 5373 const int Idx = SVN->getMaskElt(I); 5374 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5375 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5376 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5377 PackVT, SVN->getOperand(VecIdx), 5378 DAG.getConstant(EltIdx, SL, MVT::i32)); 5379 Pieces.push_back(SubVec); 5380 } else { 5381 const int Idx0 = SVN->getMaskElt(I); 5382 const int Idx1 = SVN->getMaskElt(I + 1); 5383 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5384 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5385 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5386 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5387 5388 SDValue Vec0 = SVN->getOperand(VecIdx0); 5389 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5390 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5391 5392 SDValue Vec1 = SVN->getOperand(VecIdx1); 5393 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5394 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5395 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5396 } 5397 } 5398 5399 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5400 } 5401 5402 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5403 SelectionDAG &DAG) const { 5404 SDLoc SL(Op); 5405 EVT VT = Op.getValueType(); 5406 5407 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5408 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5409 5410 // Turn into pair of packed build_vectors. 5411 // TODO: Special case for constants that can be materialized with s_mov_b64. 5412 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5413 { Op.getOperand(0), Op.getOperand(1) }); 5414 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5415 { Op.getOperand(2), Op.getOperand(3) }); 5416 5417 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5418 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5419 5420 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5421 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5422 } 5423 5424 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5425 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5426 5427 SDValue Lo = Op.getOperand(0); 5428 SDValue Hi = Op.getOperand(1); 5429 5430 // Avoid adding defined bits with the zero_extend. 5431 if (Hi.isUndef()) { 5432 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5433 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5434 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5435 } 5436 5437 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5438 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5439 5440 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5441 DAG.getConstant(16, SL, MVT::i32)); 5442 if (Lo.isUndef()) 5443 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5444 5445 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5446 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5447 5448 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5449 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5450 } 5451 5452 bool 5453 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5454 // We can fold offsets for anything that doesn't require a GOT relocation. 5455 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5456 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5457 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5458 !shouldEmitGOTReloc(GA->getGlobal()); 5459 } 5460 5461 static SDValue 5462 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5463 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5464 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5465 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5466 // lowered to the following code sequence: 5467 // 5468 // For constant address space: 5469 // s_getpc_b64 s[0:1] 5470 // s_add_u32 s0, s0, $symbol 5471 // s_addc_u32 s1, s1, 0 5472 // 5473 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5474 // a fixup or relocation is emitted to replace $symbol with a literal 5475 // constant, which is a pc-relative offset from the encoding of the $symbol 5476 // operand to the global variable. 5477 // 5478 // For global address space: 5479 // s_getpc_b64 s[0:1] 5480 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5481 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5482 // 5483 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5484 // fixups or relocations are emitted to replace $symbol@*@lo and 5485 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5486 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5487 // operand to the global variable. 5488 // 5489 // What we want here is an offset from the value returned by s_getpc 5490 // (which is the address of the s_add_u32 instruction) to the global 5491 // variable, but since the encoding of $symbol starts 4 bytes after the start 5492 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5493 // small. This requires us to add 4 to the global variable offset in order to 5494 // compute the correct address. 5495 SDValue PtrLo = 5496 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5497 SDValue PtrHi; 5498 if (GAFlags == SIInstrInfo::MO_NONE) { 5499 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5500 } else { 5501 PtrHi = 5502 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5503 } 5504 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5505 } 5506 5507 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5508 SDValue Op, 5509 SelectionDAG &DAG) const { 5510 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5511 const GlobalValue *GV = GSD->getGlobal(); 5512 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5513 shouldUseLDSConstAddress(GV)) || 5514 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5515 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5516 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5517 5518 SDLoc DL(GSD); 5519 EVT PtrVT = Op.getValueType(); 5520 5521 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5522 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5523 SIInstrInfo::MO_ABS32_LO); 5524 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5525 } 5526 5527 if (shouldEmitFixup(GV)) 5528 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5529 else if (shouldEmitPCReloc(GV)) 5530 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5531 SIInstrInfo::MO_REL32); 5532 5533 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5534 SIInstrInfo::MO_GOTPCREL32); 5535 5536 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5537 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5538 const DataLayout &DataLayout = DAG.getDataLayout(); 5539 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5540 MachinePointerInfo PtrInfo 5541 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5542 5543 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5544 MachineMemOperand::MODereferenceable | 5545 MachineMemOperand::MOInvariant); 5546 } 5547 5548 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5549 const SDLoc &DL, SDValue V) const { 5550 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5551 // the destination register. 5552 // 5553 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5554 // so we will end up with redundant moves to m0. 5555 // 5556 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5557 5558 // A Null SDValue creates a glue result. 5559 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5560 V, Chain); 5561 return SDValue(M0, 0); 5562 } 5563 5564 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5565 SDValue Op, 5566 MVT VT, 5567 unsigned Offset) const { 5568 SDLoc SL(Op); 5569 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5570 DAG.getEntryNode(), Offset, 4, false); 5571 // The local size values will have the hi 16-bits as zero. 5572 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5573 DAG.getValueType(VT)); 5574 } 5575 5576 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5577 EVT VT) { 5578 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5579 "non-hsa intrinsic with hsa target", 5580 DL.getDebugLoc()); 5581 DAG.getContext()->diagnose(BadIntrin); 5582 return DAG.getUNDEF(VT); 5583 } 5584 5585 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5586 EVT VT) { 5587 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5588 "intrinsic not supported on subtarget", 5589 DL.getDebugLoc()); 5590 DAG.getContext()->diagnose(BadIntrin); 5591 return DAG.getUNDEF(VT); 5592 } 5593 5594 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5595 ArrayRef<SDValue> Elts) { 5596 assert(!Elts.empty()); 5597 MVT Type; 5598 unsigned NumElts; 5599 5600 if (Elts.size() == 1) { 5601 Type = MVT::f32; 5602 NumElts = 1; 5603 } else if (Elts.size() == 2) { 5604 Type = MVT::v2f32; 5605 NumElts = 2; 5606 } else if (Elts.size() == 3) { 5607 Type = MVT::v3f32; 5608 NumElts = 3; 5609 } else if (Elts.size() <= 4) { 5610 Type = MVT::v4f32; 5611 NumElts = 4; 5612 } else if (Elts.size() <= 8) { 5613 Type = MVT::v8f32; 5614 NumElts = 8; 5615 } else { 5616 assert(Elts.size() <= 16); 5617 Type = MVT::v16f32; 5618 NumElts = 16; 5619 } 5620 5621 SmallVector<SDValue, 16> VecElts(NumElts); 5622 for (unsigned i = 0; i < Elts.size(); ++i) { 5623 SDValue Elt = Elts[i]; 5624 if (Elt.getValueType() != MVT::f32) 5625 Elt = DAG.getBitcast(MVT::f32, Elt); 5626 VecElts[i] = Elt; 5627 } 5628 for (unsigned i = Elts.size(); i < NumElts; ++i) 5629 VecElts[i] = DAG.getUNDEF(MVT::f32); 5630 5631 if (NumElts == 1) 5632 return VecElts[0]; 5633 return DAG.getBuildVector(Type, DL, VecElts); 5634 } 5635 5636 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5637 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5638 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5639 5640 uint64_t Value = CachePolicyConst->getZExtValue(); 5641 SDLoc DL(CachePolicy); 5642 if (GLC) { 5643 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5644 Value &= ~(uint64_t)0x1; 5645 } 5646 if (SLC) { 5647 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5648 Value &= ~(uint64_t)0x2; 5649 } 5650 if (DLC) { 5651 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5652 Value &= ~(uint64_t)0x4; 5653 } 5654 5655 return Value == 0; 5656 } 5657 5658 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5659 SDValue Src, int ExtraElts) { 5660 EVT SrcVT = Src.getValueType(); 5661 5662 SmallVector<SDValue, 8> Elts; 5663 5664 if (SrcVT.isVector()) 5665 DAG.ExtractVectorElements(Src, Elts); 5666 else 5667 Elts.push_back(Src); 5668 5669 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5670 while (ExtraElts--) 5671 Elts.push_back(Undef); 5672 5673 return DAG.getBuildVector(CastVT, DL, Elts); 5674 } 5675 5676 // Re-construct the required return value for a image load intrinsic. 5677 // This is more complicated due to the optional use TexFailCtrl which means the required 5678 // return type is an aggregate 5679 static SDValue constructRetValue(SelectionDAG &DAG, 5680 MachineSDNode *Result, 5681 ArrayRef<EVT> ResultTypes, 5682 bool IsTexFail, bool Unpacked, bool IsD16, 5683 int DMaskPop, int NumVDataDwords, 5684 const SDLoc &DL, LLVMContext &Context) { 5685 // Determine the required return type. This is the same regardless of IsTexFail flag 5686 EVT ReqRetVT = ResultTypes[0]; 5687 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5688 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5689 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5690 5691 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5692 DMaskPop : (DMaskPop + 1) / 2; 5693 5694 MVT DataDwordVT = NumDataDwords == 1 ? 5695 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5696 5697 MVT MaskPopVT = MaskPopDwords == 1 ? 5698 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5699 5700 SDValue Data(Result, 0); 5701 SDValue TexFail; 5702 5703 if (IsTexFail) { 5704 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5705 if (MaskPopVT.isVector()) { 5706 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5707 SDValue(Result, 0), ZeroIdx); 5708 } else { 5709 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5710 SDValue(Result, 0), ZeroIdx); 5711 } 5712 5713 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5714 SDValue(Result, 0), 5715 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5716 } 5717 5718 if (DataDwordVT.isVector()) 5719 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5720 NumDataDwords - MaskPopDwords); 5721 5722 if (IsD16) 5723 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5724 5725 if (!ReqRetVT.isVector()) 5726 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5727 5728 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5729 5730 if (TexFail) 5731 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5732 5733 if (Result->getNumValues() == 1) 5734 return Data; 5735 5736 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5737 } 5738 5739 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5740 SDValue *LWE, bool &IsTexFail) { 5741 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5742 5743 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5744 if (Value) { 5745 IsTexFail = true; 5746 } 5747 5748 SDLoc DL(TexFailCtrlConst); 5749 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5750 Value &= ~(uint64_t)0x1; 5751 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5752 Value &= ~(uint64_t)0x2; 5753 5754 return Value == 0; 5755 } 5756 5757 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5758 MVT PackVectorVT, 5759 SmallVectorImpl<SDValue> &PackedAddrs, 5760 unsigned DimIdx, unsigned EndIdx, 5761 unsigned NumGradients) { 5762 SDLoc DL(Op); 5763 for (unsigned I = DimIdx; I < EndIdx; I++) { 5764 SDValue Addr = Op.getOperand(I); 5765 5766 // Gradients are packed with undef for each coordinate. 5767 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5768 // 1D: undef,dx/dh; undef,dx/dv 5769 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5770 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5771 if (((I + 1) >= EndIdx) || 5772 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5773 I == DimIdx + NumGradients - 1))) { 5774 if (Addr.getValueType() != MVT::i16) 5775 Addr = DAG.getBitcast(MVT::i16, Addr); 5776 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5777 } else { 5778 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5779 I++; 5780 } 5781 Addr = DAG.getBitcast(MVT::f32, Addr); 5782 PackedAddrs.push_back(Addr); 5783 } 5784 } 5785 5786 SDValue SITargetLowering::lowerImage(SDValue Op, 5787 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5788 SelectionDAG &DAG) const { 5789 SDLoc DL(Op); 5790 MachineFunction &MF = DAG.getMachineFunction(); 5791 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5792 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5793 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5794 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5795 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5796 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5797 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5798 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5799 unsigned IntrOpcode = Intr->BaseOpcode; 5800 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5801 5802 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5803 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5804 bool IsD16 = false; 5805 bool IsG16 = false; 5806 bool IsA16 = false; 5807 SDValue VData; 5808 int NumVDataDwords; 5809 bool AdjustRetType = false; 5810 5811 unsigned AddrIdx; // Index of first address argument 5812 unsigned DMask; 5813 unsigned DMaskLanes = 0; 5814 5815 if (BaseOpcode->Atomic) { 5816 VData = Op.getOperand(2); 5817 5818 bool Is64Bit = VData.getValueType() == MVT::i64; 5819 if (BaseOpcode->AtomicX2) { 5820 SDValue VData2 = Op.getOperand(3); 5821 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5822 {VData, VData2}); 5823 if (Is64Bit) 5824 VData = DAG.getBitcast(MVT::v4i32, VData); 5825 5826 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5827 DMask = Is64Bit ? 0xf : 0x3; 5828 NumVDataDwords = Is64Bit ? 4 : 2; 5829 AddrIdx = 4; 5830 } else { 5831 DMask = Is64Bit ? 0x3 : 0x1; 5832 NumVDataDwords = Is64Bit ? 2 : 1; 5833 AddrIdx = 3; 5834 } 5835 } else { 5836 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5837 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5838 DMask = DMaskConst->getZExtValue(); 5839 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5840 5841 if (BaseOpcode->Store) { 5842 VData = Op.getOperand(2); 5843 5844 MVT StoreVT = VData.getSimpleValueType(); 5845 if (StoreVT.getScalarType() == MVT::f16) { 5846 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5847 return Op; // D16 is unsupported for this instruction 5848 5849 IsD16 = true; 5850 VData = handleD16VData(VData, DAG); 5851 } 5852 5853 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5854 } else { 5855 // Work out the num dwords based on the dmask popcount and underlying type 5856 // and whether packing is supported. 5857 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5858 if (LoadVT.getScalarType() == MVT::f16) { 5859 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5860 return Op; // D16 is unsupported for this instruction 5861 5862 IsD16 = true; 5863 } 5864 5865 // Confirm that the return type is large enough for the dmask specified 5866 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5867 (!LoadVT.isVector() && DMaskLanes > 1)) 5868 return Op; 5869 5870 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5871 NumVDataDwords = (DMaskLanes + 1) / 2; 5872 else 5873 NumVDataDwords = DMaskLanes; 5874 5875 AdjustRetType = true; 5876 } 5877 5878 AddrIdx = DMaskIdx + 1; 5879 } 5880 5881 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5882 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5883 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5884 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5885 NumCoords + NumLCM; 5886 unsigned NumMIVAddrs = NumVAddrs; 5887 5888 SmallVector<SDValue, 4> VAddrs; 5889 5890 // Optimize _L to _LZ when _L is zero 5891 if (LZMappingInfo) { 5892 if (auto ConstantLod = 5893 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5894 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5895 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5896 NumMIVAddrs--; // remove 'lod' 5897 } 5898 } 5899 } 5900 5901 // Optimize _mip away, when 'lod' is zero 5902 if (MIPMappingInfo) { 5903 if (auto ConstantLod = 5904 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5905 if (ConstantLod->isNullValue()) { 5906 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5907 NumMIVAddrs--; // remove 'lod' 5908 } 5909 } 5910 } 5911 5912 // Push back extra arguments. 5913 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 5914 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 5915 5916 // Check for 16 bit addresses or derivatives and pack if true. 5917 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5918 unsigned CoordIdx = DimIdx + NumGradients; 5919 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 5920 5921 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5922 MVT VAddrScalarVT = VAddrVT.getScalarType(); 5923 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5924 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5925 5926 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 5927 VAddrScalarVT = VAddrVT.getScalarType(); 5928 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5929 if (IsA16 || IsG16) { 5930 if (IsA16) { 5931 if (!ST->hasA16()) { 5932 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5933 "support 16 bit addresses\n"); 5934 return Op; 5935 } 5936 if (!IsG16) { 5937 LLVM_DEBUG( 5938 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 5939 "need 16 bit derivatives but got 32 bit derivatives\n"); 5940 return Op; 5941 } 5942 } else if (!ST->hasG16()) { 5943 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5944 "support 16 bit derivatives\n"); 5945 return Op; 5946 } 5947 5948 if (BaseOpcode->Gradients && !IsA16) { 5949 if (!ST->hasG16()) { 5950 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5951 "support 16 bit derivatives\n"); 5952 return Op; 5953 } 5954 // Activate g16 5955 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 5956 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 5957 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 5958 } 5959 5960 // Don't compress addresses for G16 5961 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 5962 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 5963 PackEndIdx, NumGradients); 5964 5965 if (!IsA16) { 5966 // Add uncompressed address 5967 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 5968 VAddrs.push_back(Op.getOperand(I)); 5969 } 5970 } else { 5971 for (unsigned I = DimIdx; I < CoordsEnd; I++) 5972 VAddrs.push_back(Op.getOperand(I)); 5973 } 5974 5975 // If the register allocator cannot place the address registers contiguously 5976 // without introducing moves, then using the non-sequential address encoding 5977 // is always preferable, since it saves VALU instructions and is usually a 5978 // wash in terms of code size or even better. 5979 // 5980 // However, we currently have no way of hinting to the register allocator that 5981 // MIMG addresses should be placed contiguously when it is possible to do so, 5982 // so force non-NSA for the common 2-address case as a heuristic. 5983 // 5984 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5985 // allocation when possible. 5986 bool UseNSA = 5987 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5988 SDValue VAddr; 5989 if (!UseNSA) 5990 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5991 5992 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5993 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5994 unsigned CtrlIdx; // Index of texfailctrl argument 5995 SDValue Unorm; 5996 if (!BaseOpcode->Sampler) { 5997 Unorm = True; 5998 CtrlIdx = AddrIdx + NumVAddrs + 1; 5999 } else { 6000 auto UnormConst = 6001 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6002 6003 Unorm = UnormConst->getZExtValue() ? True : False; 6004 CtrlIdx = AddrIdx + NumVAddrs + 3; 6005 } 6006 6007 SDValue TFE; 6008 SDValue LWE; 6009 SDValue TexFail = Op.getOperand(CtrlIdx); 6010 bool IsTexFail = false; 6011 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6012 return Op; 6013 6014 if (IsTexFail) { 6015 if (!DMaskLanes) { 6016 // Expecting to get an error flag since TFC is on - and dmask is 0 6017 // Force dmask to be at least 1 otherwise the instruction will fail 6018 DMask = 0x1; 6019 DMaskLanes = 1; 6020 NumVDataDwords = 1; 6021 } 6022 NumVDataDwords += 1; 6023 AdjustRetType = true; 6024 } 6025 6026 // Has something earlier tagged that the return type needs adjusting 6027 // This happens if the instruction is a load or has set TexFailCtrl flags 6028 if (AdjustRetType) { 6029 // NumVDataDwords reflects the true number of dwords required in the return type 6030 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6031 // This is a no-op load. This can be eliminated 6032 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6033 if (isa<MemSDNode>(Op)) 6034 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6035 return Undef; 6036 } 6037 6038 EVT NewVT = NumVDataDwords > 1 ? 6039 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6040 : MVT::i32; 6041 6042 ResultTypes[0] = NewVT; 6043 if (ResultTypes.size() == 3) { 6044 // Original result was aggregate type used for TexFailCtrl results 6045 // The actual instruction returns as a vector type which has now been 6046 // created. Remove the aggregate result. 6047 ResultTypes.erase(&ResultTypes[1]); 6048 } 6049 } 6050 6051 SDValue GLC; 6052 SDValue SLC; 6053 SDValue DLC; 6054 if (BaseOpcode->Atomic) { 6055 GLC = True; // TODO no-return optimization 6056 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6057 IsGFX10 ? &DLC : nullptr)) 6058 return Op; 6059 } else { 6060 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6061 IsGFX10 ? &DLC : nullptr)) 6062 return Op; 6063 } 6064 6065 SmallVector<SDValue, 26> Ops; 6066 if (BaseOpcode->Store || BaseOpcode->Atomic) 6067 Ops.push_back(VData); // vdata 6068 if (UseNSA) { 6069 for (const SDValue &Addr : VAddrs) 6070 Ops.push_back(Addr); 6071 } else { 6072 Ops.push_back(VAddr); 6073 } 6074 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6075 if (BaseOpcode->Sampler) 6076 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6077 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6078 if (IsGFX10) 6079 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6080 Ops.push_back(Unorm); 6081 if (IsGFX10) 6082 Ops.push_back(DLC); 6083 Ops.push_back(GLC); 6084 Ops.push_back(SLC); 6085 Ops.push_back(IsA16 && // r128, a16 for gfx9 6086 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6087 if (IsGFX10) 6088 Ops.push_back(IsA16 ? True : False); 6089 Ops.push_back(TFE); 6090 Ops.push_back(LWE); 6091 if (!IsGFX10) 6092 Ops.push_back(DimInfo->DA ? True : False); 6093 if (BaseOpcode->HasD16) 6094 Ops.push_back(IsD16 ? True : False); 6095 if (isa<MemSDNode>(Op)) 6096 Ops.push_back(Op.getOperand(0)); // chain 6097 6098 int NumVAddrDwords = 6099 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6100 int Opcode = -1; 6101 6102 if (IsGFX10) { 6103 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6104 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6105 : AMDGPU::MIMGEncGfx10Default, 6106 NumVDataDwords, NumVAddrDwords); 6107 } else { 6108 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6109 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6110 NumVDataDwords, NumVAddrDwords); 6111 if (Opcode == -1) 6112 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6113 NumVDataDwords, NumVAddrDwords); 6114 } 6115 assert(Opcode != -1); 6116 6117 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6118 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6119 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6120 DAG.setNodeMemRefs(NewNode, {MemRef}); 6121 } 6122 6123 if (BaseOpcode->AtomicX2) { 6124 SmallVector<SDValue, 1> Elt; 6125 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6126 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6127 } else if (!BaseOpcode->Store) { 6128 return constructRetValue(DAG, NewNode, 6129 OrigResultTypes, IsTexFail, 6130 Subtarget->hasUnpackedD16VMem(), IsD16, 6131 DMaskLanes, NumVDataDwords, DL, 6132 *DAG.getContext()); 6133 } 6134 6135 return SDValue(NewNode, 0); 6136 } 6137 6138 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6139 SDValue Offset, SDValue CachePolicy, 6140 SelectionDAG &DAG) const { 6141 MachineFunction &MF = DAG.getMachineFunction(); 6142 6143 const DataLayout &DataLayout = DAG.getDataLayout(); 6144 Align Alignment = 6145 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6146 6147 MachineMemOperand *MMO = MF.getMachineMemOperand( 6148 MachinePointerInfo(), 6149 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6150 MachineMemOperand::MOInvariant, 6151 VT.getStoreSize(), Alignment); 6152 6153 if (!Offset->isDivergent()) { 6154 SDValue Ops[] = { 6155 Rsrc, 6156 Offset, // Offset 6157 CachePolicy 6158 }; 6159 6160 // Widen vec3 load to vec4. 6161 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6162 EVT WidenedVT = 6163 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6164 auto WidenedOp = DAG.getMemIntrinsicNode( 6165 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6166 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6167 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6168 DAG.getVectorIdxConstant(0, DL)); 6169 return Subvector; 6170 } 6171 6172 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6173 DAG.getVTList(VT), Ops, VT, MMO); 6174 } 6175 6176 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6177 // assume that the buffer is unswizzled. 6178 SmallVector<SDValue, 4> Loads; 6179 unsigned NumLoads = 1; 6180 MVT LoadVT = VT.getSimpleVT(); 6181 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6182 assert((LoadVT.getScalarType() == MVT::i32 || 6183 LoadVT.getScalarType() == MVT::f32)); 6184 6185 if (NumElts == 8 || NumElts == 16) { 6186 NumLoads = NumElts / 4; 6187 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6188 } 6189 6190 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6191 SDValue Ops[] = { 6192 DAG.getEntryNode(), // Chain 6193 Rsrc, // rsrc 6194 DAG.getConstant(0, DL, MVT::i32), // vindex 6195 {}, // voffset 6196 {}, // soffset 6197 {}, // offset 6198 CachePolicy, // cachepolicy 6199 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6200 }; 6201 6202 // Use the alignment to ensure that the required offsets will fit into the 6203 // immediate offsets. 6204 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 6205 6206 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6207 for (unsigned i = 0; i < NumLoads; ++i) { 6208 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6209 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6210 LoadVT, MMO, DAG)); 6211 } 6212 6213 if (NumElts == 8 || NumElts == 16) 6214 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6215 6216 return Loads[0]; 6217 } 6218 6219 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6220 SelectionDAG &DAG) const { 6221 MachineFunction &MF = DAG.getMachineFunction(); 6222 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6223 6224 EVT VT = Op.getValueType(); 6225 SDLoc DL(Op); 6226 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6227 6228 // TODO: Should this propagate fast-math-flags? 6229 6230 switch (IntrinsicID) { 6231 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6232 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6233 return emitNonHSAIntrinsicError(DAG, DL, VT); 6234 return getPreloadedValue(DAG, *MFI, VT, 6235 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6236 } 6237 case Intrinsic::amdgcn_dispatch_ptr: 6238 case Intrinsic::amdgcn_queue_ptr: { 6239 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6240 DiagnosticInfoUnsupported BadIntrin( 6241 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6242 DL.getDebugLoc()); 6243 DAG.getContext()->diagnose(BadIntrin); 6244 return DAG.getUNDEF(VT); 6245 } 6246 6247 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6248 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6249 return getPreloadedValue(DAG, *MFI, VT, RegID); 6250 } 6251 case Intrinsic::amdgcn_implicitarg_ptr: { 6252 if (MFI->isEntryFunction()) 6253 return getImplicitArgPtr(DAG, DL); 6254 return getPreloadedValue(DAG, *MFI, VT, 6255 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6256 } 6257 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6258 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6259 // This only makes sense to call in a kernel, so just lower to null. 6260 return DAG.getConstant(0, DL, VT); 6261 } 6262 6263 return getPreloadedValue(DAG, *MFI, VT, 6264 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6265 } 6266 case Intrinsic::amdgcn_dispatch_id: { 6267 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6268 } 6269 case Intrinsic::amdgcn_rcp: 6270 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6271 case Intrinsic::amdgcn_rsq: 6272 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6273 case Intrinsic::amdgcn_rsq_legacy: 6274 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6275 return emitRemovedIntrinsicError(DAG, DL, VT); 6276 return SDValue(); 6277 case Intrinsic::amdgcn_rcp_legacy: 6278 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6279 return emitRemovedIntrinsicError(DAG, DL, VT); 6280 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6281 case Intrinsic::amdgcn_rsq_clamp: { 6282 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6283 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6284 6285 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6286 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6287 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6288 6289 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6290 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6291 DAG.getConstantFP(Max, DL, VT)); 6292 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6293 DAG.getConstantFP(Min, DL, VT)); 6294 } 6295 case Intrinsic::r600_read_ngroups_x: 6296 if (Subtarget->isAmdHsaOS()) 6297 return emitNonHSAIntrinsicError(DAG, DL, VT); 6298 6299 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6300 SI::KernelInputOffsets::NGROUPS_X, 4, false); 6301 case Intrinsic::r600_read_ngroups_y: 6302 if (Subtarget->isAmdHsaOS()) 6303 return emitNonHSAIntrinsicError(DAG, DL, VT); 6304 6305 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6306 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 6307 case Intrinsic::r600_read_ngroups_z: 6308 if (Subtarget->isAmdHsaOS()) 6309 return emitNonHSAIntrinsicError(DAG, DL, VT); 6310 6311 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6312 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 6313 case Intrinsic::r600_read_global_size_x: 6314 if (Subtarget->isAmdHsaOS()) 6315 return emitNonHSAIntrinsicError(DAG, DL, VT); 6316 6317 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6318 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 6319 case Intrinsic::r600_read_global_size_y: 6320 if (Subtarget->isAmdHsaOS()) 6321 return emitNonHSAIntrinsicError(DAG, DL, VT); 6322 6323 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6324 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 6325 case Intrinsic::r600_read_global_size_z: 6326 if (Subtarget->isAmdHsaOS()) 6327 return emitNonHSAIntrinsicError(DAG, DL, VT); 6328 6329 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6330 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 6331 case Intrinsic::r600_read_local_size_x: 6332 if (Subtarget->isAmdHsaOS()) 6333 return emitNonHSAIntrinsicError(DAG, DL, VT); 6334 6335 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6336 SI::KernelInputOffsets::LOCAL_SIZE_X); 6337 case Intrinsic::r600_read_local_size_y: 6338 if (Subtarget->isAmdHsaOS()) 6339 return emitNonHSAIntrinsicError(DAG, DL, VT); 6340 6341 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6342 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6343 case Intrinsic::r600_read_local_size_z: 6344 if (Subtarget->isAmdHsaOS()) 6345 return emitNonHSAIntrinsicError(DAG, DL, VT); 6346 6347 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6348 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6349 case Intrinsic::amdgcn_workgroup_id_x: 6350 return getPreloadedValue(DAG, *MFI, VT, 6351 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6352 case Intrinsic::amdgcn_workgroup_id_y: 6353 return getPreloadedValue(DAG, *MFI, VT, 6354 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6355 case Intrinsic::amdgcn_workgroup_id_z: 6356 return getPreloadedValue(DAG, *MFI, VT, 6357 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6358 case Intrinsic::amdgcn_workitem_id_x: 6359 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6360 SDLoc(DAG.getEntryNode()), 6361 MFI->getArgInfo().WorkItemIDX); 6362 case Intrinsic::amdgcn_workitem_id_y: 6363 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6364 SDLoc(DAG.getEntryNode()), 6365 MFI->getArgInfo().WorkItemIDY); 6366 case Intrinsic::amdgcn_workitem_id_z: 6367 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6368 SDLoc(DAG.getEntryNode()), 6369 MFI->getArgInfo().WorkItemIDZ); 6370 case Intrinsic::amdgcn_wavefrontsize: 6371 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6372 SDLoc(Op), MVT::i32); 6373 case Intrinsic::amdgcn_s_buffer_load: { 6374 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6375 SDValue GLC; 6376 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6377 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6378 IsGFX10 ? &DLC : nullptr)) 6379 return Op; 6380 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6381 DAG); 6382 } 6383 case Intrinsic::amdgcn_fdiv_fast: 6384 return lowerFDIV_FAST(Op, DAG); 6385 case Intrinsic::amdgcn_sin: 6386 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6387 6388 case Intrinsic::amdgcn_cos: 6389 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6390 6391 case Intrinsic::amdgcn_mul_u24: 6392 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6393 case Intrinsic::amdgcn_mul_i24: 6394 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6395 6396 case Intrinsic::amdgcn_log_clamp: { 6397 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6398 return SDValue(); 6399 6400 DiagnosticInfoUnsupported BadIntrin( 6401 MF.getFunction(), "intrinsic not supported on subtarget", 6402 DL.getDebugLoc()); 6403 DAG.getContext()->diagnose(BadIntrin); 6404 return DAG.getUNDEF(VT); 6405 } 6406 case Intrinsic::amdgcn_ldexp: 6407 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6408 Op.getOperand(1), Op.getOperand(2)); 6409 6410 case Intrinsic::amdgcn_fract: 6411 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6412 6413 case Intrinsic::amdgcn_class: 6414 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6415 Op.getOperand(1), Op.getOperand(2)); 6416 case Intrinsic::amdgcn_div_fmas: 6417 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6418 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6419 Op.getOperand(4)); 6420 6421 case Intrinsic::amdgcn_div_fixup: 6422 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6423 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6424 6425 case Intrinsic::amdgcn_div_scale: { 6426 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6427 6428 // Translate to the operands expected by the machine instruction. The 6429 // first parameter must be the same as the first instruction. 6430 SDValue Numerator = Op.getOperand(1); 6431 SDValue Denominator = Op.getOperand(2); 6432 6433 // Note this order is opposite of the machine instruction's operations, 6434 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6435 // intrinsic has the numerator as the first operand to match a normal 6436 // division operation. 6437 6438 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6439 6440 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6441 Denominator, Numerator); 6442 } 6443 case Intrinsic::amdgcn_icmp: { 6444 // There is a Pat that handles this variant, so return it as-is. 6445 if (Op.getOperand(1).getValueType() == MVT::i1 && 6446 Op.getConstantOperandVal(2) == 0 && 6447 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6448 return Op; 6449 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6450 } 6451 case Intrinsic::amdgcn_fcmp: { 6452 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6453 } 6454 case Intrinsic::amdgcn_ballot: 6455 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6456 case Intrinsic::amdgcn_fmed3: 6457 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6458 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6459 case Intrinsic::amdgcn_fdot2: 6460 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6461 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6462 Op.getOperand(4)); 6463 case Intrinsic::amdgcn_fmul_legacy: 6464 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6465 Op.getOperand(1), Op.getOperand(2)); 6466 case Intrinsic::amdgcn_sffbh: 6467 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6468 case Intrinsic::amdgcn_sbfe: 6469 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6470 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6471 case Intrinsic::amdgcn_ubfe: 6472 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6473 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6474 case Intrinsic::amdgcn_cvt_pkrtz: 6475 case Intrinsic::amdgcn_cvt_pknorm_i16: 6476 case Intrinsic::amdgcn_cvt_pknorm_u16: 6477 case Intrinsic::amdgcn_cvt_pk_i16: 6478 case Intrinsic::amdgcn_cvt_pk_u16: { 6479 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6480 EVT VT = Op.getValueType(); 6481 unsigned Opcode; 6482 6483 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6484 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6485 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6486 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6487 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6488 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6489 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6490 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6491 else 6492 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6493 6494 if (isTypeLegal(VT)) 6495 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6496 6497 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6498 Op.getOperand(1), Op.getOperand(2)); 6499 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6500 } 6501 case Intrinsic::amdgcn_fmad_ftz: 6502 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6503 Op.getOperand(2), Op.getOperand(3)); 6504 6505 case Intrinsic::amdgcn_if_break: 6506 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6507 Op->getOperand(1), Op->getOperand(2)), 0); 6508 6509 case Intrinsic::amdgcn_groupstaticsize: { 6510 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6511 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6512 return Op; 6513 6514 const Module *M = MF.getFunction().getParent(); 6515 const GlobalValue *GV = 6516 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6517 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6518 SIInstrInfo::MO_ABS32_LO); 6519 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6520 } 6521 case Intrinsic::amdgcn_is_shared: 6522 case Intrinsic::amdgcn_is_private: { 6523 SDLoc SL(Op); 6524 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6525 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6526 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6527 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6528 Op.getOperand(1)); 6529 6530 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6531 DAG.getConstant(1, SL, MVT::i32)); 6532 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6533 } 6534 case Intrinsic::amdgcn_alignbit: 6535 return DAG.getNode(ISD::FSHR, DL, VT, 6536 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6537 case Intrinsic::amdgcn_reloc_constant: { 6538 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6539 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6540 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6541 auto RelocSymbol = cast<GlobalVariable>( 6542 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6543 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6544 SIInstrInfo::MO_ABS32_LO); 6545 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6546 } 6547 default: 6548 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6549 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6550 return lowerImage(Op, ImageDimIntr, DAG); 6551 6552 return Op; 6553 } 6554 } 6555 6556 // This function computes an appropriate offset to pass to 6557 // MachineMemOperand::setOffset() based on the offset inputs to 6558 // an intrinsic. If any of the offsets are non-contstant or 6559 // if VIndex is non-zero then this function returns 0. Otherwise, 6560 // it returns the sum of VOffset, SOffset, and Offset. 6561 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6562 SDValue SOffset, 6563 SDValue Offset, 6564 SDValue VIndex = SDValue()) { 6565 6566 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6567 !isa<ConstantSDNode>(Offset)) 6568 return 0; 6569 6570 if (VIndex) { 6571 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6572 return 0; 6573 } 6574 6575 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6576 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6577 cast<ConstantSDNode>(Offset)->getSExtValue(); 6578 } 6579 6580 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6581 switch (MF.getFunction().getCallingConv()) { 6582 case CallingConv::AMDGPU_PS: 6583 return 1; 6584 case CallingConv::AMDGPU_VS: 6585 return 2; 6586 case CallingConv::AMDGPU_GS: 6587 return 3; 6588 case CallingConv::AMDGPU_HS: 6589 case CallingConv::AMDGPU_LS: 6590 case CallingConv::AMDGPU_ES: 6591 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6592 case CallingConv::AMDGPU_CS: 6593 case CallingConv::AMDGPU_KERNEL: 6594 case CallingConv::C: 6595 case CallingConv::Fast: 6596 default: 6597 // Assume other calling conventions are various compute callable functions 6598 return 0; 6599 } 6600 } 6601 6602 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6603 SelectionDAG &DAG) const { 6604 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6605 SDLoc DL(Op); 6606 6607 switch (IntrID) { 6608 case Intrinsic::amdgcn_ds_ordered_add: 6609 case Intrinsic::amdgcn_ds_ordered_swap: { 6610 MemSDNode *M = cast<MemSDNode>(Op); 6611 SDValue Chain = M->getOperand(0); 6612 SDValue M0 = M->getOperand(2); 6613 SDValue Value = M->getOperand(3); 6614 unsigned IndexOperand = M->getConstantOperandVal(7); 6615 unsigned WaveRelease = M->getConstantOperandVal(8); 6616 unsigned WaveDone = M->getConstantOperandVal(9); 6617 6618 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6619 IndexOperand &= ~0x3f; 6620 unsigned CountDw = 0; 6621 6622 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6623 CountDw = (IndexOperand >> 24) & 0xf; 6624 IndexOperand &= ~(0xf << 24); 6625 6626 if (CountDw < 1 || CountDw > 4) { 6627 report_fatal_error( 6628 "ds_ordered_count: dword count must be between 1 and 4"); 6629 } 6630 } 6631 6632 if (IndexOperand) 6633 report_fatal_error("ds_ordered_count: bad index operand"); 6634 6635 if (WaveDone && !WaveRelease) 6636 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6637 6638 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6639 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6640 unsigned Offset0 = OrderedCountIndex << 2; 6641 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6642 (Instruction << 4); 6643 6644 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6645 Offset1 |= (CountDw - 1) << 6; 6646 6647 unsigned Offset = Offset0 | (Offset1 << 8); 6648 6649 SDValue Ops[] = { 6650 Chain, 6651 Value, 6652 DAG.getTargetConstant(Offset, DL, MVT::i16), 6653 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6654 }; 6655 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6656 M->getVTList(), Ops, M->getMemoryVT(), 6657 M->getMemOperand()); 6658 } 6659 case Intrinsic::amdgcn_ds_fadd: { 6660 MemSDNode *M = cast<MemSDNode>(Op); 6661 unsigned Opc; 6662 switch (IntrID) { 6663 case Intrinsic::amdgcn_ds_fadd: 6664 Opc = ISD::ATOMIC_LOAD_FADD; 6665 break; 6666 } 6667 6668 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6669 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6670 M->getMemOperand()); 6671 } 6672 case Intrinsic::amdgcn_atomic_inc: 6673 case Intrinsic::amdgcn_atomic_dec: 6674 case Intrinsic::amdgcn_ds_fmin: 6675 case Intrinsic::amdgcn_ds_fmax: { 6676 MemSDNode *M = cast<MemSDNode>(Op); 6677 unsigned Opc; 6678 switch (IntrID) { 6679 case Intrinsic::amdgcn_atomic_inc: 6680 Opc = AMDGPUISD::ATOMIC_INC; 6681 break; 6682 case Intrinsic::amdgcn_atomic_dec: 6683 Opc = AMDGPUISD::ATOMIC_DEC; 6684 break; 6685 case Intrinsic::amdgcn_ds_fmin: 6686 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6687 break; 6688 case Intrinsic::amdgcn_ds_fmax: 6689 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6690 break; 6691 default: 6692 llvm_unreachable("Unknown intrinsic!"); 6693 } 6694 SDValue Ops[] = { 6695 M->getOperand(0), // Chain 6696 M->getOperand(2), // Ptr 6697 M->getOperand(3) // Value 6698 }; 6699 6700 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6701 M->getMemoryVT(), M->getMemOperand()); 6702 } 6703 case Intrinsic::amdgcn_buffer_load: 6704 case Intrinsic::amdgcn_buffer_load_format: { 6705 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6706 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6707 unsigned IdxEn = 1; 6708 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6709 IdxEn = Idx->getZExtValue() != 0; 6710 SDValue Ops[] = { 6711 Op.getOperand(0), // Chain 6712 Op.getOperand(2), // rsrc 6713 Op.getOperand(3), // vindex 6714 SDValue(), // voffset -- will be set by setBufferOffsets 6715 SDValue(), // soffset -- will be set by setBufferOffsets 6716 SDValue(), // offset -- will be set by setBufferOffsets 6717 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6718 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6719 }; 6720 6721 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6722 // We don't know the offset if vindex is non-zero, so clear it. 6723 if (IdxEn) 6724 Offset = 0; 6725 6726 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6727 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6728 6729 EVT VT = Op.getValueType(); 6730 EVT IntVT = VT.changeTypeToInteger(); 6731 auto *M = cast<MemSDNode>(Op); 6732 M->getMemOperand()->setOffset(Offset); 6733 EVT LoadVT = Op.getValueType(); 6734 6735 if (LoadVT.getScalarType() == MVT::f16) 6736 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6737 M, DAG, Ops); 6738 6739 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6740 if (LoadVT.getScalarType() == MVT::i8 || 6741 LoadVT.getScalarType() == MVT::i16) 6742 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6743 6744 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6745 M->getMemOperand(), DAG); 6746 } 6747 case Intrinsic::amdgcn_raw_buffer_load: 6748 case Intrinsic::amdgcn_raw_buffer_load_format: { 6749 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6750 6751 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6752 SDValue Ops[] = { 6753 Op.getOperand(0), // Chain 6754 Op.getOperand(2), // rsrc 6755 DAG.getConstant(0, DL, MVT::i32), // vindex 6756 Offsets.first, // voffset 6757 Op.getOperand(4), // soffset 6758 Offsets.second, // offset 6759 Op.getOperand(5), // cachepolicy, swizzled buffer 6760 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6761 }; 6762 6763 auto *M = cast<MemSDNode>(Op); 6764 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6765 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6766 } 6767 case Intrinsic::amdgcn_struct_buffer_load: 6768 case Intrinsic::amdgcn_struct_buffer_load_format: { 6769 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6770 6771 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6772 SDValue Ops[] = { 6773 Op.getOperand(0), // Chain 6774 Op.getOperand(2), // rsrc 6775 Op.getOperand(3), // vindex 6776 Offsets.first, // voffset 6777 Op.getOperand(5), // soffset 6778 Offsets.second, // offset 6779 Op.getOperand(6), // cachepolicy, swizzled buffer 6780 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6781 }; 6782 6783 auto *M = cast<MemSDNode>(Op); 6784 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6785 Ops[2])); 6786 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6787 } 6788 case Intrinsic::amdgcn_tbuffer_load: { 6789 MemSDNode *M = cast<MemSDNode>(Op); 6790 EVT LoadVT = Op.getValueType(); 6791 6792 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6793 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6794 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6795 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6796 unsigned IdxEn = 1; 6797 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6798 IdxEn = Idx->getZExtValue() != 0; 6799 SDValue Ops[] = { 6800 Op.getOperand(0), // Chain 6801 Op.getOperand(2), // rsrc 6802 Op.getOperand(3), // vindex 6803 Op.getOperand(4), // voffset 6804 Op.getOperand(5), // soffset 6805 Op.getOperand(6), // offset 6806 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6807 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6808 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6809 }; 6810 6811 if (LoadVT.getScalarType() == MVT::f16) 6812 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6813 M, DAG, Ops); 6814 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6815 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6816 DAG); 6817 } 6818 case Intrinsic::amdgcn_raw_tbuffer_load: { 6819 MemSDNode *M = cast<MemSDNode>(Op); 6820 EVT LoadVT = Op.getValueType(); 6821 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6822 6823 SDValue Ops[] = { 6824 Op.getOperand(0), // Chain 6825 Op.getOperand(2), // rsrc 6826 DAG.getConstant(0, DL, MVT::i32), // vindex 6827 Offsets.first, // voffset 6828 Op.getOperand(4), // soffset 6829 Offsets.second, // offset 6830 Op.getOperand(5), // format 6831 Op.getOperand(6), // cachepolicy, swizzled buffer 6832 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6833 }; 6834 6835 if (LoadVT.getScalarType() == MVT::f16) 6836 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6837 M, DAG, Ops); 6838 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6839 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6840 DAG); 6841 } 6842 case Intrinsic::amdgcn_struct_tbuffer_load: { 6843 MemSDNode *M = cast<MemSDNode>(Op); 6844 EVT LoadVT = Op.getValueType(); 6845 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6846 6847 SDValue Ops[] = { 6848 Op.getOperand(0), // Chain 6849 Op.getOperand(2), // rsrc 6850 Op.getOperand(3), // vindex 6851 Offsets.first, // voffset 6852 Op.getOperand(5), // soffset 6853 Offsets.second, // offset 6854 Op.getOperand(6), // format 6855 Op.getOperand(7), // cachepolicy, swizzled buffer 6856 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6857 }; 6858 6859 if (LoadVT.getScalarType() == MVT::f16) 6860 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6861 M, DAG, Ops); 6862 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6863 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6864 DAG); 6865 } 6866 case Intrinsic::amdgcn_buffer_atomic_swap: 6867 case Intrinsic::amdgcn_buffer_atomic_add: 6868 case Intrinsic::amdgcn_buffer_atomic_sub: 6869 case Intrinsic::amdgcn_buffer_atomic_csub: 6870 case Intrinsic::amdgcn_buffer_atomic_smin: 6871 case Intrinsic::amdgcn_buffer_atomic_umin: 6872 case Intrinsic::amdgcn_buffer_atomic_smax: 6873 case Intrinsic::amdgcn_buffer_atomic_umax: 6874 case Intrinsic::amdgcn_buffer_atomic_and: 6875 case Intrinsic::amdgcn_buffer_atomic_or: 6876 case Intrinsic::amdgcn_buffer_atomic_xor: { 6877 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6878 unsigned IdxEn = 1; 6879 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6880 IdxEn = Idx->getZExtValue() != 0; 6881 SDValue Ops[] = { 6882 Op.getOperand(0), // Chain 6883 Op.getOperand(2), // vdata 6884 Op.getOperand(3), // rsrc 6885 Op.getOperand(4), // vindex 6886 SDValue(), // voffset -- will be set by setBufferOffsets 6887 SDValue(), // soffset -- will be set by setBufferOffsets 6888 SDValue(), // offset -- will be set by setBufferOffsets 6889 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6890 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6891 }; 6892 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6893 // We don't know the offset if vindex is non-zero, so clear it. 6894 if (IdxEn) 6895 Offset = 0; 6896 EVT VT = Op.getValueType(); 6897 6898 auto *M = cast<MemSDNode>(Op); 6899 M->getMemOperand()->setOffset(Offset); 6900 unsigned Opcode = 0; 6901 6902 switch (IntrID) { 6903 case Intrinsic::amdgcn_buffer_atomic_swap: 6904 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6905 break; 6906 case Intrinsic::amdgcn_buffer_atomic_add: 6907 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6908 break; 6909 case Intrinsic::amdgcn_buffer_atomic_sub: 6910 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6911 break; 6912 case Intrinsic::amdgcn_buffer_atomic_csub: 6913 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 6914 break; 6915 case Intrinsic::amdgcn_buffer_atomic_smin: 6916 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6917 break; 6918 case Intrinsic::amdgcn_buffer_atomic_umin: 6919 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6920 break; 6921 case Intrinsic::amdgcn_buffer_atomic_smax: 6922 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6923 break; 6924 case Intrinsic::amdgcn_buffer_atomic_umax: 6925 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6926 break; 6927 case Intrinsic::amdgcn_buffer_atomic_and: 6928 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6929 break; 6930 case Intrinsic::amdgcn_buffer_atomic_or: 6931 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6932 break; 6933 case Intrinsic::amdgcn_buffer_atomic_xor: 6934 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6935 break; 6936 default: 6937 llvm_unreachable("unhandled atomic opcode"); 6938 } 6939 6940 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6941 M->getMemOperand()); 6942 } 6943 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6944 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6945 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6946 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6947 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6948 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6949 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6950 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6951 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6952 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6953 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6954 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6955 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6956 SDValue Ops[] = { 6957 Op.getOperand(0), // Chain 6958 Op.getOperand(2), // vdata 6959 Op.getOperand(3), // rsrc 6960 DAG.getConstant(0, DL, MVT::i32), // vindex 6961 Offsets.first, // voffset 6962 Op.getOperand(5), // soffset 6963 Offsets.second, // offset 6964 Op.getOperand(6), // cachepolicy 6965 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6966 }; 6967 EVT VT = Op.getValueType(); 6968 6969 auto *M = cast<MemSDNode>(Op); 6970 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6971 unsigned Opcode = 0; 6972 6973 switch (IntrID) { 6974 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6975 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6976 break; 6977 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6978 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6979 break; 6980 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6981 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6982 break; 6983 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6984 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6985 break; 6986 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6987 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6988 break; 6989 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6990 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6991 break; 6992 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6993 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6994 break; 6995 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6996 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6997 break; 6998 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6999 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7000 break; 7001 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7002 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7003 break; 7004 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7005 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7006 break; 7007 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7008 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7009 break; 7010 default: 7011 llvm_unreachable("unhandled atomic opcode"); 7012 } 7013 7014 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7015 M->getMemOperand()); 7016 } 7017 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7018 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7019 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7020 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7021 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7022 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7023 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7024 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7025 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7026 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7027 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7028 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 7029 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7030 SDValue Ops[] = { 7031 Op.getOperand(0), // Chain 7032 Op.getOperand(2), // vdata 7033 Op.getOperand(3), // rsrc 7034 Op.getOperand(4), // vindex 7035 Offsets.first, // voffset 7036 Op.getOperand(6), // soffset 7037 Offsets.second, // offset 7038 Op.getOperand(7), // cachepolicy 7039 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7040 }; 7041 EVT VT = Op.getValueType(); 7042 7043 auto *M = cast<MemSDNode>(Op); 7044 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7045 Ops[3])); 7046 unsigned Opcode = 0; 7047 7048 switch (IntrID) { 7049 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7050 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7051 break; 7052 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7053 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7054 break; 7055 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7056 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7057 break; 7058 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7059 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7060 break; 7061 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7062 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7063 break; 7064 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7065 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7066 break; 7067 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7068 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7069 break; 7070 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7071 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7072 break; 7073 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7074 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7075 break; 7076 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7077 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7078 break; 7079 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7080 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7081 break; 7082 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7083 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7084 break; 7085 default: 7086 llvm_unreachable("unhandled atomic opcode"); 7087 } 7088 7089 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7090 M->getMemOperand()); 7091 } 7092 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7093 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7094 unsigned IdxEn = 1; 7095 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7096 IdxEn = Idx->getZExtValue() != 0; 7097 SDValue Ops[] = { 7098 Op.getOperand(0), // Chain 7099 Op.getOperand(2), // src 7100 Op.getOperand(3), // cmp 7101 Op.getOperand(4), // rsrc 7102 Op.getOperand(5), // vindex 7103 SDValue(), // voffset -- will be set by setBufferOffsets 7104 SDValue(), // soffset -- will be set by setBufferOffsets 7105 SDValue(), // offset -- will be set by setBufferOffsets 7106 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7107 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7108 }; 7109 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7110 // We don't know the offset if vindex is non-zero, so clear it. 7111 if (IdxEn) 7112 Offset = 0; 7113 EVT VT = Op.getValueType(); 7114 auto *M = cast<MemSDNode>(Op); 7115 M->getMemOperand()->setOffset(Offset); 7116 7117 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7118 Op->getVTList(), Ops, VT, M->getMemOperand()); 7119 } 7120 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7121 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7122 SDValue Ops[] = { 7123 Op.getOperand(0), // Chain 7124 Op.getOperand(2), // src 7125 Op.getOperand(3), // cmp 7126 Op.getOperand(4), // rsrc 7127 DAG.getConstant(0, DL, MVT::i32), // vindex 7128 Offsets.first, // voffset 7129 Op.getOperand(6), // soffset 7130 Offsets.second, // offset 7131 Op.getOperand(7), // cachepolicy 7132 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7133 }; 7134 EVT VT = Op.getValueType(); 7135 auto *M = cast<MemSDNode>(Op); 7136 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7137 7138 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7139 Op->getVTList(), Ops, VT, M->getMemOperand()); 7140 } 7141 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7142 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7143 SDValue Ops[] = { 7144 Op.getOperand(0), // Chain 7145 Op.getOperand(2), // src 7146 Op.getOperand(3), // cmp 7147 Op.getOperand(4), // rsrc 7148 Op.getOperand(5), // vindex 7149 Offsets.first, // voffset 7150 Op.getOperand(7), // soffset 7151 Offsets.second, // offset 7152 Op.getOperand(8), // cachepolicy 7153 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7154 }; 7155 EVT VT = Op.getValueType(); 7156 auto *M = cast<MemSDNode>(Op); 7157 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7158 Ops[4])); 7159 7160 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7161 Op->getVTList(), Ops, VT, M->getMemOperand()); 7162 } 7163 case Intrinsic::amdgcn_global_atomic_csub: { 7164 MemSDNode *M = cast<MemSDNode>(Op); 7165 SDValue Ops[] = { 7166 M->getOperand(0), // Chain 7167 M->getOperand(2), // Ptr 7168 M->getOperand(3) // Value 7169 }; 7170 7171 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_LOAD_CSUB, SDLoc(Op), 7172 M->getVTList(), Ops, M->getMemoryVT(), 7173 M->getMemOperand()); 7174 } 7175 7176 default: 7177 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7178 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7179 return lowerImage(Op, ImageDimIntr, DAG); 7180 7181 return SDValue(); 7182 } 7183 } 7184 7185 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7186 // dwordx4 if on SI. 7187 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7188 SDVTList VTList, 7189 ArrayRef<SDValue> Ops, EVT MemVT, 7190 MachineMemOperand *MMO, 7191 SelectionDAG &DAG) const { 7192 EVT VT = VTList.VTs[0]; 7193 EVT WidenedVT = VT; 7194 EVT WidenedMemVT = MemVT; 7195 if (!Subtarget->hasDwordx3LoadStores() && 7196 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7197 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7198 WidenedVT.getVectorElementType(), 4); 7199 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7200 WidenedMemVT.getVectorElementType(), 4); 7201 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7202 } 7203 7204 assert(VTList.NumVTs == 2); 7205 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7206 7207 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7208 WidenedMemVT, MMO); 7209 if (WidenedVT != VT) { 7210 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7211 DAG.getVectorIdxConstant(0, DL)); 7212 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7213 } 7214 return NewOp; 7215 } 7216 7217 SDValue SITargetLowering::handleD16VData(SDValue VData, 7218 SelectionDAG &DAG) const { 7219 EVT StoreVT = VData.getValueType(); 7220 7221 // No change for f16 and legal vector D16 types. 7222 if (!StoreVT.isVector()) 7223 return VData; 7224 7225 SDLoc DL(VData); 7226 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7227 7228 if (Subtarget->hasUnpackedD16VMem()) { 7229 // We need to unpack the packed data to store. 7230 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7231 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7232 7233 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7234 StoreVT.getVectorNumElements()); 7235 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7236 return DAG.UnrollVectorOp(ZExt.getNode()); 7237 } 7238 7239 assert(isTypeLegal(StoreVT)); 7240 return VData; 7241 } 7242 7243 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7244 SelectionDAG &DAG) const { 7245 SDLoc DL(Op); 7246 SDValue Chain = Op.getOperand(0); 7247 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7248 MachineFunction &MF = DAG.getMachineFunction(); 7249 7250 switch (IntrinsicID) { 7251 case Intrinsic::amdgcn_exp_compr: { 7252 SDValue Src0 = Op.getOperand(4); 7253 SDValue Src1 = Op.getOperand(5); 7254 // Hack around illegal type on SI by directly selecting it. 7255 if (isTypeLegal(Src0.getValueType())) 7256 return SDValue(); 7257 7258 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7259 SDValue Undef = DAG.getUNDEF(MVT::f32); 7260 const SDValue Ops[] = { 7261 Op.getOperand(2), // tgt 7262 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7263 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7264 Undef, // src2 7265 Undef, // src3 7266 Op.getOperand(7), // vm 7267 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7268 Op.getOperand(3), // en 7269 Op.getOperand(0) // Chain 7270 }; 7271 7272 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7273 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7274 } 7275 case Intrinsic::amdgcn_s_barrier: { 7276 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7277 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7278 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7279 if (WGSize <= ST.getWavefrontSize()) 7280 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7281 Op.getOperand(0)), 0); 7282 } 7283 return SDValue(); 7284 }; 7285 case Intrinsic::amdgcn_tbuffer_store: { 7286 SDValue VData = Op.getOperand(2); 7287 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7288 if (IsD16) 7289 VData = handleD16VData(VData, DAG); 7290 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7291 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7292 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7293 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7294 unsigned IdxEn = 1; 7295 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7296 IdxEn = Idx->getZExtValue() != 0; 7297 SDValue Ops[] = { 7298 Chain, 7299 VData, // vdata 7300 Op.getOperand(3), // rsrc 7301 Op.getOperand(4), // vindex 7302 Op.getOperand(5), // voffset 7303 Op.getOperand(6), // soffset 7304 Op.getOperand(7), // offset 7305 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7306 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7307 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7308 }; 7309 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7310 AMDGPUISD::TBUFFER_STORE_FORMAT; 7311 MemSDNode *M = cast<MemSDNode>(Op); 7312 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7313 M->getMemoryVT(), M->getMemOperand()); 7314 } 7315 7316 case Intrinsic::amdgcn_struct_tbuffer_store: { 7317 SDValue VData = Op.getOperand(2); 7318 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7319 if (IsD16) 7320 VData = handleD16VData(VData, DAG); 7321 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7322 SDValue Ops[] = { 7323 Chain, 7324 VData, // vdata 7325 Op.getOperand(3), // rsrc 7326 Op.getOperand(4), // vindex 7327 Offsets.first, // voffset 7328 Op.getOperand(6), // soffset 7329 Offsets.second, // offset 7330 Op.getOperand(7), // format 7331 Op.getOperand(8), // cachepolicy, swizzled buffer 7332 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7333 }; 7334 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7335 AMDGPUISD::TBUFFER_STORE_FORMAT; 7336 MemSDNode *M = cast<MemSDNode>(Op); 7337 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7338 M->getMemoryVT(), M->getMemOperand()); 7339 } 7340 7341 case Intrinsic::amdgcn_raw_tbuffer_store: { 7342 SDValue VData = Op.getOperand(2); 7343 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7344 if (IsD16) 7345 VData = handleD16VData(VData, DAG); 7346 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7347 SDValue Ops[] = { 7348 Chain, 7349 VData, // vdata 7350 Op.getOperand(3), // rsrc 7351 DAG.getConstant(0, DL, MVT::i32), // vindex 7352 Offsets.first, // voffset 7353 Op.getOperand(5), // soffset 7354 Offsets.second, // offset 7355 Op.getOperand(6), // format 7356 Op.getOperand(7), // cachepolicy, swizzled buffer 7357 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7358 }; 7359 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7360 AMDGPUISD::TBUFFER_STORE_FORMAT; 7361 MemSDNode *M = cast<MemSDNode>(Op); 7362 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7363 M->getMemoryVT(), M->getMemOperand()); 7364 } 7365 7366 case Intrinsic::amdgcn_buffer_store: 7367 case Intrinsic::amdgcn_buffer_store_format: { 7368 SDValue VData = Op.getOperand(2); 7369 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7370 if (IsD16) 7371 VData = handleD16VData(VData, DAG); 7372 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7373 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7374 unsigned IdxEn = 1; 7375 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7376 IdxEn = Idx->getZExtValue() != 0; 7377 SDValue Ops[] = { 7378 Chain, 7379 VData, 7380 Op.getOperand(3), // rsrc 7381 Op.getOperand(4), // vindex 7382 SDValue(), // voffset -- will be set by setBufferOffsets 7383 SDValue(), // soffset -- will be set by setBufferOffsets 7384 SDValue(), // offset -- will be set by setBufferOffsets 7385 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7386 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7387 }; 7388 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7389 // We don't know the offset if vindex is non-zero, so clear it. 7390 if (IdxEn) 7391 Offset = 0; 7392 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7393 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7394 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7395 MemSDNode *M = cast<MemSDNode>(Op); 7396 M->getMemOperand()->setOffset(Offset); 7397 7398 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7399 EVT VDataType = VData.getValueType().getScalarType(); 7400 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7401 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7402 7403 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7404 M->getMemoryVT(), M->getMemOperand()); 7405 } 7406 7407 case Intrinsic::amdgcn_raw_buffer_store: 7408 case Intrinsic::amdgcn_raw_buffer_store_format: { 7409 const bool IsFormat = 7410 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7411 7412 SDValue VData = Op.getOperand(2); 7413 EVT VDataVT = VData.getValueType(); 7414 EVT EltType = VDataVT.getScalarType(); 7415 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7416 if (IsD16) 7417 VData = handleD16VData(VData, DAG); 7418 7419 if (!isTypeLegal(VDataVT)) { 7420 VData = 7421 DAG.getNode(ISD::BITCAST, DL, 7422 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7423 } 7424 7425 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7426 SDValue Ops[] = { 7427 Chain, 7428 VData, 7429 Op.getOperand(3), // rsrc 7430 DAG.getConstant(0, DL, MVT::i32), // vindex 7431 Offsets.first, // voffset 7432 Op.getOperand(5), // soffset 7433 Offsets.second, // offset 7434 Op.getOperand(6), // cachepolicy, swizzled buffer 7435 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7436 }; 7437 unsigned Opc = 7438 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7439 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7440 MemSDNode *M = cast<MemSDNode>(Op); 7441 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7442 7443 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7444 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7445 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7446 7447 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7448 M->getMemoryVT(), M->getMemOperand()); 7449 } 7450 7451 case Intrinsic::amdgcn_struct_buffer_store: 7452 case Intrinsic::amdgcn_struct_buffer_store_format: { 7453 const bool IsFormat = 7454 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7455 7456 SDValue VData = Op.getOperand(2); 7457 EVT VDataVT = VData.getValueType(); 7458 EVT EltType = VDataVT.getScalarType(); 7459 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7460 7461 if (IsD16) 7462 VData = handleD16VData(VData, DAG); 7463 7464 if (!isTypeLegal(VDataVT)) { 7465 VData = 7466 DAG.getNode(ISD::BITCAST, DL, 7467 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7468 } 7469 7470 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7471 SDValue Ops[] = { 7472 Chain, 7473 VData, 7474 Op.getOperand(3), // rsrc 7475 Op.getOperand(4), // vindex 7476 Offsets.first, // voffset 7477 Op.getOperand(6), // soffset 7478 Offsets.second, // offset 7479 Op.getOperand(7), // cachepolicy, swizzled buffer 7480 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7481 }; 7482 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7483 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7484 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7485 MemSDNode *M = cast<MemSDNode>(Op); 7486 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7487 Ops[3])); 7488 7489 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7490 EVT VDataType = VData.getValueType().getScalarType(); 7491 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7492 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7493 7494 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7495 M->getMemoryVT(), M->getMemOperand()); 7496 } 7497 7498 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7499 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7500 unsigned IdxEn = 1; 7501 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7502 IdxEn = Idx->getZExtValue() != 0; 7503 SDValue Ops[] = { 7504 Chain, 7505 Op.getOperand(2), // vdata 7506 Op.getOperand(3), // rsrc 7507 Op.getOperand(4), // vindex 7508 SDValue(), // voffset -- will be set by setBufferOffsets 7509 SDValue(), // soffset -- will be set by setBufferOffsets 7510 SDValue(), // offset -- will be set by setBufferOffsets 7511 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7512 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7513 }; 7514 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7515 // We don't know the offset if vindex is non-zero, so clear it. 7516 if (IdxEn) 7517 Offset = 0; 7518 EVT VT = Op.getOperand(2).getValueType(); 7519 7520 auto *M = cast<MemSDNode>(Op); 7521 M->getMemOperand()->setOffset(Offset); 7522 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7523 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7524 7525 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7526 M->getMemOperand()); 7527 } 7528 7529 case Intrinsic::amdgcn_global_atomic_fadd: { 7530 SDValue Ops[] = { 7531 Chain, 7532 Op.getOperand(2), // ptr 7533 Op.getOperand(3) // vdata 7534 }; 7535 EVT VT = Op.getOperand(3).getValueType(); 7536 7537 auto *M = cast<MemSDNode>(Op); 7538 if (VT.isVector()) { 7539 return DAG.getMemIntrinsicNode( 7540 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7541 M->getMemOperand()); 7542 } 7543 7544 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7545 DAG.getVTList(VT, MVT::Other), Ops, 7546 M->getMemOperand()).getValue(1); 7547 } 7548 case Intrinsic::amdgcn_end_cf: 7549 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7550 Op->getOperand(2), Chain), 0); 7551 7552 default: { 7553 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7554 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7555 return lowerImage(Op, ImageDimIntr, DAG); 7556 7557 return Op; 7558 } 7559 } 7560 } 7561 7562 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7563 // offset (the offset that is included in bounds checking and swizzling, to be 7564 // split between the instruction's voffset and immoffset fields) and soffset 7565 // (the offset that is excluded from bounds checking and swizzling, to go in 7566 // the instruction's soffset field). This function takes the first kind of 7567 // offset and figures out how to split it between voffset and immoffset. 7568 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7569 SDValue Offset, SelectionDAG &DAG) const { 7570 SDLoc DL(Offset); 7571 const unsigned MaxImm = 4095; 7572 SDValue N0 = Offset; 7573 ConstantSDNode *C1 = nullptr; 7574 7575 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7576 N0 = SDValue(); 7577 else if (DAG.isBaseWithConstantOffset(N0)) { 7578 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7579 N0 = N0.getOperand(0); 7580 } 7581 7582 if (C1) { 7583 unsigned ImmOffset = C1->getZExtValue(); 7584 // If the immediate value is too big for the immoffset field, put the value 7585 // and -4096 into the immoffset field so that the value that is copied/added 7586 // for the voffset field is a multiple of 4096, and it stands more chance 7587 // of being CSEd with the copy/add for another similar load/store. 7588 // However, do not do that rounding down to a multiple of 4096 if that is a 7589 // negative number, as it appears to be illegal to have a negative offset 7590 // in the vgpr, even if adding the immediate offset makes it positive. 7591 unsigned Overflow = ImmOffset & ~MaxImm; 7592 ImmOffset -= Overflow; 7593 if ((int32_t)Overflow < 0) { 7594 Overflow += ImmOffset; 7595 ImmOffset = 0; 7596 } 7597 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7598 if (Overflow) { 7599 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7600 if (!N0) 7601 N0 = OverflowVal; 7602 else { 7603 SDValue Ops[] = { N0, OverflowVal }; 7604 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7605 } 7606 } 7607 } 7608 if (!N0) 7609 N0 = DAG.getConstant(0, DL, MVT::i32); 7610 if (!C1) 7611 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7612 return {N0, SDValue(C1, 0)}; 7613 } 7614 7615 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7616 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7617 // pointed to by Offsets. 7618 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7619 SelectionDAG &DAG, SDValue *Offsets, 7620 unsigned Align) const { 7621 SDLoc DL(CombinedOffset); 7622 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7623 uint32_t Imm = C->getZExtValue(); 7624 uint32_t SOffset, ImmOffset; 7625 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7626 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7627 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7628 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7629 return SOffset + ImmOffset; 7630 } 7631 } 7632 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7633 SDValue N0 = CombinedOffset.getOperand(0); 7634 SDValue N1 = CombinedOffset.getOperand(1); 7635 uint32_t SOffset, ImmOffset; 7636 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7637 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7638 Subtarget, Align)) { 7639 Offsets[0] = N0; 7640 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7641 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7642 return 0; 7643 } 7644 } 7645 Offsets[0] = CombinedOffset; 7646 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7647 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7648 return 0; 7649 } 7650 7651 // Handle 8 bit and 16 bit buffer loads 7652 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7653 EVT LoadVT, SDLoc DL, 7654 ArrayRef<SDValue> Ops, 7655 MemSDNode *M) const { 7656 EVT IntVT = LoadVT.changeTypeToInteger(); 7657 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7658 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7659 7660 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7661 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7662 Ops, IntVT, 7663 M->getMemOperand()); 7664 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7665 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7666 7667 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7668 } 7669 7670 // Handle 8 bit and 16 bit buffer stores 7671 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7672 EVT VDataType, SDLoc DL, 7673 SDValue Ops[], 7674 MemSDNode *M) const { 7675 if (VDataType == MVT::f16) 7676 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7677 7678 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7679 Ops[1] = BufferStoreExt; 7680 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7681 AMDGPUISD::BUFFER_STORE_SHORT; 7682 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7683 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7684 M->getMemOperand()); 7685 } 7686 7687 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7688 ISD::LoadExtType ExtType, SDValue Op, 7689 const SDLoc &SL, EVT VT) { 7690 if (VT.bitsLT(Op.getValueType())) 7691 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7692 7693 switch (ExtType) { 7694 case ISD::SEXTLOAD: 7695 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7696 case ISD::ZEXTLOAD: 7697 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7698 case ISD::EXTLOAD: 7699 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7700 case ISD::NON_EXTLOAD: 7701 return Op; 7702 } 7703 7704 llvm_unreachable("invalid ext type"); 7705 } 7706 7707 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7708 SelectionDAG &DAG = DCI.DAG; 7709 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7710 return SDValue(); 7711 7712 // FIXME: Constant loads should all be marked invariant. 7713 unsigned AS = Ld->getAddressSpace(); 7714 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7715 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7716 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7717 return SDValue(); 7718 7719 // Don't do this early, since it may interfere with adjacent load merging for 7720 // illegal types. We can avoid losing alignment information for exotic types 7721 // pre-legalize. 7722 EVT MemVT = Ld->getMemoryVT(); 7723 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7724 MemVT.getSizeInBits() >= 32) 7725 return SDValue(); 7726 7727 SDLoc SL(Ld); 7728 7729 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7730 "unexpected vector extload"); 7731 7732 // TODO: Drop only high part of range. 7733 SDValue Ptr = Ld->getBasePtr(); 7734 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7735 MVT::i32, SL, Ld->getChain(), Ptr, 7736 Ld->getOffset(), 7737 Ld->getPointerInfo(), MVT::i32, 7738 Ld->getAlignment(), 7739 Ld->getMemOperand()->getFlags(), 7740 Ld->getAAInfo(), 7741 nullptr); // Drop ranges 7742 7743 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7744 if (MemVT.isFloatingPoint()) { 7745 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7746 "unexpected fp extload"); 7747 TruncVT = MemVT.changeTypeToInteger(); 7748 } 7749 7750 SDValue Cvt = NewLoad; 7751 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7752 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7753 DAG.getValueType(TruncVT)); 7754 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7755 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7756 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7757 } else { 7758 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7759 } 7760 7761 EVT VT = Ld->getValueType(0); 7762 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7763 7764 DCI.AddToWorklist(Cvt.getNode()); 7765 7766 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7767 // the appropriate extension from the 32-bit load. 7768 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7769 DCI.AddToWorklist(Cvt.getNode()); 7770 7771 // Handle conversion back to floating point if necessary. 7772 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7773 7774 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7775 } 7776 7777 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7778 SDLoc DL(Op); 7779 LoadSDNode *Load = cast<LoadSDNode>(Op); 7780 ISD::LoadExtType ExtType = Load->getExtensionType(); 7781 EVT MemVT = Load->getMemoryVT(); 7782 7783 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7784 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7785 return SDValue(); 7786 7787 // FIXME: Copied from PPC 7788 // First, load into 32 bits, then truncate to 1 bit. 7789 7790 SDValue Chain = Load->getChain(); 7791 SDValue BasePtr = Load->getBasePtr(); 7792 MachineMemOperand *MMO = Load->getMemOperand(); 7793 7794 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7795 7796 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7797 BasePtr, RealMemVT, MMO); 7798 7799 if (!MemVT.isVector()) { 7800 SDValue Ops[] = { 7801 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7802 NewLD.getValue(1) 7803 }; 7804 7805 return DAG.getMergeValues(Ops, DL); 7806 } 7807 7808 SmallVector<SDValue, 3> Elts; 7809 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7810 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7811 DAG.getConstant(I, DL, MVT::i32)); 7812 7813 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7814 } 7815 7816 SDValue Ops[] = { 7817 DAG.getBuildVector(MemVT, DL, Elts), 7818 NewLD.getValue(1) 7819 }; 7820 7821 return DAG.getMergeValues(Ops, DL); 7822 } 7823 7824 if (!MemVT.isVector()) 7825 return SDValue(); 7826 7827 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7828 "Custom lowering for non-i32 vectors hasn't been implemented."); 7829 7830 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7831 MemVT, *Load->getMemOperand())) { 7832 SDValue Ops[2]; 7833 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7834 return DAG.getMergeValues(Ops, DL); 7835 } 7836 7837 unsigned Alignment = Load->getAlignment(); 7838 unsigned AS = Load->getAddressSpace(); 7839 if (Subtarget->hasLDSMisalignedBug() && 7840 AS == AMDGPUAS::FLAT_ADDRESS && 7841 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7842 return SplitVectorLoad(Op, DAG); 7843 } 7844 7845 MachineFunction &MF = DAG.getMachineFunction(); 7846 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7847 // If there is a possibilty that flat instruction access scratch memory 7848 // then we need to use the same legalization rules we use for private. 7849 if (AS == AMDGPUAS::FLAT_ADDRESS && 7850 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7851 AS = MFI->hasFlatScratchInit() ? 7852 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7853 7854 unsigned NumElements = MemVT.getVectorNumElements(); 7855 7856 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7857 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7858 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7859 if (MemVT.isPow2VectorType()) 7860 return SDValue(); 7861 if (NumElements == 3) 7862 return WidenVectorLoad(Op, DAG); 7863 return SplitVectorLoad(Op, DAG); 7864 } 7865 // Non-uniform loads will be selected to MUBUF instructions, so they 7866 // have the same legalization requirements as global and private 7867 // loads. 7868 // 7869 } 7870 7871 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7872 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7873 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7874 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7875 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7876 Alignment >= 4 && NumElements < 32) { 7877 if (MemVT.isPow2VectorType()) 7878 return SDValue(); 7879 if (NumElements == 3) 7880 return WidenVectorLoad(Op, DAG); 7881 return SplitVectorLoad(Op, DAG); 7882 } 7883 // Non-uniform loads will be selected to MUBUF instructions, so they 7884 // have the same legalization requirements as global and private 7885 // loads. 7886 // 7887 } 7888 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7889 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7890 AS == AMDGPUAS::GLOBAL_ADDRESS || 7891 AS == AMDGPUAS::FLAT_ADDRESS) { 7892 if (NumElements > 4) 7893 return SplitVectorLoad(Op, DAG); 7894 // v3 loads not supported on SI. 7895 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7896 return WidenVectorLoad(Op, DAG); 7897 // v3 and v4 loads are supported for private and global memory. 7898 return SDValue(); 7899 } 7900 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7901 // Depending on the setting of the private_element_size field in the 7902 // resource descriptor, we can only make private accesses up to a certain 7903 // size. 7904 switch (Subtarget->getMaxPrivateElementSize()) { 7905 case 4: { 7906 SDValue Ops[2]; 7907 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7908 return DAG.getMergeValues(Ops, DL); 7909 } 7910 case 8: 7911 if (NumElements > 2) 7912 return SplitVectorLoad(Op, DAG); 7913 return SDValue(); 7914 case 16: 7915 // Same as global/flat 7916 if (NumElements > 4) 7917 return SplitVectorLoad(Op, DAG); 7918 // v3 loads not supported on SI. 7919 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7920 return WidenVectorLoad(Op, DAG); 7921 return SDValue(); 7922 default: 7923 llvm_unreachable("unsupported private_element_size"); 7924 } 7925 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7926 // Use ds_read_b128 if possible. 7927 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7928 MemVT.getStoreSize() == 16) 7929 return SDValue(); 7930 7931 if (NumElements > 2) 7932 return SplitVectorLoad(Op, DAG); 7933 7934 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7935 // address is negative, then the instruction is incorrectly treated as 7936 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7937 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7938 // load later in the SILoadStoreOptimizer. 7939 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7940 NumElements == 2 && MemVT.getStoreSize() == 8 && 7941 Load->getAlignment() < 8) { 7942 return SplitVectorLoad(Op, DAG); 7943 } 7944 } 7945 return SDValue(); 7946 } 7947 7948 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7949 EVT VT = Op.getValueType(); 7950 assert(VT.getSizeInBits() == 64); 7951 7952 SDLoc DL(Op); 7953 SDValue Cond = Op.getOperand(0); 7954 7955 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7956 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7957 7958 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7959 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7960 7961 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7962 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7963 7964 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7965 7966 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7967 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7968 7969 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7970 7971 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7972 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7973 } 7974 7975 // Catch division cases where we can use shortcuts with rcp and rsq 7976 // instructions. 7977 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7978 SelectionDAG &DAG) const { 7979 SDLoc SL(Op); 7980 SDValue LHS = Op.getOperand(0); 7981 SDValue RHS = Op.getOperand(1); 7982 EVT VT = Op.getValueType(); 7983 const SDNodeFlags Flags = Op->getFlags(); 7984 7985 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7986 Flags.hasApproximateFuncs(); 7987 7988 // Without !fpmath accuracy information, we can't do more because we don't 7989 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7990 if (!AllowInaccurateRcp) 7991 return SDValue(); 7992 7993 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7994 if (CLHS->isExactlyValue(1.0)) { 7995 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7996 // the CI documentation has a worst case error of 1 ulp. 7997 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7998 // use it as long as we aren't trying to use denormals. 7999 // 8000 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8001 8002 // 1.0 / sqrt(x) -> rsq(x) 8003 8004 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8005 // error seems really high at 2^29 ULP. 8006 if (RHS.getOpcode() == ISD::FSQRT) 8007 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8008 8009 // 1.0 / x -> rcp(x) 8010 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8011 } 8012 8013 // Same as for 1.0, but expand the sign out of the constant. 8014 if (CLHS->isExactlyValue(-1.0)) { 8015 // -1.0 / x -> rcp (fneg x) 8016 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8017 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8018 } 8019 } 8020 8021 // Turn into multiply by the reciprocal. 8022 // x / y -> x * (1.0 / y) 8023 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8024 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8025 } 8026 8027 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8028 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8029 SDNodeFlags Flags) { 8030 if (GlueChain->getNumValues() <= 1) { 8031 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8032 } 8033 8034 assert(GlueChain->getNumValues() == 3); 8035 8036 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8037 switch (Opcode) { 8038 default: llvm_unreachable("no chain equivalent for opcode"); 8039 case ISD::FMUL: 8040 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8041 break; 8042 } 8043 8044 return DAG.getNode(Opcode, SL, VTList, 8045 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8046 Flags); 8047 } 8048 8049 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8050 EVT VT, SDValue A, SDValue B, SDValue C, 8051 SDValue GlueChain, SDNodeFlags Flags) { 8052 if (GlueChain->getNumValues() <= 1) { 8053 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8054 } 8055 8056 assert(GlueChain->getNumValues() == 3); 8057 8058 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8059 switch (Opcode) { 8060 default: llvm_unreachable("no chain equivalent for opcode"); 8061 case ISD::FMA: 8062 Opcode = AMDGPUISD::FMA_W_CHAIN; 8063 break; 8064 } 8065 8066 return DAG.getNode(Opcode, SL, VTList, 8067 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8068 Flags); 8069 } 8070 8071 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8072 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8073 return FastLowered; 8074 8075 SDLoc SL(Op); 8076 SDValue Src0 = Op.getOperand(0); 8077 SDValue Src1 = Op.getOperand(1); 8078 8079 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8080 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8081 8082 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8083 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8084 8085 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8086 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8087 8088 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8089 } 8090 8091 // Faster 2.5 ULP division that does not support denormals. 8092 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8093 SDLoc SL(Op); 8094 SDValue LHS = Op.getOperand(1); 8095 SDValue RHS = Op.getOperand(2); 8096 8097 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8098 8099 const APFloat K0Val(BitsToFloat(0x6f800000)); 8100 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8101 8102 const APFloat K1Val(BitsToFloat(0x2f800000)); 8103 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8104 8105 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8106 8107 EVT SetCCVT = 8108 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8109 8110 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8111 8112 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8113 8114 // TODO: Should this propagate fast-math-flags? 8115 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8116 8117 // rcp does not support denormals. 8118 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8119 8120 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8121 8122 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8123 } 8124 8125 // Returns immediate value for setting the F32 denorm mode when using the 8126 // S_DENORM_MODE instruction. 8127 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8128 const SDLoc &SL, const GCNSubtarget *ST) { 8129 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8130 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8131 ? FP_DENORM_FLUSH_NONE 8132 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8133 8134 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8135 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8136 } 8137 8138 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8139 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8140 return FastLowered; 8141 8142 // The selection matcher assumes anything with a chain selecting to a 8143 // mayRaiseFPException machine instruction. Since we're introducing a chain 8144 // here, we need to explicitly report nofpexcept for the regular fdiv 8145 // lowering. 8146 SDNodeFlags Flags = Op->getFlags(); 8147 Flags.setNoFPExcept(true); 8148 8149 SDLoc SL(Op); 8150 SDValue LHS = Op.getOperand(0); 8151 SDValue RHS = Op.getOperand(1); 8152 8153 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8154 8155 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8156 8157 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8158 {RHS, RHS, LHS}, Flags); 8159 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8160 {LHS, RHS, LHS}, Flags); 8161 8162 // Denominator is scaled to not be denormal, so using rcp is ok. 8163 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8164 DenominatorScaled, Flags); 8165 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8166 DenominatorScaled, Flags); 8167 8168 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8169 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8170 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8171 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8172 8173 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8174 8175 if (!HasFP32Denormals) { 8176 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8177 // lowering. The chain dependence is insufficient, and we need glue. We do 8178 // not need the glue variants in a strictfp function. 8179 8180 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8181 8182 SDNode *EnableDenorm; 8183 if (Subtarget->hasDenormModeInst()) { 8184 const SDValue EnableDenormValue = 8185 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8186 8187 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8188 DAG.getEntryNode(), EnableDenormValue).getNode(); 8189 } else { 8190 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8191 SL, MVT::i32); 8192 EnableDenorm = 8193 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8194 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8195 } 8196 8197 SDValue Ops[3] = { 8198 NegDivScale0, 8199 SDValue(EnableDenorm, 0), 8200 SDValue(EnableDenorm, 1) 8201 }; 8202 8203 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8204 } 8205 8206 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8207 ApproxRcp, One, NegDivScale0, Flags); 8208 8209 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8210 ApproxRcp, Fma0, Flags); 8211 8212 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8213 Fma1, Fma1, Flags); 8214 8215 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8216 NumeratorScaled, Mul, Flags); 8217 8218 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8219 Fma2, Fma1, Mul, Fma2, Flags); 8220 8221 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8222 NumeratorScaled, Fma3, Flags); 8223 8224 if (!HasFP32Denormals) { 8225 SDNode *DisableDenorm; 8226 if (Subtarget->hasDenormModeInst()) { 8227 const SDValue DisableDenormValue = 8228 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8229 8230 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8231 Fma4.getValue(1), DisableDenormValue, 8232 Fma4.getValue(2)).getNode(); 8233 } else { 8234 const SDValue DisableDenormValue = 8235 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8236 8237 DisableDenorm = DAG.getMachineNode( 8238 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8239 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8240 } 8241 8242 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8243 SDValue(DisableDenorm, 0), DAG.getRoot()); 8244 DAG.setRoot(OutputChain); 8245 } 8246 8247 SDValue Scale = NumeratorScaled.getValue(1); 8248 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8249 {Fma4, Fma1, Fma3, Scale}, Flags); 8250 8251 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8252 } 8253 8254 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8255 if (DAG.getTarget().Options.UnsafeFPMath) 8256 return lowerFastUnsafeFDIV(Op, DAG); 8257 8258 SDLoc SL(Op); 8259 SDValue X = Op.getOperand(0); 8260 SDValue Y = Op.getOperand(1); 8261 8262 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8263 8264 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8265 8266 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8267 8268 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8269 8270 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8271 8272 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8273 8274 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8275 8276 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8277 8278 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8279 8280 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8281 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8282 8283 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8284 NegDivScale0, Mul, DivScale1); 8285 8286 SDValue Scale; 8287 8288 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8289 // Workaround a hardware bug on SI where the condition output from div_scale 8290 // is not usable. 8291 8292 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8293 8294 // Figure out if the scale to use for div_fmas. 8295 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8296 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8297 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8298 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8299 8300 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8301 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8302 8303 SDValue Scale0Hi 8304 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8305 SDValue Scale1Hi 8306 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8307 8308 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8309 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8310 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8311 } else { 8312 Scale = DivScale1.getValue(1); 8313 } 8314 8315 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8316 Fma4, Fma3, Mul, Scale); 8317 8318 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8319 } 8320 8321 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8322 EVT VT = Op.getValueType(); 8323 8324 if (VT == MVT::f32) 8325 return LowerFDIV32(Op, DAG); 8326 8327 if (VT == MVT::f64) 8328 return LowerFDIV64(Op, DAG); 8329 8330 if (VT == MVT::f16) 8331 return LowerFDIV16(Op, DAG); 8332 8333 llvm_unreachable("Unexpected type for fdiv"); 8334 } 8335 8336 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8337 SDLoc DL(Op); 8338 StoreSDNode *Store = cast<StoreSDNode>(Op); 8339 EVT VT = Store->getMemoryVT(); 8340 8341 if (VT == MVT::i1) { 8342 return DAG.getTruncStore(Store->getChain(), DL, 8343 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8344 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8345 } 8346 8347 assert(VT.isVector() && 8348 Store->getValue().getValueType().getScalarType() == MVT::i32); 8349 8350 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8351 VT, *Store->getMemOperand())) { 8352 return expandUnalignedStore(Store, DAG); 8353 } 8354 8355 unsigned AS = Store->getAddressSpace(); 8356 if (Subtarget->hasLDSMisalignedBug() && 8357 AS == AMDGPUAS::FLAT_ADDRESS && 8358 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8359 return SplitVectorStore(Op, DAG); 8360 } 8361 8362 MachineFunction &MF = DAG.getMachineFunction(); 8363 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8364 // If there is a possibilty that flat instruction access scratch memory 8365 // then we need to use the same legalization rules we use for private. 8366 if (AS == AMDGPUAS::FLAT_ADDRESS && 8367 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8368 AS = MFI->hasFlatScratchInit() ? 8369 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8370 8371 unsigned NumElements = VT.getVectorNumElements(); 8372 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8373 AS == AMDGPUAS::FLAT_ADDRESS) { 8374 if (NumElements > 4) 8375 return SplitVectorStore(Op, DAG); 8376 // v3 stores not supported on SI. 8377 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8378 return SplitVectorStore(Op, DAG); 8379 return SDValue(); 8380 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8381 switch (Subtarget->getMaxPrivateElementSize()) { 8382 case 4: 8383 return scalarizeVectorStore(Store, DAG); 8384 case 8: 8385 if (NumElements > 2) 8386 return SplitVectorStore(Op, DAG); 8387 return SDValue(); 8388 case 16: 8389 if (NumElements > 4 || NumElements == 3) 8390 return SplitVectorStore(Op, DAG); 8391 return SDValue(); 8392 default: 8393 llvm_unreachable("unsupported private_element_size"); 8394 } 8395 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8396 // Use ds_write_b128 if possible. 8397 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8398 VT.getStoreSize() == 16 && NumElements != 3) 8399 return SDValue(); 8400 8401 if (NumElements > 2) 8402 return SplitVectorStore(Op, DAG); 8403 8404 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8405 // address is negative, then the instruction is incorrectly treated as 8406 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8407 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8408 // store later in the SILoadStoreOptimizer. 8409 if (!Subtarget->hasUsableDSOffset() && 8410 NumElements == 2 && VT.getStoreSize() == 8 && 8411 Store->getAlignment() < 8) { 8412 return SplitVectorStore(Op, DAG); 8413 } 8414 8415 return SDValue(); 8416 } else { 8417 llvm_unreachable("unhandled address space"); 8418 } 8419 } 8420 8421 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8422 SDLoc DL(Op); 8423 EVT VT = Op.getValueType(); 8424 SDValue Arg = Op.getOperand(0); 8425 SDValue TrigVal; 8426 8427 // Propagate fast-math flags so that the multiply we introduce can be folded 8428 // if Arg is already the result of a multiply by constant. 8429 auto Flags = Op->getFlags(); 8430 8431 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8432 8433 if (Subtarget->hasTrigReducedRange()) { 8434 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8435 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8436 } else { 8437 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8438 } 8439 8440 switch (Op.getOpcode()) { 8441 case ISD::FCOS: 8442 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8443 case ISD::FSIN: 8444 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8445 default: 8446 llvm_unreachable("Wrong trig opcode"); 8447 } 8448 } 8449 8450 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8451 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8452 assert(AtomicNode->isCompareAndSwap()); 8453 unsigned AS = AtomicNode->getAddressSpace(); 8454 8455 // No custom lowering required for local address space 8456 if (!isFlatGlobalAddrSpace(AS)) 8457 return Op; 8458 8459 // Non-local address space requires custom lowering for atomic compare 8460 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8461 SDLoc DL(Op); 8462 SDValue ChainIn = Op.getOperand(0); 8463 SDValue Addr = Op.getOperand(1); 8464 SDValue Old = Op.getOperand(2); 8465 SDValue New = Op.getOperand(3); 8466 EVT VT = Op.getValueType(); 8467 MVT SimpleVT = VT.getSimpleVT(); 8468 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8469 8470 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8471 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8472 8473 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8474 Ops, VT, AtomicNode->getMemOperand()); 8475 } 8476 8477 //===----------------------------------------------------------------------===// 8478 // Custom DAG optimizations 8479 //===----------------------------------------------------------------------===// 8480 8481 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8482 DAGCombinerInfo &DCI) const { 8483 EVT VT = N->getValueType(0); 8484 EVT ScalarVT = VT.getScalarType(); 8485 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8486 return SDValue(); 8487 8488 SelectionDAG &DAG = DCI.DAG; 8489 SDLoc DL(N); 8490 8491 SDValue Src = N->getOperand(0); 8492 EVT SrcVT = Src.getValueType(); 8493 8494 // TODO: We could try to match extracting the higher bytes, which would be 8495 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8496 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8497 // about in practice. 8498 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8499 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8500 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8501 DCI.AddToWorklist(Cvt.getNode()); 8502 8503 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8504 if (ScalarVT != MVT::f32) { 8505 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8506 DAG.getTargetConstant(0, DL, MVT::i32)); 8507 } 8508 return Cvt; 8509 } 8510 } 8511 8512 return SDValue(); 8513 } 8514 8515 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8516 8517 // This is a variant of 8518 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8519 // 8520 // The normal DAG combiner will do this, but only if the add has one use since 8521 // that would increase the number of instructions. 8522 // 8523 // This prevents us from seeing a constant offset that can be folded into a 8524 // memory instruction's addressing mode. If we know the resulting add offset of 8525 // a pointer can be folded into an addressing offset, we can replace the pointer 8526 // operand with the add of new constant offset. This eliminates one of the uses, 8527 // and may allow the remaining use to also be simplified. 8528 // 8529 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8530 unsigned AddrSpace, 8531 EVT MemVT, 8532 DAGCombinerInfo &DCI) const { 8533 SDValue N0 = N->getOperand(0); 8534 SDValue N1 = N->getOperand(1); 8535 8536 // We only do this to handle cases where it's profitable when there are 8537 // multiple uses of the add, so defer to the standard combine. 8538 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8539 N0->hasOneUse()) 8540 return SDValue(); 8541 8542 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8543 if (!CN1) 8544 return SDValue(); 8545 8546 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8547 if (!CAdd) 8548 return SDValue(); 8549 8550 // If the resulting offset is too large, we can't fold it into the addressing 8551 // mode offset. 8552 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8553 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8554 8555 AddrMode AM; 8556 AM.HasBaseReg = true; 8557 AM.BaseOffs = Offset.getSExtValue(); 8558 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8559 return SDValue(); 8560 8561 SelectionDAG &DAG = DCI.DAG; 8562 SDLoc SL(N); 8563 EVT VT = N->getValueType(0); 8564 8565 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8566 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8567 8568 SDNodeFlags Flags; 8569 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8570 (N0.getOpcode() == ISD::OR || 8571 N0->getFlags().hasNoUnsignedWrap())); 8572 8573 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8574 } 8575 8576 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8577 DAGCombinerInfo &DCI) const { 8578 SDValue Ptr = N->getBasePtr(); 8579 SelectionDAG &DAG = DCI.DAG; 8580 SDLoc SL(N); 8581 8582 // TODO: We could also do this for multiplies. 8583 if (Ptr.getOpcode() == ISD::SHL) { 8584 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8585 N->getMemoryVT(), DCI); 8586 if (NewPtr) { 8587 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8588 8589 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8590 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8591 } 8592 } 8593 8594 return SDValue(); 8595 } 8596 8597 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8598 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8599 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8600 (Opc == ISD::XOR && Val == 0); 8601 } 8602 8603 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8604 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8605 // integer combine opportunities since most 64-bit operations are decomposed 8606 // this way. TODO: We won't want this for SALU especially if it is an inline 8607 // immediate. 8608 SDValue SITargetLowering::splitBinaryBitConstantOp( 8609 DAGCombinerInfo &DCI, 8610 const SDLoc &SL, 8611 unsigned Opc, SDValue LHS, 8612 const ConstantSDNode *CRHS) const { 8613 uint64_t Val = CRHS->getZExtValue(); 8614 uint32_t ValLo = Lo_32(Val); 8615 uint32_t ValHi = Hi_32(Val); 8616 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8617 8618 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8619 bitOpWithConstantIsReducible(Opc, ValHi)) || 8620 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8621 // If we need to materialize a 64-bit immediate, it will be split up later 8622 // anyway. Avoid creating the harder to understand 64-bit immediate 8623 // materialization. 8624 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8625 } 8626 8627 return SDValue(); 8628 } 8629 8630 // Returns true if argument is a boolean value which is not serialized into 8631 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8632 static bool isBoolSGPR(SDValue V) { 8633 if (V.getValueType() != MVT::i1) 8634 return false; 8635 switch (V.getOpcode()) { 8636 default: break; 8637 case ISD::SETCC: 8638 case ISD::AND: 8639 case ISD::OR: 8640 case ISD::XOR: 8641 case AMDGPUISD::FP_CLASS: 8642 return true; 8643 } 8644 return false; 8645 } 8646 8647 // If a constant has all zeroes or all ones within each byte return it. 8648 // Otherwise return 0. 8649 static uint32_t getConstantPermuteMask(uint32_t C) { 8650 // 0xff for any zero byte in the mask 8651 uint32_t ZeroByteMask = 0; 8652 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8653 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8654 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8655 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8656 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8657 if ((NonZeroByteMask & C) != NonZeroByteMask) 8658 return 0; // Partial bytes selected. 8659 return C; 8660 } 8661 8662 // Check if a node selects whole bytes from its operand 0 starting at a byte 8663 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8664 // or -1 if not succeeded. 8665 // Note byte select encoding: 8666 // value 0-3 selects corresponding source byte; 8667 // value 0xc selects zero; 8668 // value 0xff selects 0xff. 8669 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8670 assert(V.getValueSizeInBits() == 32); 8671 8672 if (V.getNumOperands() != 2) 8673 return ~0; 8674 8675 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8676 if (!N1) 8677 return ~0; 8678 8679 uint32_t C = N1->getZExtValue(); 8680 8681 switch (V.getOpcode()) { 8682 default: 8683 break; 8684 case ISD::AND: 8685 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8686 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8687 } 8688 break; 8689 8690 case ISD::OR: 8691 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8692 return (0x03020100 & ~ConstMask) | ConstMask; 8693 } 8694 break; 8695 8696 case ISD::SHL: 8697 if (C % 8) 8698 return ~0; 8699 8700 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8701 8702 case ISD::SRL: 8703 if (C % 8) 8704 return ~0; 8705 8706 return uint32_t(0x0c0c0c0c03020100ull >> C); 8707 } 8708 8709 return ~0; 8710 } 8711 8712 SDValue SITargetLowering::performAndCombine(SDNode *N, 8713 DAGCombinerInfo &DCI) const { 8714 if (DCI.isBeforeLegalize()) 8715 return SDValue(); 8716 8717 SelectionDAG &DAG = DCI.DAG; 8718 EVT VT = N->getValueType(0); 8719 SDValue LHS = N->getOperand(0); 8720 SDValue RHS = N->getOperand(1); 8721 8722 8723 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8724 if (VT == MVT::i64 && CRHS) { 8725 if (SDValue Split 8726 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8727 return Split; 8728 } 8729 8730 if (CRHS && VT == MVT::i32) { 8731 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8732 // nb = number of trailing zeroes in mask 8733 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8734 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8735 uint64_t Mask = CRHS->getZExtValue(); 8736 unsigned Bits = countPopulation(Mask); 8737 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8738 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8739 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8740 unsigned Shift = CShift->getZExtValue(); 8741 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8742 unsigned Offset = NB + Shift; 8743 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8744 SDLoc SL(N); 8745 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8746 LHS->getOperand(0), 8747 DAG.getConstant(Offset, SL, MVT::i32), 8748 DAG.getConstant(Bits, SL, MVT::i32)); 8749 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8750 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8751 DAG.getValueType(NarrowVT)); 8752 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8753 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8754 return Shl; 8755 } 8756 } 8757 } 8758 8759 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8760 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8761 isa<ConstantSDNode>(LHS.getOperand(2))) { 8762 uint32_t Sel = getConstantPermuteMask(Mask); 8763 if (!Sel) 8764 return SDValue(); 8765 8766 // Select 0xc for all zero bytes 8767 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8768 SDLoc DL(N); 8769 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8770 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8771 } 8772 } 8773 8774 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8775 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8776 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8777 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8778 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8779 8780 SDValue X = LHS.getOperand(0); 8781 SDValue Y = RHS.getOperand(0); 8782 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8783 return SDValue(); 8784 8785 if (LCC == ISD::SETO) { 8786 if (X != LHS.getOperand(1)) 8787 return SDValue(); 8788 8789 if (RCC == ISD::SETUNE) { 8790 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8791 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8792 return SDValue(); 8793 8794 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8795 SIInstrFlags::N_SUBNORMAL | 8796 SIInstrFlags::N_ZERO | 8797 SIInstrFlags::P_ZERO | 8798 SIInstrFlags::P_SUBNORMAL | 8799 SIInstrFlags::P_NORMAL; 8800 8801 static_assert(((~(SIInstrFlags::S_NAN | 8802 SIInstrFlags::Q_NAN | 8803 SIInstrFlags::N_INFINITY | 8804 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8805 "mask not equal"); 8806 8807 SDLoc DL(N); 8808 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8809 X, DAG.getConstant(Mask, DL, MVT::i32)); 8810 } 8811 } 8812 } 8813 8814 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8815 std::swap(LHS, RHS); 8816 8817 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8818 RHS.hasOneUse()) { 8819 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8820 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8821 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8822 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8823 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8824 (RHS.getOperand(0) == LHS.getOperand(0) && 8825 LHS.getOperand(0) == LHS.getOperand(1))) { 8826 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8827 unsigned NewMask = LCC == ISD::SETO ? 8828 Mask->getZExtValue() & ~OrdMask : 8829 Mask->getZExtValue() & OrdMask; 8830 8831 SDLoc DL(N); 8832 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8833 DAG.getConstant(NewMask, DL, MVT::i32)); 8834 } 8835 } 8836 8837 if (VT == MVT::i32 && 8838 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8839 // and x, (sext cc from i1) => select cc, x, 0 8840 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8841 std::swap(LHS, RHS); 8842 if (isBoolSGPR(RHS.getOperand(0))) 8843 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8844 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8845 } 8846 8847 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8848 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8849 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8850 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8851 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8852 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8853 if (LHSMask != ~0u && RHSMask != ~0u) { 8854 // Canonicalize the expression in an attempt to have fewer unique masks 8855 // and therefore fewer registers used to hold the masks. 8856 if (LHSMask > RHSMask) { 8857 std::swap(LHSMask, RHSMask); 8858 std::swap(LHS, RHS); 8859 } 8860 8861 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8862 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8863 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8864 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8865 8866 // Check of we need to combine values from two sources within a byte. 8867 if (!(LHSUsedLanes & RHSUsedLanes) && 8868 // If we select high and lower word keep it for SDWA. 8869 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8870 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8871 // Each byte in each mask is either selector mask 0-3, or has higher 8872 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8873 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8874 // mask which is not 0xff wins. By anding both masks we have a correct 8875 // result except that 0x0c shall be corrected to give 0x0c only. 8876 uint32_t Mask = LHSMask & RHSMask; 8877 for (unsigned I = 0; I < 32; I += 8) { 8878 uint32_t ByteSel = 0xff << I; 8879 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8880 Mask &= (0x0c << I) & 0xffffffff; 8881 } 8882 8883 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8884 // or 0x0c. 8885 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8886 SDLoc DL(N); 8887 8888 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8889 LHS.getOperand(0), RHS.getOperand(0), 8890 DAG.getConstant(Sel, DL, MVT::i32)); 8891 } 8892 } 8893 } 8894 8895 return SDValue(); 8896 } 8897 8898 SDValue SITargetLowering::performOrCombine(SDNode *N, 8899 DAGCombinerInfo &DCI) const { 8900 SelectionDAG &DAG = DCI.DAG; 8901 SDValue LHS = N->getOperand(0); 8902 SDValue RHS = N->getOperand(1); 8903 8904 EVT VT = N->getValueType(0); 8905 if (VT == MVT::i1) { 8906 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8907 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8908 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8909 SDValue Src = LHS.getOperand(0); 8910 if (Src != RHS.getOperand(0)) 8911 return SDValue(); 8912 8913 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8914 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8915 if (!CLHS || !CRHS) 8916 return SDValue(); 8917 8918 // Only 10 bits are used. 8919 static const uint32_t MaxMask = 0x3ff; 8920 8921 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8922 SDLoc DL(N); 8923 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8924 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8925 } 8926 8927 return SDValue(); 8928 } 8929 8930 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8931 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8932 LHS.getOpcode() == AMDGPUISD::PERM && 8933 isa<ConstantSDNode>(LHS.getOperand(2))) { 8934 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8935 if (!Sel) 8936 return SDValue(); 8937 8938 Sel |= LHS.getConstantOperandVal(2); 8939 SDLoc DL(N); 8940 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8941 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8942 } 8943 8944 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8945 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8946 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8947 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8948 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8949 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8950 if (LHSMask != ~0u && RHSMask != ~0u) { 8951 // Canonicalize the expression in an attempt to have fewer unique masks 8952 // and therefore fewer registers used to hold the masks. 8953 if (LHSMask > RHSMask) { 8954 std::swap(LHSMask, RHSMask); 8955 std::swap(LHS, RHS); 8956 } 8957 8958 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8959 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8960 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8961 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8962 8963 // Check of we need to combine values from two sources within a byte. 8964 if (!(LHSUsedLanes & RHSUsedLanes) && 8965 // If we select high and lower word keep it for SDWA. 8966 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8967 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8968 // Kill zero bytes selected by other mask. Zero value is 0xc. 8969 LHSMask &= ~RHSUsedLanes; 8970 RHSMask &= ~LHSUsedLanes; 8971 // Add 4 to each active LHS lane 8972 LHSMask |= LHSUsedLanes & 0x04040404; 8973 // Combine masks 8974 uint32_t Sel = LHSMask | RHSMask; 8975 SDLoc DL(N); 8976 8977 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8978 LHS.getOperand(0), RHS.getOperand(0), 8979 DAG.getConstant(Sel, DL, MVT::i32)); 8980 } 8981 } 8982 } 8983 8984 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 8985 return SDValue(); 8986 8987 // TODO: This could be a generic combine with a predicate for extracting the 8988 // high half of an integer being free. 8989 8990 // (or i64:x, (zero_extend i32:y)) -> 8991 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8992 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8993 RHS.getOpcode() != ISD::ZERO_EXTEND) 8994 std::swap(LHS, RHS); 8995 8996 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8997 SDValue ExtSrc = RHS.getOperand(0); 8998 EVT SrcVT = ExtSrc.getValueType(); 8999 if (SrcVT == MVT::i32) { 9000 SDLoc SL(N); 9001 SDValue LowLHS, HiBits; 9002 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9003 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9004 9005 DCI.AddToWorklist(LowOr.getNode()); 9006 DCI.AddToWorklist(HiBits.getNode()); 9007 9008 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9009 LowOr, HiBits); 9010 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9011 } 9012 } 9013 9014 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9015 if (CRHS) { 9016 if (SDValue Split 9017 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9018 return Split; 9019 } 9020 9021 return SDValue(); 9022 } 9023 9024 SDValue SITargetLowering::performXorCombine(SDNode *N, 9025 DAGCombinerInfo &DCI) const { 9026 EVT VT = N->getValueType(0); 9027 if (VT != MVT::i64) 9028 return SDValue(); 9029 9030 SDValue LHS = N->getOperand(0); 9031 SDValue RHS = N->getOperand(1); 9032 9033 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9034 if (CRHS) { 9035 if (SDValue Split 9036 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9037 return Split; 9038 } 9039 9040 return SDValue(); 9041 } 9042 9043 // Instructions that will be lowered with a final instruction that zeros the 9044 // high result bits. 9045 // XXX - probably only need to list legal operations. 9046 static bool fp16SrcZerosHighBits(unsigned Opc) { 9047 switch (Opc) { 9048 case ISD::FADD: 9049 case ISD::FSUB: 9050 case ISD::FMUL: 9051 case ISD::FDIV: 9052 case ISD::FREM: 9053 case ISD::FMA: 9054 case ISD::FMAD: 9055 case ISD::FCANONICALIZE: 9056 case ISD::FP_ROUND: 9057 case ISD::UINT_TO_FP: 9058 case ISD::SINT_TO_FP: 9059 case ISD::FABS: 9060 // Fabs is lowered to a bit operation, but it's an and which will clear the 9061 // high bits anyway. 9062 case ISD::FSQRT: 9063 case ISD::FSIN: 9064 case ISD::FCOS: 9065 case ISD::FPOWI: 9066 case ISD::FPOW: 9067 case ISD::FLOG: 9068 case ISD::FLOG2: 9069 case ISD::FLOG10: 9070 case ISD::FEXP: 9071 case ISD::FEXP2: 9072 case ISD::FCEIL: 9073 case ISD::FTRUNC: 9074 case ISD::FRINT: 9075 case ISD::FNEARBYINT: 9076 case ISD::FROUND: 9077 case ISD::FFLOOR: 9078 case ISD::FMINNUM: 9079 case ISD::FMAXNUM: 9080 case AMDGPUISD::FRACT: 9081 case AMDGPUISD::CLAMP: 9082 case AMDGPUISD::COS_HW: 9083 case AMDGPUISD::SIN_HW: 9084 case AMDGPUISD::FMIN3: 9085 case AMDGPUISD::FMAX3: 9086 case AMDGPUISD::FMED3: 9087 case AMDGPUISD::FMAD_FTZ: 9088 case AMDGPUISD::RCP: 9089 case AMDGPUISD::RSQ: 9090 case AMDGPUISD::RCP_IFLAG: 9091 case AMDGPUISD::LDEXP: 9092 return true; 9093 default: 9094 // fcopysign, select and others may be lowered to 32-bit bit operations 9095 // which don't zero the high bits. 9096 return false; 9097 } 9098 } 9099 9100 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9101 DAGCombinerInfo &DCI) const { 9102 if (!Subtarget->has16BitInsts() || 9103 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9104 return SDValue(); 9105 9106 EVT VT = N->getValueType(0); 9107 if (VT != MVT::i32) 9108 return SDValue(); 9109 9110 SDValue Src = N->getOperand(0); 9111 if (Src.getValueType() != MVT::i16) 9112 return SDValue(); 9113 9114 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9115 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9116 if (Src.getOpcode() == ISD::BITCAST) { 9117 SDValue BCSrc = Src.getOperand(0); 9118 if (BCSrc.getValueType() == MVT::f16 && 9119 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9120 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9121 } 9122 9123 return SDValue(); 9124 } 9125 9126 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9127 DAGCombinerInfo &DCI) 9128 const { 9129 SDValue Src = N->getOperand(0); 9130 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9131 9132 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9133 VTSign->getVT() == MVT::i8) || 9134 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9135 VTSign->getVT() == MVT::i16)) && 9136 Src.hasOneUse()) { 9137 auto *M = cast<MemSDNode>(Src); 9138 SDValue Ops[] = { 9139 Src.getOperand(0), // Chain 9140 Src.getOperand(1), // rsrc 9141 Src.getOperand(2), // vindex 9142 Src.getOperand(3), // voffset 9143 Src.getOperand(4), // soffset 9144 Src.getOperand(5), // offset 9145 Src.getOperand(6), 9146 Src.getOperand(7) 9147 }; 9148 // replace with BUFFER_LOAD_BYTE/SHORT 9149 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9150 Src.getOperand(0).getValueType()); 9151 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9152 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9153 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9154 ResList, 9155 Ops, M->getMemoryVT(), 9156 M->getMemOperand()); 9157 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9158 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9159 } 9160 return SDValue(); 9161 } 9162 9163 SDValue SITargetLowering::performClassCombine(SDNode *N, 9164 DAGCombinerInfo &DCI) const { 9165 SelectionDAG &DAG = DCI.DAG; 9166 SDValue Mask = N->getOperand(1); 9167 9168 // fp_class x, 0 -> false 9169 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9170 if (CMask->isNullValue()) 9171 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9172 } 9173 9174 if (N->getOperand(0).isUndef()) 9175 return DAG.getUNDEF(MVT::i1); 9176 9177 return SDValue(); 9178 } 9179 9180 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9181 DAGCombinerInfo &DCI) const { 9182 EVT VT = N->getValueType(0); 9183 SDValue N0 = N->getOperand(0); 9184 9185 if (N0.isUndef()) 9186 return N0; 9187 9188 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9189 N0.getOpcode() == ISD::SINT_TO_FP)) { 9190 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9191 N->getFlags()); 9192 } 9193 9194 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9195 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9196 N0.getOperand(0), N->getFlags()); 9197 } 9198 9199 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9200 } 9201 9202 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9203 unsigned MaxDepth) const { 9204 unsigned Opcode = Op.getOpcode(); 9205 if (Opcode == ISD::FCANONICALIZE) 9206 return true; 9207 9208 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9209 auto F = CFP->getValueAPF(); 9210 if (F.isNaN() && F.isSignaling()) 9211 return false; 9212 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9213 } 9214 9215 // If source is a result of another standard FP operation it is already in 9216 // canonical form. 9217 if (MaxDepth == 0) 9218 return false; 9219 9220 switch (Opcode) { 9221 // These will flush denorms if required. 9222 case ISD::FADD: 9223 case ISD::FSUB: 9224 case ISD::FMUL: 9225 case ISD::FCEIL: 9226 case ISD::FFLOOR: 9227 case ISD::FMA: 9228 case ISD::FMAD: 9229 case ISD::FSQRT: 9230 case ISD::FDIV: 9231 case ISD::FREM: 9232 case ISD::FP_ROUND: 9233 case ISD::FP_EXTEND: 9234 case AMDGPUISD::FMUL_LEGACY: 9235 case AMDGPUISD::FMAD_FTZ: 9236 case AMDGPUISD::RCP: 9237 case AMDGPUISD::RSQ: 9238 case AMDGPUISD::RSQ_CLAMP: 9239 case AMDGPUISD::RCP_LEGACY: 9240 case AMDGPUISD::RCP_IFLAG: 9241 case AMDGPUISD::DIV_SCALE: 9242 case AMDGPUISD::DIV_FMAS: 9243 case AMDGPUISD::DIV_FIXUP: 9244 case AMDGPUISD::FRACT: 9245 case AMDGPUISD::LDEXP: 9246 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9247 case AMDGPUISD::CVT_F32_UBYTE0: 9248 case AMDGPUISD::CVT_F32_UBYTE1: 9249 case AMDGPUISD::CVT_F32_UBYTE2: 9250 case AMDGPUISD::CVT_F32_UBYTE3: 9251 return true; 9252 9253 // It can/will be lowered or combined as a bit operation. 9254 // Need to check their input recursively to handle. 9255 case ISD::FNEG: 9256 case ISD::FABS: 9257 case ISD::FCOPYSIGN: 9258 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9259 9260 case ISD::FSIN: 9261 case ISD::FCOS: 9262 case ISD::FSINCOS: 9263 return Op.getValueType().getScalarType() != MVT::f16; 9264 9265 case ISD::FMINNUM: 9266 case ISD::FMAXNUM: 9267 case ISD::FMINNUM_IEEE: 9268 case ISD::FMAXNUM_IEEE: 9269 case AMDGPUISD::CLAMP: 9270 case AMDGPUISD::FMED3: 9271 case AMDGPUISD::FMAX3: 9272 case AMDGPUISD::FMIN3: { 9273 // FIXME: Shouldn't treat the generic operations different based these. 9274 // However, we aren't really required to flush the result from 9275 // minnum/maxnum.. 9276 9277 // snans will be quieted, so we only need to worry about denormals. 9278 if (Subtarget->supportsMinMaxDenormModes() || 9279 denormalsEnabledForType(DAG, Op.getValueType())) 9280 return true; 9281 9282 // Flushing may be required. 9283 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9284 // targets need to check their input recursively. 9285 9286 // FIXME: Does this apply with clamp? It's implemented with max. 9287 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9288 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9289 return false; 9290 } 9291 9292 return true; 9293 } 9294 case ISD::SELECT: { 9295 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9296 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9297 } 9298 case ISD::BUILD_VECTOR: { 9299 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9300 SDValue SrcOp = Op.getOperand(i); 9301 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9302 return false; 9303 } 9304 9305 return true; 9306 } 9307 case ISD::EXTRACT_VECTOR_ELT: 9308 case ISD::EXTRACT_SUBVECTOR: { 9309 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9310 } 9311 case ISD::INSERT_VECTOR_ELT: { 9312 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9313 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9314 } 9315 case ISD::UNDEF: 9316 // Could be anything. 9317 return false; 9318 9319 case ISD::BITCAST: { 9320 // Hack round the mess we make when legalizing extract_vector_elt 9321 SDValue Src = Op.getOperand(0); 9322 if (Src.getValueType() == MVT::i16 && 9323 Src.getOpcode() == ISD::TRUNCATE) { 9324 SDValue TruncSrc = Src.getOperand(0); 9325 if (TruncSrc.getValueType() == MVT::i32 && 9326 TruncSrc.getOpcode() == ISD::BITCAST && 9327 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9328 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9329 } 9330 } 9331 9332 return false; 9333 } 9334 case ISD::INTRINSIC_WO_CHAIN: { 9335 unsigned IntrinsicID 9336 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9337 // TODO: Handle more intrinsics 9338 switch (IntrinsicID) { 9339 case Intrinsic::amdgcn_cvt_pkrtz: 9340 case Intrinsic::amdgcn_cubeid: 9341 case Intrinsic::amdgcn_frexp_mant: 9342 case Intrinsic::amdgcn_fdot2: 9343 case Intrinsic::amdgcn_rcp: 9344 case Intrinsic::amdgcn_rsq: 9345 case Intrinsic::amdgcn_rsq_clamp: 9346 case Intrinsic::amdgcn_rcp_legacy: 9347 case Intrinsic::amdgcn_rsq_legacy: 9348 case Intrinsic::amdgcn_trig_preop: 9349 return true; 9350 default: 9351 break; 9352 } 9353 9354 LLVM_FALLTHROUGH; 9355 } 9356 default: 9357 return denormalsEnabledForType(DAG, Op.getValueType()) && 9358 DAG.isKnownNeverSNaN(Op); 9359 } 9360 9361 llvm_unreachable("invalid operation"); 9362 } 9363 9364 // Constant fold canonicalize. 9365 SDValue SITargetLowering::getCanonicalConstantFP( 9366 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9367 // Flush denormals to 0 if not enabled. 9368 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9369 return DAG.getConstantFP(0.0, SL, VT); 9370 9371 if (C.isNaN()) { 9372 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9373 if (C.isSignaling()) { 9374 // Quiet a signaling NaN. 9375 // FIXME: Is this supposed to preserve payload bits? 9376 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9377 } 9378 9379 // Make sure it is the canonical NaN bitpattern. 9380 // 9381 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9382 // immediate? 9383 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9384 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9385 } 9386 9387 // Already canonical. 9388 return DAG.getConstantFP(C, SL, VT); 9389 } 9390 9391 static bool vectorEltWillFoldAway(SDValue Op) { 9392 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9393 } 9394 9395 SDValue SITargetLowering::performFCanonicalizeCombine( 9396 SDNode *N, 9397 DAGCombinerInfo &DCI) const { 9398 SelectionDAG &DAG = DCI.DAG; 9399 SDValue N0 = N->getOperand(0); 9400 EVT VT = N->getValueType(0); 9401 9402 // fcanonicalize undef -> qnan 9403 if (N0.isUndef()) { 9404 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9405 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9406 } 9407 9408 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9409 EVT VT = N->getValueType(0); 9410 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9411 } 9412 9413 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9414 // (fcanonicalize k) 9415 // 9416 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9417 9418 // TODO: This could be better with wider vectors that will be split to v2f16, 9419 // and to consider uses since there aren't that many packed operations. 9420 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9421 isTypeLegal(MVT::v2f16)) { 9422 SDLoc SL(N); 9423 SDValue NewElts[2]; 9424 SDValue Lo = N0.getOperand(0); 9425 SDValue Hi = N0.getOperand(1); 9426 EVT EltVT = Lo.getValueType(); 9427 9428 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9429 for (unsigned I = 0; I != 2; ++I) { 9430 SDValue Op = N0.getOperand(I); 9431 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9432 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9433 CFP->getValueAPF()); 9434 } else if (Op.isUndef()) { 9435 // Handled below based on what the other operand is. 9436 NewElts[I] = Op; 9437 } else { 9438 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9439 } 9440 } 9441 9442 // If one half is undef, and one is constant, perfer a splat vector rather 9443 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9444 // cheaper to use and may be free with a packed operation. 9445 if (NewElts[0].isUndef()) { 9446 if (isa<ConstantFPSDNode>(NewElts[1])) 9447 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9448 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9449 } 9450 9451 if (NewElts[1].isUndef()) { 9452 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9453 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9454 } 9455 9456 return DAG.getBuildVector(VT, SL, NewElts); 9457 } 9458 } 9459 9460 unsigned SrcOpc = N0.getOpcode(); 9461 9462 // If it's free to do so, push canonicalizes further up the source, which may 9463 // find a canonical source. 9464 // 9465 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9466 // sNaNs. 9467 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9468 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9469 if (CRHS && N0.hasOneUse()) { 9470 SDLoc SL(N); 9471 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9472 N0.getOperand(0)); 9473 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9474 DCI.AddToWorklist(Canon0.getNode()); 9475 9476 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9477 } 9478 } 9479 9480 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9481 } 9482 9483 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9484 switch (Opc) { 9485 case ISD::FMAXNUM: 9486 case ISD::FMAXNUM_IEEE: 9487 return AMDGPUISD::FMAX3; 9488 case ISD::SMAX: 9489 return AMDGPUISD::SMAX3; 9490 case ISD::UMAX: 9491 return AMDGPUISD::UMAX3; 9492 case ISD::FMINNUM: 9493 case ISD::FMINNUM_IEEE: 9494 return AMDGPUISD::FMIN3; 9495 case ISD::SMIN: 9496 return AMDGPUISD::SMIN3; 9497 case ISD::UMIN: 9498 return AMDGPUISD::UMIN3; 9499 default: 9500 llvm_unreachable("Not a min/max opcode"); 9501 } 9502 } 9503 9504 SDValue SITargetLowering::performIntMed3ImmCombine( 9505 SelectionDAG &DAG, const SDLoc &SL, 9506 SDValue Op0, SDValue Op1, bool Signed) const { 9507 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9508 if (!K1) 9509 return SDValue(); 9510 9511 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9512 if (!K0) 9513 return SDValue(); 9514 9515 if (Signed) { 9516 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9517 return SDValue(); 9518 } else { 9519 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9520 return SDValue(); 9521 } 9522 9523 EVT VT = K0->getValueType(0); 9524 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9525 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9526 return DAG.getNode(Med3Opc, SL, VT, 9527 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9528 } 9529 9530 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9531 MVT NVT = MVT::i32; 9532 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9533 9534 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9535 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9536 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9537 9538 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9539 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9540 } 9541 9542 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9543 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9544 return C; 9545 9546 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9547 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9548 return C; 9549 } 9550 9551 return nullptr; 9552 } 9553 9554 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9555 const SDLoc &SL, 9556 SDValue Op0, 9557 SDValue Op1) const { 9558 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9559 if (!K1) 9560 return SDValue(); 9561 9562 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9563 if (!K0) 9564 return SDValue(); 9565 9566 // Ordered >= (although NaN inputs should have folded away by now). 9567 if (K0->getValueAPF() > K1->getValueAPF()) 9568 return SDValue(); 9569 9570 const MachineFunction &MF = DAG.getMachineFunction(); 9571 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9572 9573 // TODO: Check IEEE bit enabled? 9574 EVT VT = Op0.getValueType(); 9575 if (Info->getMode().DX10Clamp) { 9576 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9577 // hardware fmed3 behavior converting to a min. 9578 // FIXME: Should this be allowing -0.0? 9579 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9580 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9581 } 9582 9583 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9584 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9585 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9586 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9587 // then give the other result, which is different from med3 with a NaN 9588 // input. 9589 SDValue Var = Op0.getOperand(0); 9590 if (!DAG.isKnownNeverSNaN(Var)) 9591 return SDValue(); 9592 9593 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9594 9595 if ((!K0->hasOneUse() || 9596 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9597 (!K1->hasOneUse() || 9598 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9599 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9600 Var, SDValue(K0, 0), SDValue(K1, 0)); 9601 } 9602 } 9603 9604 return SDValue(); 9605 } 9606 9607 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9608 DAGCombinerInfo &DCI) const { 9609 SelectionDAG &DAG = DCI.DAG; 9610 9611 EVT VT = N->getValueType(0); 9612 unsigned Opc = N->getOpcode(); 9613 SDValue Op0 = N->getOperand(0); 9614 SDValue Op1 = N->getOperand(1); 9615 9616 // Only do this if the inner op has one use since this will just increases 9617 // register pressure for no benefit. 9618 9619 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9620 !VT.isVector() && 9621 (VT == MVT::i32 || VT == MVT::f32 || 9622 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9623 // max(max(a, b), c) -> max3(a, b, c) 9624 // min(min(a, b), c) -> min3(a, b, c) 9625 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9626 SDLoc DL(N); 9627 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9628 DL, 9629 N->getValueType(0), 9630 Op0.getOperand(0), 9631 Op0.getOperand(1), 9632 Op1); 9633 } 9634 9635 // Try commuted. 9636 // max(a, max(b, c)) -> max3(a, b, c) 9637 // min(a, min(b, c)) -> min3(a, b, c) 9638 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9639 SDLoc DL(N); 9640 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9641 DL, 9642 N->getValueType(0), 9643 Op0, 9644 Op1.getOperand(0), 9645 Op1.getOperand(1)); 9646 } 9647 } 9648 9649 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9650 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9651 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9652 return Med3; 9653 } 9654 9655 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9656 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9657 return Med3; 9658 } 9659 9660 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9661 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9662 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9663 (Opc == AMDGPUISD::FMIN_LEGACY && 9664 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9665 (VT == MVT::f32 || VT == MVT::f64 || 9666 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9667 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9668 Op0.hasOneUse()) { 9669 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9670 return Res; 9671 } 9672 9673 return SDValue(); 9674 } 9675 9676 static bool isClampZeroToOne(SDValue A, SDValue B) { 9677 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9678 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9679 // FIXME: Should this be allowing -0.0? 9680 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9681 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9682 } 9683 } 9684 9685 return false; 9686 } 9687 9688 // FIXME: Should only worry about snans for version with chain. 9689 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9690 DAGCombinerInfo &DCI) const { 9691 EVT VT = N->getValueType(0); 9692 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9693 // NaNs. With a NaN input, the order of the operands may change the result. 9694 9695 SelectionDAG &DAG = DCI.DAG; 9696 SDLoc SL(N); 9697 9698 SDValue Src0 = N->getOperand(0); 9699 SDValue Src1 = N->getOperand(1); 9700 SDValue Src2 = N->getOperand(2); 9701 9702 if (isClampZeroToOne(Src0, Src1)) { 9703 // const_a, const_b, x -> clamp is safe in all cases including signaling 9704 // nans. 9705 // FIXME: Should this be allowing -0.0? 9706 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9707 } 9708 9709 const MachineFunction &MF = DAG.getMachineFunction(); 9710 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9711 9712 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9713 // handling no dx10-clamp? 9714 if (Info->getMode().DX10Clamp) { 9715 // If NaNs is clamped to 0, we are free to reorder the inputs. 9716 9717 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9718 std::swap(Src0, Src1); 9719 9720 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9721 std::swap(Src1, Src2); 9722 9723 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9724 std::swap(Src0, Src1); 9725 9726 if (isClampZeroToOne(Src1, Src2)) 9727 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9728 } 9729 9730 return SDValue(); 9731 } 9732 9733 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9734 DAGCombinerInfo &DCI) const { 9735 SDValue Src0 = N->getOperand(0); 9736 SDValue Src1 = N->getOperand(1); 9737 if (Src0.isUndef() && Src1.isUndef()) 9738 return DCI.DAG.getUNDEF(N->getValueType(0)); 9739 return SDValue(); 9740 } 9741 9742 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9743 // expanded into a set of cmp/select instructions. 9744 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9745 unsigned NumElem, 9746 bool IsDivergentIdx) { 9747 if (UseDivergentRegisterIndexing) 9748 return false; 9749 9750 unsigned VecSize = EltSize * NumElem; 9751 9752 // Sub-dword vectors of size 2 dword or less have better implementation. 9753 if (VecSize <= 64 && EltSize < 32) 9754 return false; 9755 9756 // Always expand the rest of sub-dword instructions, otherwise it will be 9757 // lowered via memory. 9758 if (EltSize < 32) 9759 return true; 9760 9761 // Always do this if var-idx is divergent, otherwise it will become a loop. 9762 if (IsDivergentIdx) 9763 return true; 9764 9765 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9766 unsigned NumInsts = NumElem /* Number of compares */ + 9767 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9768 return NumInsts <= 16; 9769 } 9770 9771 static bool shouldExpandVectorDynExt(SDNode *N) { 9772 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9773 if (isa<ConstantSDNode>(Idx)) 9774 return false; 9775 9776 SDValue Vec = N->getOperand(0); 9777 EVT VecVT = Vec.getValueType(); 9778 EVT EltVT = VecVT.getVectorElementType(); 9779 unsigned EltSize = EltVT.getSizeInBits(); 9780 unsigned NumElem = VecVT.getVectorNumElements(); 9781 9782 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9783 Idx->isDivergent()); 9784 } 9785 9786 SDValue SITargetLowering::performExtractVectorEltCombine( 9787 SDNode *N, DAGCombinerInfo &DCI) const { 9788 SDValue Vec = N->getOperand(0); 9789 SelectionDAG &DAG = DCI.DAG; 9790 9791 EVT VecVT = Vec.getValueType(); 9792 EVT EltVT = VecVT.getVectorElementType(); 9793 9794 if ((Vec.getOpcode() == ISD::FNEG || 9795 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9796 SDLoc SL(N); 9797 EVT EltVT = N->getValueType(0); 9798 SDValue Idx = N->getOperand(1); 9799 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9800 Vec.getOperand(0), Idx); 9801 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9802 } 9803 9804 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9805 // => 9806 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9807 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9808 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9809 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9810 SDLoc SL(N); 9811 EVT EltVT = N->getValueType(0); 9812 SDValue Idx = N->getOperand(1); 9813 unsigned Opc = Vec.getOpcode(); 9814 9815 switch(Opc) { 9816 default: 9817 break; 9818 // TODO: Support other binary operations. 9819 case ISD::FADD: 9820 case ISD::FSUB: 9821 case ISD::FMUL: 9822 case ISD::ADD: 9823 case ISD::UMIN: 9824 case ISD::UMAX: 9825 case ISD::SMIN: 9826 case ISD::SMAX: 9827 case ISD::FMAXNUM: 9828 case ISD::FMINNUM: 9829 case ISD::FMAXNUM_IEEE: 9830 case ISD::FMINNUM_IEEE: { 9831 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9832 Vec.getOperand(0), Idx); 9833 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9834 Vec.getOperand(1), Idx); 9835 9836 DCI.AddToWorklist(Elt0.getNode()); 9837 DCI.AddToWorklist(Elt1.getNode()); 9838 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9839 } 9840 } 9841 } 9842 9843 unsigned VecSize = VecVT.getSizeInBits(); 9844 unsigned EltSize = EltVT.getSizeInBits(); 9845 9846 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9847 if (::shouldExpandVectorDynExt(N)) { 9848 SDLoc SL(N); 9849 SDValue Idx = N->getOperand(1); 9850 SDValue V; 9851 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9852 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9853 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9854 if (I == 0) 9855 V = Elt; 9856 else 9857 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9858 } 9859 return V; 9860 } 9861 9862 if (!DCI.isBeforeLegalize()) 9863 return SDValue(); 9864 9865 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9866 // elements. This exposes more load reduction opportunities by replacing 9867 // multiple small extract_vector_elements with a single 32-bit extract. 9868 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9869 if (isa<MemSDNode>(Vec) && 9870 EltSize <= 16 && 9871 EltVT.isByteSized() && 9872 VecSize > 32 && 9873 VecSize % 32 == 0 && 9874 Idx) { 9875 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9876 9877 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9878 unsigned EltIdx = BitIndex / 32; 9879 unsigned LeftoverBitIdx = BitIndex % 32; 9880 SDLoc SL(N); 9881 9882 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9883 DCI.AddToWorklist(Cast.getNode()); 9884 9885 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9886 DAG.getConstant(EltIdx, SL, MVT::i32)); 9887 DCI.AddToWorklist(Elt.getNode()); 9888 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9889 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9890 DCI.AddToWorklist(Srl.getNode()); 9891 9892 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9893 DCI.AddToWorklist(Trunc.getNode()); 9894 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9895 } 9896 9897 return SDValue(); 9898 } 9899 9900 SDValue 9901 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9902 DAGCombinerInfo &DCI) const { 9903 SDValue Vec = N->getOperand(0); 9904 SDValue Idx = N->getOperand(2); 9905 EVT VecVT = Vec.getValueType(); 9906 EVT EltVT = VecVT.getVectorElementType(); 9907 9908 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9909 // => BUILD_VECTOR n x select (e, const-idx) 9910 if (!::shouldExpandVectorDynExt(N)) 9911 return SDValue(); 9912 9913 SelectionDAG &DAG = DCI.DAG; 9914 SDLoc SL(N); 9915 SDValue Ins = N->getOperand(1); 9916 EVT IdxVT = Idx.getValueType(); 9917 9918 SmallVector<SDValue, 16> Ops; 9919 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9920 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9921 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9922 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9923 Ops.push_back(V); 9924 } 9925 9926 return DAG.getBuildVector(VecVT, SL, Ops); 9927 } 9928 9929 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9930 const SDNode *N0, 9931 const SDNode *N1) const { 9932 EVT VT = N0->getValueType(0); 9933 9934 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9935 // support denormals ever. 9936 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9937 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9938 getSubtarget()->hasMadF16())) && 9939 isOperationLegal(ISD::FMAD, VT)) 9940 return ISD::FMAD; 9941 9942 const TargetOptions &Options = DAG.getTarget().Options; 9943 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9944 (N0->getFlags().hasAllowContract() && 9945 N1->getFlags().hasAllowContract())) && 9946 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9947 return ISD::FMA; 9948 } 9949 9950 return 0; 9951 } 9952 9953 // For a reassociatable opcode perform: 9954 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9955 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9956 SelectionDAG &DAG) const { 9957 EVT VT = N->getValueType(0); 9958 if (VT != MVT::i32 && VT != MVT::i64) 9959 return SDValue(); 9960 9961 unsigned Opc = N->getOpcode(); 9962 SDValue Op0 = N->getOperand(0); 9963 SDValue Op1 = N->getOperand(1); 9964 9965 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9966 return SDValue(); 9967 9968 if (Op0->isDivergent()) 9969 std::swap(Op0, Op1); 9970 9971 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9972 return SDValue(); 9973 9974 SDValue Op2 = Op1.getOperand(1); 9975 Op1 = Op1.getOperand(0); 9976 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9977 return SDValue(); 9978 9979 if (Op1->isDivergent()) 9980 std::swap(Op1, Op2); 9981 9982 // If either operand is constant this will conflict with 9983 // DAGCombiner::ReassociateOps(). 9984 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9985 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9986 return SDValue(); 9987 9988 SDLoc SL(N); 9989 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9990 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9991 } 9992 9993 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9994 EVT VT, 9995 SDValue N0, SDValue N1, SDValue N2, 9996 bool Signed) { 9997 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9998 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9999 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10000 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10001 } 10002 10003 SDValue SITargetLowering::performAddCombine(SDNode *N, 10004 DAGCombinerInfo &DCI) const { 10005 SelectionDAG &DAG = DCI.DAG; 10006 EVT VT = N->getValueType(0); 10007 SDLoc SL(N); 10008 SDValue LHS = N->getOperand(0); 10009 SDValue RHS = N->getOperand(1); 10010 10011 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10012 && Subtarget->hasMad64_32() && 10013 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10014 VT.getScalarSizeInBits() <= 64) { 10015 if (LHS.getOpcode() != ISD::MUL) 10016 std::swap(LHS, RHS); 10017 10018 SDValue MulLHS = LHS.getOperand(0); 10019 SDValue MulRHS = LHS.getOperand(1); 10020 SDValue AddRHS = RHS; 10021 10022 // TODO: Maybe restrict if SGPR inputs. 10023 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10024 numBitsUnsigned(MulRHS, DAG) <= 32) { 10025 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10026 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10027 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10028 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10029 } 10030 10031 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10032 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10033 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10034 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10035 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10036 } 10037 10038 return SDValue(); 10039 } 10040 10041 if (SDValue V = reassociateScalarOps(N, DAG)) { 10042 return V; 10043 } 10044 10045 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10046 return SDValue(); 10047 10048 // add x, zext (setcc) => addcarry x, 0, setcc 10049 // add x, sext (setcc) => subcarry x, 0, setcc 10050 unsigned Opc = LHS.getOpcode(); 10051 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10052 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10053 std::swap(RHS, LHS); 10054 10055 Opc = RHS.getOpcode(); 10056 switch (Opc) { 10057 default: break; 10058 case ISD::ZERO_EXTEND: 10059 case ISD::SIGN_EXTEND: 10060 case ISD::ANY_EXTEND: { 10061 auto Cond = RHS.getOperand(0); 10062 // If this won't be a real VOPC output, we would still need to insert an 10063 // extra instruction anyway. 10064 if (!isBoolSGPR(Cond)) 10065 break; 10066 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10067 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10068 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10069 return DAG.getNode(Opc, SL, VTList, Args); 10070 } 10071 case ISD::ADDCARRY: { 10072 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10073 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10074 if (!C || C->getZExtValue() != 0) break; 10075 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10076 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10077 } 10078 } 10079 return SDValue(); 10080 } 10081 10082 SDValue SITargetLowering::performSubCombine(SDNode *N, 10083 DAGCombinerInfo &DCI) const { 10084 SelectionDAG &DAG = DCI.DAG; 10085 EVT VT = N->getValueType(0); 10086 10087 if (VT != MVT::i32) 10088 return SDValue(); 10089 10090 SDLoc SL(N); 10091 SDValue LHS = N->getOperand(0); 10092 SDValue RHS = N->getOperand(1); 10093 10094 // sub x, zext (setcc) => subcarry x, 0, setcc 10095 // sub x, sext (setcc) => addcarry x, 0, setcc 10096 unsigned Opc = RHS.getOpcode(); 10097 switch (Opc) { 10098 default: break; 10099 case ISD::ZERO_EXTEND: 10100 case ISD::SIGN_EXTEND: 10101 case ISD::ANY_EXTEND: { 10102 auto Cond = RHS.getOperand(0); 10103 // If this won't be a real VOPC output, we would still need to insert an 10104 // extra instruction anyway. 10105 if (!isBoolSGPR(Cond)) 10106 break; 10107 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10108 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10109 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10110 return DAG.getNode(Opc, SL, VTList, Args); 10111 } 10112 } 10113 10114 if (LHS.getOpcode() == ISD::SUBCARRY) { 10115 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10116 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10117 if (!C || !C->isNullValue()) 10118 return SDValue(); 10119 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10120 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10121 } 10122 return SDValue(); 10123 } 10124 10125 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10126 DAGCombinerInfo &DCI) const { 10127 10128 if (N->getValueType(0) != MVT::i32) 10129 return SDValue(); 10130 10131 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10132 if (!C || C->getZExtValue() != 0) 10133 return SDValue(); 10134 10135 SelectionDAG &DAG = DCI.DAG; 10136 SDValue LHS = N->getOperand(0); 10137 10138 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10139 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10140 unsigned LHSOpc = LHS.getOpcode(); 10141 unsigned Opc = N->getOpcode(); 10142 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10143 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10144 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10145 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10146 } 10147 return SDValue(); 10148 } 10149 10150 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10151 DAGCombinerInfo &DCI) const { 10152 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10153 return SDValue(); 10154 10155 SelectionDAG &DAG = DCI.DAG; 10156 EVT VT = N->getValueType(0); 10157 10158 SDLoc SL(N); 10159 SDValue LHS = N->getOperand(0); 10160 SDValue RHS = N->getOperand(1); 10161 10162 // These should really be instruction patterns, but writing patterns with 10163 // source modiifiers is a pain. 10164 10165 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10166 if (LHS.getOpcode() == ISD::FADD) { 10167 SDValue A = LHS.getOperand(0); 10168 if (A == LHS.getOperand(1)) { 10169 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10170 if (FusedOp != 0) { 10171 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10172 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10173 } 10174 } 10175 } 10176 10177 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10178 if (RHS.getOpcode() == ISD::FADD) { 10179 SDValue A = RHS.getOperand(0); 10180 if (A == RHS.getOperand(1)) { 10181 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10182 if (FusedOp != 0) { 10183 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10184 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10185 } 10186 } 10187 } 10188 10189 return SDValue(); 10190 } 10191 10192 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10193 DAGCombinerInfo &DCI) const { 10194 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10195 return SDValue(); 10196 10197 SelectionDAG &DAG = DCI.DAG; 10198 SDLoc SL(N); 10199 EVT VT = N->getValueType(0); 10200 assert(!VT.isVector()); 10201 10202 // Try to get the fneg to fold into the source modifier. This undoes generic 10203 // DAG combines and folds them into the mad. 10204 // 10205 // Only do this if we are not trying to support denormals. v_mad_f32 does 10206 // not support denormals ever. 10207 SDValue LHS = N->getOperand(0); 10208 SDValue RHS = N->getOperand(1); 10209 if (LHS.getOpcode() == ISD::FADD) { 10210 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10211 SDValue A = LHS.getOperand(0); 10212 if (A == LHS.getOperand(1)) { 10213 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10214 if (FusedOp != 0){ 10215 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10216 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10217 10218 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10219 } 10220 } 10221 } 10222 10223 if (RHS.getOpcode() == ISD::FADD) { 10224 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10225 10226 SDValue A = RHS.getOperand(0); 10227 if (A == RHS.getOperand(1)) { 10228 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10229 if (FusedOp != 0){ 10230 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10231 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10232 } 10233 } 10234 } 10235 10236 return SDValue(); 10237 } 10238 10239 SDValue SITargetLowering::performFMACombine(SDNode *N, 10240 DAGCombinerInfo &DCI) const { 10241 SelectionDAG &DAG = DCI.DAG; 10242 EVT VT = N->getValueType(0); 10243 SDLoc SL(N); 10244 10245 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10246 return SDValue(); 10247 10248 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10249 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10250 SDValue Op1 = N->getOperand(0); 10251 SDValue Op2 = N->getOperand(1); 10252 SDValue FMA = N->getOperand(2); 10253 10254 if (FMA.getOpcode() != ISD::FMA || 10255 Op1.getOpcode() != ISD::FP_EXTEND || 10256 Op2.getOpcode() != ISD::FP_EXTEND) 10257 return SDValue(); 10258 10259 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10260 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10261 // is sufficient to allow generaing fdot2. 10262 const TargetOptions &Options = DAG.getTarget().Options; 10263 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10264 (N->getFlags().hasAllowContract() && 10265 FMA->getFlags().hasAllowContract())) { 10266 Op1 = Op1.getOperand(0); 10267 Op2 = Op2.getOperand(0); 10268 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10269 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10270 return SDValue(); 10271 10272 SDValue Vec1 = Op1.getOperand(0); 10273 SDValue Idx1 = Op1.getOperand(1); 10274 SDValue Vec2 = Op2.getOperand(0); 10275 10276 SDValue FMAOp1 = FMA.getOperand(0); 10277 SDValue FMAOp2 = FMA.getOperand(1); 10278 SDValue FMAAcc = FMA.getOperand(2); 10279 10280 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10281 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10282 return SDValue(); 10283 10284 FMAOp1 = FMAOp1.getOperand(0); 10285 FMAOp2 = FMAOp2.getOperand(0); 10286 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10287 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10288 return SDValue(); 10289 10290 SDValue Vec3 = FMAOp1.getOperand(0); 10291 SDValue Vec4 = FMAOp2.getOperand(0); 10292 SDValue Idx2 = FMAOp1.getOperand(1); 10293 10294 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10295 // Idx1 and Idx2 cannot be the same. 10296 Idx1 == Idx2) 10297 return SDValue(); 10298 10299 if (Vec1 == Vec2 || Vec3 == Vec4) 10300 return SDValue(); 10301 10302 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10303 return SDValue(); 10304 10305 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10306 (Vec1 == Vec4 && Vec2 == Vec3)) { 10307 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10308 DAG.getTargetConstant(0, SL, MVT::i1)); 10309 } 10310 } 10311 return SDValue(); 10312 } 10313 10314 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10315 DAGCombinerInfo &DCI) const { 10316 SelectionDAG &DAG = DCI.DAG; 10317 SDLoc SL(N); 10318 10319 SDValue LHS = N->getOperand(0); 10320 SDValue RHS = N->getOperand(1); 10321 EVT VT = LHS.getValueType(); 10322 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10323 10324 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10325 if (!CRHS) { 10326 CRHS = dyn_cast<ConstantSDNode>(LHS); 10327 if (CRHS) { 10328 std::swap(LHS, RHS); 10329 CC = getSetCCSwappedOperands(CC); 10330 } 10331 } 10332 10333 if (CRHS) { 10334 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10335 isBoolSGPR(LHS.getOperand(0))) { 10336 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10337 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10338 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10339 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10340 if ((CRHS->isAllOnesValue() && 10341 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10342 (CRHS->isNullValue() && 10343 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10344 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10345 DAG.getConstant(-1, SL, MVT::i1)); 10346 if ((CRHS->isAllOnesValue() && 10347 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10348 (CRHS->isNullValue() && 10349 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10350 return LHS.getOperand(0); 10351 } 10352 10353 uint64_t CRHSVal = CRHS->getZExtValue(); 10354 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10355 LHS.getOpcode() == ISD::SELECT && 10356 isa<ConstantSDNode>(LHS.getOperand(1)) && 10357 isa<ConstantSDNode>(LHS.getOperand(2)) && 10358 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10359 isBoolSGPR(LHS.getOperand(0))) { 10360 // Given CT != FT: 10361 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10362 // setcc (select cc, CT, CF), CF, ne => cc 10363 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10364 // setcc (select cc, CT, CF), CT, eq => cc 10365 uint64_t CT = LHS.getConstantOperandVal(1); 10366 uint64_t CF = LHS.getConstantOperandVal(2); 10367 10368 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10369 (CT == CRHSVal && CC == ISD::SETNE)) 10370 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10371 DAG.getConstant(-1, SL, MVT::i1)); 10372 if ((CF == CRHSVal && CC == ISD::SETNE) || 10373 (CT == CRHSVal && CC == ISD::SETEQ)) 10374 return LHS.getOperand(0); 10375 } 10376 } 10377 10378 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10379 VT != MVT::f16)) 10380 return SDValue(); 10381 10382 // Match isinf/isfinite pattern 10383 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10384 // (fcmp one (fabs x), inf) -> (fp_class x, 10385 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10386 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10387 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10388 if (!CRHS) 10389 return SDValue(); 10390 10391 const APFloat &APF = CRHS->getValueAPF(); 10392 if (APF.isInfinity() && !APF.isNegative()) { 10393 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10394 SIInstrFlags::N_INFINITY; 10395 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10396 SIInstrFlags::P_ZERO | 10397 SIInstrFlags::N_NORMAL | 10398 SIInstrFlags::P_NORMAL | 10399 SIInstrFlags::N_SUBNORMAL | 10400 SIInstrFlags::P_SUBNORMAL; 10401 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10402 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10403 DAG.getConstant(Mask, SL, MVT::i32)); 10404 } 10405 } 10406 10407 return SDValue(); 10408 } 10409 10410 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10411 DAGCombinerInfo &DCI) const { 10412 SelectionDAG &DAG = DCI.DAG; 10413 SDLoc SL(N); 10414 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10415 10416 SDValue Src = N->getOperand(0); 10417 SDValue Shift = N->getOperand(0); 10418 10419 // TODO: Extend type shouldn't matter (assuming legal types). 10420 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10421 Shift = Shift.getOperand(0); 10422 10423 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10424 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10425 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10426 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10427 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10428 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10429 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10430 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10431 SDLoc(Shift.getOperand(0)), MVT::i32); 10432 10433 unsigned ShiftOffset = 8 * Offset; 10434 if (Shift.getOpcode() == ISD::SHL) 10435 ShiftOffset -= C->getZExtValue(); 10436 else 10437 ShiftOffset += C->getZExtValue(); 10438 10439 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10440 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10441 MVT::f32, Shift); 10442 } 10443 } 10444 } 10445 10446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10447 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10448 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10449 // We simplified Src. If this node is not dead, visit it again so it is 10450 // folded properly. 10451 if (N->getOpcode() != ISD::DELETED_NODE) 10452 DCI.AddToWorklist(N); 10453 return SDValue(N, 0); 10454 } 10455 10456 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10457 if (SDValue DemandedSrc = 10458 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10459 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10460 10461 return SDValue(); 10462 } 10463 10464 SDValue SITargetLowering::performClampCombine(SDNode *N, 10465 DAGCombinerInfo &DCI) const { 10466 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10467 if (!CSrc) 10468 return SDValue(); 10469 10470 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10471 const APFloat &F = CSrc->getValueAPF(); 10472 APFloat Zero = APFloat::getZero(F.getSemantics()); 10473 if (F < Zero || 10474 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10475 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10476 } 10477 10478 APFloat One(F.getSemantics(), "1.0"); 10479 if (F > One) 10480 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10481 10482 return SDValue(CSrc, 0); 10483 } 10484 10485 10486 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10487 DAGCombinerInfo &DCI) const { 10488 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10489 return SDValue(); 10490 switch (N->getOpcode()) { 10491 default: 10492 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10493 case ISD::ADD: 10494 return performAddCombine(N, DCI); 10495 case ISD::SUB: 10496 return performSubCombine(N, DCI); 10497 case ISD::ADDCARRY: 10498 case ISD::SUBCARRY: 10499 return performAddCarrySubCarryCombine(N, DCI); 10500 case ISD::FADD: 10501 return performFAddCombine(N, DCI); 10502 case ISD::FSUB: 10503 return performFSubCombine(N, DCI); 10504 case ISD::SETCC: 10505 return performSetCCCombine(N, DCI); 10506 case ISD::FMAXNUM: 10507 case ISD::FMINNUM: 10508 case ISD::FMAXNUM_IEEE: 10509 case ISD::FMINNUM_IEEE: 10510 case ISD::SMAX: 10511 case ISD::SMIN: 10512 case ISD::UMAX: 10513 case ISD::UMIN: 10514 case AMDGPUISD::FMIN_LEGACY: 10515 case AMDGPUISD::FMAX_LEGACY: 10516 return performMinMaxCombine(N, DCI); 10517 case ISD::FMA: 10518 return performFMACombine(N, DCI); 10519 case ISD::LOAD: { 10520 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10521 return Widended; 10522 LLVM_FALLTHROUGH; 10523 } 10524 case ISD::STORE: 10525 case ISD::ATOMIC_LOAD: 10526 case ISD::ATOMIC_STORE: 10527 case ISD::ATOMIC_CMP_SWAP: 10528 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10529 case ISD::ATOMIC_SWAP: 10530 case ISD::ATOMIC_LOAD_ADD: 10531 case ISD::ATOMIC_LOAD_SUB: 10532 case ISD::ATOMIC_LOAD_AND: 10533 case ISD::ATOMIC_LOAD_OR: 10534 case ISD::ATOMIC_LOAD_XOR: 10535 case ISD::ATOMIC_LOAD_NAND: 10536 case ISD::ATOMIC_LOAD_MIN: 10537 case ISD::ATOMIC_LOAD_MAX: 10538 case ISD::ATOMIC_LOAD_UMIN: 10539 case ISD::ATOMIC_LOAD_UMAX: 10540 case ISD::ATOMIC_LOAD_FADD: 10541 case AMDGPUISD::ATOMIC_INC: 10542 case AMDGPUISD::ATOMIC_DEC: 10543 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10544 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10545 if (DCI.isBeforeLegalize()) 10546 break; 10547 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10548 case ISD::AND: 10549 return performAndCombine(N, DCI); 10550 case ISD::OR: 10551 return performOrCombine(N, DCI); 10552 case ISD::XOR: 10553 return performXorCombine(N, DCI); 10554 case ISD::ZERO_EXTEND: 10555 return performZeroExtendCombine(N, DCI); 10556 case ISD::SIGN_EXTEND_INREG: 10557 return performSignExtendInRegCombine(N , DCI); 10558 case AMDGPUISD::FP_CLASS: 10559 return performClassCombine(N, DCI); 10560 case ISD::FCANONICALIZE: 10561 return performFCanonicalizeCombine(N, DCI); 10562 case AMDGPUISD::RCP: 10563 return performRcpCombine(N, DCI); 10564 case AMDGPUISD::FRACT: 10565 case AMDGPUISD::RSQ: 10566 case AMDGPUISD::RCP_LEGACY: 10567 case AMDGPUISD::RCP_IFLAG: 10568 case AMDGPUISD::RSQ_CLAMP: 10569 case AMDGPUISD::LDEXP: { 10570 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10571 SDValue Src = N->getOperand(0); 10572 if (Src.isUndef()) 10573 return Src; 10574 break; 10575 } 10576 case ISD::SINT_TO_FP: 10577 case ISD::UINT_TO_FP: 10578 return performUCharToFloatCombine(N, DCI); 10579 case AMDGPUISD::CVT_F32_UBYTE0: 10580 case AMDGPUISD::CVT_F32_UBYTE1: 10581 case AMDGPUISD::CVT_F32_UBYTE2: 10582 case AMDGPUISD::CVT_F32_UBYTE3: 10583 return performCvtF32UByteNCombine(N, DCI); 10584 case AMDGPUISD::FMED3: 10585 return performFMed3Combine(N, DCI); 10586 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10587 return performCvtPkRTZCombine(N, DCI); 10588 case AMDGPUISD::CLAMP: 10589 return performClampCombine(N, DCI); 10590 case ISD::SCALAR_TO_VECTOR: { 10591 SelectionDAG &DAG = DCI.DAG; 10592 EVT VT = N->getValueType(0); 10593 10594 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10595 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10596 SDLoc SL(N); 10597 SDValue Src = N->getOperand(0); 10598 EVT EltVT = Src.getValueType(); 10599 if (EltVT == MVT::f16) 10600 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10601 10602 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10603 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10604 } 10605 10606 break; 10607 } 10608 case ISD::EXTRACT_VECTOR_ELT: 10609 return performExtractVectorEltCombine(N, DCI); 10610 case ISD::INSERT_VECTOR_ELT: 10611 return performInsertVectorEltCombine(N, DCI); 10612 } 10613 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10614 } 10615 10616 /// Helper function for adjustWritemask 10617 static unsigned SubIdx2Lane(unsigned Idx) { 10618 switch (Idx) { 10619 default: return 0; 10620 case AMDGPU::sub0: return 0; 10621 case AMDGPU::sub1: return 1; 10622 case AMDGPU::sub2: return 2; 10623 case AMDGPU::sub3: return 3; 10624 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10625 } 10626 } 10627 10628 /// Adjust the writemask of MIMG instructions 10629 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10630 SelectionDAG &DAG) const { 10631 unsigned Opcode = Node->getMachineOpcode(); 10632 10633 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10634 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10635 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10636 return Node; // not implemented for D16 10637 10638 SDNode *Users[5] = { nullptr }; 10639 unsigned Lane = 0; 10640 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10641 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10642 unsigned NewDmask = 0; 10643 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10644 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10645 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10646 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10647 unsigned TFCLane = 0; 10648 bool HasChain = Node->getNumValues() > 1; 10649 10650 if (OldDmask == 0) { 10651 // These are folded out, but on the chance it happens don't assert. 10652 return Node; 10653 } 10654 10655 unsigned OldBitsSet = countPopulation(OldDmask); 10656 // Work out which is the TFE/LWE lane if that is enabled. 10657 if (UsesTFC) { 10658 TFCLane = OldBitsSet; 10659 } 10660 10661 // Try to figure out the used register components 10662 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10663 I != E; ++I) { 10664 10665 // Don't look at users of the chain. 10666 if (I.getUse().getResNo() != 0) 10667 continue; 10668 10669 // Abort if we can't understand the usage 10670 if (!I->isMachineOpcode() || 10671 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10672 return Node; 10673 10674 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10675 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10676 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10677 // set, etc. 10678 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10679 10680 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10681 if (UsesTFC && Lane == TFCLane) { 10682 Users[Lane] = *I; 10683 } else { 10684 // Set which texture component corresponds to the lane. 10685 unsigned Comp; 10686 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10687 Comp = countTrailingZeros(Dmask); 10688 Dmask &= ~(1 << Comp); 10689 } 10690 10691 // Abort if we have more than one user per component. 10692 if (Users[Lane]) 10693 return Node; 10694 10695 Users[Lane] = *I; 10696 NewDmask |= 1 << Comp; 10697 } 10698 } 10699 10700 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10701 bool NoChannels = !NewDmask; 10702 if (NoChannels) { 10703 if (!UsesTFC) { 10704 // No uses of the result and not using TFC. Then do nothing. 10705 return Node; 10706 } 10707 // If the original dmask has one channel - then nothing to do 10708 if (OldBitsSet == 1) 10709 return Node; 10710 // Use an arbitrary dmask - required for the instruction to work 10711 NewDmask = 1; 10712 } 10713 // Abort if there's no change 10714 if (NewDmask == OldDmask) 10715 return Node; 10716 10717 unsigned BitsSet = countPopulation(NewDmask); 10718 10719 // Check for TFE or LWE - increase the number of channels by one to account 10720 // for the extra return value 10721 // This will need adjustment for D16 if this is also included in 10722 // adjustWriteMask (this function) but at present D16 are excluded. 10723 unsigned NewChannels = BitsSet + UsesTFC; 10724 10725 int NewOpcode = 10726 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10727 assert(NewOpcode != -1 && 10728 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10729 "failed to find equivalent MIMG op"); 10730 10731 // Adjust the writemask in the node 10732 SmallVector<SDValue, 12> Ops; 10733 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10734 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10735 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10736 10737 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10738 10739 MVT ResultVT = NewChannels == 1 ? 10740 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10741 NewChannels == 5 ? 8 : NewChannels); 10742 SDVTList NewVTList = HasChain ? 10743 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10744 10745 10746 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10747 NewVTList, Ops); 10748 10749 if (HasChain) { 10750 // Update chain. 10751 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10752 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10753 } 10754 10755 if (NewChannels == 1) { 10756 assert(Node->hasNUsesOfValue(1, 0)); 10757 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10758 SDLoc(Node), Users[Lane]->getValueType(0), 10759 SDValue(NewNode, 0)); 10760 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10761 return nullptr; 10762 } 10763 10764 // Update the users of the node with the new indices 10765 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10766 SDNode *User = Users[i]; 10767 if (!User) { 10768 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10769 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10770 if (i || !NoChannels) 10771 continue; 10772 } else { 10773 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10774 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10775 } 10776 10777 switch (Idx) { 10778 default: break; 10779 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10780 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10781 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10782 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10783 } 10784 } 10785 10786 DAG.RemoveDeadNode(Node); 10787 return nullptr; 10788 } 10789 10790 static bool isFrameIndexOp(SDValue Op) { 10791 if (Op.getOpcode() == ISD::AssertZext) 10792 Op = Op.getOperand(0); 10793 10794 return isa<FrameIndexSDNode>(Op); 10795 } 10796 10797 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10798 /// with frame index operands. 10799 /// LLVM assumes that inputs are to these instructions are registers. 10800 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10801 SelectionDAG &DAG) const { 10802 if (Node->getOpcode() == ISD::CopyToReg) { 10803 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10804 SDValue SrcVal = Node->getOperand(2); 10805 10806 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10807 // to try understanding copies to physical registers. 10808 if (SrcVal.getValueType() == MVT::i1 && 10809 Register::isPhysicalRegister(DestReg->getReg())) { 10810 SDLoc SL(Node); 10811 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10812 SDValue VReg = DAG.getRegister( 10813 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10814 10815 SDNode *Glued = Node->getGluedNode(); 10816 SDValue ToVReg 10817 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10818 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10819 SDValue ToResultReg 10820 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10821 VReg, ToVReg.getValue(1)); 10822 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10823 DAG.RemoveDeadNode(Node); 10824 return ToResultReg.getNode(); 10825 } 10826 } 10827 10828 SmallVector<SDValue, 8> Ops; 10829 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10830 if (!isFrameIndexOp(Node->getOperand(i))) { 10831 Ops.push_back(Node->getOperand(i)); 10832 continue; 10833 } 10834 10835 SDLoc DL(Node); 10836 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10837 Node->getOperand(i).getValueType(), 10838 Node->getOperand(i)), 0)); 10839 } 10840 10841 return DAG.UpdateNodeOperands(Node, Ops); 10842 } 10843 10844 /// Fold the instructions after selecting them. 10845 /// Returns null if users were already updated. 10846 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10847 SelectionDAG &DAG) const { 10848 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10849 unsigned Opcode = Node->getMachineOpcode(); 10850 10851 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10852 !TII->isGather4(Opcode)) { 10853 return adjustWritemask(Node, DAG); 10854 } 10855 10856 if (Opcode == AMDGPU::INSERT_SUBREG || 10857 Opcode == AMDGPU::REG_SEQUENCE) { 10858 legalizeTargetIndependentNode(Node, DAG); 10859 return Node; 10860 } 10861 10862 switch (Opcode) { 10863 case AMDGPU::V_DIV_SCALE_F32: 10864 case AMDGPU::V_DIV_SCALE_F64: { 10865 // Satisfy the operand register constraint when one of the inputs is 10866 // undefined. Ordinarily each undef value will have its own implicit_def of 10867 // a vreg, so force these to use a single register. 10868 SDValue Src0 = Node->getOperand(0); 10869 SDValue Src1 = Node->getOperand(1); 10870 SDValue Src2 = Node->getOperand(2); 10871 10872 if ((Src0.isMachineOpcode() && 10873 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10874 (Src0 == Src1 || Src0 == Src2)) 10875 break; 10876 10877 MVT VT = Src0.getValueType().getSimpleVT(); 10878 const TargetRegisterClass *RC = 10879 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10880 10881 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10882 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10883 10884 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10885 UndefReg, Src0, SDValue()); 10886 10887 // src0 must be the same register as src1 or src2, even if the value is 10888 // undefined, so make sure we don't violate this constraint. 10889 if (Src0.isMachineOpcode() && 10890 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10891 if (Src1.isMachineOpcode() && 10892 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10893 Src0 = Src1; 10894 else if (Src2.isMachineOpcode() && 10895 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10896 Src0 = Src2; 10897 else { 10898 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10899 Src0 = UndefReg; 10900 Src1 = UndefReg; 10901 } 10902 } else 10903 break; 10904 10905 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10906 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10907 Ops.push_back(Node->getOperand(I)); 10908 10909 Ops.push_back(ImpDef.getValue(1)); 10910 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10911 } 10912 default: 10913 break; 10914 } 10915 10916 return Node; 10917 } 10918 10919 /// Assign the register class depending on the number of 10920 /// bits set in the writemask 10921 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10922 SDNode *Node) const { 10923 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10924 10925 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10926 10927 if (TII->isVOP3(MI.getOpcode())) { 10928 // Make sure constant bus requirements are respected. 10929 TII->legalizeOperandsVOP3(MRI, MI); 10930 10931 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10932 // This saves a chain-copy of registers and better ballance register 10933 // use between vgpr and agpr as agpr tuples tend to be big. 10934 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10935 unsigned Opc = MI.getOpcode(); 10936 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10937 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10938 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10939 if (I == -1) 10940 break; 10941 MachineOperand &Op = MI.getOperand(I); 10942 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10943 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10944 !Register::isVirtualRegister(Op.getReg()) || 10945 !TRI->isAGPR(MRI, Op.getReg())) 10946 continue; 10947 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10948 if (!Src || !Src->isCopy() || 10949 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10950 continue; 10951 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10952 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10953 // All uses of agpr64 and agpr32 can also accept vgpr except for 10954 // v_accvgpr_read, but we do not produce agpr reads during selection, 10955 // so no use checks are needed. 10956 MRI.setRegClass(Op.getReg(), NewRC); 10957 } 10958 } 10959 10960 return; 10961 } 10962 10963 // Replace unused atomics with the no return version. 10964 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10965 if (NoRetAtomicOp != -1) { 10966 if (!Node->hasAnyUseOfValue(0)) { 10967 MI.setDesc(TII->get(NoRetAtomicOp)); 10968 MI.RemoveOperand(0); 10969 return; 10970 } 10971 10972 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10973 // instruction, because the return type of these instructions is a vec2 of 10974 // the memory type, so it can be tied to the input operand. 10975 // This means these instructions always have a use, so we need to add a 10976 // special case to check if the atomic has only one extract_subreg use, 10977 // which itself has no uses. 10978 if ((Node->hasNUsesOfValue(1, 0) && 10979 Node->use_begin()->isMachineOpcode() && 10980 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10981 !Node->use_begin()->hasAnyUseOfValue(0))) { 10982 Register Def = MI.getOperand(0).getReg(); 10983 10984 // Change this into a noret atomic. 10985 MI.setDesc(TII->get(NoRetAtomicOp)); 10986 MI.RemoveOperand(0); 10987 10988 // If we only remove the def operand from the atomic instruction, the 10989 // extract_subreg will be left with a use of a vreg without a def. 10990 // So we need to insert an implicit_def to avoid machine verifier 10991 // errors. 10992 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10993 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10994 } 10995 return; 10996 } 10997 } 10998 10999 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11000 uint64_t Val) { 11001 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11002 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11003 } 11004 11005 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11006 const SDLoc &DL, 11007 SDValue Ptr) const { 11008 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11009 11010 // Build the half of the subregister with the constants before building the 11011 // full 128-bit register. If we are building multiple resource descriptors, 11012 // this will allow CSEing of the 2-component register. 11013 const SDValue Ops0[] = { 11014 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11015 buildSMovImm32(DAG, DL, 0), 11016 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11017 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11018 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11019 }; 11020 11021 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11022 MVT::v2i32, Ops0), 0); 11023 11024 // Combine the constants and the pointer. 11025 const SDValue Ops1[] = { 11026 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11027 Ptr, 11028 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11029 SubRegHi, 11030 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11031 }; 11032 11033 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11034 } 11035 11036 /// Return a resource descriptor with the 'Add TID' bit enabled 11037 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11038 /// of the resource descriptor) to create an offset, which is added to 11039 /// the resource pointer. 11040 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11041 SDValue Ptr, uint32_t RsrcDword1, 11042 uint64_t RsrcDword2And3) const { 11043 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11044 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11045 if (RsrcDword1) { 11046 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11047 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11048 0); 11049 } 11050 11051 SDValue DataLo = buildSMovImm32(DAG, DL, 11052 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11053 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11054 11055 const SDValue Ops[] = { 11056 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11057 PtrLo, 11058 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11059 PtrHi, 11060 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11061 DataLo, 11062 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11063 DataHi, 11064 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11065 }; 11066 11067 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11068 } 11069 11070 //===----------------------------------------------------------------------===// 11071 // SI Inline Assembly Support 11072 //===----------------------------------------------------------------------===// 11073 11074 std::pair<unsigned, const TargetRegisterClass *> 11075 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11076 StringRef Constraint, 11077 MVT VT) const { 11078 const TargetRegisterClass *RC = nullptr; 11079 if (Constraint.size() == 1) { 11080 const unsigned BitWidth = VT.getSizeInBits(); 11081 switch (Constraint[0]) { 11082 default: 11083 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11084 case 's': 11085 case 'r': 11086 switch (BitWidth) { 11087 case 16: 11088 RC = &AMDGPU::SReg_32RegClass; 11089 break; 11090 case 64: 11091 RC = &AMDGPU::SGPR_64RegClass; 11092 break; 11093 default: 11094 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11095 if (!RC) 11096 return std::make_pair(0U, nullptr); 11097 break; 11098 } 11099 break; 11100 case 'v': 11101 switch (BitWidth) { 11102 case 16: 11103 RC = &AMDGPU::VGPR_32RegClass; 11104 break; 11105 default: 11106 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11107 if (!RC) 11108 return std::make_pair(0U, nullptr); 11109 break; 11110 } 11111 break; 11112 case 'a': 11113 if (!Subtarget->hasMAIInsts()) 11114 break; 11115 switch (BitWidth) { 11116 case 16: 11117 RC = &AMDGPU::AGPR_32RegClass; 11118 break; 11119 default: 11120 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11121 if (!RC) 11122 return std::make_pair(0U, nullptr); 11123 break; 11124 } 11125 break; 11126 } 11127 // We actually support i128, i16 and f16 as inline parameters 11128 // even if they are not reported as legal 11129 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11130 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11131 return std::make_pair(0U, RC); 11132 } 11133 11134 if (Constraint.size() > 1) { 11135 if (Constraint[1] == 'v') { 11136 RC = &AMDGPU::VGPR_32RegClass; 11137 } else if (Constraint[1] == 's') { 11138 RC = &AMDGPU::SGPR_32RegClass; 11139 } else if (Constraint[1] == 'a') { 11140 RC = &AMDGPU::AGPR_32RegClass; 11141 } 11142 11143 if (RC) { 11144 uint32_t Idx; 11145 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11146 if (!Failed && Idx < RC->getNumRegs()) 11147 return std::make_pair(RC->getRegister(Idx), RC); 11148 } 11149 } 11150 11151 // FIXME: Returns VS_32 for physical SGPR constraints 11152 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11153 } 11154 11155 SITargetLowering::ConstraintType 11156 SITargetLowering::getConstraintType(StringRef Constraint) const { 11157 if (Constraint.size() == 1) { 11158 switch (Constraint[0]) { 11159 default: break; 11160 case 's': 11161 case 'v': 11162 case 'a': 11163 return C_RegisterClass; 11164 case 'A': 11165 return C_Other; 11166 } 11167 } 11168 return TargetLowering::getConstraintType(Constraint); 11169 } 11170 11171 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11172 std::string &Constraint, 11173 std::vector<SDValue> &Ops, 11174 SelectionDAG &DAG) const { 11175 if (Constraint.length() == 1 && Constraint[0] == 'A') { 11176 LowerAsmOperandForConstraintA(Op, Ops, DAG); 11177 } else { 11178 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11179 } 11180 } 11181 11182 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op, 11183 std::vector<SDValue> &Ops, 11184 SelectionDAG &DAG) const { 11185 unsigned Size = Op.getScalarValueSizeInBits(); 11186 if (Size > 64) 11187 return; 11188 11189 uint64_t Val; 11190 bool IsConst = false; 11191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11192 Val = C->getSExtValue(); 11193 IsConst = true; 11194 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11195 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11196 IsConst = true; 11197 } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11198 if (Size != 16 || Op.getNumOperands() != 2) 11199 return; 11200 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11201 return; 11202 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11203 Val = C->getSExtValue(); 11204 IsConst = true; 11205 } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11206 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11207 IsConst = true; 11208 } 11209 } 11210 11211 if (IsConst) { 11212 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11213 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11214 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11215 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11216 // Clear unused bits of fp constants 11217 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11218 unsigned UnusedBits = 64 - Size; 11219 Val = (Val << UnusedBits) >> UnusedBits; 11220 } 11221 auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64); 11222 Ops.push_back(Res); 11223 } 11224 } 11225 } 11226 11227 // Figure out which registers should be reserved for stack access. Only after 11228 // the function is legalized do we know all of the non-spill stack objects or if 11229 // calls are present. 11230 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11231 MachineRegisterInfo &MRI = MF.getRegInfo(); 11232 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11233 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11234 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11235 11236 if (Info->isEntryFunction()) { 11237 // Callable functions have fixed registers used for stack access. 11238 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11239 } 11240 11241 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11242 Info->getStackPtrOffsetReg())); 11243 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11244 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11245 11246 // We need to worry about replacing the default register with itself in case 11247 // of MIR testcases missing the MFI. 11248 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11249 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11250 11251 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11252 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11253 11254 Info->limitOccupancy(MF); 11255 11256 if (ST.isWave32() && !MF.empty()) { 11257 // Add VCC_HI def because many instructions marked as imp-use VCC where 11258 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11259 // having a use of undef. 11260 11261 const SIInstrInfo *TII = ST.getInstrInfo(); 11262 DebugLoc DL; 11263 11264 MachineBasicBlock &MBB = MF.front(); 11265 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11266 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11267 11268 for (auto &MBB : MF) { 11269 for (auto &MI : MBB) { 11270 TII->fixImplicitOperands(MI); 11271 } 11272 } 11273 } 11274 11275 TargetLoweringBase::finalizeLowering(MF); 11276 11277 // Allocate a VGPR for future SGPR Spill if 11278 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11279 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11280 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11281 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11282 Info->reserveVGPRforSGPRSpills(MF); 11283 } 11284 11285 void SITargetLowering::computeKnownBitsForFrameIndex( 11286 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11287 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11288 11289 // Set the high bits to zero based on the maximum allowed scratch size per 11290 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11291 // calculation won't overflow, so assume the sign bit is never set. 11292 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11293 } 11294 11295 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11296 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11297 const Align CacheLineAlign = Align(64); 11298 11299 // Pre-GFX10 target did not benefit from loop alignment 11300 if (!ML || DisableLoopAlignment || 11301 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11302 getSubtarget()->hasInstFwdPrefetchBug()) 11303 return PrefAlign; 11304 11305 // On GFX10 I$ is 4 x 64 bytes cache lines. 11306 // By default prefetcher keeps one cache line behind and reads two ahead. 11307 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11308 // behind and one ahead. 11309 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11310 // If loop fits 64 bytes it always spans no more than two cache lines and 11311 // does not need an alignment. 11312 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11313 // Else if loop is less or equal 192 bytes we need two lines behind. 11314 11315 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11316 const MachineBasicBlock *Header = ML->getHeader(); 11317 if (Header->getAlignment() != PrefAlign) 11318 return Header->getAlignment(); // Already processed. 11319 11320 unsigned LoopSize = 0; 11321 for (const MachineBasicBlock *MBB : ML->blocks()) { 11322 // If inner loop block is aligned assume in average half of the alignment 11323 // size to be added as nops. 11324 if (MBB != Header) 11325 LoopSize += MBB->getAlignment().value() / 2; 11326 11327 for (const MachineInstr &MI : *MBB) { 11328 LoopSize += TII->getInstSizeInBytes(MI); 11329 if (LoopSize > 192) 11330 return PrefAlign; 11331 } 11332 } 11333 11334 if (LoopSize <= 64) 11335 return PrefAlign; 11336 11337 if (LoopSize <= 128) 11338 return CacheLineAlign; 11339 11340 // If any of parent loops is surrounded by prefetch instructions do not 11341 // insert new for inner loop, which would reset parent's settings. 11342 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11343 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11344 auto I = Exit->getFirstNonDebugInstr(); 11345 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11346 return CacheLineAlign; 11347 } 11348 } 11349 11350 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11351 MachineBasicBlock *Exit = ML->getExitBlock(); 11352 11353 if (Pre && Exit) { 11354 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11355 TII->get(AMDGPU::S_INST_PREFETCH)) 11356 .addImm(1); // prefetch 2 lines behind PC 11357 11358 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11359 TII->get(AMDGPU::S_INST_PREFETCH)) 11360 .addImm(2); // prefetch 1 line behind PC 11361 } 11362 11363 return CacheLineAlign; 11364 } 11365 11366 LLVM_ATTRIBUTE_UNUSED 11367 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11368 assert(N->getOpcode() == ISD::CopyFromReg); 11369 do { 11370 // Follow the chain until we find an INLINEASM node. 11371 N = N->getOperand(0).getNode(); 11372 if (N->getOpcode() == ISD::INLINEASM || 11373 N->getOpcode() == ISD::INLINEASM_BR) 11374 return true; 11375 } while (N->getOpcode() == ISD::CopyFromReg); 11376 return false; 11377 } 11378 11379 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11380 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11381 { 11382 switch (N->getOpcode()) { 11383 case ISD::CopyFromReg: 11384 { 11385 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11386 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11387 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11388 Register Reg = R->getReg(); 11389 11390 // FIXME: Why does this need to consider isLiveIn? 11391 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11392 return !TRI->isSGPRReg(MRI, Reg); 11393 11394 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11395 return KDA->isDivergent(V); 11396 11397 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11398 return !TRI->isSGPRReg(MRI, Reg); 11399 } 11400 break; 11401 case ISD::LOAD: { 11402 const LoadSDNode *L = cast<LoadSDNode>(N); 11403 unsigned AS = L->getAddressSpace(); 11404 // A flat load may access private memory. 11405 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11406 } break; 11407 case ISD::CALLSEQ_END: 11408 return true; 11409 break; 11410 case ISD::INTRINSIC_WO_CHAIN: 11411 { 11412 11413 } 11414 return AMDGPU::isIntrinsicSourceOfDivergence( 11415 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11416 case ISD::INTRINSIC_W_CHAIN: 11417 return AMDGPU::isIntrinsicSourceOfDivergence( 11418 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11419 } 11420 return false; 11421 } 11422 11423 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11424 EVT VT) const { 11425 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11426 case MVT::f32: 11427 return hasFP32Denormals(DAG.getMachineFunction()); 11428 case MVT::f64: 11429 case MVT::f16: 11430 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11431 default: 11432 return false; 11433 } 11434 } 11435 11436 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11437 const SelectionDAG &DAG, 11438 bool SNaN, 11439 unsigned Depth) const { 11440 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11441 const MachineFunction &MF = DAG.getMachineFunction(); 11442 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11443 11444 if (Info->getMode().DX10Clamp) 11445 return true; // Clamped to 0. 11446 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11447 } 11448 11449 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11450 SNaN, Depth); 11451 } 11452 11453 TargetLowering::AtomicExpansionKind 11454 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11455 switch (RMW->getOperation()) { 11456 case AtomicRMWInst::FAdd: { 11457 Type *Ty = RMW->getType(); 11458 11459 // We don't have a way to support 16-bit atomics now, so just leave them 11460 // as-is. 11461 if (Ty->isHalfTy()) 11462 return AtomicExpansionKind::None; 11463 11464 if (!Ty->isFloatTy()) 11465 return AtomicExpansionKind::CmpXChg; 11466 11467 // TODO: Do have these for flat. Older targets also had them for buffers. 11468 unsigned AS = RMW->getPointerAddressSpace(); 11469 11470 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11471 return RMW->use_empty() ? AtomicExpansionKind::None : 11472 AtomicExpansionKind::CmpXChg; 11473 } 11474 11475 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11476 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11477 } 11478 default: 11479 break; 11480 } 11481 11482 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11483 } 11484 11485 const TargetRegisterClass * 11486 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11487 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11488 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11489 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11490 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11491 : &AMDGPU::SReg_32RegClass; 11492 if (!TRI->isSGPRClass(RC) && !isDivergent) 11493 return TRI->getEquivalentSGPRClass(RC); 11494 else if (TRI->isSGPRClass(RC) && isDivergent) 11495 return TRI->getEquivalentVGPRClass(RC); 11496 11497 return RC; 11498 } 11499 11500 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11501 // uniform values (as produced by the mask results of control flow intrinsics) 11502 // used outside of divergent blocks. The phi users need to also be treated as 11503 // always uniform. 11504 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11505 unsigned WaveSize) { 11506 // FIXME: We asssume we never cast the mask results of a control flow 11507 // intrinsic. 11508 // Early exit if the type won't be consistent as a compile time hack. 11509 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11510 if (!IT || IT->getBitWidth() != WaveSize) 11511 return false; 11512 11513 if (!isa<Instruction>(V)) 11514 return false; 11515 if (!Visited.insert(V).second) 11516 return false; 11517 bool Result = false; 11518 for (auto U : V->users()) { 11519 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11520 if (V == U->getOperand(1)) { 11521 switch (Intrinsic->getIntrinsicID()) { 11522 default: 11523 Result = false; 11524 break; 11525 case Intrinsic::amdgcn_if_break: 11526 case Intrinsic::amdgcn_if: 11527 case Intrinsic::amdgcn_else: 11528 Result = true; 11529 break; 11530 } 11531 } 11532 if (V == U->getOperand(0)) { 11533 switch (Intrinsic->getIntrinsicID()) { 11534 default: 11535 Result = false; 11536 break; 11537 case Intrinsic::amdgcn_end_cf: 11538 case Intrinsic::amdgcn_loop: 11539 Result = true; 11540 break; 11541 } 11542 } 11543 } else { 11544 Result = hasCFUser(U, Visited, WaveSize); 11545 } 11546 if (Result) 11547 break; 11548 } 11549 return Result; 11550 } 11551 11552 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11553 const Value *V) const { 11554 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11555 if (CI->isInlineAsm()) { 11556 // FIXME: This cannot give a correct answer. This should only trigger in 11557 // the case where inline asm returns mixed SGPR and VGPR results, used 11558 // outside the defining block. We don't have a specific result to 11559 // consider, so this assumes if any value is SGPR, the overall register 11560 // also needs to be SGPR. 11561 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11562 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11563 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11564 for (auto &TC : TargetConstraints) { 11565 if (TC.Type == InlineAsm::isOutput) { 11566 ComputeConstraintToUse(TC, SDValue()); 11567 unsigned AssignedReg; 11568 const TargetRegisterClass *RC; 11569 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11570 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11571 if (RC) { 11572 MachineRegisterInfo &MRI = MF.getRegInfo(); 11573 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11574 return true; 11575 else if (SIRI->isSGPRClass(RC)) 11576 return true; 11577 } 11578 } 11579 } 11580 } 11581 } 11582 SmallPtrSet<const Value *, 16> Visited; 11583 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11584 } 11585