1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUSubtarget.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 19 #include "SIDefines.h" 20 #include "SIInstrInfo.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "SIRegisterInfo.h" 23 #include "Utils/AMDGPUBaseInfo.h" 24 #include "llvm/ADT/APFloat.h" 25 #include "llvm/ADT/APInt.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/BitVector.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/ADT/StringSwitch.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CallingConvLower.h" 36 #include "llvm/CodeGen/DAGCombine.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineLoopInfo.h" 45 #include "llvm/CodeGen/MachineMemOperand.h" 46 #include "llvm/CodeGen/MachineModuleInfo.h" 47 #include "llvm/CodeGen/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/SelectionDAG.h" 50 #include "llvm/CodeGen/SelectionDAGNodes.h" 51 #include "llvm/CodeGen/TargetCallingConv.h" 52 #include "llvm/CodeGen/TargetRegisterInfo.h" 53 #include "llvm/CodeGen/ValueTypes.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DebugLoc.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/DiagnosticInfo.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/GlobalValue.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Type.h" 66 #include "llvm/Support/Casting.h" 67 #include "llvm/Support/CodeGen.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Support/Compiler.h" 70 #include "llvm/Support/ErrorHandling.h" 71 #include "llvm/Support/KnownBits.h" 72 #include "llvm/Support/MachineValueType.h" 73 #include "llvm/Support/MathExtras.h" 74 #include "llvm/Target/TargetOptions.h" 75 #include <cassert> 76 #include <cmath> 77 #include <cstdint> 78 #include <iterator> 79 #include <tuple> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 #define DEBUG_TYPE "si-lower" 86 87 STATISTIC(NumTailCalls, "Number of tail calls"); 88 89 static cl::opt<bool> DisableLoopAlignment( 90 "amdgpu-disable-loop-alignment", 91 cl::desc("Do not align and prefetch loops"), 92 cl::init(false)); 93 94 static cl::opt<bool> VGPRReserveforSGPRSpill( 95 "amdgpu-reserve-vgpr-for-sgpr-spill", 96 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 97 98 static cl::opt<bool> UseDivergentRegisterIndexing( 99 "amdgpu-use-divergent-register-indexing", 100 cl::Hidden, 101 cl::desc("Use indirect register addressing for divergent indexes"), 102 cl::init(false)); 103 104 static bool hasFP32Denormals(const MachineFunction &MF) { 105 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 106 return Info->getMode().allFP32Denormals(); 107 } 108 109 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 110 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 111 return Info->getMode().allFP64FP16Denormals(); 112 } 113 114 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 115 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 116 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 117 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 118 return AMDGPU::SGPR0 + Reg; 119 } 120 } 121 llvm_unreachable("Cannot allocate sgpr"); 122 } 123 124 SITargetLowering::SITargetLowering(const TargetMachine &TM, 125 const GCNSubtarget &STI) 126 : AMDGPUTargetLowering(TM, STI), 127 Subtarget(&STI) { 128 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 129 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 130 131 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 132 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 133 134 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 135 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 136 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 137 138 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 139 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 140 141 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 142 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 143 144 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 145 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 146 147 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 148 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 149 150 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 151 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 152 153 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 154 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 155 156 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 157 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 158 159 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 160 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 161 162 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 163 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 164 165 if (Subtarget->has16BitInsts()) { 166 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 167 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 168 169 // Unless there are also VOP3P operations, not operations are really legal. 170 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 171 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 172 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 173 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 174 } 175 176 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 177 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 178 179 computeRegisterProperties(Subtarget->getRegisterInfo()); 180 181 // The boolean content concept here is too inflexible. Compares only ever 182 // really produce a 1-bit result. Any copy/extend from these will turn into a 183 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 184 // it's what most targets use. 185 setBooleanContents(ZeroOrOneBooleanContent); 186 setBooleanVectorContents(ZeroOrOneBooleanContent); 187 188 // We need to custom lower vector stores from local memory 189 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 190 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::i1, Custom); 196 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 197 198 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 199 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 204 setOperationAction(ISD::STORE, MVT::i1, Custom); 205 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 206 207 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 208 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 209 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 210 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 211 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 212 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 213 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 214 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 215 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 216 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 217 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 218 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 219 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 220 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 221 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 222 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 223 224 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 225 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 227 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 228 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 229 230 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 231 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 232 233 setOperationAction(ISD::SELECT, MVT::i1, Promote); 234 setOperationAction(ISD::SELECT, MVT::i64, Custom); 235 setOperationAction(ISD::SELECT, MVT::f64, Promote); 236 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 237 238 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 239 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 242 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 243 244 setOperationAction(ISD::SETCC, MVT::i1, Promote); 245 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 246 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 247 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 248 249 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 250 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 251 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 252 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 253 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 254 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 255 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 256 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 257 258 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 266 267 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 268 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 269 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 270 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 271 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 272 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 273 274 setOperationAction(ISD::UADDO, MVT::i32, Legal); 275 setOperationAction(ISD::USUBO, MVT::i32, Legal); 276 277 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 278 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 279 280 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 281 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 282 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 283 284 #if 0 285 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 286 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 287 #endif 288 289 // We only support LOAD/STORE and vector manipulation ops for vectors 290 // with > 4 elements. 291 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 292 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 293 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 294 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 295 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 296 switch (Op) { 297 case ISD::LOAD: 298 case ISD::STORE: 299 case ISD::BUILD_VECTOR: 300 case ISD::BITCAST: 301 case ISD::EXTRACT_VECTOR_ELT: 302 case ISD::INSERT_VECTOR_ELT: 303 case ISD::INSERT_SUBVECTOR: 304 case ISD::EXTRACT_SUBVECTOR: 305 case ISD::SCALAR_TO_VECTOR: 306 break; 307 case ISD::CONCAT_VECTORS: 308 setOperationAction(Op, VT, Custom); 309 break; 310 default: 311 setOperationAction(Op, VT, Expand); 312 break; 313 } 314 } 315 } 316 317 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 318 319 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 320 // is expanded to avoid having two separate loops in case the index is a VGPR. 321 322 // Most operations are naturally 32-bit vector operations. We only support 323 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 324 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 325 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 326 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 327 328 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 329 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 330 331 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 332 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 333 334 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 335 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 336 } 337 338 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 339 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 340 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 341 342 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 343 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 344 345 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 346 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 347 348 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 349 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 350 } 351 352 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 353 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 354 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 355 356 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 357 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 358 359 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 360 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 361 362 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 363 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 364 } 365 366 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 367 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 368 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 369 370 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 371 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 372 373 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 374 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 375 376 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 377 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 378 } 379 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 383 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 384 385 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 387 388 // Avoid stack access for these. 389 // TODO: Generalize to more vector types. 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 394 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 400 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 404 405 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 407 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 409 410 // Deal with vec3 vector operations when widened to vec4. 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 415 416 // Deal with vec5 vector operations when widened to vec8. 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 420 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 421 422 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 423 // and output demarshalling 424 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 425 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 426 427 // We can't return success/failure, only the old value, 428 // let LLVM add the comparison 429 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 430 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 431 432 if (Subtarget->hasFlatAddressSpace()) { 433 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 434 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 435 } 436 437 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 438 439 // FIXME: This should be narrowed to i32, but that only happens if i64 is 440 // illegal. 441 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 442 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 443 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 444 445 // On SI this is s_memtime and s_memrealtime on VI. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 447 setOperationAction(ISD::TRAP, MVT::Other, Custom); 448 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 449 450 if (Subtarget->has16BitInsts()) { 451 setOperationAction(ISD::FPOW, MVT::f16, Promote); 452 setOperationAction(ISD::FLOG, MVT::f16, Custom); 453 setOperationAction(ISD::FEXP, MVT::f16, Custom); 454 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 455 } 456 457 if (Subtarget->hasMadMacF32Insts()) 458 setOperationAction(ISD::FMAD, MVT::f32, Legal); 459 460 if (!Subtarget->hasBFI()) { 461 // fcopysign can be done in a single instruction with BFI. 462 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 463 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 464 } 465 466 if (!Subtarget->hasBCNT(32)) 467 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 468 469 if (!Subtarget->hasBCNT(64)) 470 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 471 472 if (Subtarget->hasFFBH()) 473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 474 475 if (Subtarget->hasFFBL()) 476 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 477 478 // We only really have 32-bit BFE instructions (and 16-bit on VI). 479 // 480 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 481 // effort to match them now. We want this to be false for i64 cases when the 482 // extraction isn't restricted to the upper or lower half. Ideally we would 483 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 484 // span the midpoint are probably relatively rare, so don't worry about them 485 // for now. 486 if (Subtarget->hasBFE()) 487 setHasExtractBitsInsn(true); 488 489 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 490 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 491 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 492 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 493 494 495 // These are really only legal for ieee_mode functions. We should be avoiding 496 // them for functions that don't have ieee_mode enabled, so just say they are 497 // legal. 498 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 499 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 500 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 501 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 502 503 504 if (Subtarget->haveRoundOpsF64()) { 505 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 506 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 507 setOperationAction(ISD::FRINT, MVT::f64, Legal); 508 } else { 509 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 510 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 511 setOperationAction(ISD::FRINT, MVT::f64, Custom); 512 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 513 } 514 515 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 516 517 setOperationAction(ISD::FSIN, MVT::f32, Custom); 518 setOperationAction(ISD::FCOS, MVT::f32, Custom); 519 setOperationAction(ISD::FDIV, MVT::f32, Custom); 520 setOperationAction(ISD::FDIV, MVT::f64, Custom); 521 522 if (Subtarget->has16BitInsts()) { 523 setOperationAction(ISD::Constant, MVT::i16, Legal); 524 525 setOperationAction(ISD::SMIN, MVT::i16, Legal); 526 setOperationAction(ISD::SMAX, MVT::i16, Legal); 527 528 setOperationAction(ISD::UMIN, MVT::i16, Legal); 529 setOperationAction(ISD::UMAX, MVT::i16, Legal); 530 531 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 532 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 533 534 setOperationAction(ISD::ROTR, MVT::i16, Promote); 535 setOperationAction(ISD::ROTL, MVT::i16, Promote); 536 537 setOperationAction(ISD::SDIV, MVT::i16, Promote); 538 setOperationAction(ISD::UDIV, MVT::i16, Promote); 539 setOperationAction(ISD::SREM, MVT::i16, Promote); 540 setOperationAction(ISD::UREM, MVT::i16, Promote); 541 542 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 543 544 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 545 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 546 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 547 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 548 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 549 550 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 551 552 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 553 554 setOperationAction(ISD::LOAD, MVT::i16, Custom); 555 556 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 557 558 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 559 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 560 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 561 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 562 563 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 564 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 565 566 // F16 - Constant Actions. 567 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 568 569 // F16 - Load/Store Actions. 570 setOperationAction(ISD::LOAD, MVT::f16, Promote); 571 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 572 setOperationAction(ISD::STORE, MVT::f16, Promote); 573 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 574 575 // F16 - VOP1 Actions. 576 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 577 setOperationAction(ISD::FCOS, MVT::f16, Custom); 578 setOperationAction(ISD::FSIN, MVT::f16, Custom); 579 580 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 581 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 582 583 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 584 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 585 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 586 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 587 setOperationAction(ISD::FROUND, MVT::f16, Custom); 588 589 // F16 - VOP2 Actions. 590 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 591 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 592 593 setOperationAction(ISD::FDIV, MVT::f16, Custom); 594 595 // F16 - VOP3 Actions. 596 setOperationAction(ISD::FMA, MVT::f16, Legal); 597 if (STI.hasMadF16()) 598 setOperationAction(ISD::FMAD, MVT::f16, Legal); 599 600 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 601 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 602 switch (Op) { 603 case ISD::LOAD: 604 case ISD::STORE: 605 case ISD::BUILD_VECTOR: 606 case ISD::BITCAST: 607 case ISD::EXTRACT_VECTOR_ELT: 608 case ISD::INSERT_VECTOR_ELT: 609 case ISD::INSERT_SUBVECTOR: 610 case ISD::EXTRACT_SUBVECTOR: 611 case ISD::SCALAR_TO_VECTOR: 612 break; 613 case ISD::CONCAT_VECTORS: 614 setOperationAction(Op, VT, Custom); 615 break; 616 default: 617 setOperationAction(Op, VT, Expand); 618 break; 619 } 620 } 621 } 622 623 // v_perm_b32 can handle either of these. 624 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 625 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 626 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 627 628 // XXX - Do these do anything? Vector constants turn into build_vector. 629 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 630 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 631 632 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 633 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 634 635 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 636 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 637 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 638 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 639 640 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 641 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 642 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 643 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 644 645 setOperationAction(ISD::AND, MVT::v2i16, Promote); 646 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 647 setOperationAction(ISD::OR, MVT::v2i16, Promote); 648 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 649 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 650 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 651 652 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 653 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 654 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 655 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 656 657 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 658 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 659 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 660 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 661 662 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 663 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 664 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 665 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 666 667 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 668 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 669 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 670 671 if (!Subtarget->hasVOP3PInsts()) { 672 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 673 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 674 } 675 676 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 677 // This isn't really legal, but this avoids the legalizer unrolling it (and 678 // allows matching fneg (fabs x) patterns) 679 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 680 681 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 682 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 683 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 684 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 685 686 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 687 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 688 689 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 690 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 691 } 692 693 if (Subtarget->hasVOP3PInsts()) { 694 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 695 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 696 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 697 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 698 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 699 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 700 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 701 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 702 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 703 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 704 705 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 706 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 707 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 708 709 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 710 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 711 712 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 713 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 716 717 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 718 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 719 720 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 721 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 722 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 723 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 724 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 725 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 726 727 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 728 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 729 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 730 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 731 732 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 733 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 734 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 735 736 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 737 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 740 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 741 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 742 743 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 744 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 745 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 746 } 747 748 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 749 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 750 751 if (Subtarget->has16BitInsts()) { 752 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 753 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 754 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 755 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 756 } else { 757 // Legalization hack. 758 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 759 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 760 761 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 762 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 763 } 764 765 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 766 setOperationAction(ISD::SELECT, VT, Custom); 767 } 768 769 setOperationAction(ISD::SMULO, MVT::i64, Custom); 770 setOperationAction(ISD::UMULO, MVT::i64, Custom); 771 772 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 773 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 774 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 775 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 776 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 777 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 778 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 779 780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 785 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 786 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 787 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 788 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 789 790 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 795 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 796 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 797 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 798 799 setTargetDAGCombine(ISD::ADD); 800 setTargetDAGCombine(ISD::ADDCARRY); 801 setTargetDAGCombine(ISD::SUB); 802 setTargetDAGCombine(ISD::SUBCARRY); 803 setTargetDAGCombine(ISD::FADD); 804 setTargetDAGCombine(ISD::FSUB); 805 setTargetDAGCombine(ISD::FMINNUM); 806 setTargetDAGCombine(ISD::FMAXNUM); 807 setTargetDAGCombine(ISD::FMINNUM_IEEE); 808 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 809 setTargetDAGCombine(ISD::FMA); 810 setTargetDAGCombine(ISD::SMIN); 811 setTargetDAGCombine(ISD::SMAX); 812 setTargetDAGCombine(ISD::UMIN); 813 setTargetDAGCombine(ISD::UMAX); 814 setTargetDAGCombine(ISD::SETCC); 815 setTargetDAGCombine(ISD::AND); 816 setTargetDAGCombine(ISD::OR); 817 setTargetDAGCombine(ISD::XOR); 818 setTargetDAGCombine(ISD::SINT_TO_FP); 819 setTargetDAGCombine(ISD::UINT_TO_FP); 820 setTargetDAGCombine(ISD::FCANONICALIZE); 821 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 822 setTargetDAGCombine(ISD::ZERO_EXTEND); 823 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 824 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 825 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 826 827 // All memory operations. Some folding on the pointer operand is done to help 828 // matching the constant offsets in the addressing modes. 829 setTargetDAGCombine(ISD::LOAD); 830 setTargetDAGCombine(ISD::STORE); 831 setTargetDAGCombine(ISD::ATOMIC_LOAD); 832 setTargetDAGCombine(ISD::ATOMIC_STORE); 833 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 834 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 835 setTargetDAGCombine(ISD::ATOMIC_SWAP); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 844 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 845 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 846 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 847 848 // FIXME: In other contexts we pretend this is a per-function property. 849 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 850 851 setSchedulingPreference(Sched::RegPressure); 852 } 853 854 const GCNSubtarget *SITargetLowering::getSubtarget() const { 855 return Subtarget; 856 } 857 858 //===----------------------------------------------------------------------===// 859 // TargetLowering queries 860 //===----------------------------------------------------------------------===// 861 862 // v_mad_mix* support a conversion from f16 to f32. 863 // 864 // There is only one special case when denormals are enabled we don't currently, 865 // where this is OK to use. 866 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 867 EVT DestVT, EVT SrcVT) const { 868 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 869 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 870 DestVT.getScalarType() == MVT::f32 && 871 SrcVT.getScalarType() == MVT::f16 && 872 // TODO: This probably only requires no input flushing? 873 !hasFP32Denormals(DAG.getMachineFunction()); 874 } 875 876 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 877 // SI has some legal vector types, but no legal vector operations. Say no 878 // shuffles are legal in order to prefer scalarizing some vector operations. 879 return false; 880 } 881 882 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 883 CallingConv::ID CC, 884 EVT VT) const { 885 if (CC == CallingConv::AMDGPU_KERNEL) 886 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 887 888 if (VT.isVector()) { 889 EVT ScalarVT = VT.getScalarType(); 890 unsigned Size = ScalarVT.getSizeInBits(); 891 if (Size == 32) 892 return ScalarVT.getSimpleVT(); 893 894 if (Size > 32) 895 return MVT::i32; 896 897 if (Size == 16 && Subtarget->has16BitInsts()) 898 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 899 } else if (VT.getSizeInBits() > 32) 900 return MVT::i32; 901 902 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 903 } 904 905 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 906 CallingConv::ID CC, 907 EVT VT) const { 908 if (CC == CallingConv::AMDGPU_KERNEL) 909 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 910 911 if (VT.isVector()) { 912 unsigned NumElts = VT.getVectorNumElements(); 913 EVT ScalarVT = VT.getScalarType(); 914 unsigned Size = ScalarVT.getSizeInBits(); 915 916 if (Size == 32) 917 return NumElts; 918 919 if (Size > 32) 920 return NumElts * ((Size + 31) / 32); 921 922 if (Size == 16 && Subtarget->has16BitInsts()) 923 return (NumElts + 1) / 2; 924 } else if (VT.getSizeInBits() > 32) 925 return (VT.getSizeInBits() + 31) / 32; 926 927 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 928 } 929 930 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 931 LLVMContext &Context, CallingConv::ID CC, 932 EVT VT, EVT &IntermediateVT, 933 unsigned &NumIntermediates, MVT &RegisterVT) const { 934 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 935 unsigned NumElts = VT.getVectorNumElements(); 936 EVT ScalarVT = VT.getScalarType(); 937 unsigned Size = ScalarVT.getSizeInBits(); 938 if (Size == 32) { 939 RegisterVT = ScalarVT.getSimpleVT(); 940 IntermediateVT = RegisterVT; 941 NumIntermediates = NumElts; 942 return NumIntermediates; 943 } 944 945 if (Size > 32) { 946 RegisterVT = MVT::i32; 947 IntermediateVT = RegisterVT; 948 NumIntermediates = NumElts * ((Size + 31) / 32); 949 return NumIntermediates; 950 } 951 952 // FIXME: We should fix the ABI to be the same on targets without 16-bit 953 // support, but unless we can properly handle 3-vectors, it will be still be 954 // inconsistent. 955 if (Size == 16 && Subtarget->has16BitInsts()) { 956 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 957 IntermediateVT = RegisterVT; 958 NumIntermediates = (NumElts + 1) / 2; 959 return NumIntermediates; 960 } 961 } 962 963 return TargetLowering::getVectorTypeBreakdownForCallingConv( 964 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 965 } 966 967 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 968 assert(DMaskLanes != 0); 969 970 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 971 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 972 return EVT::getVectorVT(Ty->getContext(), 973 EVT::getEVT(VT->getElementType()), 974 NumElts); 975 } 976 977 return EVT::getEVT(Ty); 978 } 979 980 // Peek through TFE struct returns to only use the data size. 981 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 982 auto *ST = dyn_cast<StructType>(Ty); 983 if (!ST) 984 return memVTFromImageData(Ty, DMaskLanes); 985 986 // Some intrinsics return an aggregate type - special case to work out the 987 // correct memVT. 988 // 989 // Only limited forms of aggregate type currently expected. 990 if (ST->getNumContainedTypes() != 2 || 991 !ST->getContainedType(1)->isIntegerTy(32)) 992 return EVT(); 993 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 994 } 995 996 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 997 const CallInst &CI, 998 MachineFunction &MF, 999 unsigned IntrID) const { 1000 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1001 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1002 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1003 (Intrinsic::ID)IntrID); 1004 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1005 return false; 1006 1007 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1008 1009 if (RsrcIntr->IsImage) { 1010 Info.ptrVal = MFI->getImagePSV( 1011 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1012 CI.getArgOperand(RsrcIntr->RsrcArg)); 1013 Info.align.reset(); 1014 } else { 1015 Info.ptrVal = MFI->getBufferPSV( 1016 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1017 CI.getArgOperand(RsrcIntr->RsrcArg)); 1018 } 1019 1020 Info.flags = MachineMemOperand::MODereferenceable; 1021 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1022 unsigned DMaskLanes = 4; 1023 1024 if (RsrcIntr->IsImage) { 1025 const AMDGPU::ImageDimIntrinsicInfo *Intr 1026 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1027 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1028 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1029 1030 if (!BaseOpcode->Gather4) { 1031 // If this isn't a gather, we may have excess loaded elements in the 1032 // IR type. Check the dmask for the real number of elements loaded. 1033 unsigned DMask 1034 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1035 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1036 } 1037 1038 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1039 } else 1040 Info.memVT = EVT::getEVT(CI.getType()); 1041 1042 // FIXME: What does alignment mean for an image? 1043 Info.opc = ISD::INTRINSIC_W_CHAIN; 1044 Info.flags |= MachineMemOperand::MOLoad; 1045 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1046 Info.opc = ISD::INTRINSIC_VOID; 1047 1048 Type *DataTy = CI.getArgOperand(0)->getType(); 1049 if (RsrcIntr->IsImage) { 1050 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1051 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1052 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1053 } else 1054 Info.memVT = EVT::getEVT(DataTy); 1055 1056 Info.flags |= MachineMemOperand::MOStore; 1057 } else { 1058 // Atomic 1059 Info.opc = ISD::INTRINSIC_W_CHAIN; 1060 Info.memVT = MVT::getVT(CI.getType()); 1061 Info.flags = MachineMemOperand::MOLoad | 1062 MachineMemOperand::MOStore | 1063 MachineMemOperand::MODereferenceable; 1064 1065 // XXX - Should this be volatile without known ordering? 1066 Info.flags |= MachineMemOperand::MOVolatile; 1067 } 1068 return true; 1069 } 1070 1071 switch (IntrID) { 1072 case Intrinsic::amdgcn_atomic_inc: 1073 case Intrinsic::amdgcn_atomic_dec: 1074 case Intrinsic::amdgcn_ds_ordered_add: 1075 case Intrinsic::amdgcn_ds_ordered_swap: 1076 case Intrinsic::amdgcn_ds_fadd: 1077 case Intrinsic::amdgcn_ds_fmin: 1078 case Intrinsic::amdgcn_ds_fmax: { 1079 Info.opc = ISD::INTRINSIC_W_CHAIN; 1080 Info.memVT = MVT::getVT(CI.getType()); 1081 Info.ptrVal = CI.getOperand(0); 1082 Info.align.reset(); 1083 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1084 1085 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1086 if (!Vol->isZero()) 1087 Info.flags |= MachineMemOperand::MOVolatile; 1088 1089 return true; 1090 } 1091 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1092 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1093 1094 Info.opc = ISD::INTRINSIC_VOID; 1095 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1096 Info.ptrVal = MFI->getBufferPSV( 1097 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1098 CI.getArgOperand(1)); 1099 Info.align.reset(); 1100 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1101 1102 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1103 if (!Vol || !Vol->isZero()) 1104 Info.flags |= MachineMemOperand::MOVolatile; 1105 1106 return true; 1107 } 1108 case Intrinsic::amdgcn_global_atomic_fadd: { 1109 Info.opc = ISD::INTRINSIC_VOID; 1110 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1111 ->getPointerElementType()); 1112 Info.ptrVal = CI.getOperand(0); 1113 Info.align.reset(); 1114 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1115 1116 return true; 1117 } 1118 case Intrinsic::amdgcn_ds_append: 1119 case Intrinsic::amdgcn_ds_consume: { 1120 Info.opc = ISD::INTRINSIC_W_CHAIN; 1121 Info.memVT = MVT::getVT(CI.getType()); 1122 Info.ptrVal = CI.getOperand(0); 1123 Info.align.reset(); 1124 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1125 1126 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1127 if (!Vol->isZero()) 1128 Info.flags |= MachineMemOperand::MOVolatile; 1129 1130 return true; 1131 } 1132 case Intrinsic::amdgcn_global_atomic_csub: { 1133 Info.opc = ISD::INTRINSIC_W_CHAIN; 1134 Info.memVT = MVT::getVT(CI.getType()); 1135 Info.ptrVal = CI.getOperand(0); 1136 Info.align.reset(); 1137 Info.flags = MachineMemOperand::MOLoad | 1138 MachineMemOperand::MOStore | 1139 MachineMemOperand::MODereferenceable | 1140 MachineMemOperand::MOVolatile; 1141 return true; 1142 } 1143 case Intrinsic::amdgcn_ds_gws_init: 1144 case Intrinsic::amdgcn_ds_gws_barrier: 1145 case Intrinsic::amdgcn_ds_gws_sema_v: 1146 case Intrinsic::amdgcn_ds_gws_sema_br: 1147 case Intrinsic::amdgcn_ds_gws_sema_p: 1148 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1149 Info.opc = ISD::INTRINSIC_VOID; 1150 1151 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1152 Info.ptrVal = 1153 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1154 1155 // This is an abstract access, but we need to specify a type and size. 1156 Info.memVT = MVT::i32; 1157 Info.size = 4; 1158 Info.align = Align(4); 1159 1160 Info.flags = MachineMemOperand::MOStore; 1161 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1162 Info.flags = MachineMemOperand::MOLoad; 1163 return true; 1164 } 1165 default: 1166 return false; 1167 } 1168 } 1169 1170 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1171 SmallVectorImpl<Value*> &Ops, 1172 Type *&AccessTy) const { 1173 switch (II->getIntrinsicID()) { 1174 case Intrinsic::amdgcn_atomic_inc: 1175 case Intrinsic::amdgcn_atomic_dec: 1176 case Intrinsic::amdgcn_ds_ordered_add: 1177 case Intrinsic::amdgcn_ds_ordered_swap: 1178 case Intrinsic::amdgcn_ds_fadd: 1179 case Intrinsic::amdgcn_ds_fmin: 1180 case Intrinsic::amdgcn_ds_fmax: { 1181 Value *Ptr = II->getArgOperand(0); 1182 AccessTy = II->getType(); 1183 Ops.push_back(Ptr); 1184 return true; 1185 } 1186 default: 1187 return false; 1188 } 1189 } 1190 1191 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1192 if (!Subtarget->hasFlatInstOffsets()) { 1193 // Flat instructions do not have offsets, and only have the register 1194 // address. 1195 return AM.BaseOffs == 0 && AM.Scale == 0; 1196 } 1197 1198 return AM.Scale == 0 && 1199 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1200 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1201 /*Signed=*/false)); 1202 } 1203 1204 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1205 if (Subtarget->hasFlatGlobalInsts()) 1206 return AM.Scale == 0 && 1207 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1208 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1209 /*Signed=*/true)); 1210 1211 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1212 // Assume the we will use FLAT for all global memory accesses 1213 // on VI. 1214 // FIXME: This assumption is currently wrong. On VI we still use 1215 // MUBUF instructions for the r + i addressing mode. As currently 1216 // implemented, the MUBUF instructions only work on buffer < 4GB. 1217 // It may be possible to support > 4GB buffers with MUBUF instructions, 1218 // by setting the stride value in the resource descriptor which would 1219 // increase the size limit to (stride * 4GB). However, this is risky, 1220 // because it has never been validated. 1221 return isLegalFlatAddressingMode(AM); 1222 } 1223 1224 return isLegalMUBUFAddressingMode(AM); 1225 } 1226 1227 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1228 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1229 // additionally can do r + r + i with addr64. 32-bit has more addressing 1230 // mode options. Depending on the resource constant, it can also do 1231 // (i64 r0) + (i32 r1) * (i14 i). 1232 // 1233 // Private arrays end up using a scratch buffer most of the time, so also 1234 // assume those use MUBUF instructions. Scratch loads / stores are currently 1235 // implemented as mubuf instructions with offen bit set, so slightly 1236 // different than the normal addr64. 1237 if (!isUInt<12>(AM.BaseOffs)) 1238 return false; 1239 1240 // FIXME: Since we can split immediate into soffset and immediate offset, 1241 // would it make sense to allow any immediate? 1242 1243 switch (AM.Scale) { 1244 case 0: // r + i or just i, depending on HasBaseReg. 1245 return true; 1246 case 1: 1247 return true; // We have r + r or r + i. 1248 case 2: 1249 if (AM.HasBaseReg) { 1250 // Reject 2 * r + r. 1251 return false; 1252 } 1253 1254 // Allow 2 * r as r + r 1255 // Or 2 * r + i is allowed as r + r + i. 1256 return true; 1257 default: // Don't allow n * r 1258 return false; 1259 } 1260 } 1261 1262 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1263 const AddrMode &AM, Type *Ty, 1264 unsigned AS, Instruction *I) const { 1265 // No global is ever allowed as a base. 1266 if (AM.BaseGV) 1267 return false; 1268 1269 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1270 return isLegalGlobalAddressingMode(AM); 1271 1272 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1273 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1274 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1275 // If the offset isn't a multiple of 4, it probably isn't going to be 1276 // correctly aligned. 1277 // FIXME: Can we get the real alignment here? 1278 if (AM.BaseOffs % 4 != 0) 1279 return isLegalMUBUFAddressingMode(AM); 1280 1281 // There are no SMRD extloads, so if we have to do a small type access we 1282 // will use a MUBUF load. 1283 // FIXME?: We also need to do this if unaligned, but we don't know the 1284 // alignment here. 1285 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1286 return isLegalGlobalAddressingMode(AM); 1287 1288 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1289 // SMRD instructions have an 8-bit, dword offset on SI. 1290 if (!isUInt<8>(AM.BaseOffs / 4)) 1291 return false; 1292 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1293 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1294 // in 8-bits, it can use a smaller encoding. 1295 if (!isUInt<32>(AM.BaseOffs / 4)) 1296 return false; 1297 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1298 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1299 if (!isUInt<20>(AM.BaseOffs)) 1300 return false; 1301 } else 1302 llvm_unreachable("unhandled generation"); 1303 1304 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1305 return true; 1306 1307 if (AM.Scale == 1 && AM.HasBaseReg) 1308 return true; 1309 1310 return false; 1311 1312 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1313 return isLegalMUBUFAddressingMode(AM); 1314 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1315 AS == AMDGPUAS::REGION_ADDRESS) { 1316 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1317 // field. 1318 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1319 // an 8-bit dword offset but we don't know the alignment here. 1320 if (!isUInt<16>(AM.BaseOffs)) 1321 return false; 1322 1323 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1324 return true; 1325 1326 if (AM.Scale == 1 && AM.HasBaseReg) 1327 return true; 1328 1329 return false; 1330 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1331 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1332 // For an unknown address space, this usually means that this is for some 1333 // reason being used for pure arithmetic, and not based on some addressing 1334 // computation. We don't have instructions that compute pointers with any 1335 // addressing modes, so treat them as having no offset like flat 1336 // instructions. 1337 return isLegalFlatAddressingMode(AM); 1338 } 1339 1340 // Assume a user alias of global for unknown address spaces. 1341 return isLegalGlobalAddressingMode(AM); 1342 } 1343 1344 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1345 const SelectionDAG &DAG) const { 1346 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1347 return (MemVT.getSizeInBits() <= 4 * 32); 1348 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1349 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1350 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1351 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1352 return (MemVT.getSizeInBits() <= 2 * 32); 1353 } 1354 return true; 1355 } 1356 1357 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1358 unsigned Size, unsigned AddrSpace, unsigned Align, 1359 MachineMemOperand::Flags Flags, bool *IsFast) const { 1360 if (IsFast) 1361 *IsFast = false; 1362 1363 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1364 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1365 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1366 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1367 // with adjacent offsets. 1368 bool AlignedBy4 = (Align % 4 == 0); 1369 if (IsFast) 1370 *IsFast = AlignedBy4; 1371 1372 return AlignedBy4; 1373 } 1374 1375 // FIXME: We have to be conservative here and assume that flat operations 1376 // will access scratch. If we had access to the IR function, then we 1377 // could determine if any private memory was used in the function. 1378 if (!Subtarget->hasUnalignedScratchAccess() && 1379 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1380 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1381 bool AlignedBy4 = Align >= 4; 1382 if (IsFast) 1383 *IsFast = AlignedBy4; 1384 1385 return AlignedBy4; 1386 } 1387 1388 if (Subtarget->hasUnalignedBufferAccess()) { 1389 // If we have an uniform constant load, it still requires using a slow 1390 // buffer instruction if unaligned. 1391 if (IsFast) { 1392 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1393 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1394 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1395 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1396 Align >= 4 : Align != 2; 1397 } 1398 1399 return true; 1400 } 1401 1402 // Smaller than dword value must be aligned. 1403 if (Size < 32) 1404 return false; 1405 1406 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1407 // byte-address are ignored, thus forcing Dword alignment. 1408 // This applies to private, global, and constant memory. 1409 if (IsFast) 1410 *IsFast = true; 1411 1412 return Size >= 32 && Align >= 4; 1413 } 1414 1415 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1416 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1417 bool *IsFast) const { 1418 if (IsFast) 1419 *IsFast = false; 1420 1421 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1422 // which isn't a simple VT. 1423 // Until MVT is extended to handle this, simply check for the size and 1424 // rely on the condition below: allow accesses if the size is a multiple of 4. 1425 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1426 VT.getStoreSize() > 16)) { 1427 return false; 1428 } 1429 1430 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1431 Align, Flags, IsFast); 1432 } 1433 1434 EVT SITargetLowering::getOptimalMemOpType( 1435 const MemOp &Op, const AttributeList &FuncAttributes) const { 1436 // FIXME: Should account for address space here. 1437 1438 // The default fallback uses the private pointer size as a guess for a type to 1439 // use. Make sure we switch these to 64-bit accesses. 1440 1441 if (Op.size() >= 16 && 1442 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1443 return MVT::v4i32; 1444 1445 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1446 return MVT::v2i32; 1447 1448 // Use the default. 1449 return MVT::Other; 1450 } 1451 1452 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1453 unsigned DestAS) const { 1454 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1455 } 1456 1457 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1458 const MemSDNode *MemNode = cast<MemSDNode>(N); 1459 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1460 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1461 return I && I->getMetadata("amdgpu.noclobber"); 1462 } 1463 1464 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1465 unsigned DestAS) const { 1466 // Flat -> private/local is a simple truncate. 1467 // Flat -> global is no-op 1468 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1469 return true; 1470 1471 return isNoopAddrSpaceCast(SrcAS, DestAS); 1472 } 1473 1474 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1475 const MemSDNode *MemNode = cast<MemSDNode>(N); 1476 1477 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1478 } 1479 1480 TargetLoweringBase::LegalizeTypeAction 1481 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1482 int NumElts = VT.getVectorNumElements(); 1483 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1484 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1485 return TargetLoweringBase::getPreferredVectorAction(VT); 1486 } 1487 1488 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1489 Type *Ty) const { 1490 // FIXME: Could be smarter if called for vector constants. 1491 return true; 1492 } 1493 1494 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1495 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1496 switch (Op) { 1497 case ISD::LOAD: 1498 case ISD::STORE: 1499 1500 // These operations are done with 32-bit instructions anyway. 1501 case ISD::AND: 1502 case ISD::OR: 1503 case ISD::XOR: 1504 case ISD::SELECT: 1505 // TODO: Extensions? 1506 return true; 1507 default: 1508 return false; 1509 } 1510 } 1511 1512 // SimplifySetCC uses this function to determine whether or not it should 1513 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1514 if (VT == MVT::i1 && Op == ISD::SETCC) 1515 return false; 1516 1517 return TargetLowering::isTypeDesirableForOp(Op, VT); 1518 } 1519 1520 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1521 const SDLoc &SL, 1522 SDValue Chain, 1523 uint64_t Offset) const { 1524 const DataLayout &DL = DAG.getDataLayout(); 1525 MachineFunction &MF = DAG.getMachineFunction(); 1526 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1527 1528 const ArgDescriptor *InputPtrReg; 1529 const TargetRegisterClass *RC; 1530 1531 std::tie(InputPtrReg, RC) 1532 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1533 1534 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1535 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1536 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1537 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1538 1539 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1540 } 1541 1542 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1543 const SDLoc &SL) const { 1544 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1545 FIRST_IMPLICIT); 1546 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1547 } 1548 1549 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1550 const SDLoc &SL, SDValue Val, 1551 bool Signed, 1552 const ISD::InputArg *Arg) const { 1553 // First, if it is a widened vector, narrow it. 1554 if (VT.isVector() && 1555 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1556 EVT NarrowedVT = 1557 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1558 VT.getVectorNumElements()); 1559 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1560 DAG.getConstant(0, SL, MVT::i32)); 1561 } 1562 1563 // Then convert the vector elements or scalar value. 1564 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1565 VT.bitsLT(MemVT)) { 1566 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1567 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1568 } 1569 1570 if (MemVT.isFloatingPoint()) 1571 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1572 else if (Signed) 1573 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1574 else 1575 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1576 1577 return Val; 1578 } 1579 1580 SDValue SITargetLowering::lowerKernargMemParameter( 1581 SelectionDAG &DAG, EVT VT, EVT MemVT, 1582 const SDLoc &SL, SDValue Chain, 1583 uint64_t Offset, unsigned Align, bool Signed, 1584 const ISD::InputArg *Arg) const { 1585 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1586 1587 // Try to avoid using an extload by loading earlier than the argument address, 1588 // and extracting the relevant bits. The load should hopefully be merged with 1589 // the previous argument. 1590 if (MemVT.getStoreSize() < 4 && Align < 4) { 1591 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1592 int64_t AlignDownOffset = alignDown(Offset, 4); 1593 int64_t OffsetDiff = Offset - AlignDownOffset; 1594 1595 EVT IntVT = MemVT.changeTypeToInteger(); 1596 1597 // TODO: If we passed in the base kernel offset we could have a better 1598 // alignment than 4, but we don't really need it. 1599 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1600 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1601 MachineMemOperand::MODereferenceable | 1602 MachineMemOperand::MOInvariant); 1603 1604 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1605 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1606 1607 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1608 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1609 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1610 1611 1612 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1613 } 1614 1615 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1616 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1617 MachineMemOperand::MODereferenceable | 1618 MachineMemOperand::MOInvariant); 1619 1620 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1621 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1622 } 1623 1624 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1625 const SDLoc &SL, SDValue Chain, 1626 const ISD::InputArg &Arg) const { 1627 MachineFunction &MF = DAG.getMachineFunction(); 1628 MachineFrameInfo &MFI = MF.getFrameInfo(); 1629 1630 if (Arg.Flags.isByVal()) { 1631 unsigned Size = Arg.Flags.getByValSize(); 1632 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1633 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1634 } 1635 1636 unsigned ArgOffset = VA.getLocMemOffset(); 1637 unsigned ArgSize = VA.getValVT().getStoreSize(); 1638 1639 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1640 1641 // Create load nodes to retrieve arguments from the stack. 1642 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1643 SDValue ArgValue; 1644 1645 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1646 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1647 MVT MemVT = VA.getValVT(); 1648 1649 switch (VA.getLocInfo()) { 1650 default: 1651 break; 1652 case CCValAssign::BCvt: 1653 MemVT = VA.getLocVT(); 1654 break; 1655 case CCValAssign::SExt: 1656 ExtType = ISD::SEXTLOAD; 1657 break; 1658 case CCValAssign::ZExt: 1659 ExtType = ISD::ZEXTLOAD; 1660 break; 1661 case CCValAssign::AExt: 1662 ExtType = ISD::EXTLOAD; 1663 break; 1664 } 1665 1666 ArgValue = DAG.getExtLoad( 1667 ExtType, SL, VA.getLocVT(), Chain, FIN, 1668 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1669 MemVT); 1670 return ArgValue; 1671 } 1672 1673 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1674 const SIMachineFunctionInfo &MFI, 1675 EVT VT, 1676 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1677 const ArgDescriptor *Reg; 1678 const TargetRegisterClass *RC; 1679 1680 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1681 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1682 } 1683 1684 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1685 CallingConv::ID CallConv, 1686 ArrayRef<ISD::InputArg> Ins, 1687 BitVector &Skipped, 1688 FunctionType *FType, 1689 SIMachineFunctionInfo *Info) { 1690 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1691 const ISD::InputArg *Arg = &Ins[I]; 1692 1693 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1694 "vector type argument should have been split"); 1695 1696 // First check if it's a PS input addr. 1697 if (CallConv == CallingConv::AMDGPU_PS && 1698 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1699 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1700 1701 // Inconveniently only the first part of the split is marked as isSplit, 1702 // so skip to the end. We only want to increment PSInputNum once for the 1703 // entire split argument. 1704 if (Arg->Flags.isSplit()) { 1705 while (!Arg->Flags.isSplitEnd()) { 1706 assert((!Arg->VT.isVector() || 1707 Arg->VT.getScalarSizeInBits() == 16) && 1708 "unexpected vector split in ps argument type"); 1709 if (!SkipArg) 1710 Splits.push_back(*Arg); 1711 Arg = &Ins[++I]; 1712 } 1713 } 1714 1715 if (SkipArg) { 1716 // We can safely skip PS inputs. 1717 Skipped.set(Arg->getOrigArgIndex()); 1718 ++PSInputNum; 1719 continue; 1720 } 1721 1722 Info->markPSInputAllocated(PSInputNum); 1723 if (Arg->Used) 1724 Info->markPSInputEnabled(PSInputNum); 1725 1726 ++PSInputNum; 1727 } 1728 1729 Splits.push_back(*Arg); 1730 } 1731 } 1732 1733 // Allocate special inputs passed in VGPRs. 1734 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1735 MachineFunction &MF, 1736 const SIRegisterInfo &TRI, 1737 SIMachineFunctionInfo &Info) const { 1738 const LLT S32 = LLT::scalar(32); 1739 MachineRegisterInfo &MRI = MF.getRegInfo(); 1740 1741 if (Info.hasWorkItemIDX()) { 1742 Register Reg = AMDGPU::VGPR0; 1743 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1744 1745 CCInfo.AllocateReg(Reg); 1746 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1747 } 1748 1749 if (Info.hasWorkItemIDY()) { 1750 Register Reg = AMDGPU::VGPR1; 1751 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1752 1753 CCInfo.AllocateReg(Reg); 1754 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1755 } 1756 1757 if (Info.hasWorkItemIDZ()) { 1758 Register Reg = AMDGPU::VGPR2; 1759 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1760 1761 CCInfo.AllocateReg(Reg); 1762 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1763 } 1764 } 1765 1766 // Try to allocate a VGPR at the end of the argument list, or if no argument 1767 // VGPRs are left allocating a stack slot. 1768 // If \p Mask is is given it indicates bitfield position in the register. 1769 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1770 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1771 ArgDescriptor Arg = ArgDescriptor()) { 1772 if (Arg.isSet()) 1773 return ArgDescriptor::createArg(Arg, Mask); 1774 1775 ArrayRef<MCPhysReg> ArgVGPRs 1776 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1777 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1778 if (RegIdx == ArgVGPRs.size()) { 1779 // Spill to stack required. 1780 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1781 1782 return ArgDescriptor::createStack(Offset, Mask); 1783 } 1784 1785 unsigned Reg = ArgVGPRs[RegIdx]; 1786 Reg = CCInfo.AllocateReg(Reg); 1787 assert(Reg != AMDGPU::NoRegister); 1788 1789 MachineFunction &MF = CCInfo.getMachineFunction(); 1790 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1791 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1792 return ArgDescriptor::createRegister(Reg, Mask); 1793 } 1794 1795 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1796 const TargetRegisterClass *RC, 1797 unsigned NumArgRegs) { 1798 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1799 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1800 if (RegIdx == ArgSGPRs.size()) 1801 report_fatal_error("ran out of SGPRs for arguments"); 1802 1803 unsigned Reg = ArgSGPRs[RegIdx]; 1804 Reg = CCInfo.AllocateReg(Reg); 1805 assert(Reg != AMDGPU::NoRegister); 1806 1807 MachineFunction &MF = CCInfo.getMachineFunction(); 1808 MF.addLiveIn(Reg, RC); 1809 return ArgDescriptor::createRegister(Reg); 1810 } 1811 1812 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1813 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1814 } 1815 1816 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1817 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1818 } 1819 1820 /// Allocate implicit function VGPR arguments at the end of allocated user 1821 /// arguments. 1822 void SITargetLowering::allocateSpecialInputVGPRs( 1823 CCState &CCInfo, MachineFunction &MF, 1824 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1825 const unsigned Mask = 0x3ff; 1826 ArgDescriptor Arg; 1827 1828 if (Info.hasWorkItemIDX()) { 1829 Arg = allocateVGPR32Input(CCInfo, Mask); 1830 Info.setWorkItemIDX(Arg); 1831 } 1832 1833 if (Info.hasWorkItemIDY()) { 1834 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1835 Info.setWorkItemIDY(Arg); 1836 } 1837 1838 if (Info.hasWorkItemIDZ()) 1839 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1840 } 1841 1842 /// Allocate implicit function VGPR arguments in fixed registers. 1843 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1844 CCState &CCInfo, MachineFunction &MF, 1845 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1846 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1847 if (!Reg) 1848 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1849 1850 const unsigned Mask = 0x3ff; 1851 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1852 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1853 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1854 } 1855 1856 void SITargetLowering::allocateSpecialInputSGPRs( 1857 CCState &CCInfo, 1858 MachineFunction &MF, 1859 const SIRegisterInfo &TRI, 1860 SIMachineFunctionInfo &Info) const { 1861 auto &ArgInfo = Info.getArgInfo(); 1862 1863 // TODO: Unify handling with private memory pointers. 1864 1865 if (Info.hasDispatchPtr()) 1866 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1867 1868 if (Info.hasQueuePtr()) 1869 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1870 1871 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1872 // constant offset from the kernarg segment. 1873 if (Info.hasImplicitArgPtr()) 1874 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1875 1876 if (Info.hasDispatchID()) 1877 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1878 1879 // flat_scratch_init is not applicable for non-kernel functions. 1880 1881 if (Info.hasWorkGroupIDX()) 1882 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1883 1884 if (Info.hasWorkGroupIDY()) 1885 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1886 1887 if (Info.hasWorkGroupIDZ()) 1888 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1889 } 1890 1891 // Allocate special inputs passed in user SGPRs. 1892 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1893 MachineFunction &MF, 1894 const SIRegisterInfo &TRI, 1895 SIMachineFunctionInfo &Info) const { 1896 if (Info.hasImplicitBufferPtr()) { 1897 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1898 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1899 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1900 } 1901 1902 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1903 if (Info.hasPrivateSegmentBuffer()) { 1904 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1905 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1906 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1907 } 1908 1909 if (Info.hasDispatchPtr()) { 1910 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1911 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1912 CCInfo.AllocateReg(DispatchPtrReg); 1913 } 1914 1915 if (Info.hasQueuePtr()) { 1916 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1917 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1918 CCInfo.AllocateReg(QueuePtrReg); 1919 } 1920 1921 if (Info.hasKernargSegmentPtr()) { 1922 MachineRegisterInfo &MRI = MF.getRegInfo(); 1923 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1924 CCInfo.AllocateReg(InputPtrReg); 1925 1926 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1927 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1928 } 1929 1930 if (Info.hasDispatchID()) { 1931 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1932 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1933 CCInfo.AllocateReg(DispatchIDReg); 1934 } 1935 1936 if (Info.hasFlatScratchInit()) { 1937 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1938 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1939 CCInfo.AllocateReg(FlatScratchInitReg); 1940 } 1941 1942 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1943 // these from the dispatch pointer. 1944 } 1945 1946 // Allocate special input registers that are initialized per-wave. 1947 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1948 MachineFunction &MF, 1949 SIMachineFunctionInfo &Info, 1950 CallingConv::ID CallConv, 1951 bool IsShader) const { 1952 if (Info.hasWorkGroupIDX()) { 1953 unsigned Reg = Info.addWorkGroupIDX(); 1954 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1955 CCInfo.AllocateReg(Reg); 1956 } 1957 1958 if (Info.hasWorkGroupIDY()) { 1959 unsigned Reg = Info.addWorkGroupIDY(); 1960 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1961 CCInfo.AllocateReg(Reg); 1962 } 1963 1964 if (Info.hasWorkGroupIDZ()) { 1965 unsigned Reg = Info.addWorkGroupIDZ(); 1966 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1967 CCInfo.AllocateReg(Reg); 1968 } 1969 1970 if (Info.hasWorkGroupInfo()) { 1971 unsigned Reg = Info.addWorkGroupInfo(); 1972 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1973 CCInfo.AllocateReg(Reg); 1974 } 1975 1976 if (Info.hasPrivateSegmentWaveByteOffset()) { 1977 // Scratch wave offset passed in system SGPR. 1978 unsigned PrivateSegmentWaveByteOffsetReg; 1979 1980 if (IsShader) { 1981 PrivateSegmentWaveByteOffsetReg = 1982 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1983 1984 // This is true if the scratch wave byte offset doesn't have a fixed 1985 // location. 1986 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1987 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1988 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1989 } 1990 } else 1991 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1992 1993 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1994 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1995 } 1996 } 1997 1998 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1999 MachineFunction &MF, 2000 const SIRegisterInfo &TRI, 2001 SIMachineFunctionInfo &Info) { 2002 // Now that we've figured out where the scratch register inputs are, see if 2003 // should reserve the arguments and use them directly. 2004 MachineFrameInfo &MFI = MF.getFrameInfo(); 2005 bool HasStackObjects = MFI.hasStackObjects(); 2006 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2007 2008 // Record that we know we have non-spill stack objects so we don't need to 2009 // check all stack objects later. 2010 if (HasStackObjects) 2011 Info.setHasNonSpillStackObjects(true); 2012 2013 // Everything live out of a block is spilled with fast regalloc, so it's 2014 // almost certain that spilling will be required. 2015 if (TM.getOptLevel() == CodeGenOpt::None) 2016 HasStackObjects = true; 2017 2018 // For now assume stack access is needed in any callee functions, so we need 2019 // the scratch registers to pass in. 2020 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2021 2022 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2023 // If we have stack objects, we unquestionably need the private buffer 2024 // resource. For the Code Object V2 ABI, this will be the first 4 user 2025 // SGPR inputs. We can reserve those and use them directly. 2026 2027 Register PrivateSegmentBufferReg = 2028 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2029 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2030 } else { 2031 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2032 // We tentatively reserve the last registers (skipping the last registers 2033 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2034 // we'll replace these with the ones immediately after those which were 2035 // really allocated. In the prologue copies will be inserted from the 2036 // argument to these reserved registers. 2037 2038 // Without HSA, relocations are used for the scratch pointer and the 2039 // buffer resource setup is always inserted in the prologue. Scratch wave 2040 // offset is still in an input SGPR. 2041 Info.setScratchRSrcReg(ReservedBufferReg); 2042 } 2043 2044 MachineRegisterInfo &MRI = MF.getRegInfo(); 2045 2046 // For entry functions we have to set up the stack pointer if we use it, 2047 // whereas non-entry functions get this "for free". This means there is no 2048 // intrinsic advantage to using S32 over S34 in cases where we do not have 2049 // calls but do need a frame pointer (i.e. if we are requested to have one 2050 // because frame pointer elimination is disabled). To keep things simple we 2051 // only ever use S32 as the call ABI stack pointer, and so using it does not 2052 // imply we need a separate frame pointer. 2053 // 2054 // Try to use s32 as the SP, but move it if it would interfere with input 2055 // arguments. This won't work with calls though. 2056 // 2057 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2058 // registers. 2059 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2060 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2061 } else { 2062 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2063 2064 if (MFI.hasCalls()) 2065 report_fatal_error("call in graphics shader with too many input SGPRs"); 2066 2067 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2068 if (!MRI.isLiveIn(Reg)) { 2069 Info.setStackPtrOffsetReg(Reg); 2070 break; 2071 } 2072 } 2073 2074 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2075 report_fatal_error("failed to find register for SP"); 2076 } 2077 2078 // hasFP should be accurate for entry functions even before the frame is 2079 // finalized, because it does not rely on the known stack size, only 2080 // properties like whether variable sized objects are present. 2081 if (ST.getFrameLowering()->hasFP(MF)) { 2082 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2083 } 2084 } 2085 2086 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2087 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2088 return !Info->isEntryFunction(); 2089 } 2090 2091 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2092 2093 } 2094 2095 void SITargetLowering::insertCopiesSplitCSR( 2096 MachineBasicBlock *Entry, 2097 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2098 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2099 2100 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2101 if (!IStart) 2102 return; 2103 2104 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2105 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2106 MachineBasicBlock::iterator MBBI = Entry->begin(); 2107 for (const MCPhysReg *I = IStart; *I; ++I) { 2108 const TargetRegisterClass *RC = nullptr; 2109 if (AMDGPU::SReg_64RegClass.contains(*I)) 2110 RC = &AMDGPU::SGPR_64RegClass; 2111 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2112 RC = &AMDGPU::SGPR_32RegClass; 2113 else 2114 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2115 2116 Register NewVR = MRI->createVirtualRegister(RC); 2117 // Create copy from CSR to a virtual register. 2118 Entry->addLiveIn(*I); 2119 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2120 .addReg(*I); 2121 2122 // Insert the copy-back instructions right before the terminator. 2123 for (auto *Exit : Exits) 2124 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2125 TII->get(TargetOpcode::COPY), *I) 2126 .addReg(NewVR); 2127 } 2128 } 2129 2130 SDValue SITargetLowering::LowerFormalArguments( 2131 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2132 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2133 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2134 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2135 2136 MachineFunction &MF = DAG.getMachineFunction(); 2137 const Function &Fn = MF.getFunction(); 2138 FunctionType *FType = MF.getFunction().getFunctionType(); 2139 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2140 2141 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2142 DiagnosticInfoUnsupported NoGraphicsHSA( 2143 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2144 DAG.getContext()->diagnose(NoGraphicsHSA); 2145 return DAG.getEntryNode(); 2146 } 2147 2148 SmallVector<ISD::InputArg, 16> Splits; 2149 SmallVector<CCValAssign, 16> ArgLocs; 2150 BitVector Skipped(Ins.size()); 2151 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2152 *DAG.getContext()); 2153 2154 bool IsShader = AMDGPU::isShader(CallConv); 2155 bool IsKernel = AMDGPU::isKernel(CallConv); 2156 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2157 2158 if (IsShader) { 2159 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2160 2161 // At least one interpolation mode must be enabled or else the GPU will 2162 // hang. 2163 // 2164 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2165 // set PSInputAddr, the user wants to enable some bits after the compilation 2166 // based on run-time states. Since we can't know what the final PSInputEna 2167 // will look like, so we shouldn't do anything here and the user should take 2168 // responsibility for the correct programming. 2169 // 2170 // Otherwise, the following restrictions apply: 2171 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2172 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2173 // enabled too. 2174 if (CallConv == CallingConv::AMDGPU_PS) { 2175 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2176 ((Info->getPSInputAddr() & 0xF) == 0 && 2177 Info->isPSInputAllocated(11))) { 2178 CCInfo.AllocateReg(AMDGPU::VGPR0); 2179 CCInfo.AllocateReg(AMDGPU::VGPR1); 2180 Info->markPSInputAllocated(0); 2181 Info->markPSInputEnabled(0); 2182 } 2183 if (Subtarget->isAmdPalOS()) { 2184 // For isAmdPalOS, the user does not enable some bits after compilation 2185 // based on run-time states; the register values being generated here are 2186 // the final ones set in hardware. Therefore we need to apply the 2187 // workaround to PSInputAddr and PSInputEnable together. (The case where 2188 // a bit is set in PSInputAddr but not PSInputEnable is where the 2189 // frontend set up an input arg for a particular interpolation mode, but 2190 // nothing uses that input arg. Really we should have an earlier pass 2191 // that removes such an arg.) 2192 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2193 if ((PsInputBits & 0x7F) == 0 || 2194 ((PsInputBits & 0xF) == 0 && 2195 (PsInputBits >> 11 & 1))) 2196 Info->markPSInputEnabled( 2197 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2198 } 2199 } 2200 2201 assert(!Info->hasDispatchPtr() && 2202 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2203 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2204 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2205 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2206 !Info->hasWorkItemIDZ()); 2207 } else if (IsKernel) { 2208 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2209 } else { 2210 Splits.append(Ins.begin(), Ins.end()); 2211 } 2212 2213 if (IsEntryFunc) { 2214 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2215 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2216 } else { 2217 // For the fixed ABI, pass workitem IDs in the last argument register. 2218 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2219 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2220 } 2221 2222 if (IsKernel) { 2223 analyzeFormalArgumentsCompute(CCInfo, Ins); 2224 } else { 2225 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2226 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2227 } 2228 2229 SmallVector<SDValue, 16> Chains; 2230 2231 // FIXME: This is the minimum kernel argument alignment. We should improve 2232 // this to the maximum alignment of the arguments. 2233 // 2234 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2235 // kern arg offset. 2236 const unsigned KernelArgBaseAlign = 16; 2237 2238 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2239 const ISD::InputArg &Arg = Ins[i]; 2240 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2241 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2242 continue; 2243 } 2244 2245 CCValAssign &VA = ArgLocs[ArgIdx++]; 2246 MVT VT = VA.getLocVT(); 2247 2248 if (IsEntryFunc && VA.isMemLoc()) { 2249 VT = Ins[i].VT; 2250 EVT MemVT = VA.getLocVT(); 2251 2252 const uint64_t Offset = VA.getLocMemOffset(); 2253 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2254 2255 SDValue Arg = lowerKernargMemParameter( 2256 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2257 Chains.push_back(Arg.getValue(1)); 2258 2259 auto *ParamTy = 2260 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2261 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2262 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2263 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2264 // On SI local pointers are just offsets into LDS, so they are always 2265 // less than 16-bits. On CI and newer they could potentially be 2266 // real pointers, so we can't guarantee their size. 2267 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2268 DAG.getValueType(MVT::i16)); 2269 } 2270 2271 InVals.push_back(Arg); 2272 continue; 2273 } else if (!IsEntryFunc && VA.isMemLoc()) { 2274 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2275 InVals.push_back(Val); 2276 if (!Arg.Flags.isByVal()) 2277 Chains.push_back(Val.getValue(1)); 2278 continue; 2279 } 2280 2281 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2282 2283 Register Reg = VA.getLocReg(); 2284 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2285 EVT ValVT = VA.getValVT(); 2286 2287 Reg = MF.addLiveIn(Reg, RC); 2288 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2289 2290 if (Arg.Flags.isSRet()) { 2291 // The return object should be reasonably addressable. 2292 2293 // FIXME: This helps when the return is a real sret. If it is a 2294 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2295 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2296 unsigned NumBits 2297 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2298 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2299 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2300 } 2301 2302 // If this is an 8 or 16-bit value, it is really passed promoted 2303 // to 32 bits. Insert an assert[sz]ext to capture this, then 2304 // truncate to the right size. 2305 switch (VA.getLocInfo()) { 2306 case CCValAssign::Full: 2307 break; 2308 case CCValAssign::BCvt: 2309 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2310 break; 2311 case CCValAssign::SExt: 2312 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2313 DAG.getValueType(ValVT)); 2314 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2315 break; 2316 case CCValAssign::ZExt: 2317 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2318 DAG.getValueType(ValVT)); 2319 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2320 break; 2321 case CCValAssign::AExt: 2322 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2323 break; 2324 default: 2325 llvm_unreachable("Unknown loc info!"); 2326 } 2327 2328 InVals.push_back(Val); 2329 } 2330 2331 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2332 // Special inputs come after user arguments. 2333 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2334 } 2335 2336 // Start adding system SGPRs. 2337 if (IsEntryFunc) { 2338 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2339 } else { 2340 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2341 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2342 } 2343 2344 auto &ArgUsageInfo = 2345 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2346 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2347 2348 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2349 Info->setBytesInStackArgArea(StackArgSize); 2350 2351 return Chains.empty() ? Chain : 2352 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2353 } 2354 2355 // TODO: If return values can't fit in registers, we should return as many as 2356 // possible in registers before passing on stack. 2357 bool SITargetLowering::CanLowerReturn( 2358 CallingConv::ID CallConv, 2359 MachineFunction &MF, bool IsVarArg, 2360 const SmallVectorImpl<ISD::OutputArg> &Outs, 2361 LLVMContext &Context) const { 2362 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2363 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2364 // for shaders. Vector types should be explicitly handled by CC. 2365 if (AMDGPU::isEntryFunctionCC(CallConv)) 2366 return true; 2367 2368 SmallVector<CCValAssign, 16> RVLocs; 2369 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2370 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2371 } 2372 2373 SDValue 2374 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2375 bool isVarArg, 2376 const SmallVectorImpl<ISD::OutputArg> &Outs, 2377 const SmallVectorImpl<SDValue> &OutVals, 2378 const SDLoc &DL, SelectionDAG &DAG) const { 2379 MachineFunction &MF = DAG.getMachineFunction(); 2380 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2381 2382 if (AMDGPU::isKernel(CallConv)) { 2383 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2384 OutVals, DL, DAG); 2385 } 2386 2387 bool IsShader = AMDGPU::isShader(CallConv); 2388 2389 Info->setIfReturnsVoid(Outs.empty()); 2390 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2391 2392 // CCValAssign - represent the assignment of the return value to a location. 2393 SmallVector<CCValAssign, 48> RVLocs; 2394 SmallVector<ISD::OutputArg, 48> Splits; 2395 2396 // CCState - Info about the registers and stack slots. 2397 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2398 *DAG.getContext()); 2399 2400 // Analyze outgoing return values. 2401 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2402 2403 SDValue Flag; 2404 SmallVector<SDValue, 48> RetOps; 2405 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2406 2407 // Add return address for callable functions. 2408 if (!Info->isEntryFunction()) { 2409 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2410 SDValue ReturnAddrReg = CreateLiveInRegister( 2411 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2412 2413 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2414 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2415 MVT::i64); 2416 Chain = 2417 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2418 Flag = Chain.getValue(1); 2419 RetOps.push_back(ReturnAddrVirtualReg); 2420 } 2421 2422 // Copy the result values into the output registers. 2423 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2424 ++I, ++RealRVLocIdx) { 2425 CCValAssign &VA = RVLocs[I]; 2426 assert(VA.isRegLoc() && "Can only return in registers!"); 2427 // TODO: Partially return in registers if return values don't fit. 2428 SDValue Arg = OutVals[RealRVLocIdx]; 2429 2430 // Copied from other backends. 2431 switch (VA.getLocInfo()) { 2432 case CCValAssign::Full: 2433 break; 2434 case CCValAssign::BCvt: 2435 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2436 break; 2437 case CCValAssign::SExt: 2438 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2439 break; 2440 case CCValAssign::ZExt: 2441 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2442 break; 2443 case CCValAssign::AExt: 2444 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2445 break; 2446 default: 2447 llvm_unreachable("Unknown loc info!"); 2448 } 2449 2450 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2451 Flag = Chain.getValue(1); 2452 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2453 } 2454 2455 // FIXME: Does sret work properly? 2456 if (!Info->isEntryFunction()) { 2457 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2458 const MCPhysReg *I = 2459 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2460 if (I) { 2461 for (; *I; ++I) { 2462 if (AMDGPU::SReg_64RegClass.contains(*I)) 2463 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2464 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2465 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2466 else 2467 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2468 } 2469 } 2470 } 2471 2472 // Update chain and glue. 2473 RetOps[0] = Chain; 2474 if (Flag.getNode()) 2475 RetOps.push_back(Flag); 2476 2477 unsigned Opc = AMDGPUISD::ENDPGM; 2478 if (!IsWaveEnd) 2479 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2480 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2481 } 2482 2483 SDValue SITargetLowering::LowerCallResult( 2484 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2485 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2486 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2487 SDValue ThisVal) const { 2488 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2489 2490 // Assign locations to each value returned by this call. 2491 SmallVector<CCValAssign, 16> RVLocs; 2492 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2493 *DAG.getContext()); 2494 CCInfo.AnalyzeCallResult(Ins, RetCC); 2495 2496 // Copy all of the result registers out of their specified physreg. 2497 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2498 CCValAssign VA = RVLocs[i]; 2499 SDValue Val; 2500 2501 if (VA.isRegLoc()) { 2502 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2503 Chain = Val.getValue(1); 2504 InFlag = Val.getValue(2); 2505 } else if (VA.isMemLoc()) { 2506 report_fatal_error("TODO: return values in memory"); 2507 } else 2508 llvm_unreachable("unknown argument location type"); 2509 2510 switch (VA.getLocInfo()) { 2511 case CCValAssign::Full: 2512 break; 2513 case CCValAssign::BCvt: 2514 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2515 break; 2516 case CCValAssign::ZExt: 2517 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2518 DAG.getValueType(VA.getValVT())); 2519 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2520 break; 2521 case CCValAssign::SExt: 2522 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2523 DAG.getValueType(VA.getValVT())); 2524 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2525 break; 2526 case CCValAssign::AExt: 2527 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2528 break; 2529 default: 2530 llvm_unreachable("Unknown loc info!"); 2531 } 2532 2533 InVals.push_back(Val); 2534 } 2535 2536 return Chain; 2537 } 2538 2539 // Add code to pass special inputs required depending on used features separate 2540 // from the explicit user arguments present in the IR. 2541 void SITargetLowering::passSpecialInputs( 2542 CallLoweringInfo &CLI, 2543 CCState &CCInfo, 2544 const SIMachineFunctionInfo &Info, 2545 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2546 SmallVectorImpl<SDValue> &MemOpChains, 2547 SDValue Chain) const { 2548 // If we don't have a call site, this was a call inserted by 2549 // legalization. These can never use special inputs. 2550 if (!CLI.CB) 2551 return; 2552 2553 SelectionDAG &DAG = CLI.DAG; 2554 const SDLoc &DL = CLI.DL; 2555 2556 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2557 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2558 2559 const AMDGPUFunctionArgInfo *CalleeArgInfo 2560 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2561 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2562 auto &ArgUsageInfo = 2563 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2564 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2565 } 2566 2567 // TODO: Unify with private memory register handling. This is complicated by 2568 // the fact that at least in kernels, the input argument is not necessarily 2569 // in the same location as the input. 2570 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2571 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2572 AMDGPUFunctionArgInfo::QUEUE_PTR, 2573 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2574 AMDGPUFunctionArgInfo::DISPATCH_ID, 2575 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2576 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2577 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2578 }; 2579 2580 for (auto InputID : InputRegs) { 2581 const ArgDescriptor *OutgoingArg; 2582 const TargetRegisterClass *ArgRC; 2583 2584 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2585 if (!OutgoingArg) 2586 continue; 2587 2588 const ArgDescriptor *IncomingArg; 2589 const TargetRegisterClass *IncomingArgRC; 2590 std::tie(IncomingArg, IncomingArgRC) 2591 = CallerArgInfo.getPreloadedValue(InputID); 2592 assert(IncomingArgRC == ArgRC); 2593 2594 // All special arguments are ints for now. 2595 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2596 SDValue InputReg; 2597 2598 if (IncomingArg) { 2599 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2600 } else { 2601 // The implicit arg ptr is special because it doesn't have a corresponding 2602 // input for kernels, and is computed from the kernarg segment pointer. 2603 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2604 InputReg = getImplicitArgPtr(DAG, DL); 2605 } 2606 2607 if (OutgoingArg->isRegister()) { 2608 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2609 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2610 report_fatal_error("failed to allocate implicit input argument"); 2611 } else { 2612 unsigned SpecialArgOffset = 2613 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2614 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2615 SpecialArgOffset); 2616 MemOpChains.push_back(ArgStore); 2617 } 2618 } 2619 2620 // Pack workitem IDs into a single register or pass it as is if already 2621 // packed. 2622 const ArgDescriptor *OutgoingArg; 2623 const TargetRegisterClass *ArgRC; 2624 2625 std::tie(OutgoingArg, ArgRC) = 2626 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2627 if (!OutgoingArg) 2628 std::tie(OutgoingArg, ArgRC) = 2629 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2630 if (!OutgoingArg) 2631 std::tie(OutgoingArg, ArgRC) = 2632 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2633 if (!OutgoingArg) 2634 return; 2635 2636 const ArgDescriptor *IncomingArgX 2637 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2638 const ArgDescriptor *IncomingArgY 2639 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2640 const ArgDescriptor *IncomingArgZ 2641 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2642 2643 SDValue InputReg; 2644 SDLoc SL; 2645 2646 // If incoming ids are not packed we need to pack them. 2647 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2648 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2649 2650 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2651 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2652 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2653 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2654 InputReg = InputReg.getNode() ? 2655 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2656 } 2657 2658 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2659 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2660 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2661 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2662 InputReg = InputReg.getNode() ? 2663 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2664 } 2665 2666 if (!InputReg.getNode()) { 2667 // Workitem ids are already packed, any of present incoming arguments 2668 // will carry all required fields. 2669 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2670 IncomingArgX ? *IncomingArgX : 2671 IncomingArgY ? *IncomingArgY : 2672 *IncomingArgZ, ~0u); 2673 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2674 } 2675 2676 if (OutgoingArg->isRegister()) { 2677 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2678 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2679 } else { 2680 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2681 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2682 SpecialArgOffset); 2683 MemOpChains.push_back(ArgStore); 2684 } 2685 } 2686 2687 static bool canGuaranteeTCO(CallingConv::ID CC) { 2688 return CC == CallingConv::Fast; 2689 } 2690 2691 /// Return true if we might ever do TCO for calls with this calling convention. 2692 static bool mayTailCallThisCC(CallingConv::ID CC) { 2693 switch (CC) { 2694 case CallingConv::C: 2695 return true; 2696 default: 2697 return canGuaranteeTCO(CC); 2698 } 2699 } 2700 2701 bool SITargetLowering::isEligibleForTailCallOptimization( 2702 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2703 const SmallVectorImpl<ISD::OutputArg> &Outs, 2704 const SmallVectorImpl<SDValue> &OutVals, 2705 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2706 if (!mayTailCallThisCC(CalleeCC)) 2707 return false; 2708 2709 MachineFunction &MF = DAG.getMachineFunction(); 2710 const Function &CallerF = MF.getFunction(); 2711 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2712 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2713 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2714 2715 // Kernels aren't callable, and don't have a live in return address so it 2716 // doesn't make sense to do a tail call with entry functions. 2717 if (!CallerPreserved) 2718 return false; 2719 2720 bool CCMatch = CallerCC == CalleeCC; 2721 2722 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2723 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2724 return true; 2725 return false; 2726 } 2727 2728 // TODO: Can we handle var args? 2729 if (IsVarArg) 2730 return false; 2731 2732 for (const Argument &Arg : CallerF.args()) { 2733 if (Arg.hasByValAttr()) 2734 return false; 2735 } 2736 2737 LLVMContext &Ctx = *DAG.getContext(); 2738 2739 // Check that the call results are passed in the same way. 2740 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2741 CCAssignFnForCall(CalleeCC, IsVarArg), 2742 CCAssignFnForCall(CallerCC, IsVarArg))) 2743 return false; 2744 2745 // The callee has to preserve all registers the caller needs to preserve. 2746 if (!CCMatch) { 2747 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2748 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2749 return false; 2750 } 2751 2752 // Nothing more to check if the callee is taking no arguments. 2753 if (Outs.empty()) 2754 return true; 2755 2756 SmallVector<CCValAssign, 16> ArgLocs; 2757 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2758 2759 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2760 2761 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2762 // If the stack arguments for this call do not fit into our own save area then 2763 // the call cannot be made tail. 2764 // TODO: Is this really necessary? 2765 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2766 return false; 2767 2768 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2769 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2770 } 2771 2772 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2773 if (!CI->isTailCall()) 2774 return false; 2775 2776 const Function *ParentFn = CI->getParent()->getParent(); 2777 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2778 return false; 2779 return true; 2780 } 2781 2782 // The wave scratch offset register is used as the global base pointer. 2783 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2784 SmallVectorImpl<SDValue> &InVals) const { 2785 SelectionDAG &DAG = CLI.DAG; 2786 const SDLoc &DL = CLI.DL; 2787 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2788 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2789 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2790 SDValue Chain = CLI.Chain; 2791 SDValue Callee = CLI.Callee; 2792 bool &IsTailCall = CLI.IsTailCall; 2793 CallingConv::ID CallConv = CLI.CallConv; 2794 bool IsVarArg = CLI.IsVarArg; 2795 bool IsSibCall = false; 2796 bool IsThisReturn = false; 2797 MachineFunction &MF = DAG.getMachineFunction(); 2798 2799 if (Callee.isUndef() || isNullConstant(Callee)) { 2800 if (!CLI.IsTailCall) { 2801 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2802 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2803 } 2804 2805 return Chain; 2806 } 2807 2808 if (IsVarArg) { 2809 return lowerUnhandledCall(CLI, InVals, 2810 "unsupported call to variadic function "); 2811 } 2812 2813 if (!CLI.CB) 2814 report_fatal_error("unsupported libcall legalization"); 2815 2816 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2817 !CLI.CB->getCalledFunction()) { 2818 return lowerUnhandledCall(CLI, InVals, 2819 "unsupported indirect call to function "); 2820 } 2821 2822 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2823 return lowerUnhandledCall(CLI, InVals, 2824 "unsupported required tail call to function "); 2825 } 2826 2827 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2828 // Note the issue is with the CC of the calling function, not of the call 2829 // itself. 2830 return lowerUnhandledCall(CLI, InVals, 2831 "unsupported call from graphics shader of function "); 2832 } 2833 2834 if (IsTailCall) { 2835 IsTailCall = isEligibleForTailCallOptimization( 2836 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2837 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2838 report_fatal_error("failed to perform tail call elimination on a call " 2839 "site marked musttail"); 2840 } 2841 2842 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2843 2844 // A sibling call is one where we're under the usual C ABI and not planning 2845 // to change that but can still do a tail call: 2846 if (!TailCallOpt && IsTailCall) 2847 IsSibCall = true; 2848 2849 if (IsTailCall) 2850 ++NumTailCalls; 2851 } 2852 2853 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2854 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2855 SmallVector<SDValue, 8> MemOpChains; 2856 2857 // Analyze operands of the call, assigning locations to each operand. 2858 SmallVector<CCValAssign, 16> ArgLocs; 2859 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2860 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2861 2862 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2863 // With a fixed ABI, allocate fixed registers before user arguments. 2864 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2865 } 2866 2867 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2868 2869 // Get a count of how many bytes are to be pushed on the stack. 2870 unsigned NumBytes = CCInfo.getNextStackOffset(); 2871 2872 if (IsSibCall) { 2873 // Since we're not changing the ABI to make this a tail call, the memory 2874 // operands are already available in the caller's incoming argument space. 2875 NumBytes = 0; 2876 } 2877 2878 // FPDiff is the byte offset of the call's argument area from the callee's. 2879 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2880 // by this amount for a tail call. In a sibling call it must be 0 because the 2881 // caller will deallocate the entire stack and the callee still expects its 2882 // arguments to begin at SP+0. Completely unused for non-tail calls. 2883 int32_t FPDiff = 0; 2884 MachineFrameInfo &MFI = MF.getFrameInfo(); 2885 2886 // Adjust the stack pointer for the new arguments... 2887 // These operations are automatically eliminated by the prolog/epilog pass 2888 if (!IsSibCall) { 2889 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2890 2891 SmallVector<SDValue, 4> CopyFromChains; 2892 2893 // In the HSA case, this should be an identity copy. 2894 SDValue ScratchRSrcReg 2895 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2896 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2897 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2898 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2899 } 2900 2901 MVT PtrVT = MVT::i32; 2902 2903 // Walk the register/memloc assignments, inserting copies/loads. 2904 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2905 CCValAssign &VA = ArgLocs[i]; 2906 SDValue Arg = OutVals[i]; 2907 2908 // Promote the value if needed. 2909 switch (VA.getLocInfo()) { 2910 case CCValAssign::Full: 2911 break; 2912 case CCValAssign::BCvt: 2913 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2914 break; 2915 case CCValAssign::ZExt: 2916 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2917 break; 2918 case CCValAssign::SExt: 2919 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2920 break; 2921 case CCValAssign::AExt: 2922 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2923 break; 2924 case CCValAssign::FPExt: 2925 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2926 break; 2927 default: 2928 llvm_unreachable("Unknown loc info!"); 2929 } 2930 2931 if (VA.isRegLoc()) { 2932 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2933 } else { 2934 assert(VA.isMemLoc()); 2935 2936 SDValue DstAddr; 2937 MachinePointerInfo DstInfo; 2938 2939 unsigned LocMemOffset = VA.getLocMemOffset(); 2940 int32_t Offset = LocMemOffset; 2941 2942 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2943 MaybeAlign Alignment; 2944 2945 if (IsTailCall) { 2946 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2947 unsigned OpSize = Flags.isByVal() ? 2948 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2949 2950 // FIXME: We can have better than the minimum byval required alignment. 2951 Alignment = 2952 Flags.isByVal() 2953 ? Flags.getNonZeroByValAlign() 2954 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2955 2956 Offset = Offset + FPDiff; 2957 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2958 2959 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2960 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2961 2962 // Make sure any stack arguments overlapping with where we're storing 2963 // are loaded before this eventual operation. Otherwise they'll be 2964 // clobbered. 2965 2966 // FIXME: Why is this really necessary? This seems to just result in a 2967 // lot of code to copy the stack and write them back to the same 2968 // locations, which are supposed to be immutable? 2969 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2970 } else { 2971 DstAddr = PtrOff; 2972 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2973 Alignment = 2974 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2975 } 2976 2977 if (Outs[i].Flags.isByVal()) { 2978 SDValue SizeNode = 2979 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2980 SDValue Cpy = 2981 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2982 Outs[i].Flags.getNonZeroByValAlign(), 2983 /*isVol = */ false, /*AlwaysInline = */ true, 2984 /*isTailCall = */ false, DstInfo, 2985 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2986 2987 MemOpChains.push_back(Cpy); 2988 } else { 2989 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2990 Alignment ? Alignment->value() : 0); 2991 MemOpChains.push_back(Store); 2992 } 2993 } 2994 } 2995 2996 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2997 // Copy special input registers after user input arguments. 2998 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2999 } 3000 3001 if (!MemOpChains.empty()) 3002 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3003 3004 // Build a sequence of copy-to-reg nodes chained together with token chain 3005 // and flag operands which copy the outgoing args into the appropriate regs. 3006 SDValue InFlag; 3007 for (auto &RegToPass : RegsToPass) { 3008 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3009 RegToPass.second, InFlag); 3010 InFlag = Chain.getValue(1); 3011 } 3012 3013 3014 SDValue PhysReturnAddrReg; 3015 if (IsTailCall) { 3016 // Since the return is being combined with the call, we need to pass on the 3017 // return address. 3018 3019 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3020 SDValue ReturnAddrReg = CreateLiveInRegister( 3021 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3022 3023 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3024 MVT::i64); 3025 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3026 InFlag = Chain.getValue(1); 3027 } 3028 3029 // We don't usually want to end the call-sequence here because we would tidy 3030 // the frame up *after* the call, however in the ABI-changing tail-call case 3031 // we've carefully laid out the parameters so that when sp is reset they'll be 3032 // in the correct location. 3033 if (IsTailCall && !IsSibCall) { 3034 Chain = DAG.getCALLSEQ_END(Chain, 3035 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3036 DAG.getTargetConstant(0, DL, MVT::i32), 3037 InFlag, DL); 3038 InFlag = Chain.getValue(1); 3039 } 3040 3041 std::vector<SDValue> Ops; 3042 Ops.push_back(Chain); 3043 Ops.push_back(Callee); 3044 // Add a redundant copy of the callee global which will not be legalized, as 3045 // we need direct access to the callee later. 3046 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3047 const GlobalValue *GV = GSD->getGlobal(); 3048 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3049 } else { 3050 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3051 } 3052 3053 if (IsTailCall) { 3054 // Each tail call may have to adjust the stack by a different amount, so 3055 // this information must travel along with the operation for eventual 3056 // consumption by emitEpilogue. 3057 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3058 3059 Ops.push_back(PhysReturnAddrReg); 3060 } 3061 3062 // Add argument registers to the end of the list so that they are known live 3063 // into the call. 3064 for (auto &RegToPass : RegsToPass) { 3065 Ops.push_back(DAG.getRegister(RegToPass.first, 3066 RegToPass.second.getValueType())); 3067 } 3068 3069 // Add a register mask operand representing the call-preserved registers. 3070 3071 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3072 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3073 assert(Mask && "Missing call preserved mask for calling convention"); 3074 Ops.push_back(DAG.getRegisterMask(Mask)); 3075 3076 if (InFlag.getNode()) 3077 Ops.push_back(InFlag); 3078 3079 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3080 3081 // If we're doing a tall call, use a TC_RETURN here rather than an 3082 // actual call instruction. 3083 if (IsTailCall) { 3084 MFI.setHasTailCall(); 3085 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3086 } 3087 3088 // Returns a chain and a flag for retval copy to use. 3089 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3090 Chain = Call.getValue(0); 3091 InFlag = Call.getValue(1); 3092 3093 uint64_t CalleePopBytes = NumBytes; 3094 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3095 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3096 InFlag, DL); 3097 if (!Ins.empty()) 3098 InFlag = Chain.getValue(1); 3099 3100 // Handle result values, copying them out of physregs into vregs that we 3101 // return. 3102 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3103 InVals, IsThisReturn, 3104 IsThisReturn ? OutVals[0] : SDValue()); 3105 } 3106 3107 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3108 // except for applying the wave size scale to the increment amount. 3109 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3110 SDValue Op, SelectionDAG &DAG) const { 3111 const MachineFunction &MF = DAG.getMachineFunction(); 3112 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3113 3114 SDLoc dl(Op); 3115 EVT VT = Op.getValueType(); 3116 SDValue Tmp1 = Op; 3117 SDValue Tmp2 = Op.getValue(1); 3118 SDValue Tmp3 = Op.getOperand(2); 3119 SDValue Chain = Tmp1.getOperand(0); 3120 3121 Register SPReg = Info->getStackPtrOffsetReg(); 3122 3123 // Chain the dynamic stack allocation so that it doesn't modify the stack 3124 // pointer when other instructions are using the stack. 3125 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3126 3127 SDValue Size = Tmp2.getOperand(1); 3128 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3129 Chain = SP.getValue(1); 3130 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue(); 3131 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3132 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3133 unsigned Opc = 3134 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3135 ISD::ADD : ISD::SUB; 3136 3137 SDValue ScaledSize = DAG.getNode( 3138 ISD::SHL, dl, VT, Size, 3139 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3140 3141 unsigned StackAlign = TFL->getStackAlignment(); 3142 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3143 if (Align > StackAlign) { 3144 Tmp1 = DAG.getNode( 3145 ISD::AND, dl, VT, Tmp1, 3146 DAG.getConstant(-(uint64_t)Align << ST.getWavefrontSizeLog2(), dl, VT)); 3147 } 3148 3149 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3150 Tmp2 = DAG.getCALLSEQ_END( 3151 Chain, DAG.getIntPtrConstant(0, dl, true), 3152 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3153 3154 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3155 } 3156 3157 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3158 SelectionDAG &DAG) const { 3159 // We only handle constant sizes here to allow non-entry block, static sized 3160 // allocas. A truly dynamic value is more difficult to support because we 3161 // don't know if the size value is uniform or not. If the size isn't uniform, 3162 // we would need to do a wave reduction to get the maximum size to know how 3163 // much to increment the uniform stack pointer. 3164 SDValue Size = Op.getOperand(1); 3165 if (isa<ConstantSDNode>(Size)) 3166 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3167 3168 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3169 } 3170 3171 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3172 const MachineFunction &MF) const { 3173 Register Reg = StringSwitch<Register>(RegName) 3174 .Case("m0", AMDGPU::M0) 3175 .Case("exec", AMDGPU::EXEC) 3176 .Case("exec_lo", AMDGPU::EXEC_LO) 3177 .Case("exec_hi", AMDGPU::EXEC_HI) 3178 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3179 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3180 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3181 .Default(Register()); 3182 3183 if (Reg == AMDGPU::NoRegister) { 3184 report_fatal_error(Twine("invalid register name \"" 3185 + StringRef(RegName) + "\".")); 3186 3187 } 3188 3189 if (!Subtarget->hasFlatScrRegister() && 3190 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3191 report_fatal_error(Twine("invalid register \"" 3192 + StringRef(RegName) + "\" for subtarget.")); 3193 } 3194 3195 switch (Reg) { 3196 case AMDGPU::M0: 3197 case AMDGPU::EXEC_LO: 3198 case AMDGPU::EXEC_HI: 3199 case AMDGPU::FLAT_SCR_LO: 3200 case AMDGPU::FLAT_SCR_HI: 3201 if (VT.getSizeInBits() == 32) 3202 return Reg; 3203 break; 3204 case AMDGPU::EXEC: 3205 case AMDGPU::FLAT_SCR: 3206 if (VT.getSizeInBits() == 64) 3207 return Reg; 3208 break; 3209 default: 3210 llvm_unreachable("missing register type checking"); 3211 } 3212 3213 report_fatal_error(Twine("invalid type for register \"" 3214 + StringRef(RegName) + "\".")); 3215 } 3216 3217 // If kill is not the last instruction, split the block so kill is always a 3218 // proper terminator. 3219 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3220 MachineBasicBlock *BB) const { 3221 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3222 3223 MachineBasicBlock::iterator SplitPoint(&MI); 3224 ++SplitPoint; 3225 3226 if (SplitPoint == BB->end()) { 3227 // Don't bother with a new block. 3228 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3229 return BB; 3230 } 3231 3232 MachineFunction *MF = BB->getParent(); 3233 MachineBasicBlock *SplitBB 3234 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3235 3236 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3237 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3238 3239 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3240 BB->addSuccessor(SplitBB); 3241 3242 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3243 return SplitBB; 3244 } 3245 3246 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3247 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3248 // be the first instruction in the remainder block. 3249 // 3250 /// \returns { LoopBody, Remainder } 3251 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3252 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3253 MachineFunction *MF = MBB.getParent(); 3254 MachineBasicBlock::iterator I(&MI); 3255 3256 // To insert the loop we need to split the block. Move everything after this 3257 // point to a new block, and insert a new empty block between the two. 3258 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3259 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3260 MachineFunction::iterator MBBI(MBB); 3261 ++MBBI; 3262 3263 MF->insert(MBBI, LoopBB); 3264 MF->insert(MBBI, RemainderBB); 3265 3266 LoopBB->addSuccessor(LoopBB); 3267 LoopBB->addSuccessor(RemainderBB); 3268 3269 // Move the rest of the block into a new block. 3270 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3271 3272 if (InstInLoop) { 3273 auto Next = std::next(I); 3274 3275 // Move instruction to loop body. 3276 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3277 3278 // Move the rest of the block. 3279 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3280 } else { 3281 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3282 } 3283 3284 MBB.addSuccessor(LoopBB); 3285 3286 return std::make_pair(LoopBB, RemainderBB); 3287 } 3288 3289 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3290 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3291 MachineBasicBlock *MBB = MI.getParent(); 3292 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3293 auto I = MI.getIterator(); 3294 auto E = std::next(I); 3295 3296 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3297 .addImm(0); 3298 3299 MIBundleBuilder Bundler(*MBB, I, E); 3300 finalizeBundle(*MBB, Bundler.begin()); 3301 } 3302 3303 MachineBasicBlock * 3304 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3305 MachineBasicBlock *BB) const { 3306 const DebugLoc &DL = MI.getDebugLoc(); 3307 3308 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3309 3310 MachineBasicBlock *LoopBB; 3311 MachineBasicBlock *RemainderBB; 3312 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3313 3314 // Apparently kill flags are only valid if the def is in the same block? 3315 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3316 Src->setIsKill(false); 3317 3318 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3319 3320 MachineBasicBlock::iterator I = LoopBB->end(); 3321 3322 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3323 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3324 3325 // Clear TRAP_STS.MEM_VIOL 3326 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3327 .addImm(0) 3328 .addImm(EncodedReg); 3329 3330 bundleInstWithWaitcnt(MI); 3331 3332 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3333 3334 // Load and check TRAP_STS.MEM_VIOL 3335 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3336 .addImm(EncodedReg); 3337 3338 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3339 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3340 .addReg(Reg, RegState::Kill) 3341 .addImm(0); 3342 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3343 .addMBB(LoopBB); 3344 3345 return RemainderBB; 3346 } 3347 3348 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3349 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3350 // will only do one iteration. In the worst case, this will loop 64 times. 3351 // 3352 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3353 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3354 const SIInstrInfo *TII, 3355 MachineRegisterInfo &MRI, 3356 MachineBasicBlock &OrigBB, 3357 MachineBasicBlock &LoopBB, 3358 const DebugLoc &DL, 3359 const MachineOperand &IdxReg, 3360 unsigned InitReg, 3361 unsigned ResultReg, 3362 unsigned PhiReg, 3363 unsigned InitSaveExecReg, 3364 int Offset, 3365 bool UseGPRIdxMode, 3366 bool IsIndirectSrc) { 3367 MachineFunction *MF = OrigBB.getParent(); 3368 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3369 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3370 MachineBasicBlock::iterator I = LoopBB.begin(); 3371 3372 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3373 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3374 Register NewExec = MRI.createVirtualRegister(BoolRC); 3375 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3376 Register CondReg = MRI.createVirtualRegister(BoolRC); 3377 3378 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3379 .addReg(InitReg) 3380 .addMBB(&OrigBB) 3381 .addReg(ResultReg) 3382 .addMBB(&LoopBB); 3383 3384 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3385 .addReg(InitSaveExecReg) 3386 .addMBB(&OrigBB) 3387 .addReg(NewExec) 3388 .addMBB(&LoopBB); 3389 3390 // Read the next variant <- also loop target. 3391 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3392 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3393 3394 // Compare the just read M0 value to all possible Idx values. 3395 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3396 .addReg(CurrentIdxReg) 3397 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3398 3399 // Update EXEC, save the original EXEC value to VCC. 3400 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3401 : AMDGPU::S_AND_SAVEEXEC_B64), 3402 NewExec) 3403 .addReg(CondReg, RegState::Kill); 3404 3405 MRI.setSimpleHint(NewExec, CondReg); 3406 3407 if (UseGPRIdxMode) { 3408 unsigned IdxReg; 3409 if (Offset == 0) { 3410 IdxReg = CurrentIdxReg; 3411 } else { 3412 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3413 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3414 .addReg(CurrentIdxReg, RegState::Kill) 3415 .addImm(Offset); 3416 } 3417 unsigned IdxMode = IsIndirectSrc ? 3418 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3419 MachineInstr *SetOn = 3420 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3421 .addReg(IdxReg, RegState::Kill) 3422 .addImm(IdxMode); 3423 SetOn->getOperand(3).setIsUndef(); 3424 } else { 3425 // Move index from VCC into M0 3426 if (Offset == 0) { 3427 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3428 .addReg(CurrentIdxReg, RegState::Kill); 3429 } else { 3430 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3431 .addReg(CurrentIdxReg, RegState::Kill) 3432 .addImm(Offset); 3433 } 3434 } 3435 3436 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3437 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3438 MachineInstr *InsertPt = 3439 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3440 : AMDGPU::S_XOR_B64_term), Exec) 3441 .addReg(Exec) 3442 .addReg(NewExec); 3443 3444 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3445 // s_cbranch_scc0? 3446 3447 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3448 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3449 .addMBB(&LoopBB); 3450 3451 return InsertPt->getIterator(); 3452 } 3453 3454 // This has slightly sub-optimal regalloc when the source vector is killed by 3455 // the read. The register allocator does not understand that the kill is 3456 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3457 // subregister from it, using 1 more VGPR than necessary. This was saved when 3458 // this was expanded after register allocation. 3459 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3460 MachineBasicBlock &MBB, 3461 MachineInstr &MI, 3462 unsigned InitResultReg, 3463 unsigned PhiReg, 3464 int Offset, 3465 bool UseGPRIdxMode, 3466 bool IsIndirectSrc) { 3467 MachineFunction *MF = MBB.getParent(); 3468 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3469 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3470 MachineRegisterInfo &MRI = MF->getRegInfo(); 3471 const DebugLoc &DL = MI.getDebugLoc(); 3472 MachineBasicBlock::iterator I(&MI); 3473 3474 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3475 Register DstReg = MI.getOperand(0).getReg(); 3476 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3477 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3478 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3479 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3480 3481 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3482 3483 // Save the EXEC mask 3484 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3485 .addReg(Exec); 3486 3487 MachineBasicBlock *LoopBB; 3488 MachineBasicBlock *RemainderBB; 3489 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3490 3491 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3492 3493 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3494 InitResultReg, DstReg, PhiReg, TmpExec, 3495 Offset, UseGPRIdxMode, IsIndirectSrc); 3496 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3497 MachineFunction::iterator MBBI(LoopBB); 3498 ++MBBI; 3499 MF->insert(MBBI, LandingPad); 3500 LoopBB->removeSuccessor(RemainderBB); 3501 LandingPad->addSuccessor(RemainderBB); 3502 LoopBB->addSuccessor(LandingPad); 3503 MachineBasicBlock::iterator First = LandingPad->begin(); 3504 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3505 .addReg(SaveExec); 3506 3507 return InsPt; 3508 } 3509 3510 // Returns subreg index, offset 3511 static std::pair<unsigned, int> 3512 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3513 const TargetRegisterClass *SuperRC, 3514 unsigned VecReg, 3515 int Offset) { 3516 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3517 3518 // Skip out of bounds offsets, or else we would end up using an undefined 3519 // register. 3520 if (Offset >= NumElts || Offset < 0) 3521 return std::make_pair(AMDGPU::sub0, Offset); 3522 3523 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3524 } 3525 3526 // Return true if the index is an SGPR and was set. 3527 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3528 MachineRegisterInfo &MRI, 3529 MachineInstr &MI, 3530 int Offset, 3531 bool UseGPRIdxMode, 3532 bool IsIndirectSrc) { 3533 MachineBasicBlock *MBB = MI.getParent(); 3534 const DebugLoc &DL = MI.getDebugLoc(); 3535 MachineBasicBlock::iterator I(&MI); 3536 3537 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3538 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3539 3540 assert(Idx->getReg() != AMDGPU::NoRegister); 3541 3542 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3543 return false; 3544 3545 if (UseGPRIdxMode) { 3546 unsigned IdxMode = IsIndirectSrc ? 3547 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3548 if (Offset == 0) { 3549 MachineInstr *SetOn = 3550 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3551 .add(*Idx) 3552 .addImm(IdxMode); 3553 3554 SetOn->getOperand(3).setIsUndef(); 3555 } else { 3556 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3557 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3558 .add(*Idx) 3559 .addImm(Offset); 3560 MachineInstr *SetOn = 3561 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3562 .addReg(Tmp, RegState::Kill) 3563 .addImm(IdxMode); 3564 3565 SetOn->getOperand(3).setIsUndef(); 3566 } 3567 3568 return true; 3569 } 3570 3571 if (Offset == 0) { 3572 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3573 .add(*Idx); 3574 } else { 3575 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3576 .add(*Idx) 3577 .addImm(Offset); 3578 } 3579 3580 return true; 3581 } 3582 3583 // Control flow needs to be inserted if indexing with a VGPR. 3584 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3585 MachineBasicBlock &MBB, 3586 const GCNSubtarget &ST) { 3587 const SIInstrInfo *TII = ST.getInstrInfo(); 3588 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3589 MachineFunction *MF = MBB.getParent(); 3590 MachineRegisterInfo &MRI = MF->getRegInfo(); 3591 3592 Register Dst = MI.getOperand(0).getReg(); 3593 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3594 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3595 3596 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3597 3598 unsigned SubReg; 3599 std::tie(SubReg, Offset) 3600 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3601 3602 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3603 3604 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3605 MachineBasicBlock::iterator I(&MI); 3606 const DebugLoc &DL = MI.getDebugLoc(); 3607 3608 if (UseGPRIdxMode) { 3609 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3610 // to avoid interfering with other uses, so probably requires a new 3611 // optimization pass. 3612 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3613 .addReg(SrcReg, RegState::Undef, SubReg) 3614 .addReg(SrcReg, RegState::Implicit) 3615 .addReg(AMDGPU::M0, RegState::Implicit); 3616 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3617 } else { 3618 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3619 .addReg(SrcReg, RegState::Undef, SubReg) 3620 .addReg(SrcReg, RegState::Implicit); 3621 } 3622 3623 MI.eraseFromParent(); 3624 3625 return &MBB; 3626 } 3627 3628 const DebugLoc &DL = MI.getDebugLoc(); 3629 MachineBasicBlock::iterator I(&MI); 3630 3631 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3632 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3633 3634 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3635 3636 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3637 Offset, UseGPRIdxMode, true); 3638 MachineBasicBlock *LoopBB = InsPt->getParent(); 3639 3640 if (UseGPRIdxMode) { 3641 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3642 .addReg(SrcReg, RegState::Undef, SubReg) 3643 .addReg(SrcReg, RegState::Implicit) 3644 .addReg(AMDGPU::M0, RegState::Implicit); 3645 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3646 } else { 3647 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3648 .addReg(SrcReg, RegState::Undef, SubReg) 3649 .addReg(SrcReg, RegState::Implicit); 3650 } 3651 3652 MI.eraseFromParent(); 3653 3654 return LoopBB; 3655 } 3656 3657 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3658 MachineBasicBlock &MBB, 3659 const GCNSubtarget &ST) { 3660 const SIInstrInfo *TII = ST.getInstrInfo(); 3661 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3662 MachineFunction *MF = MBB.getParent(); 3663 MachineRegisterInfo &MRI = MF->getRegInfo(); 3664 3665 Register Dst = MI.getOperand(0).getReg(); 3666 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3667 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3668 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3669 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3670 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3671 3672 // This can be an immediate, but will be folded later. 3673 assert(Val->getReg()); 3674 3675 unsigned SubReg; 3676 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3677 SrcVec->getReg(), 3678 Offset); 3679 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3680 3681 if (Idx->getReg() == AMDGPU::NoRegister) { 3682 MachineBasicBlock::iterator I(&MI); 3683 const DebugLoc &DL = MI.getDebugLoc(); 3684 3685 assert(Offset == 0); 3686 3687 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3688 .add(*SrcVec) 3689 .add(*Val) 3690 .addImm(SubReg); 3691 3692 MI.eraseFromParent(); 3693 return &MBB; 3694 } 3695 3696 const MCInstrDesc &MovRelDesc 3697 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3698 3699 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3700 MachineBasicBlock::iterator I(&MI); 3701 const DebugLoc &DL = MI.getDebugLoc(); 3702 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3703 .addReg(SrcVec->getReg()) 3704 .add(*Val) 3705 .addImm(SubReg); 3706 if (UseGPRIdxMode) 3707 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3708 3709 MI.eraseFromParent(); 3710 return &MBB; 3711 } 3712 3713 if (Val->isReg()) 3714 MRI.clearKillFlags(Val->getReg()); 3715 3716 const DebugLoc &DL = MI.getDebugLoc(); 3717 3718 Register PhiReg = MRI.createVirtualRegister(VecRC); 3719 3720 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3721 Offset, UseGPRIdxMode, false); 3722 MachineBasicBlock *LoopBB = InsPt->getParent(); 3723 3724 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3725 .addReg(PhiReg) 3726 .add(*Val) 3727 .addImm(AMDGPU::sub0); 3728 if (UseGPRIdxMode) 3729 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3730 3731 MI.eraseFromParent(); 3732 return LoopBB; 3733 } 3734 3735 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3736 MachineInstr &MI, MachineBasicBlock *BB) const { 3737 3738 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3739 MachineFunction *MF = BB->getParent(); 3740 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3741 3742 switch (MI.getOpcode()) { 3743 case AMDGPU::S_UADDO_PSEUDO: 3744 case AMDGPU::S_USUBO_PSEUDO: { 3745 const DebugLoc &DL = MI.getDebugLoc(); 3746 MachineOperand &Dest0 = MI.getOperand(0); 3747 MachineOperand &Dest1 = MI.getOperand(1); 3748 MachineOperand &Src0 = MI.getOperand(2); 3749 MachineOperand &Src1 = MI.getOperand(3); 3750 3751 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3752 ? AMDGPU::S_ADD_I32 3753 : AMDGPU::S_SUB_I32; 3754 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3755 3756 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3757 .addImm(1) 3758 .addImm(0); 3759 3760 MI.eraseFromParent(); 3761 return BB; 3762 } 3763 case AMDGPU::S_ADD_U64_PSEUDO: 3764 case AMDGPU::S_SUB_U64_PSEUDO: { 3765 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3766 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3767 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3768 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3769 const DebugLoc &DL = MI.getDebugLoc(); 3770 3771 MachineOperand &Dest = MI.getOperand(0); 3772 MachineOperand &Src0 = MI.getOperand(1); 3773 MachineOperand &Src1 = MI.getOperand(2); 3774 3775 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3776 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3777 3778 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3779 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3780 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3781 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3782 3783 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3784 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3785 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3786 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3787 3788 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3789 3790 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3791 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3792 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3793 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3794 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3795 .addReg(DestSub0) 3796 .addImm(AMDGPU::sub0) 3797 .addReg(DestSub1) 3798 .addImm(AMDGPU::sub1); 3799 MI.eraseFromParent(); 3800 return BB; 3801 } 3802 case AMDGPU::V_ADD_U64_PSEUDO: 3803 case AMDGPU::V_SUB_U64_PSEUDO: { 3804 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3805 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3806 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3807 const DebugLoc &DL = MI.getDebugLoc(); 3808 3809 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3810 3811 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3812 3813 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3814 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3815 3816 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3817 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3818 3819 MachineOperand &Dest = MI.getOperand(0); 3820 MachineOperand &Src0 = MI.getOperand(1); 3821 MachineOperand &Src1 = MI.getOperand(2); 3822 3823 const TargetRegisterClass *Src0RC = Src0.isReg() 3824 ? MRI.getRegClass(Src0.getReg()) 3825 : &AMDGPU::VReg_64RegClass; 3826 const TargetRegisterClass *Src1RC = Src1.isReg() 3827 ? MRI.getRegClass(Src1.getReg()) 3828 : &AMDGPU::VReg_64RegClass; 3829 3830 const TargetRegisterClass *Src0SubRC = 3831 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3832 const TargetRegisterClass *Src1SubRC = 3833 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3834 3835 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3836 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3837 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3838 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3839 3840 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3841 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3842 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3843 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3844 3845 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3846 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3847 .addReg(CarryReg, RegState::Define) 3848 .add(SrcReg0Sub0) 3849 .add(SrcReg1Sub0) 3850 .addImm(0); // clamp bit 3851 3852 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3853 MachineInstr *HiHalf = 3854 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3855 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3856 .add(SrcReg0Sub1) 3857 .add(SrcReg1Sub1) 3858 .addReg(CarryReg, RegState::Kill) 3859 .addImm(0); // clamp bit 3860 3861 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3862 .addReg(DestSub0) 3863 .addImm(AMDGPU::sub0) 3864 .addReg(DestSub1) 3865 .addImm(AMDGPU::sub1); 3866 TII->legalizeOperands(*LoHalf); 3867 TII->legalizeOperands(*HiHalf); 3868 MI.eraseFromParent(); 3869 return BB; 3870 } 3871 case AMDGPU::S_ADD_CO_PSEUDO: 3872 case AMDGPU::S_SUB_CO_PSEUDO: { 3873 // This pseudo has a chance to be selected 3874 // only from uniform add/subcarry node. All the VGPR operands 3875 // therefore assumed to be splat vectors. 3876 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3877 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3878 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3879 MachineBasicBlock::iterator MII = MI; 3880 const DebugLoc &DL = MI.getDebugLoc(); 3881 MachineOperand &Dest = MI.getOperand(0); 3882 MachineOperand &Src0 = MI.getOperand(2); 3883 MachineOperand &Src1 = MI.getOperand(3); 3884 MachineOperand &Src2 = MI.getOperand(4); 3885 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3886 ? AMDGPU::S_ADDC_U32 3887 : AMDGPU::S_SUBB_U32; 3888 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3889 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3890 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3891 .addReg(Src0.getReg()); 3892 Src0.setReg(RegOp0); 3893 } 3894 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3895 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3896 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3897 .addReg(Src1.getReg()); 3898 Src1.setReg(RegOp1); 3899 } 3900 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3901 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3902 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3903 .addReg(Src2.getReg()); 3904 Src2.setReg(RegOp2); 3905 } 3906 3907 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3908 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3909 .addReg(Src2.getReg()) 3910 .addImm(0); 3911 } else { 3912 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3913 .addReg(Src2.getReg()) 3914 .addImm(0); 3915 } 3916 3917 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3918 MI.eraseFromParent(); 3919 return BB; 3920 } 3921 case AMDGPU::SI_INIT_M0: { 3922 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3923 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3924 .add(MI.getOperand(0)); 3925 MI.eraseFromParent(); 3926 return BB; 3927 } 3928 case AMDGPU::SI_INIT_EXEC: 3929 // This should be before all vector instructions. 3930 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3931 AMDGPU::EXEC) 3932 .addImm(MI.getOperand(0).getImm()); 3933 MI.eraseFromParent(); 3934 return BB; 3935 3936 case AMDGPU::SI_INIT_EXEC_LO: 3937 // This should be before all vector instructions. 3938 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3939 AMDGPU::EXEC_LO) 3940 .addImm(MI.getOperand(0).getImm()); 3941 MI.eraseFromParent(); 3942 return BB; 3943 3944 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3945 // Extract the thread count from an SGPR input and set EXEC accordingly. 3946 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3947 // 3948 // S_BFE_U32 count, input, {shift, 7} 3949 // S_BFM_B64 exec, count, 0 3950 // S_CMP_EQ_U32 count, 64 3951 // S_CMOV_B64 exec, -1 3952 MachineInstr *FirstMI = &*BB->begin(); 3953 MachineRegisterInfo &MRI = MF->getRegInfo(); 3954 Register InputReg = MI.getOperand(0).getReg(); 3955 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3956 bool Found = false; 3957 3958 // Move the COPY of the input reg to the beginning, so that we can use it. 3959 for (auto I = BB->begin(); I != &MI; I++) { 3960 if (I->getOpcode() != TargetOpcode::COPY || 3961 I->getOperand(0).getReg() != InputReg) 3962 continue; 3963 3964 if (I == FirstMI) { 3965 FirstMI = &*++BB->begin(); 3966 } else { 3967 I->removeFromParent(); 3968 BB->insert(FirstMI, &*I); 3969 } 3970 Found = true; 3971 break; 3972 } 3973 assert(Found); 3974 (void)Found; 3975 3976 // This should be before all vector instructions. 3977 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3978 bool isWave32 = getSubtarget()->isWave32(); 3979 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3980 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3981 .addReg(InputReg) 3982 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3983 BuildMI(*BB, FirstMI, DebugLoc(), 3984 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3985 Exec) 3986 .addReg(CountReg) 3987 .addImm(0); 3988 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3989 .addReg(CountReg, RegState::Kill) 3990 .addImm(getSubtarget()->getWavefrontSize()); 3991 BuildMI(*BB, FirstMI, DebugLoc(), 3992 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3993 Exec) 3994 .addImm(-1); 3995 MI.eraseFromParent(); 3996 return BB; 3997 } 3998 3999 case AMDGPU::GET_GROUPSTATICSIZE: { 4000 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4001 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4002 DebugLoc DL = MI.getDebugLoc(); 4003 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4004 .add(MI.getOperand(0)) 4005 .addImm(MFI->getLDSSize()); 4006 MI.eraseFromParent(); 4007 return BB; 4008 } 4009 case AMDGPU::SI_INDIRECT_SRC_V1: 4010 case AMDGPU::SI_INDIRECT_SRC_V2: 4011 case AMDGPU::SI_INDIRECT_SRC_V4: 4012 case AMDGPU::SI_INDIRECT_SRC_V8: 4013 case AMDGPU::SI_INDIRECT_SRC_V16: 4014 case AMDGPU::SI_INDIRECT_SRC_V32: 4015 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4016 case AMDGPU::SI_INDIRECT_DST_V1: 4017 case AMDGPU::SI_INDIRECT_DST_V2: 4018 case AMDGPU::SI_INDIRECT_DST_V4: 4019 case AMDGPU::SI_INDIRECT_DST_V8: 4020 case AMDGPU::SI_INDIRECT_DST_V16: 4021 case AMDGPU::SI_INDIRECT_DST_V32: 4022 return emitIndirectDst(MI, *BB, *getSubtarget()); 4023 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4024 case AMDGPU::SI_KILL_I1_PSEUDO: 4025 return splitKillBlock(MI, BB); 4026 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4027 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4028 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4029 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4030 4031 Register Dst = MI.getOperand(0).getReg(); 4032 Register Src0 = MI.getOperand(1).getReg(); 4033 Register Src1 = MI.getOperand(2).getReg(); 4034 const DebugLoc &DL = MI.getDebugLoc(); 4035 Register SrcCond = MI.getOperand(3).getReg(); 4036 4037 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4038 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4039 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4040 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4041 4042 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4043 .addReg(SrcCond); 4044 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4045 .addImm(0) 4046 .addReg(Src0, 0, AMDGPU::sub0) 4047 .addImm(0) 4048 .addReg(Src1, 0, AMDGPU::sub0) 4049 .addReg(SrcCondCopy); 4050 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4051 .addImm(0) 4052 .addReg(Src0, 0, AMDGPU::sub1) 4053 .addImm(0) 4054 .addReg(Src1, 0, AMDGPU::sub1) 4055 .addReg(SrcCondCopy); 4056 4057 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4058 .addReg(DstLo) 4059 .addImm(AMDGPU::sub0) 4060 .addReg(DstHi) 4061 .addImm(AMDGPU::sub1); 4062 MI.eraseFromParent(); 4063 return BB; 4064 } 4065 case AMDGPU::SI_BR_UNDEF: { 4066 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4067 const DebugLoc &DL = MI.getDebugLoc(); 4068 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4069 .add(MI.getOperand(0)); 4070 Br->getOperand(1).setIsUndef(true); // read undef SCC 4071 MI.eraseFromParent(); 4072 return BB; 4073 } 4074 case AMDGPU::ADJCALLSTACKUP: 4075 case AMDGPU::ADJCALLSTACKDOWN: { 4076 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4077 MachineInstrBuilder MIB(*MF, &MI); 4078 4079 // Add an implicit use of the frame offset reg to prevent the restore copy 4080 // inserted after the call from being reorderd after stack operations in the 4081 // the caller's frame. 4082 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4083 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4084 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4085 return BB; 4086 } 4087 case AMDGPU::SI_CALL_ISEL: { 4088 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4089 const DebugLoc &DL = MI.getDebugLoc(); 4090 4091 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4092 4093 MachineInstrBuilder MIB; 4094 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4095 4096 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4097 MIB.add(MI.getOperand(I)); 4098 4099 MIB.cloneMemRefs(MI); 4100 MI.eraseFromParent(); 4101 return BB; 4102 } 4103 case AMDGPU::V_ADD_I32_e32: 4104 case AMDGPU::V_SUB_I32_e32: 4105 case AMDGPU::V_SUBREV_I32_e32: { 4106 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4107 const DebugLoc &DL = MI.getDebugLoc(); 4108 unsigned Opc = MI.getOpcode(); 4109 4110 bool NeedClampOperand = false; 4111 if (TII->pseudoToMCOpcode(Opc) == -1) { 4112 Opc = AMDGPU::getVOPe64(Opc); 4113 NeedClampOperand = true; 4114 } 4115 4116 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4117 if (TII->isVOP3(*I)) { 4118 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4119 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4120 I.addReg(TRI->getVCC(), RegState::Define); 4121 } 4122 I.add(MI.getOperand(1)) 4123 .add(MI.getOperand(2)); 4124 if (NeedClampOperand) 4125 I.addImm(0); // clamp bit for e64 encoding 4126 4127 TII->legalizeOperands(*I); 4128 4129 MI.eraseFromParent(); 4130 return BB; 4131 } 4132 case AMDGPU::DS_GWS_INIT: 4133 case AMDGPU::DS_GWS_SEMA_V: 4134 case AMDGPU::DS_GWS_SEMA_BR: 4135 case AMDGPU::DS_GWS_SEMA_P: 4136 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4137 case AMDGPU::DS_GWS_BARRIER: 4138 // A s_waitcnt 0 is required to be the instruction immediately following. 4139 if (getSubtarget()->hasGWSAutoReplay()) { 4140 bundleInstWithWaitcnt(MI); 4141 return BB; 4142 } 4143 4144 return emitGWSMemViolTestLoop(MI, BB); 4145 case AMDGPU::S_SETREG_B32: { 4146 if (!getSubtarget()->hasDenormModeInst()) 4147 return BB; 4148 4149 // Try to optimize cases that only set the denormal mode or rounding mode. 4150 // 4151 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4152 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4153 // instead. 4154 // 4155 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4156 // allow you to have a no side effect instruction in the output of a 4157 // sideeffecting pattern. 4158 4159 // TODO: Should also emit a no side effects pseudo if only FP bits are 4160 // touched, even if not all of them or to a variable. 4161 unsigned ID, Offset, Width; 4162 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4163 if (ID != AMDGPU::Hwreg::ID_MODE) 4164 return BB; 4165 4166 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4167 const unsigned SetMask = WidthMask << Offset; 4168 unsigned SetDenormOp = 0; 4169 unsigned SetRoundOp = 0; 4170 4171 // The dedicated instructions can only set the whole denorm or round mode at 4172 // once, not a subset of bits in either. 4173 if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4174 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) { 4175 // If this fully sets both the round and denorm mode, emit the two 4176 // dedicated instructions for these. 4177 assert(Offset == 0); 4178 SetRoundOp = AMDGPU::S_ROUND_MODE; 4179 SetDenormOp = AMDGPU::S_DENORM_MODE; 4180 } else if (Width == 4) { 4181 if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) { 4182 SetRoundOp = AMDGPU::S_ROUND_MODE; 4183 assert(Offset == 0); 4184 } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) { 4185 SetDenormOp = AMDGPU::S_DENORM_MODE; 4186 assert(Offset == 4); 4187 } 4188 } 4189 4190 if (SetRoundOp || SetDenormOp) { 4191 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4192 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4193 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4194 unsigned ImmVal = Def->getOperand(1).getImm(); 4195 if (SetRoundOp) { 4196 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4197 .addImm(ImmVal & 0xf); 4198 4199 // If we also have the denorm mode, get just the denorm mode bits. 4200 ImmVal >>= 4; 4201 } 4202 4203 if (SetDenormOp) { 4204 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4205 .addImm(ImmVal & 0xf); 4206 } 4207 4208 MI.eraseFromParent(); 4209 } 4210 } 4211 4212 return BB; 4213 } 4214 default: 4215 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4216 } 4217 } 4218 4219 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4220 return isTypeLegal(VT.getScalarType()); 4221 } 4222 4223 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4224 // This currently forces unfolding various combinations of fsub into fma with 4225 // free fneg'd operands. As long as we have fast FMA (controlled by 4226 // isFMAFasterThanFMulAndFAdd), we should perform these. 4227 4228 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4229 // most of these combines appear to be cycle neutral but save on instruction 4230 // count / code size. 4231 return true; 4232 } 4233 4234 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4235 EVT VT) const { 4236 if (!VT.isVector()) { 4237 return MVT::i1; 4238 } 4239 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4240 } 4241 4242 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4243 // TODO: Should i16 be used always if legal? For now it would force VALU 4244 // shifts. 4245 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4246 } 4247 4248 // Answering this is somewhat tricky and depends on the specific device which 4249 // have different rates for fma or all f64 operations. 4250 // 4251 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4252 // regardless of which device (although the number of cycles differs between 4253 // devices), so it is always profitable for f64. 4254 // 4255 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4256 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4257 // which we can always do even without fused FP ops since it returns the same 4258 // result as the separate operations and since it is always full 4259 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4260 // however does not support denormals, so we do report fma as faster if we have 4261 // a fast fma device and require denormals. 4262 // 4263 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4264 EVT VT) const { 4265 VT = VT.getScalarType(); 4266 4267 switch (VT.getSimpleVT().SimpleTy) { 4268 case MVT::f32: { 4269 // This is as fast on some subtargets. However, we always have full rate f32 4270 // mad available which returns the same result as the separate operations 4271 // which we should prefer over fma. We can't use this if we want to support 4272 // denormals, so only report this in these cases. 4273 if (hasFP32Denormals(MF)) 4274 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4275 4276 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4277 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4278 } 4279 case MVT::f64: 4280 return true; 4281 case MVT::f16: 4282 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4283 default: 4284 break; 4285 } 4286 4287 return false; 4288 } 4289 4290 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4291 const SDNode *N) const { 4292 // TODO: Check future ftz flag 4293 // v_mad_f32/v_mac_f32 do not support denormals. 4294 EVT VT = N->getValueType(0); 4295 if (VT == MVT::f32) 4296 return Subtarget->hasMadMacF32Insts() && 4297 !hasFP32Denormals(DAG.getMachineFunction()); 4298 if (VT == MVT::f16) { 4299 return Subtarget->hasMadF16() && 4300 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4301 } 4302 4303 return false; 4304 } 4305 4306 //===----------------------------------------------------------------------===// 4307 // Custom DAG Lowering Operations 4308 //===----------------------------------------------------------------------===// 4309 4310 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4311 // wider vector type is legal. 4312 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4313 SelectionDAG &DAG) const { 4314 unsigned Opc = Op.getOpcode(); 4315 EVT VT = Op.getValueType(); 4316 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4317 4318 SDValue Lo, Hi; 4319 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4320 4321 SDLoc SL(Op); 4322 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4323 Op->getFlags()); 4324 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4325 Op->getFlags()); 4326 4327 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4328 } 4329 4330 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4331 // wider vector type is legal. 4332 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4333 SelectionDAG &DAG) const { 4334 unsigned Opc = Op.getOpcode(); 4335 EVT VT = Op.getValueType(); 4336 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4337 4338 SDValue Lo0, Hi0; 4339 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4340 SDValue Lo1, Hi1; 4341 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4342 4343 SDLoc SL(Op); 4344 4345 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4346 Op->getFlags()); 4347 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4348 Op->getFlags()); 4349 4350 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4351 } 4352 4353 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4354 SelectionDAG &DAG) const { 4355 unsigned Opc = Op.getOpcode(); 4356 EVT VT = Op.getValueType(); 4357 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4358 4359 SDValue Lo0, Hi0; 4360 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4361 SDValue Lo1, Hi1; 4362 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4363 SDValue Lo2, Hi2; 4364 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4365 4366 SDLoc SL(Op); 4367 4368 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4369 Op->getFlags()); 4370 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4371 Op->getFlags()); 4372 4373 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4374 } 4375 4376 4377 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4378 switch (Op.getOpcode()) { 4379 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4380 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4381 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4382 case ISD::LOAD: { 4383 SDValue Result = LowerLOAD(Op, DAG); 4384 assert((!Result.getNode() || 4385 Result.getNode()->getNumValues() == 2) && 4386 "Load should return a value and a chain"); 4387 return Result; 4388 } 4389 4390 case ISD::FSIN: 4391 case ISD::FCOS: 4392 return LowerTrig(Op, DAG); 4393 case ISD::SELECT: return LowerSELECT(Op, DAG); 4394 case ISD::FDIV: return LowerFDIV(Op, DAG); 4395 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4396 case ISD::STORE: return LowerSTORE(Op, DAG); 4397 case ISD::GlobalAddress: { 4398 MachineFunction &MF = DAG.getMachineFunction(); 4399 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4400 return LowerGlobalAddress(MFI, Op, DAG); 4401 } 4402 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4403 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4404 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4405 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4406 case ISD::INSERT_SUBVECTOR: 4407 return lowerINSERT_SUBVECTOR(Op, DAG); 4408 case ISD::INSERT_VECTOR_ELT: 4409 return lowerINSERT_VECTOR_ELT(Op, DAG); 4410 case ISD::EXTRACT_VECTOR_ELT: 4411 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4412 case ISD::VECTOR_SHUFFLE: 4413 return lowerVECTOR_SHUFFLE(Op, DAG); 4414 case ISD::BUILD_VECTOR: 4415 return lowerBUILD_VECTOR(Op, DAG); 4416 case ISD::FP_ROUND: 4417 return lowerFP_ROUND(Op, DAG); 4418 case ISD::TRAP: 4419 return lowerTRAP(Op, DAG); 4420 case ISD::DEBUGTRAP: 4421 return lowerDEBUGTRAP(Op, DAG); 4422 case ISD::FABS: 4423 case ISD::FNEG: 4424 case ISD::FCANONICALIZE: 4425 case ISD::BSWAP: 4426 return splitUnaryVectorOp(Op, DAG); 4427 case ISD::FMINNUM: 4428 case ISD::FMAXNUM: 4429 return lowerFMINNUM_FMAXNUM(Op, DAG); 4430 case ISD::FMA: 4431 return splitTernaryVectorOp(Op, DAG); 4432 case ISD::SHL: 4433 case ISD::SRA: 4434 case ISD::SRL: 4435 case ISD::ADD: 4436 case ISD::SUB: 4437 case ISD::MUL: 4438 case ISD::SMIN: 4439 case ISD::SMAX: 4440 case ISD::UMIN: 4441 case ISD::UMAX: 4442 case ISD::FADD: 4443 case ISD::FMUL: 4444 case ISD::FMINNUM_IEEE: 4445 case ISD::FMAXNUM_IEEE: 4446 return splitBinaryVectorOp(Op, DAG); 4447 case ISD::SMULO: 4448 case ISD::UMULO: 4449 return lowerXMULO(Op, DAG); 4450 case ISD::DYNAMIC_STACKALLOC: 4451 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4452 } 4453 return SDValue(); 4454 } 4455 4456 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4457 const SDLoc &DL, 4458 SelectionDAG &DAG, bool Unpacked) { 4459 if (!LoadVT.isVector()) 4460 return Result; 4461 4462 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4463 // Truncate to v2i16/v4i16. 4464 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4465 4466 // Workaround legalizer not scalarizing truncate after vector op 4467 // legalization byt not creating intermediate vector trunc. 4468 SmallVector<SDValue, 4> Elts; 4469 DAG.ExtractVectorElements(Result, Elts); 4470 for (SDValue &Elt : Elts) 4471 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4472 4473 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4474 4475 // Bitcast to original type (v2f16/v4f16). 4476 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4477 } 4478 4479 // Cast back to the original packed type. 4480 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4481 } 4482 4483 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4484 MemSDNode *M, 4485 SelectionDAG &DAG, 4486 ArrayRef<SDValue> Ops, 4487 bool IsIntrinsic) const { 4488 SDLoc DL(M); 4489 4490 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4491 EVT LoadVT = M->getValueType(0); 4492 4493 EVT EquivLoadVT = LoadVT; 4494 if (Unpacked && LoadVT.isVector()) { 4495 EquivLoadVT = LoadVT.isVector() ? 4496 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4497 LoadVT.getVectorNumElements()) : LoadVT; 4498 } 4499 4500 // Change from v4f16/v2f16 to EquivLoadVT. 4501 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4502 4503 SDValue Load 4504 = DAG.getMemIntrinsicNode( 4505 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4506 VTList, Ops, M->getMemoryVT(), 4507 M->getMemOperand()); 4508 if (!Unpacked) // Just adjusted the opcode. 4509 return Load; 4510 4511 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4512 4513 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4514 } 4515 4516 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4517 SelectionDAG &DAG, 4518 ArrayRef<SDValue> Ops) const { 4519 SDLoc DL(M); 4520 EVT LoadVT = M->getValueType(0); 4521 EVT EltType = LoadVT.getScalarType(); 4522 EVT IntVT = LoadVT.changeTypeToInteger(); 4523 4524 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4525 4526 unsigned Opc = 4527 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4528 4529 if (IsD16) { 4530 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4531 } 4532 4533 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4534 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4535 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4536 4537 if (isTypeLegal(LoadVT)) { 4538 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4539 M->getMemOperand(), DAG); 4540 } 4541 4542 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4543 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4544 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4545 M->getMemOperand(), DAG); 4546 return DAG.getMergeValues( 4547 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4548 DL); 4549 } 4550 4551 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4552 SDNode *N, SelectionDAG &DAG) { 4553 EVT VT = N->getValueType(0); 4554 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4555 int CondCode = CD->getSExtValue(); 4556 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4557 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4558 return DAG.getUNDEF(VT); 4559 4560 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4561 4562 SDValue LHS = N->getOperand(1); 4563 SDValue RHS = N->getOperand(2); 4564 4565 SDLoc DL(N); 4566 4567 EVT CmpVT = LHS.getValueType(); 4568 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4569 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4570 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4571 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4572 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4573 } 4574 4575 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4576 4577 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4578 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4579 4580 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4581 DAG.getCondCode(CCOpcode)); 4582 if (VT.bitsEq(CCVT)) 4583 return SetCC; 4584 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4585 } 4586 4587 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4588 SDNode *N, SelectionDAG &DAG) { 4589 EVT VT = N->getValueType(0); 4590 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4591 4592 int CondCode = CD->getSExtValue(); 4593 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4594 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4595 return DAG.getUNDEF(VT); 4596 } 4597 4598 SDValue Src0 = N->getOperand(1); 4599 SDValue Src1 = N->getOperand(2); 4600 EVT CmpVT = Src0.getValueType(); 4601 SDLoc SL(N); 4602 4603 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4604 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4605 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4606 } 4607 4608 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4609 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4610 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4611 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4612 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4613 Src1, DAG.getCondCode(CCOpcode)); 4614 if (VT.bitsEq(CCVT)) 4615 return SetCC; 4616 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4617 } 4618 4619 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4620 SelectionDAG &DAG) { 4621 EVT VT = N->getValueType(0); 4622 SDValue Src = N->getOperand(1); 4623 SDLoc SL(N); 4624 4625 if (Src.getOpcode() == ISD::SETCC) { 4626 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4627 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4628 Src.getOperand(1), Src.getOperand(2)); 4629 } 4630 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4631 // (ballot 0) -> 0 4632 if (Arg->isNullValue()) 4633 return DAG.getConstant(0, SL, VT); 4634 4635 // (ballot 1) -> EXEC/EXEC_LO 4636 if (Arg->isOne()) { 4637 Register Exec; 4638 if (VT.getScalarSizeInBits() == 32) 4639 Exec = AMDGPU::EXEC_LO; 4640 else if (VT.getScalarSizeInBits() == 64) 4641 Exec = AMDGPU::EXEC; 4642 else 4643 return SDValue(); 4644 4645 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4646 } 4647 } 4648 4649 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4650 // ISD::SETNE) 4651 return DAG.getNode( 4652 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4653 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4654 } 4655 4656 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4657 SmallVectorImpl<SDValue> &Results, 4658 SelectionDAG &DAG) const { 4659 switch (N->getOpcode()) { 4660 case ISD::INSERT_VECTOR_ELT: { 4661 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4662 Results.push_back(Res); 4663 return; 4664 } 4665 case ISD::EXTRACT_VECTOR_ELT: { 4666 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4667 Results.push_back(Res); 4668 return; 4669 } 4670 case ISD::INTRINSIC_WO_CHAIN: { 4671 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4672 switch (IID) { 4673 case Intrinsic::amdgcn_cvt_pkrtz: { 4674 SDValue Src0 = N->getOperand(1); 4675 SDValue Src1 = N->getOperand(2); 4676 SDLoc SL(N); 4677 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4678 Src0, Src1); 4679 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4680 return; 4681 } 4682 case Intrinsic::amdgcn_cvt_pknorm_i16: 4683 case Intrinsic::amdgcn_cvt_pknorm_u16: 4684 case Intrinsic::amdgcn_cvt_pk_i16: 4685 case Intrinsic::amdgcn_cvt_pk_u16: { 4686 SDValue Src0 = N->getOperand(1); 4687 SDValue Src1 = N->getOperand(2); 4688 SDLoc SL(N); 4689 unsigned Opcode; 4690 4691 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4692 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4693 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4694 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4695 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4696 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4697 else 4698 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4699 4700 EVT VT = N->getValueType(0); 4701 if (isTypeLegal(VT)) 4702 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4703 else { 4704 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4705 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4706 } 4707 return; 4708 } 4709 } 4710 break; 4711 } 4712 case ISD::INTRINSIC_W_CHAIN: { 4713 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4714 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4715 // FIXME: Hacky 4716 Results.push_back(Res.getOperand(0)); 4717 Results.push_back(Res.getOperand(1)); 4718 } else { 4719 Results.push_back(Res); 4720 Results.push_back(Res.getValue(1)); 4721 } 4722 return; 4723 } 4724 4725 break; 4726 } 4727 case ISD::SELECT: { 4728 SDLoc SL(N); 4729 EVT VT = N->getValueType(0); 4730 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4731 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4732 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4733 4734 EVT SelectVT = NewVT; 4735 if (NewVT.bitsLT(MVT::i32)) { 4736 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4737 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4738 SelectVT = MVT::i32; 4739 } 4740 4741 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4742 N->getOperand(0), LHS, RHS); 4743 4744 if (NewVT != SelectVT) 4745 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4746 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4747 return; 4748 } 4749 case ISD::FNEG: { 4750 if (N->getValueType(0) != MVT::v2f16) 4751 break; 4752 4753 SDLoc SL(N); 4754 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4755 4756 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4757 BC, 4758 DAG.getConstant(0x80008000, SL, MVT::i32)); 4759 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4760 return; 4761 } 4762 case ISD::FABS: { 4763 if (N->getValueType(0) != MVT::v2f16) 4764 break; 4765 4766 SDLoc SL(N); 4767 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4768 4769 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4770 BC, 4771 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4772 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4773 return; 4774 } 4775 default: 4776 break; 4777 } 4778 } 4779 4780 /// Helper function for LowerBRCOND 4781 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4782 4783 SDNode *Parent = Value.getNode(); 4784 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4785 I != E; ++I) { 4786 4787 if (I.getUse().get() != Value) 4788 continue; 4789 4790 if (I->getOpcode() == Opcode) 4791 return *I; 4792 } 4793 return nullptr; 4794 } 4795 4796 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4797 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4798 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4799 case Intrinsic::amdgcn_if: 4800 return AMDGPUISD::IF; 4801 case Intrinsic::amdgcn_else: 4802 return AMDGPUISD::ELSE; 4803 case Intrinsic::amdgcn_loop: 4804 return AMDGPUISD::LOOP; 4805 case Intrinsic::amdgcn_end_cf: 4806 llvm_unreachable("should not occur"); 4807 default: 4808 return 0; 4809 } 4810 } 4811 4812 // break, if_break, else_break are all only used as inputs to loop, not 4813 // directly as branch conditions. 4814 return 0; 4815 } 4816 4817 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4818 const Triple &TT = getTargetMachine().getTargetTriple(); 4819 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4820 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4821 AMDGPU::shouldEmitConstantsToTextSection(TT); 4822 } 4823 4824 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4825 // FIXME: Either avoid relying on address space here or change the default 4826 // address space for functions to avoid the explicit check. 4827 return (GV->getValueType()->isFunctionTy() || 4828 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4829 !shouldEmitFixup(GV) && 4830 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4831 } 4832 4833 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4834 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4835 } 4836 4837 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4838 if (!GV->hasExternalLinkage()) 4839 return true; 4840 4841 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4842 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4843 } 4844 4845 /// This transforms the control flow intrinsics to get the branch destination as 4846 /// last parameter, also switches branch target with BR if the need arise 4847 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4848 SelectionDAG &DAG) const { 4849 SDLoc DL(BRCOND); 4850 4851 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4852 SDValue Target = BRCOND.getOperand(2); 4853 SDNode *BR = nullptr; 4854 SDNode *SetCC = nullptr; 4855 4856 if (Intr->getOpcode() == ISD::SETCC) { 4857 // As long as we negate the condition everything is fine 4858 SetCC = Intr; 4859 Intr = SetCC->getOperand(0).getNode(); 4860 4861 } else { 4862 // Get the target from BR if we don't negate the condition 4863 BR = findUser(BRCOND, ISD::BR); 4864 assert(BR && "brcond missing unconditional branch user"); 4865 Target = BR->getOperand(1); 4866 } 4867 4868 unsigned CFNode = isCFIntrinsic(Intr); 4869 if (CFNode == 0) { 4870 // This is a uniform branch so we don't need to legalize. 4871 return BRCOND; 4872 } 4873 4874 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4875 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4876 4877 assert(!SetCC || 4878 (SetCC->getConstantOperandVal(1) == 1 && 4879 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4880 ISD::SETNE)); 4881 4882 // operands of the new intrinsic call 4883 SmallVector<SDValue, 4> Ops; 4884 if (HaveChain) 4885 Ops.push_back(BRCOND.getOperand(0)); 4886 4887 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4888 Ops.push_back(Target); 4889 4890 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4891 4892 // build the new intrinsic call 4893 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4894 4895 if (!HaveChain) { 4896 SDValue Ops[] = { 4897 SDValue(Result, 0), 4898 BRCOND.getOperand(0) 4899 }; 4900 4901 Result = DAG.getMergeValues(Ops, DL).getNode(); 4902 } 4903 4904 if (BR) { 4905 // Give the branch instruction our target 4906 SDValue Ops[] = { 4907 BR->getOperand(0), 4908 BRCOND.getOperand(2) 4909 }; 4910 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4911 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4912 } 4913 4914 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4915 4916 // Copy the intrinsic results to registers 4917 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4918 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4919 if (!CopyToReg) 4920 continue; 4921 4922 Chain = DAG.getCopyToReg( 4923 Chain, DL, 4924 CopyToReg->getOperand(1), 4925 SDValue(Result, i - 1), 4926 SDValue()); 4927 4928 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4929 } 4930 4931 // Remove the old intrinsic from the chain 4932 DAG.ReplaceAllUsesOfValueWith( 4933 SDValue(Intr, Intr->getNumValues() - 1), 4934 Intr->getOperand(0)); 4935 4936 return Chain; 4937 } 4938 4939 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4940 SelectionDAG &DAG) const { 4941 MVT VT = Op.getSimpleValueType(); 4942 SDLoc DL(Op); 4943 // Checking the depth 4944 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4945 return DAG.getConstant(0, DL, VT); 4946 4947 MachineFunction &MF = DAG.getMachineFunction(); 4948 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4949 // Check for kernel and shader functions 4950 if (Info->isEntryFunction()) 4951 return DAG.getConstant(0, DL, VT); 4952 4953 MachineFrameInfo &MFI = MF.getFrameInfo(); 4954 // There is a call to @llvm.returnaddress in this function 4955 MFI.setReturnAddressIsTaken(true); 4956 4957 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4958 // Get the return address reg and mark it as an implicit live-in 4959 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4960 4961 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4962 } 4963 4964 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4965 SDValue Op, 4966 const SDLoc &DL, 4967 EVT VT) const { 4968 return Op.getValueType().bitsLE(VT) ? 4969 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4970 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4971 DAG.getTargetConstant(0, DL, MVT::i32)); 4972 } 4973 4974 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4975 assert(Op.getValueType() == MVT::f16 && 4976 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4977 4978 SDValue Src = Op.getOperand(0); 4979 EVT SrcVT = Src.getValueType(); 4980 if (SrcVT != MVT::f64) 4981 return Op; 4982 4983 SDLoc DL(Op); 4984 4985 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4986 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4987 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4988 } 4989 4990 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4991 SelectionDAG &DAG) const { 4992 EVT VT = Op.getValueType(); 4993 const MachineFunction &MF = DAG.getMachineFunction(); 4994 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4995 bool IsIEEEMode = Info->getMode().IEEE; 4996 4997 // FIXME: Assert during selection that this is only selected for 4998 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4999 // mode functions, but this happens to be OK since it's only done in cases 5000 // where there is known no sNaN. 5001 if (IsIEEEMode) 5002 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5003 5004 if (VT == MVT::v4f16) 5005 return splitBinaryVectorOp(Op, DAG); 5006 return Op; 5007 } 5008 5009 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5010 EVT VT = Op.getValueType(); 5011 SDLoc SL(Op); 5012 SDValue LHS = Op.getOperand(0); 5013 SDValue RHS = Op.getOperand(1); 5014 bool isSigned = Op.getOpcode() == ISD::SMULO; 5015 5016 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5017 const APInt &C = RHSC->getAPIntValue(); 5018 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5019 if (C.isPowerOf2()) { 5020 // smulo(x, signed_min) is same as umulo(x, signed_min). 5021 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5022 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5023 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5024 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5025 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5026 SL, VT, Result, ShiftAmt), 5027 LHS, ISD::SETNE); 5028 return DAG.getMergeValues({ Result, Overflow }, SL); 5029 } 5030 } 5031 5032 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5033 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5034 SL, VT, LHS, RHS); 5035 5036 SDValue Sign = isSigned 5037 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5038 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5039 : DAG.getConstant(0, SL, VT); 5040 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5041 5042 return DAG.getMergeValues({ Result, Overflow }, SL); 5043 } 5044 5045 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5046 SDLoc SL(Op); 5047 SDValue Chain = Op.getOperand(0); 5048 5049 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5050 !Subtarget->isTrapHandlerEnabled()) 5051 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5052 5053 MachineFunction &MF = DAG.getMachineFunction(); 5054 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5055 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 5056 assert(UserSGPR != AMDGPU::NoRegister); 5057 SDValue QueuePtr = CreateLiveInRegister( 5058 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5059 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5060 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5061 QueuePtr, SDValue()); 5062 SDValue Ops[] = { 5063 ToReg, 5064 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5065 SGPR01, 5066 ToReg.getValue(1) 5067 }; 5068 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5069 } 5070 5071 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5072 SDLoc SL(Op); 5073 SDValue Chain = Op.getOperand(0); 5074 MachineFunction &MF = DAG.getMachineFunction(); 5075 5076 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5077 !Subtarget->isTrapHandlerEnabled()) { 5078 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5079 "debugtrap handler not supported", 5080 Op.getDebugLoc(), 5081 DS_Warning); 5082 LLVMContext &Ctx = MF.getFunction().getContext(); 5083 Ctx.diagnose(NoTrap); 5084 return Chain; 5085 } 5086 5087 SDValue Ops[] = { 5088 Chain, 5089 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5090 }; 5091 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5092 } 5093 5094 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5095 SelectionDAG &DAG) const { 5096 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5097 if (Subtarget->hasApertureRegs()) { 5098 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5099 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5100 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5101 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5102 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5103 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5104 unsigned Encoding = 5105 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5106 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5107 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5108 5109 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5110 SDValue ApertureReg = SDValue( 5111 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5112 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5113 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5114 } 5115 5116 MachineFunction &MF = DAG.getMachineFunction(); 5117 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5118 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5119 assert(UserSGPR != AMDGPU::NoRegister); 5120 5121 SDValue QueuePtr = CreateLiveInRegister( 5122 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5123 5124 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5125 // private_segment_aperture_base_hi. 5126 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5127 5128 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 5129 5130 // TODO: Use custom target PseudoSourceValue. 5131 // TODO: We should use the value from the IR intrinsic call, but it might not 5132 // be available and how do we get it? 5133 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5134 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5135 MinAlign(64, StructOffset), 5136 MachineMemOperand::MODereferenceable | 5137 MachineMemOperand::MOInvariant); 5138 } 5139 5140 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5141 SelectionDAG &DAG) const { 5142 SDLoc SL(Op); 5143 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5144 5145 SDValue Src = ASC->getOperand(0); 5146 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5147 5148 const AMDGPUTargetMachine &TM = 5149 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5150 5151 // flat -> local/private 5152 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5153 unsigned DestAS = ASC->getDestAddressSpace(); 5154 5155 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5156 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5157 unsigned NullVal = TM.getNullPointerValue(DestAS); 5158 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5159 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5160 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5161 5162 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5163 NonNull, Ptr, SegmentNullPtr); 5164 } 5165 } 5166 5167 // local/private -> flat 5168 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5169 unsigned SrcAS = ASC->getSrcAddressSpace(); 5170 5171 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5172 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5173 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5174 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5175 5176 SDValue NonNull 5177 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5178 5179 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5180 SDValue CvtPtr 5181 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5182 5183 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5184 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5185 FlatNullPtr); 5186 } 5187 } 5188 5189 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5190 Src.getValueType() == MVT::i64) 5191 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5192 5193 // global <-> flat are no-ops and never emitted. 5194 5195 const MachineFunction &MF = DAG.getMachineFunction(); 5196 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5197 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5198 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5199 5200 return DAG.getUNDEF(ASC->getValueType(0)); 5201 } 5202 5203 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5204 // the small vector and inserting them into the big vector. That is better than 5205 // the default expansion of doing it via a stack slot. Even though the use of 5206 // the stack slot would be optimized away afterwards, the stack slot itself 5207 // remains. 5208 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5209 SelectionDAG &DAG) const { 5210 SDValue Vec = Op.getOperand(0); 5211 SDValue Ins = Op.getOperand(1); 5212 SDValue Idx = Op.getOperand(2); 5213 EVT VecVT = Vec.getValueType(); 5214 EVT InsVT = Ins.getValueType(); 5215 EVT EltVT = VecVT.getVectorElementType(); 5216 unsigned InsNumElts = InsVT.getVectorNumElements(); 5217 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5218 SDLoc SL(Op); 5219 5220 for (unsigned I = 0; I != InsNumElts; ++I) { 5221 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5222 DAG.getConstant(I, SL, MVT::i32)); 5223 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5224 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5225 } 5226 return Vec; 5227 } 5228 5229 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5230 SelectionDAG &DAG) const { 5231 SDValue Vec = Op.getOperand(0); 5232 SDValue InsVal = Op.getOperand(1); 5233 SDValue Idx = Op.getOperand(2); 5234 EVT VecVT = Vec.getValueType(); 5235 EVT EltVT = VecVT.getVectorElementType(); 5236 unsigned VecSize = VecVT.getSizeInBits(); 5237 unsigned EltSize = EltVT.getSizeInBits(); 5238 5239 5240 assert(VecSize <= 64); 5241 5242 unsigned NumElts = VecVT.getVectorNumElements(); 5243 SDLoc SL(Op); 5244 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5245 5246 if (NumElts == 4 && EltSize == 16 && KIdx) { 5247 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5248 5249 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5250 DAG.getConstant(0, SL, MVT::i32)); 5251 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5252 DAG.getConstant(1, SL, MVT::i32)); 5253 5254 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5255 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5256 5257 unsigned Idx = KIdx->getZExtValue(); 5258 bool InsertLo = Idx < 2; 5259 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5260 InsertLo ? LoVec : HiVec, 5261 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5262 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5263 5264 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5265 5266 SDValue Concat = InsertLo ? 5267 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5268 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5269 5270 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5271 } 5272 5273 if (isa<ConstantSDNode>(Idx)) 5274 return SDValue(); 5275 5276 MVT IntVT = MVT::getIntegerVT(VecSize); 5277 5278 // Avoid stack access for dynamic indexing. 5279 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5280 5281 // Create a congruent vector with the target value in each element so that 5282 // the required element can be masked and ORed into the target vector. 5283 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5284 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5285 5286 assert(isPowerOf2_32(EltSize)); 5287 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5288 5289 // Convert vector index to bit-index. 5290 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5291 5292 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5293 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5294 DAG.getConstant(0xffff, SL, IntVT), 5295 ScaledIdx); 5296 5297 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5298 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5299 DAG.getNOT(SL, BFM, IntVT), BCVec); 5300 5301 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5302 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5303 } 5304 5305 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5306 SelectionDAG &DAG) const { 5307 SDLoc SL(Op); 5308 5309 EVT ResultVT = Op.getValueType(); 5310 SDValue Vec = Op.getOperand(0); 5311 SDValue Idx = Op.getOperand(1); 5312 EVT VecVT = Vec.getValueType(); 5313 unsigned VecSize = VecVT.getSizeInBits(); 5314 EVT EltVT = VecVT.getVectorElementType(); 5315 assert(VecSize <= 64); 5316 5317 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5318 5319 // Make sure we do any optimizations that will make it easier to fold 5320 // source modifiers before obscuring it with bit operations. 5321 5322 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5323 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5324 return Combined; 5325 5326 unsigned EltSize = EltVT.getSizeInBits(); 5327 assert(isPowerOf2_32(EltSize)); 5328 5329 MVT IntVT = MVT::getIntegerVT(VecSize); 5330 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5331 5332 // Convert vector index to bit-index (* EltSize) 5333 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5334 5335 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5336 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5337 5338 if (ResultVT == MVT::f16) { 5339 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5340 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5341 } 5342 5343 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5344 } 5345 5346 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5347 assert(Elt % 2 == 0); 5348 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5349 } 5350 5351 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5352 SelectionDAG &DAG) const { 5353 SDLoc SL(Op); 5354 EVT ResultVT = Op.getValueType(); 5355 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5356 5357 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5358 EVT EltVT = PackVT.getVectorElementType(); 5359 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5360 5361 // vector_shuffle <0,1,6,7> lhs, rhs 5362 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5363 // 5364 // vector_shuffle <6,7,2,3> lhs, rhs 5365 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5366 // 5367 // vector_shuffle <6,7,0,1> lhs, rhs 5368 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5369 5370 // Avoid scalarizing when both halves are reading from consecutive elements. 5371 SmallVector<SDValue, 4> Pieces; 5372 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5373 if (elementPairIsContiguous(SVN->getMask(), I)) { 5374 const int Idx = SVN->getMaskElt(I); 5375 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5376 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5377 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5378 PackVT, SVN->getOperand(VecIdx), 5379 DAG.getConstant(EltIdx, SL, MVT::i32)); 5380 Pieces.push_back(SubVec); 5381 } else { 5382 const int Idx0 = SVN->getMaskElt(I); 5383 const int Idx1 = SVN->getMaskElt(I + 1); 5384 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5385 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5386 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5387 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5388 5389 SDValue Vec0 = SVN->getOperand(VecIdx0); 5390 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5391 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5392 5393 SDValue Vec1 = SVN->getOperand(VecIdx1); 5394 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5395 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5396 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5397 } 5398 } 5399 5400 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5401 } 5402 5403 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5404 SelectionDAG &DAG) const { 5405 SDLoc SL(Op); 5406 EVT VT = Op.getValueType(); 5407 5408 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5409 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5410 5411 // Turn into pair of packed build_vectors. 5412 // TODO: Special case for constants that can be materialized with s_mov_b64. 5413 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5414 { Op.getOperand(0), Op.getOperand(1) }); 5415 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5416 { Op.getOperand(2), Op.getOperand(3) }); 5417 5418 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5419 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5420 5421 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5422 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5423 } 5424 5425 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5426 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5427 5428 SDValue Lo = Op.getOperand(0); 5429 SDValue Hi = Op.getOperand(1); 5430 5431 // Avoid adding defined bits with the zero_extend. 5432 if (Hi.isUndef()) { 5433 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5434 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5435 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5436 } 5437 5438 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5439 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5440 5441 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5442 DAG.getConstant(16, SL, MVT::i32)); 5443 if (Lo.isUndef()) 5444 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5445 5446 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5447 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5448 5449 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5450 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5451 } 5452 5453 bool 5454 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5455 // We can fold offsets for anything that doesn't require a GOT relocation. 5456 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5457 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5458 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5459 !shouldEmitGOTReloc(GA->getGlobal()); 5460 } 5461 5462 static SDValue 5463 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5464 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5465 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5466 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5467 // lowered to the following code sequence: 5468 // 5469 // For constant address space: 5470 // s_getpc_b64 s[0:1] 5471 // s_add_u32 s0, s0, $symbol 5472 // s_addc_u32 s1, s1, 0 5473 // 5474 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5475 // a fixup or relocation is emitted to replace $symbol with a literal 5476 // constant, which is a pc-relative offset from the encoding of the $symbol 5477 // operand to the global variable. 5478 // 5479 // For global address space: 5480 // s_getpc_b64 s[0:1] 5481 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5482 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5483 // 5484 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5485 // fixups or relocations are emitted to replace $symbol@*@lo and 5486 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5487 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5488 // operand to the global variable. 5489 // 5490 // What we want here is an offset from the value returned by s_getpc 5491 // (which is the address of the s_add_u32 instruction) to the global 5492 // variable, but since the encoding of $symbol starts 4 bytes after the start 5493 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5494 // small. This requires us to add 4 to the global variable offset in order to 5495 // compute the correct address. 5496 SDValue PtrLo = 5497 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5498 SDValue PtrHi; 5499 if (GAFlags == SIInstrInfo::MO_NONE) { 5500 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5501 } else { 5502 PtrHi = 5503 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5504 } 5505 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5506 } 5507 5508 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5509 SDValue Op, 5510 SelectionDAG &DAG) const { 5511 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5512 const GlobalValue *GV = GSD->getGlobal(); 5513 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5514 shouldUseLDSConstAddress(GV)) || 5515 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5516 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5517 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5518 5519 SDLoc DL(GSD); 5520 EVT PtrVT = Op.getValueType(); 5521 5522 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5523 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5524 SIInstrInfo::MO_ABS32_LO); 5525 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5526 } 5527 5528 if (shouldEmitFixup(GV)) 5529 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5530 else if (shouldEmitPCReloc(GV)) 5531 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5532 SIInstrInfo::MO_REL32); 5533 5534 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5535 SIInstrInfo::MO_GOTPCREL32); 5536 5537 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5538 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5539 const DataLayout &DataLayout = DAG.getDataLayout(); 5540 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5541 MachinePointerInfo PtrInfo 5542 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5543 5544 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5545 MachineMemOperand::MODereferenceable | 5546 MachineMemOperand::MOInvariant); 5547 } 5548 5549 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5550 const SDLoc &DL, SDValue V) const { 5551 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5552 // the destination register. 5553 // 5554 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5555 // so we will end up with redundant moves to m0. 5556 // 5557 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5558 5559 // A Null SDValue creates a glue result. 5560 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5561 V, Chain); 5562 return SDValue(M0, 0); 5563 } 5564 5565 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5566 SDValue Op, 5567 MVT VT, 5568 unsigned Offset) const { 5569 SDLoc SL(Op); 5570 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5571 DAG.getEntryNode(), Offset, 4, false); 5572 // The local size values will have the hi 16-bits as zero. 5573 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5574 DAG.getValueType(VT)); 5575 } 5576 5577 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5578 EVT VT) { 5579 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5580 "non-hsa intrinsic with hsa target", 5581 DL.getDebugLoc()); 5582 DAG.getContext()->diagnose(BadIntrin); 5583 return DAG.getUNDEF(VT); 5584 } 5585 5586 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5587 EVT VT) { 5588 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5589 "intrinsic not supported on subtarget", 5590 DL.getDebugLoc()); 5591 DAG.getContext()->diagnose(BadIntrin); 5592 return DAG.getUNDEF(VT); 5593 } 5594 5595 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5596 ArrayRef<SDValue> Elts) { 5597 assert(!Elts.empty()); 5598 MVT Type; 5599 unsigned NumElts; 5600 5601 if (Elts.size() == 1) { 5602 Type = MVT::f32; 5603 NumElts = 1; 5604 } else if (Elts.size() == 2) { 5605 Type = MVT::v2f32; 5606 NumElts = 2; 5607 } else if (Elts.size() == 3) { 5608 Type = MVT::v3f32; 5609 NumElts = 3; 5610 } else if (Elts.size() <= 4) { 5611 Type = MVT::v4f32; 5612 NumElts = 4; 5613 } else if (Elts.size() <= 8) { 5614 Type = MVT::v8f32; 5615 NumElts = 8; 5616 } else { 5617 assert(Elts.size() <= 16); 5618 Type = MVT::v16f32; 5619 NumElts = 16; 5620 } 5621 5622 SmallVector<SDValue, 16> VecElts(NumElts); 5623 for (unsigned i = 0; i < Elts.size(); ++i) { 5624 SDValue Elt = Elts[i]; 5625 if (Elt.getValueType() != MVT::f32) 5626 Elt = DAG.getBitcast(MVT::f32, Elt); 5627 VecElts[i] = Elt; 5628 } 5629 for (unsigned i = Elts.size(); i < NumElts; ++i) 5630 VecElts[i] = DAG.getUNDEF(MVT::f32); 5631 5632 if (NumElts == 1) 5633 return VecElts[0]; 5634 return DAG.getBuildVector(Type, DL, VecElts); 5635 } 5636 5637 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5638 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5639 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5640 5641 uint64_t Value = CachePolicyConst->getZExtValue(); 5642 SDLoc DL(CachePolicy); 5643 if (GLC) { 5644 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5645 Value &= ~(uint64_t)0x1; 5646 } 5647 if (SLC) { 5648 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5649 Value &= ~(uint64_t)0x2; 5650 } 5651 if (DLC) { 5652 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5653 Value &= ~(uint64_t)0x4; 5654 } 5655 5656 return Value == 0; 5657 } 5658 5659 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5660 SDValue Src, int ExtraElts) { 5661 EVT SrcVT = Src.getValueType(); 5662 5663 SmallVector<SDValue, 8> Elts; 5664 5665 if (SrcVT.isVector()) 5666 DAG.ExtractVectorElements(Src, Elts); 5667 else 5668 Elts.push_back(Src); 5669 5670 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5671 while (ExtraElts--) 5672 Elts.push_back(Undef); 5673 5674 return DAG.getBuildVector(CastVT, DL, Elts); 5675 } 5676 5677 // Re-construct the required return value for a image load intrinsic. 5678 // This is more complicated due to the optional use TexFailCtrl which means the required 5679 // return type is an aggregate 5680 static SDValue constructRetValue(SelectionDAG &DAG, 5681 MachineSDNode *Result, 5682 ArrayRef<EVT> ResultTypes, 5683 bool IsTexFail, bool Unpacked, bool IsD16, 5684 int DMaskPop, int NumVDataDwords, 5685 const SDLoc &DL, LLVMContext &Context) { 5686 // Determine the required return type. This is the same regardless of IsTexFail flag 5687 EVT ReqRetVT = ResultTypes[0]; 5688 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5689 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5690 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5691 5692 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5693 DMaskPop : (DMaskPop + 1) / 2; 5694 5695 MVT DataDwordVT = NumDataDwords == 1 ? 5696 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5697 5698 MVT MaskPopVT = MaskPopDwords == 1 ? 5699 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5700 5701 SDValue Data(Result, 0); 5702 SDValue TexFail; 5703 5704 if (IsTexFail) { 5705 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5706 if (MaskPopVT.isVector()) { 5707 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5708 SDValue(Result, 0), ZeroIdx); 5709 } else { 5710 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5711 SDValue(Result, 0), ZeroIdx); 5712 } 5713 5714 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5715 SDValue(Result, 0), 5716 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5717 } 5718 5719 if (DataDwordVT.isVector()) 5720 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5721 NumDataDwords - MaskPopDwords); 5722 5723 if (IsD16) 5724 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5725 5726 if (!ReqRetVT.isVector()) 5727 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5728 5729 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5730 5731 if (TexFail) 5732 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5733 5734 if (Result->getNumValues() == 1) 5735 return Data; 5736 5737 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5738 } 5739 5740 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5741 SDValue *LWE, bool &IsTexFail) { 5742 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5743 5744 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5745 if (Value) { 5746 IsTexFail = true; 5747 } 5748 5749 SDLoc DL(TexFailCtrlConst); 5750 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5751 Value &= ~(uint64_t)0x1; 5752 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5753 Value &= ~(uint64_t)0x2; 5754 5755 return Value == 0; 5756 } 5757 5758 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5759 MVT PackVectorVT, 5760 SmallVectorImpl<SDValue> &PackedAddrs, 5761 unsigned DimIdx, unsigned EndIdx, 5762 unsigned NumGradients) { 5763 SDLoc DL(Op); 5764 for (unsigned I = DimIdx; I < EndIdx; I++) { 5765 SDValue Addr = Op.getOperand(I); 5766 5767 // Gradients are packed with undef for each coordinate. 5768 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5769 // 1D: undef,dx/dh; undef,dx/dv 5770 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5771 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5772 if (((I + 1) >= EndIdx) || 5773 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5774 I == DimIdx + NumGradients - 1))) { 5775 if (Addr.getValueType() != MVT::i16) 5776 Addr = DAG.getBitcast(MVT::i16, Addr); 5777 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5778 } else { 5779 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5780 I++; 5781 } 5782 Addr = DAG.getBitcast(MVT::f32, Addr); 5783 PackedAddrs.push_back(Addr); 5784 } 5785 } 5786 5787 SDValue SITargetLowering::lowerImage(SDValue Op, 5788 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5789 SelectionDAG &DAG) const { 5790 SDLoc DL(Op); 5791 MachineFunction &MF = DAG.getMachineFunction(); 5792 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5793 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5794 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5795 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5796 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5797 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5798 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5799 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5800 unsigned IntrOpcode = Intr->BaseOpcode; 5801 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5802 5803 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5804 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5805 bool IsD16 = false; 5806 bool IsG16 = false; 5807 bool IsA16 = false; 5808 SDValue VData; 5809 int NumVDataDwords; 5810 bool AdjustRetType = false; 5811 5812 unsigned AddrIdx; // Index of first address argument 5813 unsigned DMask; 5814 unsigned DMaskLanes = 0; 5815 5816 if (BaseOpcode->Atomic) { 5817 VData = Op.getOperand(2); 5818 5819 bool Is64Bit = VData.getValueType() == MVT::i64; 5820 if (BaseOpcode->AtomicX2) { 5821 SDValue VData2 = Op.getOperand(3); 5822 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5823 {VData, VData2}); 5824 if (Is64Bit) 5825 VData = DAG.getBitcast(MVT::v4i32, VData); 5826 5827 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5828 DMask = Is64Bit ? 0xf : 0x3; 5829 NumVDataDwords = Is64Bit ? 4 : 2; 5830 AddrIdx = 4; 5831 } else { 5832 DMask = Is64Bit ? 0x3 : 0x1; 5833 NumVDataDwords = Is64Bit ? 2 : 1; 5834 AddrIdx = 3; 5835 } 5836 } else { 5837 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5838 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5839 DMask = DMaskConst->getZExtValue(); 5840 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5841 5842 if (BaseOpcode->Store) { 5843 VData = Op.getOperand(2); 5844 5845 MVT StoreVT = VData.getSimpleValueType(); 5846 if (StoreVT.getScalarType() == MVT::f16) { 5847 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5848 return Op; // D16 is unsupported for this instruction 5849 5850 IsD16 = true; 5851 VData = handleD16VData(VData, DAG); 5852 } 5853 5854 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5855 } else { 5856 // Work out the num dwords based on the dmask popcount and underlying type 5857 // and whether packing is supported. 5858 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5859 if (LoadVT.getScalarType() == MVT::f16) { 5860 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5861 return Op; // D16 is unsupported for this instruction 5862 5863 IsD16 = true; 5864 } 5865 5866 // Confirm that the return type is large enough for the dmask specified 5867 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5868 (!LoadVT.isVector() && DMaskLanes > 1)) 5869 return Op; 5870 5871 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5872 NumVDataDwords = (DMaskLanes + 1) / 2; 5873 else 5874 NumVDataDwords = DMaskLanes; 5875 5876 AdjustRetType = true; 5877 } 5878 5879 AddrIdx = DMaskIdx + 1; 5880 } 5881 5882 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5883 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5884 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5885 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5886 NumCoords + NumLCM; 5887 unsigned NumMIVAddrs = NumVAddrs; 5888 5889 SmallVector<SDValue, 4> VAddrs; 5890 5891 // Optimize _L to _LZ when _L is zero 5892 if (LZMappingInfo) { 5893 if (auto ConstantLod = 5894 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5895 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5896 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5897 NumMIVAddrs--; // remove 'lod' 5898 } 5899 } 5900 } 5901 5902 // Optimize _mip away, when 'lod' is zero 5903 if (MIPMappingInfo) { 5904 if (auto ConstantLod = 5905 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5906 if (ConstantLod->isNullValue()) { 5907 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5908 NumMIVAddrs--; // remove 'lod' 5909 } 5910 } 5911 } 5912 5913 // Push back extra arguments. 5914 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 5915 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 5916 5917 // Check for 16 bit addresses or derivatives and pack if true. 5918 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5919 unsigned CoordIdx = DimIdx + NumGradients; 5920 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 5921 5922 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5923 MVT VAddrScalarVT = VAddrVT.getScalarType(); 5924 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5925 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5926 5927 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 5928 VAddrScalarVT = VAddrVT.getScalarType(); 5929 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5930 if (IsA16 || IsG16) { 5931 if (IsA16) { 5932 if (!ST->hasA16()) { 5933 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5934 "support 16 bit addresses\n"); 5935 return Op; 5936 } 5937 if (!IsG16) { 5938 LLVM_DEBUG( 5939 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 5940 "need 16 bit derivatives but got 32 bit derivatives\n"); 5941 return Op; 5942 } 5943 } else if (!ST->hasG16()) { 5944 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5945 "support 16 bit derivatives\n"); 5946 return Op; 5947 } 5948 5949 if (BaseOpcode->Gradients && !IsA16) { 5950 if (!ST->hasG16()) { 5951 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5952 "support 16 bit derivatives\n"); 5953 return Op; 5954 } 5955 // Activate g16 5956 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 5957 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 5958 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 5959 } 5960 5961 // Don't compress addresses for G16 5962 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 5963 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 5964 PackEndIdx, NumGradients); 5965 5966 if (!IsA16) { 5967 // Add uncompressed address 5968 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 5969 VAddrs.push_back(Op.getOperand(I)); 5970 } 5971 } else { 5972 for (unsigned I = DimIdx; I < CoordsEnd; I++) 5973 VAddrs.push_back(Op.getOperand(I)); 5974 } 5975 5976 // If the register allocator cannot place the address registers contiguously 5977 // without introducing moves, then using the non-sequential address encoding 5978 // is always preferable, since it saves VALU instructions and is usually a 5979 // wash in terms of code size or even better. 5980 // 5981 // However, we currently have no way of hinting to the register allocator that 5982 // MIMG addresses should be placed contiguously when it is possible to do so, 5983 // so force non-NSA for the common 2-address case as a heuristic. 5984 // 5985 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5986 // allocation when possible. 5987 bool UseNSA = 5988 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5989 SDValue VAddr; 5990 if (!UseNSA) 5991 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5992 5993 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5994 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5995 unsigned CtrlIdx; // Index of texfailctrl argument 5996 SDValue Unorm; 5997 if (!BaseOpcode->Sampler) { 5998 Unorm = True; 5999 CtrlIdx = AddrIdx + NumVAddrs + 1; 6000 } else { 6001 auto UnormConst = 6002 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6003 6004 Unorm = UnormConst->getZExtValue() ? True : False; 6005 CtrlIdx = AddrIdx + NumVAddrs + 3; 6006 } 6007 6008 SDValue TFE; 6009 SDValue LWE; 6010 SDValue TexFail = Op.getOperand(CtrlIdx); 6011 bool IsTexFail = false; 6012 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6013 return Op; 6014 6015 if (IsTexFail) { 6016 if (!DMaskLanes) { 6017 // Expecting to get an error flag since TFC is on - and dmask is 0 6018 // Force dmask to be at least 1 otherwise the instruction will fail 6019 DMask = 0x1; 6020 DMaskLanes = 1; 6021 NumVDataDwords = 1; 6022 } 6023 NumVDataDwords += 1; 6024 AdjustRetType = true; 6025 } 6026 6027 // Has something earlier tagged that the return type needs adjusting 6028 // This happens if the instruction is a load or has set TexFailCtrl flags 6029 if (AdjustRetType) { 6030 // NumVDataDwords reflects the true number of dwords required in the return type 6031 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6032 // This is a no-op load. This can be eliminated 6033 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6034 if (isa<MemSDNode>(Op)) 6035 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6036 return Undef; 6037 } 6038 6039 EVT NewVT = NumVDataDwords > 1 ? 6040 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6041 : MVT::i32; 6042 6043 ResultTypes[0] = NewVT; 6044 if (ResultTypes.size() == 3) { 6045 // Original result was aggregate type used for TexFailCtrl results 6046 // The actual instruction returns as a vector type which has now been 6047 // created. Remove the aggregate result. 6048 ResultTypes.erase(&ResultTypes[1]); 6049 } 6050 } 6051 6052 SDValue GLC; 6053 SDValue SLC; 6054 SDValue DLC; 6055 if (BaseOpcode->Atomic) { 6056 GLC = True; // TODO no-return optimization 6057 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6058 IsGFX10 ? &DLC : nullptr)) 6059 return Op; 6060 } else { 6061 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6062 IsGFX10 ? &DLC : nullptr)) 6063 return Op; 6064 } 6065 6066 SmallVector<SDValue, 26> Ops; 6067 if (BaseOpcode->Store || BaseOpcode->Atomic) 6068 Ops.push_back(VData); // vdata 6069 if (UseNSA) { 6070 for (const SDValue &Addr : VAddrs) 6071 Ops.push_back(Addr); 6072 } else { 6073 Ops.push_back(VAddr); 6074 } 6075 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6076 if (BaseOpcode->Sampler) 6077 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6078 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6079 if (IsGFX10) 6080 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6081 Ops.push_back(Unorm); 6082 if (IsGFX10) 6083 Ops.push_back(DLC); 6084 Ops.push_back(GLC); 6085 Ops.push_back(SLC); 6086 Ops.push_back(IsA16 && // r128, a16 for gfx9 6087 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6088 if (IsGFX10) 6089 Ops.push_back(IsA16 ? True : False); 6090 Ops.push_back(TFE); 6091 Ops.push_back(LWE); 6092 if (!IsGFX10) 6093 Ops.push_back(DimInfo->DA ? True : False); 6094 if (BaseOpcode->HasD16) 6095 Ops.push_back(IsD16 ? True : False); 6096 if (isa<MemSDNode>(Op)) 6097 Ops.push_back(Op.getOperand(0)); // chain 6098 6099 int NumVAddrDwords = 6100 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6101 int Opcode = -1; 6102 6103 if (IsGFX10) { 6104 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6105 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6106 : AMDGPU::MIMGEncGfx10Default, 6107 NumVDataDwords, NumVAddrDwords); 6108 } else { 6109 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6110 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6111 NumVDataDwords, NumVAddrDwords); 6112 if (Opcode == -1) 6113 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6114 NumVDataDwords, NumVAddrDwords); 6115 } 6116 assert(Opcode != -1); 6117 6118 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6119 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6120 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6121 DAG.setNodeMemRefs(NewNode, {MemRef}); 6122 } 6123 6124 if (BaseOpcode->AtomicX2) { 6125 SmallVector<SDValue, 1> Elt; 6126 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6127 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6128 } else if (!BaseOpcode->Store) { 6129 return constructRetValue(DAG, NewNode, 6130 OrigResultTypes, IsTexFail, 6131 Subtarget->hasUnpackedD16VMem(), IsD16, 6132 DMaskLanes, NumVDataDwords, DL, 6133 *DAG.getContext()); 6134 } 6135 6136 return SDValue(NewNode, 0); 6137 } 6138 6139 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6140 SDValue Offset, SDValue CachePolicy, 6141 SelectionDAG &DAG) const { 6142 MachineFunction &MF = DAG.getMachineFunction(); 6143 6144 const DataLayout &DataLayout = DAG.getDataLayout(); 6145 Align Alignment = 6146 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6147 6148 MachineMemOperand *MMO = MF.getMachineMemOperand( 6149 MachinePointerInfo(), 6150 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6151 MachineMemOperand::MOInvariant, 6152 VT.getStoreSize(), Alignment); 6153 6154 if (!Offset->isDivergent()) { 6155 SDValue Ops[] = { 6156 Rsrc, 6157 Offset, // Offset 6158 CachePolicy 6159 }; 6160 6161 // Widen vec3 load to vec4. 6162 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6163 EVT WidenedVT = 6164 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6165 auto WidenedOp = DAG.getMemIntrinsicNode( 6166 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6167 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6168 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6169 DAG.getVectorIdxConstant(0, DL)); 6170 return Subvector; 6171 } 6172 6173 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6174 DAG.getVTList(VT), Ops, VT, MMO); 6175 } 6176 6177 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6178 // assume that the buffer is unswizzled. 6179 SmallVector<SDValue, 4> Loads; 6180 unsigned NumLoads = 1; 6181 MVT LoadVT = VT.getSimpleVT(); 6182 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6183 assert((LoadVT.getScalarType() == MVT::i32 || 6184 LoadVT.getScalarType() == MVT::f32)); 6185 6186 if (NumElts == 8 || NumElts == 16) { 6187 NumLoads = NumElts / 4; 6188 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6189 } 6190 6191 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6192 SDValue Ops[] = { 6193 DAG.getEntryNode(), // Chain 6194 Rsrc, // rsrc 6195 DAG.getConstant(0, DL, MVT::i32), // vindex 6196 {}, // voffset 6197 {}, // soffset 6198 {}, // offset 6199 CachePolicy, // cachepolicy 6200 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6201 }; 6202 6203 // Use the alignment to ensure that the required offsets will fit into the 6204 // immediate offsets. 6205 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 6206 6207 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6208 for (unsigned i = 0; i < NumLoads; ++i) { 6209 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6210 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6211 LoadVT, MMO, DAG)); 6212 } 6213 6214 if (NumElts == 8 || NumElts == 16) 6215 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6216 6217 return Loads[0]; 6218 } 6219 6220 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6221 SelectionDAG &DAG) const { 6222 MachineFunction &MF = DAG.getMachineFunction(); 6223 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6224 6225 EVT VT = Op.getValueType(); 6226 SDLoc DL(Op); 6227 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6228 6229 // TODO: Should this propagate fast-math-flags? 6230 6231 switch (IntrinsicID) { 6232 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6233 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6234 return emitNonHSAIntrinsicError(DAG, DL, VT); 6235 return getPreloadedValue(DAG, *MFI, VT, 6236 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6237 } 6238 case Intrinsic::amdgcn_dispatch_ptr: 6239 case Intrinsic::amdgcn_queue_ptr: { 6240 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6241 DiagnosticInfoUnsupported BadIntrin( 6242 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6243 DL.getDebugLoc()); 6244 DAG.getContext()->diagnose(BadIntrin); 6245 return DAG.getUNDEF(VT); 6246 } 6247 6248 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6249 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6250 return getPreloadedValue(DAG, *MFI, VT, RegID); 6251 } 6252 case Intrinsic::amdgcn_implicitarg_ptr: { 6253 if (MFI->isEntryFunction()) 6254 return getImplicitArgPtr(DAG, DL); 6255 return getPreloadedValue(DAG, *MFI, VT, 6256 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6257 } 6258 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6259 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6260 // This only makes sense to call in a kernel, so just lower to null. 6261 return DAG.getConstant(0, DL, VT); 6262 } 6263 6264 return getPreloadedValue(DAG, *MFI, VT, 6265 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6266 } 6267 case Intrinsic::amdgcn_dispatch_id: { 6268 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6269 } 6270 case Intrinsic::amdgcn_rcp: 6271 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6272 case Intrinsic::amdgcn_rsq: 6273 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6274 case Intrinsic::amdgcn_rsq_legacy: 6275 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6276 return emitRemovedIntrinsicError(DAG, DL, VT); 6277 return SDValue(); 6278 case Intrinsic::amdgcn_rcp_legacy: 6279 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6280 return emitRemovedIntrinsicError(DAG, DL, VT); 6281 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6282 case Intrinsic::amdgcn_rsq_clamp: { 6283 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6284 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6285 6286 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6287 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6288 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6289 6290 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6291 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6292 DAG.getConstantFP(Max, DL, VT)); 6293 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6294 DAG.getConstantFP(Min, DL, VT)); 6295 } 6296 case Intrinsic::r600_read_ngroups_x: 6297 if (Subtarget->isAmdHsaOS()) 6298 return emitNonHSAIntrinsicError(DAG, DL, VT); 6299 6300 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6301 SI::KernelInputOffsets::NGROUPS_X, 4, false); 6302 case Intrinsic::r600_read_ngroups_y: 6303 if (Subtarget->isAmdHsaOS()) 6304 return emitNonHSAIntrinsicError(DAG, DL, VT); 6305 6306 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6307 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 6308 case Intrinsic::r600_read_ngroups_z: 6309 if (Subtarget->isAmdHsaOS()) 6310 return emitNonHSAIntrinsicError(DAG, DL, VT); 6311 6312 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6313 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 6314 case Intrinsic::r600_read_global_size_x: 6315 if (Subtarget->isAmdHsaOS()) 6316 return emitNonHSAIntrinsicError(DAG, DL, VT); 6317 6318 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6319 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 6320 case Intrinsic::r600_read_global_size_y: 6321 if (Subtarget->isAmdHsaOS()) 6322 return emitNonHSAIntrinsicError(DAG, DL, VT); 6323 6324 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6325 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 6326 case Intrinsic::r600_read_global_size_z: 6327 if (Subtarget->isAmdHsaOS()) 6328 return emitNonHSAIntrinsicError(DAG, DL, VT); 6329 6330 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6331 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 6332 case Intrinsic::r600_read_local_size_x: 6333 if (Subtarget->isAmdHsaOS()) 6334 return emitNonHSAIntrinsicError(DAG, DL, VT); 6335 6336 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6337 SI::KernelInputOffsets::LOCAL_SIZE_X); 6338 case Intrinsic::r600_read_local_size_y: 6339 if (Subtarget->isAmdHsaOS()) 6340 return emitNonHSAIntrinsicError(DAG, DL, VT); 6341 6342 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6343 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6344 case Intrinsic::r600_read_local_size_z: 6345 if (Subtarget->isAmdHsaOS()) 6346 return emitNonHSAIntrinsicError(DAG, DL, VT); 6347 6348 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6349 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6350 case Intrinsic::amdgcn_workgroup_id_x: 6351 return getPreloadedValue(DAG, *MFI, VT, 6352 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6353 case Intrinsic::amdgcn_workgroup_id_y: 6354 return getPreloadedValue(DAG, *MFI, VT, 6355 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6356 case Intrinsic::amdgcn_workgroup_id_z: 6357 return getPreloadedValue(DAG, *MFI, VT, 6358 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6359 case Intrinsic::amdgcn_workitem_id_x: 6360 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6361 SDLoc(DAG.getEntryNode()), 6362 MFI->getArgInfo().WorkItemIDX); 6363 case Intrinsic::amdgcn_workitem_id_y: 6364 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6365 SDLoc(DAG.getEntryNode()), 6366 MFI->getArgInfo().WorkItemIDY); 6367 case Intrinsic::amdgcn_workitem_id_z: 6368 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6369 SDLoc(DAG.getEntryNode()), 6370 MFI->getArgInfo().WorkItemIDZ); 6371 case Intrinsic::amdgcn_wavefrontsize: 6372 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6373 SDLoc(Op), MVT::i32); 6374 case Intrinsic::amdgcn_s_buffer_load: { 6375 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6376 SDValue GLC; 6377 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6378 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6379 IsGFX10 ? &DLC : nullptr)) 6380 return Op; 6381 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6382 DAG); 6383 } 6384 case Intrinsic::amdgcn_fdiv_fast: 6385 return lowerFDIV_FAST(Op, DAG); 6386 case Intrinsic::amdgcn_sin: 6387 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6388 6389 case Intrinsic::amdgcn_cos: 6390 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6391 6392 case Intrinsic::amdgcn_mul_u24: 6393 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6394 case Intrinsic::amdgcn_mul_i24: 6395 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6396 6397 case Intrinsic::amdgcn_log_clamp: { 6398 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6399 return SDValue(); 6400 6401 DiagnosticInfoUnsupported BadIntrin( 6402 MF.getFunction(), "intrinsic not supported on subtarget", 6403 DL.getDebugLoc()); 6404 DAG.getContext()->diagnose(BadIntrin); 6405 return DAG.getUNDEF(VT); 6406 } 6407 case Intrinsic::amdgcn_ldexp: 6408 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6409 Op.getOperand(1), Op.getOperand(2)); 6410 6411 case Intrinsic::amdgcn_fract: 6412 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6413 6414 case Intrinsic::amdgcn_class: 6415 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6416 Op.getOperand(1), Op.getOperand(2)); 6417 case Intrinsic::amdgcn_div_fmas: 6418 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6419 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6420 Op.getOperand(4)); 6421 6422 case Intrinsic::amdgcn_div_fixup: 6423 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6424 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6425 6426 case Intrinsic::amdgcn_div_scale: { 6427 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6428 6429 // Translate to the operands expected by the machine instruction. The 6430 // first parameter must be the same as the first instruction. 6431 SDValue Numerator = Op.getOperand(1); 6432 SDValue Denominator = Op.getOperand(2); 6433 6434 // Note this order is opposite of the machine instruction's operations, 6435 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6436 // intrinsic has the numerator as the first operand to match a normal 6437 // division operation. 6438 6439 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6440 6441 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6442 Denominator, Numerator); 6443 } 6444 case Intrinsic::amdgcn_icmp: { 6445 // There is a Pat that handles this variant, so return it as-is. 6446 if (Op.getOperand(1).getValueType() == MVT::i1 && 6447 Op.getConstantOperandVal(2) == 0 && 6448 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6449 return Op; 6450 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6451 } 6452 case Intrinsic::amdgcn_fcmp: { 6453 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6454 } 6455 case Intrinsic::amdgcn_ballot: 6456 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6457 case Intrinsic::amdgcn_fmed3: 6458 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6459 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6460 case Intrinsic::amdgcn_fdot2: 6461 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6462 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6463 Op.getOperand(4)); 6464 case Intrinsic::amdgcn_fmul_legacy: 6465 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6466 Op.getOperand(1), Op.getOperand(2)); 6467 case Intrinsic::amdgcn_sffbh: 6468 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6469 case Intrinsic::amdgcn_sbfe: 6470 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6471 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6472 case Intrinsic::amdgcn_ubfe: 6473 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6474 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6475 case Intrinsic::amdgcn_cvt_pkrtz: 6476 case Intrinsic::amdgcn_cvt_pknorm_i16: 6477 case Intrinsic::amdgcn_cvt_pknorm_u16: 6478 case Intrinsic::amdgcn_cvt_pk_i16: 6479 case Intrinsic::amdgcn_cvt_pk_u16: { 6480 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6481 EVT VT = Op.getValueType(); 6482 unsigned Opcode; 6483 6484 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6485 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6486 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6487 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6488 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6489 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6490 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6491 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6492 else 6493 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6494 6495 if (isTypeLegal(VT)) 6496 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6497 6498 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6499 Op.getOperand(1), Op.getOperand(2)); 6500 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6501 } 6502 case Intrinsic::amdgcn_fmad_ftz: 6503 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6504 Op.getOperand(2), Op.getOperand(3)); 6505 6506 case Intrinsic::amdgcn_if_break: 6507 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6508 Op->getOperand(1), Op->getOperand(2)), 0); 6509 6510 case Intrinsic::amdgcn_groupstaticsize: { 6511 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6512 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6513 return Op; 6514 6515 const Module *M = MF.getFunction().getParent(); 6516 const GlobalValue *GV = 6517 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6518 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6519 SIInstrInfo::MO_ABS32_LO); 6520 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6521 } 6522 case Intrinsic::amdgcn_is_shared: 6523 case Intrinsic::amdgcn_is_private: { 6524 SDLoc SL(Op); 6525 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6526 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6527 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6528 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6529 Op.getOperand(1)); 6530 6531 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6532 DAG.getConstant(1, SL, MVT::i32)); 6533 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6534 } 6535 case Intrinsic::amdgcn_alignbit: 6536 return DAG.getNode(ISD::FSHR, DL, VT, 6537 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6538 case Intrinsic::amdgcn_reloc_constant: { 6539 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6540 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6541 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6542 auto RelocSymbol = cast<GlobalVariable>( 6543 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6544 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6545 SIInstrInfo::MO_ABS32_LO); 6546 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6547 } 6548 default: 6549 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6550 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6551 return lowerImage(Op, ImageDimIntr, DAG); 6552 6553 return Op; 6554 } 6555 } 6556 6557 // This function computes an appropriate offset to pass to 6558 // MachineMemOperand::setOffset() based on the offset inputs to 6559 // an intrinsic. If any of the offsets are non-contstant or 6560 // if VIndex is non-zero then this function returns 0. Otherwise, 6561 // it returns the sum of VOffset, SOffset, and Offset. 6562 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6563 SDValue SOffset, 6564 SDValue Offset, 6565 SDValue VIndex = SDValue()) { 6566 6567 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6568 !isa<ConstantSDNode>(Offset)) 6569 return 0; 6570 6571 if (VIndex) { 6572 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6573 return 0; 6574 } 6575 6576 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6577 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6578 cast<ConstantSDNode>(Offset)->getSExtValue(); 6579 } 6580 6581 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6582 switch (MF.getFunction().getCallingConv()) { 6583 case CallingConv::AMDGPU_PS: 6584 return 1; 6585 case CallingConv::AMDGPU_VS: 6586 return 2; 6587 case CallingConv::AMDGPU_GS: 6588 return 3; 6589 case CallingConv::AMDGPU_HS: 6590 case CallingConv::AMDGPU_LS: 6591 case CallingConv::AMDGPU_ES: 6592 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6593 case CallingConv::AMDGPU_CS: 6594 case CallingConv::AMDGPU_KERNEL: 6595 case CallingConv::C: 6596 case CallingConv::Fast: 6597 default: 6598 // Assume other calling conventions are various compute callable functions 6599 return 0; 6600 } 6601 } 6602 6603 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6604 SelectionDAG &DAG) const { 6605 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6606 SDLoc DL(Op); 6607 6608 switch (IntrID) { 6609 case Intrinsic::amdgcn_ds_ordered_add: 6610 case Intrinsic::amdgcn_ds_ordered_swap: { 6611 MemSDNode *M = cast<MemSDNode>(Op); 6612 SDValue Chain = M->getOperand(0); 6613 SDValue M0 = M->getOperand(2); 6614 SDValue Value = M->getOperand(3); 6615 unsigned IndexOperand = M->getConstantOperandVal(7); 6616 unsigned WaveRelease = M->getConstantOperandVal(8); 6617 unsigned WaveDone = M->getConstantOperandVal(9); 6618 6619 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6620 IndexOperand &= ~0x3f; 6621 unsigned CountDw = 0; 6622 6623 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6624 CountDw = (IndexOperand >> 24) & 0xf; 6625 IndexOperand &= ~(0xf << 24); 6626 6627 if (CountDw < 1 || CountDw > 4) { 6628 report_fatal_error( 6629 "ds_ordered_count: dword count must be between 1 and 4"); 6630 } 6631 } 6632 6633 if (IndexOperand) 6634 report_fatal_error("ds_ordered_count: bad index operand"); 6635 6636 if (WaveDone && !WaveRelease) 6637 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6638 6639 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6640 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6641 unsigned Offset0 = OrderedCountIndex << 2; 6642 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6643 (Instruction << 4); 6644 6645 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6646 Offset1 |= (CountDw - 1) << 6; 6647 6648 unsigned Offset = Offset0 | (Offset1 << 8); 6649 6650 SDValue Ops[] = { 6651 Chain, 6652 Value, 6653 DAG.getTargetConstant(Offset, DL, MVT::i16), 6654 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6655 }; 6656 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6657 M->getVTList(), Ops, M->getMemoryVT(), 6658 M->getMemOperand()); 6659 } 6660 case Intrinsic::amdgcn_ds_fadd: { 6661 MemSDNode *M = cast<MemSDNode>(Op); 6662 unsigned Opc; 6663 switch (IntrID) { 6664 case Intrinsic::amdgcn_ds_fadd: 6665 Opc = ISD::ATOMIC_LOAD_FADD; 6666 break; 6667 } 6668 6669 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6670 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6671 M->getMemOperand()); 6672 } 6673 case Intrinsic::amdgcn_atomic_inc: 6674 case Intrinsic::amdgcn_atomic_dec: 6675 case Intrinsic::amdgcn_ds_fmin: 6676 case Intrinsic::amdgcn_ds_fmax: { 6677 MemSDNode *M = cast<MemSDNode>(Op); 6678 unsigned Opc; 6679 switch (IntrID) { 6680 case Intrinsic::amdgcn_atomic_inc: 6681 Opc = AMDGPUISD::ATOMIC_INC; 6682 break; 6683 case Intrinsic::amdgcn_atomic_dec: 6684 Opc = AMDGPUISD::ATOMIC_DEC; 6685 break; 6686 case Intrinsic::amdgcn_ds_fmin: 6687 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6688 break; 6689 case Intrinsic::amdgcn_ds_fmax: 6690 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6691 break; 6692 default: 6693 llvm_unreachable("Unknown intrinsic!"); 6694 } 6695 SDValue Ops[] = { 6696 M->getOperand(0), // Chain 6697 M->getOperand(2), // Ptr 6698 M->getOperand(3) // Value 6699 }; 6700 6701 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6702 M->getMemoryVT(), M->getMemOperand()); 6703 } 6704 case Intrinsic::amdgcn_buffer_load: 6705 case Intrinsic::amdgcn_buffer_load_format: { 6706 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6707 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6708 unsigned IdxEn = 1; 6709 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6710 IdxEn = Idx->getZExtValue() != 0; 6711 SDValue Ops[] = { 6712 Op.getOperand(0), // Chain 6713 Op.getOperand(2), // rsrc 6714 Op.getOperand(3), // vindex 6715 SDValue(), // voffset -- will be set by setBufferOffsets 6716 SDValue(), // soffset -- will be set by setBufferOffsets 6717 SDValue(), // offset -- will be set by setBufferOffsets 6718 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6719 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6720 }; 6721 6722 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6723 // We don't know the offset if vindex is non-zero, so clear it. 6724 if (IdxEn) 6725 Offset = 0; 6726 6727 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6728 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6729 6730 EVT VT = Op.getValueType(); 6731 EVT IntVT = VT.changeTypeToInteger(); 6732 auto *M = cast<MemSDNode>(Op); 6733 M->getMemOperand()->setOffset(Offset); 6734 EVT LoadVT = Op.getValueType(); 6735 6736 if (LoadVT.getScalarType() == MVT::f16) 6737 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6738 M, DAG, Ops); 6739 6740 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6741 if (LoadVT.getScalarType() == MVT::i8 || 6742 LoadVT.getScalarType() == MVT::i16) 6743 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6744 6745 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6746 M->getMemOperand(), DAG); 6747 } 6748 case Intrinsic::amdgcn_raw_buffer_load: 6749 case Intrinsic::amdgcn_raw_buffer_load_format: { 6750 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6751 6752 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6753 SDValue Ops[] = { 6754 Op.getOperand(0), // Chain 6755 Op.getOperand(2), // rsrc 6756 DAG.getConstant(0, DL, MVT::i32), // vindex 6757 Offsets.first, // voffset 6758 Op.getOperand(4), // soffset 6759 Offsets.second, // offset 6760 Op.getOperand(5), // cachepolicy, swizzled buffer 6761 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6762 }; 6763 6764 auto *M = cast<MemSDNode>(Op); 6765 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6766 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6767 } 6768 case Intrinsic::amdgcn_struct_buffer_load: 6769 case Intrinsic::amdgcn_struct_buffer_load_format: { 6770 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6771 6772 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6773 SDValue Ops[] = { 6774 Op.getOperand(0), // Chain 6775 Op.getOperand(2), // rsrc 6776 Op.getOperand(3), // vindex 6777 Offsets.first, // voffset 6778 Op.getOperand(5), // soffset 6779 Offsets.second, // offset 6780 Op.getOperand(6), // cachepolicy, swizzled buffer 6781 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6782 }; 6783 6784 auto *M = cast<MemSDNode>(Op); 6785 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6786 Ops[2])); 6787 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6788 } 6789 case Intrinsic::amdgcn_tbuffer_load: { 6790 MemSDNode *M = cast<MemSDNode>(Op); 6791 EVT LoadVT = Op.getValueType(); 6792 6793 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6794 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6795 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6796 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6797 unsigned IdxEn = 1; 6798 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6799 IdxEn = Idx->getZExtValue() != 0; 6800 SDValue Ops[] = { 6801 Op.getOperand(0), // Chain 6802 Op.getOperand(2), // rsrc 6803 Op.getOperand(3), // vindex 6804 Op.getOperand(4), // voffset 6805 Op.getOperand(5), // soffset 6806 Op.getOperand(6), // offset 6807 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6808 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6809 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6810 }; 6811 6812 if (LoadVT.getScalarType() == MVT::f16) 6813 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6814 M, DAG, Ops); 6815 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6816 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6817 DAG); 6818 } 6819 case Intrinsic::amdgcn_raw_tbuffer_load: { 6820 MemSDNode *M = cast<MemSDNode>(Op); 6821 EVT LoadVT = Op.getValueType(); 6822 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6823 6824 SDValue Ops[] = { 6825 Op.getOperand(0), // Chain 6826 Op.getOperand(2), // rsrc 6827 DAG.getConstant(0, DL, MVT::i32), // vindex 6828 Offsets.first, // voffset 6829 Op.getOperand(4), // soffset 6830 Offsets.second, // offset 6831 Op.getOperand(5), // format 6832 Op.getOperand(6), // cachepolicy, swizzled buffer 6833 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6834 }; 6835 6836 if (LoadVT.getScalarType() == MVT::f16) 6837 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6838 M, DAG, Ops); 6839 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6840 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6841 DAG); 6842 } 6843 case Intrinsic::amdgcn_struct_tbuffer_load: { 6844 MemSDNode *M = cast<MemSDNode>(Op); 6845 EVT LoadVT = Op.getValueType(); 6846 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6847 6848 SDValue Ops[] = { 6849 Op.getOperand(0), // Chain 6850 Op.getOperand(2), // rsrc 6851 Op.getOperand(3), // vindex 6852 Offsets.first, // voffset 6853 Op.getOperand(5), // soffset 6854 Offsets.second, // offset 6855 Op.getOperand(6), // format 6856 Op.getOperand(7), // cachepolicy, swizzled buffer 6857 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6858 }; 6859 6860 if (LoadVT.getScalarType() == MVT::f16) 6861 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6862 M, DAG, Ops); 6863 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6864 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6865 DAG); 6866 } 6867 case Intrinsic::amdgcn_buffer_atomic_swap: 6868 case Intrinsic::amdgcn_buffer_atomic_add: 6869 case Intrinsic::amdgcn_buffer_atomic_sub: 6870 case Intrinsic::amdgcn_buffer_atomic_csub: 6871 case Intrinsic::amdgcn_buffer_atomic_smin: 6872 case Intrinsic::amdgcn_buffer_atomic_umin: 6873 case Intrinsic::amdgcn_buffer_atomic_smax: 6874 case Intrinsic::amdgcn_buffer_atomic_umax: 6875 case Intrinsic::amdgcn_buffer_atomic_and: 6876 case Intrinsic::amdgcn_buffer_atomic_or: 6877 case Intrinsic::amdgcn_buffer_atomic_xor: { 6878 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6879 unsigned IdxEn = 1; 6880 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6881 IdxEn = Idx->getZExtValue() != 0; 6882 SDValue Ops[] = { 6883 Op.getOperand(0), // Chain 6884 Op.getOperand(2), // vdata 6885 Op.getOperand(3), // rsrc 6886 Op.getOperand(4), // vindex 6887 SDValue(), // voffset -- will be set by setBufferOffsets 6888 SDValue(), // soffset -- will be set by setBufferOffsets 6889 SDValue(), // offset -- will be set by setBufferOffsets 6890 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6891 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6892 }; 6893 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6894 // We don't know the offset if vindex is non-zero, so clear it. 6895 if (IdxEn) 6896 Offset = 0; 6897 EVT VT = Op.getValueType(); 6898 6899 auto *M = cast<MemSDNode>(Op); 6900 M->getMemOperand()->setOffset(Offset); 6901 unsigned Opcode = 0; 6902 6903 switch (IntrID) { 6904 case Intrinsic::amdgcn_buffer_atomic_swap: 6905 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6906 break; 6907 case Intrinsic::amdgcn_buffer_atomic_add: 6908 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6909 break; 6910 case Intrinsic::amdgcn_buffer_atomic_sub: 6911 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6912 break; 6913 case Intrinsic::amdgcn_buffer_atomic_csub: 6914 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 6915 break; 6916 case Intrinsic::amdgcn_buffer_atomic_smin: 6917 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6918 break; 6919 case Intrinsic::amdgcn_buffer_atomic_umin: 6920 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6921 break; 6922 case Intrinsic::amdgcn_buffer_atomic_smax: 6923 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6924 break; 6925 case Intrinsic::amdgcn_buffer_atomic_umax: 6926 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6927 break; 6928 case Intrinsic::amdgcn_buffer_atomic_and: 6929 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6930 break; 6931 case Intrinsic::amdgcn_buffer_atomic_or: 6932 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6933 break; 6934 case Intrinsic::amdgcn_buffer_atomic_xor: 6935 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6936 break; 6937 default: 6938 llvm_unreachable("unhandled atomic opcode"); 6939 } 6940 6941 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6942 M->getMemOperand()); 6943 } 6944 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6945 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6946 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6947 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6948 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6949 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6950 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6951 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6952 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6953 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6954 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6955 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6956 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6957 SDValue Ops[] = { 6958 Op.getOperand(0), // Chain 6959 Op.getOperand(2), // vdata 6960 Op.getOperand(3), // rsrc 6961 DAG.getConstant(0, DL, MVT::i32), // vindex 6962 Offsets.first, // voffset 6963 Op.getOperand(5), // soffset 6964 Offsets.second, // offset 6965 Op.getOperand(6), // cachepolicy 6966 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6967 }; 6968 EVT VT = Op.getValueType(); 6969 6970 auto *M = cast<MemSDNode>(Op); 6971 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6972 unsigned Opcode = 0; 6973 6974 switch (IntrID) { 6975 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6976 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6977 break; 6978 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6979 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6980 break; 6981 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6982 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6983 break; 6984 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6985 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6986 break; 6987 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6988 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6989 break; 6990 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6991 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6992 break; 6993 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6994 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6995 break; 6996 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6997 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6998 break; 6999 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7000 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7001 break; 7002 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7003 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7004 break; 7005 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7006 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7007 break; 7008 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7009 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7010 break; 7011 default: 7012 llvm_unreachable("unhandled atomic opcode"); 7013 } 7014 7015 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7016 M->getMemOperand()); 7017 } 7018 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7019 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7020 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7021 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7022 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7023 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7024 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7025 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7026 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7027 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7028 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7029 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 7030 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7031 SDValue Ops[] = { 7032 Op.getOperand(0), // Chain 7033 Op.getOperand(2), // vdata 7034 Op.getOperand(3), // rsrc 7035 Op.getOperand(4), // vindex 7036 Offsets.first, // voffset 7037 Op.getOperand(6), // soffset 7038 Offsets.second, // offset 7039 Op.getOperand(7), // cachepolicy 7040 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7041 }; 7042 EVT VT = Op.getValueType(); 7043 7044 auto *M = cast<MemSDNode>(Op); 7045 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7046 Ops[3])); 7047 unsigned Opcode = 0; 7048 7049 switch (IntrID) { 7050 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7051 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7052 break; 7053 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7054 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7055 break; 7056 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7057 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7058 break; 7059 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7060 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7061 break; 7062 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7063 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7064 break; 7065 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7066 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7067 break; 7068 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7069 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7070 break; 7071 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7072 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7073 break; 7074 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7075 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7076 break; 7077 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7078 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7079 break; 7080 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7081 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7082 break; 7083 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7084 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7085 break; 7086 default: 7087 llvm_unreachable("unhandled atomic opcode"); 7088 } 7089 7090 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7091 M->getMemOperand()); 7092 } 7093 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7094 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7095 unsigned IdxEn = 1; 7096 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7097 IdxEn = Idx->getZExtValue() != 0; 7098 SDValue Ops[] = { 7099 Op.getOperand(0), // Chain 7100 Op.getOperand(2), // src 7101 Op.getOperand(3), // cmp 7102 Op.getOperand(4), // rsrc 7103 Op.getOperand(5), // vindex 7104 SDValue(), // voffset -- will be set by setBufferOffsets 7105 SDValue(), // soffset -- will be set by setBufferOffsets 7106 SDValue(), // offset -- will be set by setBufferOffsets 7107 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7108 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7109 }; 7110 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7111 // We don't know the offset if vindex is non-zero, so clear it. 7112 if (IdxEn) 7113 Offset = 0; 7114 EVT VT = Op.getValueType(); 7115 auto *M = cast<MemSDNode>(Op); 7116 M->getMemOperand()->setOffset(Offset); 7117 7118 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7119 Op->getVTList(), Ops, VT, M->getMemOperand()); 7120 } 7121 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7122 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7123 SDValue Ops[] = { 7124 Op.getOperand(0), // Chain 7125 Op.getOperand(2), // src 7126 Op.getOperand(3), // cmp 7127 Op.getOperand(4), // rsrc 7128 DAG.getConstant(0, DL, MVT::i32), // vindex 7129 Offsets.first, // voffset 7130 Op.getOperand(6), // soffset 7131 Offsets.second, // offset 7132 Op.getOperand(7), // cachepolicy 7133 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7134 }; 7135 EVT VT = Op.getValueType(); 7136 auto *M = cast<MemSDNode>(Op); 7137 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7138 7139 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7140 Op->getVTList(), Ops, VT, M->getMemOperand()); 7141 } 7142 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7143 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7144 SDValue Ops[] = { 7145 Op.getOperand(0), // Chain 7146 Op.getOperand(2), // src 7147 Op.getOperand(3), // cmp 7148 Op.getOperand(4), // rsrc 7149 Op.getOperand(5), // vindex 7150 Offsets.first, // voffset 7151 Op.getOperand(7), // soffset 7152 Offsets.second, // offset 7153 Op.getOperand(8), // cachepolicy 7154 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7155 }; 7156 EVT VT = Op.getValueType(); 7157 auto *M = cast<MemSDNode>(Op); 7158 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7159 Ops[4])); 7160 7161 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7162 Op->getVTList(), Ops, VT, M->getMemOperand()); 7163 } 7164 case Intrinsic::amdgcn_global_atomic_csub: { 7165 MemSDNode *M = cast<MemSDNode>(Op); 7166 SDValue Ops[] = { 7167 M->getOperand(0), // Chain 7168 M->getOperand(2), // Ptr 7169 M->getOperand(3) // Value 7170 }; 7171 7172 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_LOAD_CSUB, SDLoc(Op), 7173 M->getVTList(), Ops, M->getMemoryVT(), 7174 M->getMemOperand()); 7175 } 7176 7177 default: 7178 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7179 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7180 return lowerImage(Op, ImageDimIntr, DAG); 7181 7182 return SDValue(); 7183 } 7184 } 7185 7186 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7187 // dwordx4 if on SI. 7188 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7189 SDVTList VTList, 7190 ArrayRef<SDValue> Ops, EVT MemVT, 7191 MachineMemOperand *MMO, 7192 SelectionDAG &DAG) const { 7193 EVT VT = VTList.VTs[0]; 7194 EVT WidenedVT = VT; 7195 EVT WidenedMemVT = MemVT; 7196 if (!Subtarget->hasDwordx3LoadStores() && 7197 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7198 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7199 WidenedVT.getVectorElementType(), 4); 7200 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7201 WidenedMemVT.getVectorElementType(), 4); 7202 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7203 } 7204 7205 assert(VTList.NumVTs == 2); 7206 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7207 7208 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7209 WidenedMemVT, MMO); 7210 if (WidenedVT != VT) { 7211 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7212 DAG.getVectorIdxConstant(0, DL)); 7213 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7214 } 7215 return NewOp; 7216 } 7217 7218 SDValue SITargetLowering::handleD16VData(SDValue VData, 7219 SelectionDAG &DAG) const { 7220 EVT StoreVT = VData.getValueType(); 7221 7222 // No change for f16 and legal vector D16 types. 7223 if (!StoreVT.isVector()) 7224 return VData; 7225 7226 SDLoc DL(VData); 7227 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7228 7229 if (Subtarget->hasUnpackedD16VMem()) { 7230 // We need to unpack the packed data to store. 7231 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7232 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7233 7234 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7235 StoreVT.getVectorNumElements()); 7236 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7237 return DAG.UnrollVectorOp(ZExt.getNode()); 7238 } 7239 7240 assert(isTypeLegal(StoreVT)); 7241 return VData; 7242 } 7243 7244 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7245 SelectionDAG &DAG) const { 7246 SDLoc DL(Op); 7247 SDValue Chain = Op.getOperand(0); 7248 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7249 MachineFunction &MF = DAG.getMachineFunction(); 7250 7251 switch (IntrinsicID) { 7252 case Intrinsic::amdgcn_exp_compr: { 7253 SDValue Src0 = Op.getOperand(4); 7254 SDValue Src1 = Op.getOperand(5); 7255 // Hack around illegal type on SI by directly selecting it. 7256 if (isTypeLegal(Src0.getValueType())) 7257 return SDValue(); 7258 7259 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7260 SDValue Undef = DAG.getUNDEF(MVT::f32); 7261 const SDValue Ops[] = { 7262 Op.getOperand(2), // tgt 7263 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7264 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7265 Undef, // src2 7266 Undef, // src3 7267 Op.getOperand(7), // vm 7268 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7269 Op.getOperand(3), // en 7270 Op.getOperand(0) // Chain 7271 }; 7272 7273 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7274 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7275 } 7276 case Intrinsic::amdgcn_s_barrier: { 7277 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7278 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7279 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7280 if (WGSize <= ST.getWavefrontSize()) 7281 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7282 Op.getOperand(0)), 0); 7283 } 7284 return SDValue(); 7285 }; 7286 case Intrinsic::amdgcn_tbuffer_store: { 7287 SDValue VData = Op.getOperand(2); 7288 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7289 if (IsD16) 7290 VData = handleD16VData(VData, DAG); 7291 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7292 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7293 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7294 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7295 unsigned IdxEn = 1; 7296 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7297 IdxEn = Idx->getZExtValue() != 0; 7298 SDValue Ops[] = { 7299 Chain, 7300 VData, // vdata 7301 Op.getOperand(3), // rsrc 7302 Op.getOperand(4), // vindex 7303 Op.getOperand(5), // voffset 7304 Op.getOperand(6), // soffset 7305 Op.getOperand(7), // offset 7306 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7307 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7308 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7309 }; 7310 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7311 AMDGPUISD::TBUFFER_STORE_FORMAT; 7312 MemSDNode *M = cast<MemSDNode>(Op); 7313 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7314 M->getMemoryVT(), M->getMemOperand()); 7315 } 7316 7317 case Intrinsic::amdgcn_struct_tbuffer_store: { 7318 SDValue VData = Op.getOperand(2); 7319 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7320 if (IsD16) 7321 VData = handleD16VData(VData, DAG); 7322 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7323 SDValue Ops[] = { 7324 Chain, 7325 VData, // vdata 7326 Op.getOperand(3), // rsrc 7327 Op.getOperand(4), // vindex 7328 Offsets.first, // voffset 7329 Op.getOperand(6), // soffset 7330 Offsets.second, // offset 7331 Op.getOperand(7), // format 7332 Op.getOperand(8), // cachepolicy, swizzled buffer 7333 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7334 }; 7335 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7336 AMDGPUISD::TBUFFER_STORE_FORMAT; 7337 MemSDNode *M = cast<MemSDNode>(Op); 7338 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7339 M->getMemoryVT(), M->getMemOperand()); 7340 } 7341 7342 case Intrinsic::amdgcn_raw_tbuffer_store: { 7343 SDValue VData = Op.getOperand(2); 7344 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7345 if (IsD16) 7346 VData = handleD16VData(VData, DAG); 7347 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7348 SDValue Ops[] = { 7349 Chain, 7350 VData, // vdata 7351 Op.getOperand(3), // rsrc 7352 DAG.getConstant(0, DL, MVT::i32), // vindex 7353 Offsets.first, // voffset 7354 Op.getOperand(5), // soffset 7355 Offsets.second, // offset 7356 Op.getOperand(6), // format 7357 Op.getOperand(7), // cachepolicy, swizzled buffer 7358 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7359 }; 7360 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7361 AMDGPUISD::TBUFFER_STORE_FORMAT; 7362 MemSDNode *M = cast<MemSDNode>(Op); 7363 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7364 M->getMemoryVT(), M->getMemOperand()); 7365 } 7366 7367 case Intrinsic::amdgcn_buffer_store: 7368 case Intrinsic::amdgcn_buffer_store_format: { 7369 SDValue VData = Op.getOperand(2); 7370 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7371 if (IsD16) 7372 VData = handleD16VData(VData, DAG); 7373 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7374 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7375 unsigned IdxEn = 1; 7376 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7377 IdxEn = Idx->getZExtValue() != 0; 7378 SDValue Ops[] = { 7379 Chain, 7380 VData, 7381 Op.getOperand(3), // rsrc 7382 Op.getOperand(4), // vindex 7383 SDValue(), // voffset -- will be set by setBufferOffsets 7384 SDValue(), // soffset -- will be set by setBufferOffsets 7385 SDValue(), // offset -- will be set by setBufferOffsets 7386 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7387 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7388 }; 7389 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7390 // We don't know the offset if vindex is non-zero, so clear it. 7391 if (IdxEn) 7392 Offset = 0; 7393 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7394 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7395 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7396 MemSDNode *M = cast<MemSDNode>(Op); 7397 M->getMemOperand()->setOffset(Offset); 7398 7399 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7400 EVT VDataType = VData.getValueType().getScalarType(); 7401 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7402 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7403 7404 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7405 M->getMemoryVT(), M->getMemOperand()); 7406 } 7407 7408 case Intrinsic::amdgcn_raw_buffer_store: 7409 case Intrinsic::amdgcn_raw_buffer_store_format: { 7410 const bool IsFormat = 7411 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7412 7413 SDValue VData = Op.getOperand(2); 7414 EVT VDataVT = VData.getValueType(); 7415 EVT EltType = VDataVT.getScalarType(); 7416 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7417 if (IsD16) 7418 VData = handleD16VData(VData, DAG); 7419 7420 if (!isTypeLegal(VDataVT)) { 7421 VData = 7422 DAG.getNode(ISD::BITCAST, DL, 7423 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7424 } 7425 7426 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7427 SDValue Ops[] = { 7428 Chain, 7429 VData, 7430 Op.getOperand(3), // rsrc 7431 DAG.getConstant(0, DL, MVT::i32), // vindex 7432 Offsets.first, // voffset 7433 Op.getOperand(5), // soffset 7434 Offsets.second, // offset 7435 Op.getOperand(6), // cachepolicy, swizzled buffer 7436 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7437 }; 7438 unsigned Opc = 7439 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7440 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7441 MemSDNode *M = cast<MemSDNode>(Op); 7442 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7443 7444 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7445 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7446 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7447 7448 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7449 M->getMemoryVT(), M->getMemOperand()); 7450 } 7451 7452 case Intrinsic::amdgcn_struct_buffer_store: 7453 case Intrinsic::amdgcn_struct_buffer_store_format: { 7454 const bool IsFormat = 7455 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7456 7457 SDValue VData = Op.getOperand(2); 7458 EVT VDataVT = VData.getValueType(); 7459 EVT EltType = VDataVT.getScalarType(); 7460 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7461 7462 if (IsD16) 7463 VData = handleD16VData(VData, DAG); 7464 7465 if (!isTypeLegal(VDataVT)) { 7466 VData = 7467 DAG.getNode(ISD::BITCAST, DL, 7468 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7469 } 7470 7471 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7472 SDValue Ops[] = { 7473 Chain, 7474 VData, 7475 Op.getOperand(3), // rsrc 7476 Op.getOperand(4), // vindex 7477 Offsets.first, // voffset 7478 Op.getOperand(6), // soffset 7479 Offsets.second, // offset 7480 Op.getOperand(7), // cachepolicy, swizzled buffer 7481 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7482 }; 7483 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7484 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7485 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7486 MemSDNode *M = cast<MemSDNode>(Op); 7487 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7488 Ops[3])); 7489 7490 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7491 EVT VDataType = VData.getValueType().getScalarType(); 7492 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7493 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7494 7495 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7496 M->getMemoryVT(), M->getMemOperand()); 7497 } 7498 7499 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7500 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7501 unsigned IdxEn = 1; 7502 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7503 IdxEn = Idx->getZExtValue() != 0; 7504 SDValue Ops[] = { 7505 Chain, 7506 Op.getOperand(2), // vdata 7507 Op.getOperand(3), // rsrc 7508 Op.getOperand(4), // vindex 7509 SDValue(), // voffset -- will be set by setBufferOffsets 7510 SDValue(), // soffset -- will be set by setBufferOffsets 7511 SDValue(), // offset -- will be set by setBufferOffsets 7512 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7513 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7514 }; 7515 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7516 // We don't know the offset if vindex is non-zero, so clear it. 7517 if (IdxEn) 7518 Offset = 0; 7519 EVT VT = Op.getOperand(2).getValueType(); 7520 7521 auto *M = cast<MemSDNode>(Op); 7522 M->getMemOperand()->setOffset(Offset); 7523 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7524 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7525 7526 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7527 M->getMemOperand()); 7528 } 7529 7530 case Intrinsic::amdgcn_global_atomic_fadd: { 7531 SDValue Ops[] = { 7532 Chain, 7533 Op.getOperand(2), // ptr 7534 Op.getOperand(3) // vdata 7535 }; 7536 EVT VT = Op.getOperand(3).getValueType(); 7537 7538 auto *M = cast<MemSDNode>(Op); 7539 if (VT.isVector()) { 7540 return DAG.getMemIntrinsicNode( 7541 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7542 M->getMemOperand()); 7543 } 7544 7545 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7546 DAG.getVTList(VT, MVT::Other), Ops, 7547 M->getMemOperand()).getValue(1); 7548 } 7549 case Intrinsic::amdgcn_end_cf: 7550 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7551 Op->getOperand(2), Chain), 0); 7552 7553 default: { 7554 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7555 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7556 return lowerImage(Op, ImageDimIntr, DAG); 7557 7558 return Op; 7559 } 7560 } 7561 } 7562 7563 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7564 // offset (the offset that is included in bounds checking and swizzling, to be 7565 // split between the instruction's voffset and immoffset fields) and soffset 7566 // (the offset that is excluded from bounds checking and swizzling, to go in 7567 // the instruction's soffset field). This function takes the first kind of 7568 // offset and figures out how to split it between voffset and immoffset. 7569 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7570 SDValue Offset, SelectionDAG &DAG) const { 7571 SDLoc DL(Offset); 7572 const unsigned MaxImm = 4095; 7573 SDValue N0 = Offset; 7574 ConstantSDNode *C1 = nullptr; 7575 7576 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7577 N0 = SDValue(); 7578 else if (DAG.isBaseWithConstantOffset(N0)) { 7579 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7580 N0 = N0.getOperand(0); 7581 } 7582 7583 if (C1) { 7584 unsigned ImmOffset = C1->getZExtValue(); 7585 // If the immediate value is too big for the immoffset field, put the value 7586 // and -4096 into the immoffset field so that the value that is copied/added 7587 // for the voffset field is a multiple of 4096, and it stands more chance 7588 // of being CSEd with the copy/add for another similar load/store. 7589 // However, do not do that rounding down to a multiple of 4096 if that is a 7590 // negative number, as it appears to be illegal to have a negative offset 7591 // in the vgpr, even if adding the immediate offset makes it positive. 7592 unsigned Overflow = ImmOffset & ~MaxImm; 7593 ImmOffset -= Overflow; 7594 if ((int32_t)Overflow < 0) { 7595 Overflow += ImmOffset; 7596 ImmOffset = 0; 7597 } 7598 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7599 if (Overflow) { 7600 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7601 if (!N0) 7602 N0 = OverflowVal; 7603 else { 7604 SDValue Ops[] = { N0, OverflowVal }; 7605 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7606 } 7607 } 7608 } 7609 if (!N0) 7610 N0 = DAG.getConstant(0, DL, MVT::i32); 7611 if (!C1) 7612 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7613 return {N0, SDValue(C1, 0)}; 7614 } 7615 7616 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7617 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7618 // pointed to by Offsets. 7619 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7620 SelectionDAG &DAG, SDValue *Offsets, 7621 unsigned Align) const { 7622 SDLoc DL(CombinedOffset); 7623 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7624 uint32_t Imm = C->getZExtValue(); 7625 uint32_t SOffset, ImmOffset; 7626 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7627 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7628 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7629 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7630 return SOffset + ImmOffset; 7631 } 7632 } 7633 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7634 SDValue N0 = CombinedOffset.getOperand(0); 7635 SDValue N1 = CombinedOffset.getOperand(1); 7636 uint32_t SOffset, ImmOffset; 7637 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7638 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7639 Subtarget, Align)) { 7640 Offsets[0] = N0; 7641 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7642 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7643 return 0; 7644 } 7645 } 7646 Offsets[0] = CombinedOffset; 7647 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7648 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7649 return 0; 7650 } 7651 7652 // Handle 8 bit and 16 bit buffer loads 7653 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7654 EVT LoadVT, SDLoc DL, 7655 ArrayRef<SDValue> Ops, 7656 MemSDNode *M) const { 7657 EVT IntVT = LoadVT.changeTypeToInteger(); 7658 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7659 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7660 7661 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7662 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7663 Ops, IntVT, 7664 M->getMemOperand()); 7665 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7666 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7667 7668 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7669 } 7670 7671 // Handle 8 bit and 16 bit buffer stores 7672 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7673 EVT VDataType, SDLoc DL, 7674 SDValue Ops[], 7675 MemSDNode *M) const { 7676 if (VDataType == MVT::f16) 7677 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7678 7679 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7680 Ops[1] = BufferStoreExt; 7681 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7682 AMDGPUISD::BUFFER_STORE_SHORT; 7683 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7684 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7685 M->getMemOperand()); 7686 } 7687 7688 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7689 ISD::LoadExtType ExtType, SDValue Op, 7690 const SDLoc &SL, EVT VT) { 7691 if (VT.bitsLT(Op.getValueType())) 7692 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7693 7694 switch (ExtType) { 7695 case ISD::SEXTLOAD: 7696 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7697 case ISD::ZEXTLOAD: 7698 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7699 case ISD::EXTLOAD: 7700 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7701 case ISD::NON_EXTLOAD: 7702 return Op; 7703 } 7704 7705 llvm_unreachable("invalid ext type"); 7706 } 7707 7708 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7709 SelectionDAG &DAG = DCI.DAG; 7710 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7711 return SDValue(); 7712 7713 // FIXME: Constant loads should all be marked invariant. 7714 unsigned AS = Ld->getAddressSpace(); 7715 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7716 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7717 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7718 return SDValue(); 7719 7720 // Don't do this early, since it may interfere with adjacent load merging for 7721 // illegal types. We can avoid losing alignment information for exotic types 7722 // pre-legalize. 7723 EVT MemVT = Ld->getMemoryVT(); 7724 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7725 MemVT.getSizeInBits() >= 32) 7726 return SDValue(); 7727 7728 SDLoc SL(Ld); 7729 7730 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7731 "unexpected vector extload"); 7732 7733 // TODO: Drop only high part of range. 7734 SDValue Ptr = Ld->getBasePtr(); 7735 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7736 MVT::i32, SL, Ld->getChain(), Ptr, 7737 Ld->getOffset(), 7738 Ld->getPointerInfo(), MVT::i32, 7739 Ld->getAlignment(), 7740 Ld->getMemOperand()->getFlags(), 7741 Ld->getAAInfo(), 7742 nullptr); // Drop ranges 7743 7744 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7745 if (MemVT.isFloatingPoint()) { 7746 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7747 "unexpected fp extload"); 7748 TruncVT = MemVT.changeTypeToInteger(); 7749 } 7750 7751 SDValue Cvt = NewLoad; 7752 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7753 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7754 DAG.getValueType(TruncVT)); 7755 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7756 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7757 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7758 } else { 7759 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7760 } 7761 7762 EVT VT = Ld->getValueType(0); 7763 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7764 7765 DCI.AddToWorklist(Cvt.getNode()); 7766 7767 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7768 // the appropriate extension from the 32-bit load. 7769 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7770 DCI.AddToWorklist(Cvt.getNode()); 7771 7772 // Handle conversion back to floating point if necessary. 7773 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7774 7775 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7776 } 7777 7778 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7779 SDLoc DL(Op); 7780 LoadSDNode *Load = cast<LoadSDNode>(Op); 7781 ISD::LoadExtType ExtType = Load->getExtensionType(); 7782 EVT MemVT = Load->getMemoryVT(); 7783 7784 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7785 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7786 return SDValue(); 7787 7788 // FIXME: Copied from PPC 7789 // First, load into 32 bits, then truncate to 1 bit. 7790 7791 SDValue Chain = Load->getChain(); 7792 SDValue BasePtr = Load->getBasePtr(); 7793 MachineMemOperand *MMO = Load->getMemOperand(); 7794 7795 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7796 7797 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7798 BasePtr, RealMemVT, MMO); 7799 7800 if (!MemVT.isVector()) { 7801 SDValue Ops[] = { 7802 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7803 NewLD.getValue(1) 7804 }; 7805 7806 return DAG.getMergeValues(Ops, DL); 7807 } 7808 7809 SmallVector<SDValue, 3> Elts; 7810 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7811 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7812 DAG.getConstant(I, DL, MVT::i32)); 7813 7814 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7815 } 7816 7817 SDValue Ops[] = { 7818 DAG.getBuildVector(MemVT, DL, Elts), 7819 NewLD.getValue(1) 7820 }; 7821 7822 return DAG.getMergeValues(Ops, DL); 7823 } 7824 7825 if (!MemVT.isVector()) 7826 return SDValue(); 7827 7828 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7829 "Custom lowering for non-i32 vectors hasn't been implemented."); 7830 7831 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7832 MemVT, *Load->getMemOperand())) { 7833 SDValue Ops[2]; 7834 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7835 return DAG.getMergeValues(Ops, DL); 7836 } 7837 7838 unsigned Alignment = Load->getAlignment(); 7839 unsigned AS = Load->getAddressSpace(); 7840 if (Subtarget->hasLDSMisalignedBug() && 7841 AS == AMDGPUAS::FLAT_ADDRESS && 7842 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7843 return SplitVectorLoad(Op, DAG); 7844 } 7845 7846 MachineFunction &MF = DAG.getMachineFunction(); 7847 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7848 // If there is a possibilty that flat instruction access scratch memory 7849 // then we need to use the same legalization rules we use for private. 7850 if (AS == AMDGPUAS::FLAT_ADDRESS && 7851 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7852 AS = MFI->hasFlatScratchInit() ? 7853 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7854 7855 unsigned NumElements = MemVT.getVectorNumElements(); 7856 7857 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7858 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7859 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7860 if (MemVT.isPow2VectorType()) 7861 return SDValue(); 7862 if (NumElements == 3) 7863 return WidenVectorLoad(Op, DAG); 7864 return SplitVectorLoad(Op, DAG); 7865 } 7866 // Non-uniform loads will be selected to MUBUF instructions, so they 7867 // have the same legalization requirements as global and private 7868 // loads. 7869 // 7870 } 7871 7872 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7873 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7874 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7875 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7876 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7877 Alignment >= 4 && NumElements < 32) { 7878 if (MemVT.isPow2VectorType()) 7879 return SDValue(); 7880 if (NumElements == 3) 7881 return WidenVectorLoad(Op, DAG); 7882 return SplitVectorLoad(Op, DAG); 7883 } 7884 // Non-uniform loads will be selected to MUBUF instructions, so they 7885 // have the same legalization requirements as global and private 7886 // loads. 7887 // 7888 } 7889 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7890 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7891 AS == AMDGPUAS::GLOBAL_ADDRESS || 7892 AS == AMDGPUAS::FLAT_ADDRESS) { 7893 if (NumElements > 4) 7894 return SplitVectorLoad(Op, DAG); 7895 // v3 loads not supported on SI. 7896 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7897 return WidenVectorLoad(Op, DAG); 7898 // v3 and v4 loads are supported for private and global memory. 7899 return SDValue(); 7900 } 7901 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7902 // Depending on the setting of the private_element_size field in the 7903 // resource descriptor, we can only make private accesses up to a certain 7904 // size. 7905 switch (Subtarget->getMaxPrivateElementSize()) { 7906 case 4: { 7907 SDValue Ops[2]; 7908 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7909 return DAG.getMergeValues(Ops, DL); 7910 } 7911 case 8: 7912 if (NumElements > 2) 7913 return SplitVectorLoad(Op, DAG); 7914 return SDValue(); 7915 case 16: 7916 // Same as global/flat 7917 if (NumElements > 4) 7918 return SplitVectorLoad(Op, DAG); 7919 // v3 loads not supported on SI. 7920 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7921 return WidenVectorLoad(Op, DAG); 7922 return SDValue(); 7923 default: 7924 llvm_unreachable("unsupported private_element_size"); 7925 } 7926 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7927 // Use ds_read_b128 if possible. 7928 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7929 MemVT.getStoreSize() == 16) 7930 return SDValue(); 7931 7932 if (NumElements > 2) 7933 return SplitVectorLoad(Op, DAG); 7934 7935 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7936 // address is negative, then the instruction is incorrectly treated as 7937 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7938 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7939 // load later in the SILoadStoreOptimizer. 7940 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7941 NumElements == 2 && MemVT.getStoreSize() == 8 && 7942 Load->getAlignment() < 8) { 7943 return SplitVectorLoad(Op, DAG); 7944 } 7945 } 7946 return SDValue(); 7947 } 7948 7949 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7950 EVT VT = Op.getValueType(); 7951 assert(VT.getSizeInBits() == 64); 7952 7953 SDLoc DL(Op); 7954 SDValue Cond = Op.getOperand(0); 7955 7956 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7957 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7958 7959 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7960 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7961 7962 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7963 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7964 7965 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7966 7967 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7968 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7969 7970 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7971 7972 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7973 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7974 } 7975 7976 // Catch division cases where we can use shortcuts with rcp and rsq 7977 // instructions. 7978 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7979 SelectionDAG &DAG) const { 7980 SDLoc SL(Op); 7981 SDValue LHS = Op.getOperand(0); 7982 SDValue RHS = Op.getOperand(1); 7983 EVT VT = Op.getValueType(); 7984 const SDNodeFlags Flags = Op->getFlags(); 7985 7986 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7987 Flags.hasApproximateFuncs(); 7988 7989 // Without !fpmath accuracy information, we can't do more because we don't 7990 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7991 if (!AllowInaccurateRcp) 7992 return SDValue(); 7993 7994 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7995 if (CLHS->isExactlyValue(1.0)) { 7996 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7997 // the CI documentation has a worst case error of 1 ulp. 7998 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7999 // use it as long as we aren't trying to use denormals. 8000 // 8001 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8002 8003 // 1.0 / sqrt(x) -> rsq(x) 8004 8005 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8006 // error seems really high at 2^29 ULP. 8007 if (RHS.getOpcode() == ISD::FSQRT) 8008 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8009 8010 // 1.0 / x -> rcp(x) 8011 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8012 } 8013 8014 // Same as for 1.0, but expand the sign out of the constant. 8015 if (CLHS->isExactlyValue(-1.0)) { 8016 // -1.0 / x -> rcp (fneg x) 8017 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8018 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8019 } 8020 } 8021 8022 // Turn into multiply by the reciprocal. 8023 // x / y -> x * (1.0 / y) 8024 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8025 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8026 } 8027 8028 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8029 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8030 SDNodeFlags Flags) { 8031 if (GlueChain->getNumValues() <= 1) { 8032 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8033 } 8034 8035 assert(GlueChain->getNumValues() == 3); 8036 8037 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8038 switch (Opcode) { 8039 default: llvm_unreachable("no chain equivalent for opcode"); 8040 case ISD::FMUL: 8041 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8042 break; 8043 } 8044 8045 return DAG.getNode(Opcode, SL, VTList, 8046 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8047 Flags); 8048 } 8049 8050 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8051 EVT VT, SDValue A, SDValue B, SDValue C, 8052 SDValue GlueChain, SDNodeFlags Flags) { 8053 if (GlueChain->getNumValues() <= 1) { 8054 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8055 } 8056 8057 assert(GlueChain->getNumValues() == 3); 8058 8059 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8060 switch (Opcode) { 8061 default: llvm_unreachable("no chain equivalent for opcode"); 8062 case ISD::FMA: 8063 Opcode = AMDGPUISD::FMA_W_CHAIN; 8064 break; 8065 } 8066 8067 return DAG.getNode(Opcode, SL, VTList, 8068 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8069 Flags); 8070 } 8071 8072 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8073 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8074 return FastLowered; 8075 8076 SDLoc SL(Op); 8077 SDValue Src0 = Op.getOperand(0); 8078 SDValue Src1 = Op.getOperand(1); 8079 8080 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8081 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8082 8083 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8084 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8085 8086 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8087 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8088 8089 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8090 } 8091 8092 // Faster 2.5 ULP division that does not support denormals. 8093 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8094 SDLoc SL(Op); 8095 SDValue LHS = Op.getOperand(1); 8096 SDValue RHS = Op.getOperand(2); 8097 8098 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8099 8100 const APFloat K0Val(BitsToFloat(0x6f800000)); 8101 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8102 8103 const APFloat K1Val(BitsToFloat(0x2f800000)); 8104 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8105 8106 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8107 8108 EVT SetCCVT = 8109 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8110 8111 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8112 8113 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8114 8115 // TODO: Should this propagate fast-math-flags? 8116 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8117 8118 // rcp does not support denormals. 8119 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8120 8121 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8122 8123 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8124 } 8125 8126 // Returns immediate value for setting the F32 denorm mode when using the 8127 // S_DENORM_MODE instruction. 8128 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8129 const SDLoc &SL, const GCNSubtarget *ST) { 8130 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8131 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8132 ? FP_DENORM_FLUSH_NONE 8133 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8134 8135 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8136 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8137 } 8138 8139 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8140 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8141 return FastLowered; 8142 8143 // The selection matcher assumes anything with a chain selecting to a 8144 // mayRaiseFPException machine instruction. Since we're introducing a chain 8145 // here, we need to explicitly report nofpexcept for the regular fdiv 8146 // lowering. 8147 SDNodeFlags Flags = Op->getFlags(); 8148 Flags.setNoFPExcept(true); 8149 8150 SDLoc SL(Op); 8151 SDValue LHS = Op.getOperand(0); 8152 SDValue RHS = Op.getOperand(1); 8153 8154 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8155 8156 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8157 8158 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8159 {RHS, RHS, LHS}, Flags); 8160 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8161 {LHS, RHS, LHS}, Flags); 8162 8163 // Denominator is scaled to not be denormal, so using rcp is ok. 8164 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8165 DenominatorScaled, Flags); 8166 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8167 DenominatorScaled, Flags); 8168 8169 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8170 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8171 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8172 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8173 8174 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8175 8176 if (!HasFP32Denormals) { 8177 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8178 // lowering. The chain dependence is insufficient, and we need glue. We do 8179 // not need the glue variants in a strictfp function. 8180 8181 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8182 8183 SDNode *EnableDenorm; 8184 if (Subtarget->hasDenormModeInst()) { 8185 const SDValue EnableDenormValue = 8186 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8187 8188 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8189 DAG.getEntryNode(), EnableDenormValue).getNode(); 8190 } else { 8191 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8192 SL, MVT::i32); 8193 EnableDenorm = 8194 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8195 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8196 } 8197 8198 SDValue Ops[3] = { 8199 NegDivScale0, 8200 SDValue(EnableDenorm, 0), 8201 SDValue(EnableDenorm, 1) 8202 }; 8203 8204 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8205 } 8206 8207 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8208 ApproxRcp, One, NegDivScale0, Flags); 8209 8210 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8211 ApproxRcp, Fma0, Flags); 8212 8213 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8214 Fma1, Fma1, Flags); 8215 8216 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8217 NumeratorScaled, Mul, Flags); 8218 8219 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8220 Fma2, Fma1, Mul, Fma2, Flags); 8221 8222 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8223 NumeratorScaled, Fma3, Flags); 8224 8225 if (!HasFP32Denormals) { 8226 SDNode *DisableDenorm; 8227 if (Subtarget->hasDenormModeInst()) { 8228 const SDValue DisableDenormValue = 8229 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8230 8231 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8232 Fma4.getValue(1), DisableDenormValue, 8233 Fma4.getValue(2)).getNode(); 8234 } else { 8235 const SDValue DisableDenormValue = 8236 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8237 8238 DisableDenorm = DAG.getMachineNode( 8239 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8240 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8241 } 8242 8243 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8244 SDValue(DisableDenorm, 0), DAG.getRoot()); 8245 DAG.setRoot(OutputChain); 8246 } 8247 8248 SDValue Scale = NumeratorScaled.getValue(1); 8249 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8250 {Fma4, Fma1, Fma3, Scale}, Flags); 8251 8252 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8253 } 8254 8255 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8256 if (DAG.getTarget().Options.UnsafeFPMath) 8257 return lowerFastUnsafeFDIV(Op, DAG); 8258 8259 SDLoc SL(Op); 8260 SDValue X = Op.getOperand(0); 8261 SDValue Y = Op.getOperand(1); 8262 8263 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8264 8265 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8266 8267 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8268 8269 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8270 8271 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8272 8273 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8274 8275 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8276 8277 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8278 8279 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8280 8281 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8282 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8283 8284 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8285 NegDivScale0, Mul, DivScale1); 8286 8287 SDValue Scale; 8288 8289 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8290 // Workaround a hardware bug on SI where the condition output from div_scale 8291 // is not usable. 8292 8293 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8294 8295 // Figure out if the scale to use for div_fmas. 8296 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8297 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8298 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8299 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8300 8301 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8302 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8303 8304 SDValue Scale0Hi 8305 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8306 SDValue Scale1Hi 8307 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8308 8309 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8310 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8311 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8312 } else { 8313 Scale = DivScale1.getValue(1); 8314 } 8315 8316 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8317 Fma4, Fma3, Mul, Scale); 8318 8319 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8320 } 8321 8322 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8323 EVT VT = Op.getValueType(); 8324 8325 if (VT == MVT::f32) 8326 return LowerFDIV32(Op, DAG); 8327 8328 if (VT == MVT::f64) 8329 return LowerFDIV64(Op, DAG); 8330 8331 if (VT == MVT::f16) 8332 return LowerFDIV16(Op, DAG); 8333 8334 llvm_unreachable("Unexpected type for fdiv"); 8335 } 8336 8337 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8338 SDLoc DL(Op); 8339 StoreSDNode *Store = cast<StoreSDNode>(Op); 8340 EVT VT = Store->getMemoryVT(); 8341 8342 if (VT == MVT::i1) { 8343 return DAG.getTruncStore(Store->getChain(), DL, 8344 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8345 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8346 } 8347 8348 assert(VT.isVector() && 8349 Store->getValue().getValueType().getScalarType() == MVT::i32); 8350 8351 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8352 VT, *Store->getMemOperand())) { 8353 return expandUnalignedStore(Store, DAG); 8354 } 8355 8356 unsigned AS = Store->getAddressSpace(); 8357 if (Subtarget->hasLDSMisalignedBug() && 8358 AS == AMDGPUAS::FLAT_ADDRESS && 8359 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8360 return SplitVectorStore(Op, DAG); 8361 } 8362 8363 MachineFunction &MF = DAG.getMachineFunction(); 8364 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8365 // If there is a possibilty that flat instruction access scratch memory 8366 // then we need to use the same legalization rules we use for private. 8367 if (AS == AMDGPUAS::FLAT_ADDRESS && 8368 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8369 AS = MFI->hasFlatScratchInit() ? 8370 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8371 8372 unsigned NumElements = VT.getVectorNumElements(); 8373 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8374 AS == AMDGPUAS::FLAT_ADDRESS) { 8375 if (NumElements > 4) 8376 return SplitVectorStore(Op, DAG); 8377 // v3 stores not supported on SI. 8378 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8379 return SplitVectorStore(Op, DAG); 8380 return SDValue(); 8381 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8382 switch (Subtarget->getMaxPrivateElementSize()) { 8383 case 4: 8384 return scalarizeVectorStore(Store, DAG); 8385 case 8: 8386 if (NumElements > 2) 8387 return SplitVectorStore(Op, DAG); 8388 return SDValue(); 8389 case 16: 8390 if (NumElements > 4 || NumElements == 3) 8391 return SplitVectorStore(Op, DAG); 8392 return SDValue(); 8393 default: 8394 llvm_unreachable("unsupported private_element_size"); 8395 } 8396 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8397 // Use ds_write_b128 if possible. 8398 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8399 VT.getStoreSize() == 16 && NumElements != 3) 8400 return SDValue(); 8401 8402 if (NumElements > 2) 8403 return SplitVectorStore(Op, DAG); 8404 8405 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8406 // address is negative, then the instruction is incorrectly treated as 8407 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8408 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8409 // store later in the SILoadStoreOptimizer. 8410 if (!Subtarget->hasUsableDSOffset() && 8411 NumElements == 2 && VT.getStoreSize() == 8 && 8412 Store->getAlignment() < 8) { 8413 return SplitVectorStore(Op, DAG); 8414 } 8415 8416 return SDValue(); 8417 } else { 8418 llvm_unreachable("unhandled address space"); 8419 } 8420 } 8421 8422 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8423 SDLoc DL(Op); 8424 EVT VT = Op.getValueType(); 8425 SDValue Arg = Op.getOperand(0); 8426 SDValue TrigVal; 8427 8428 // Propagate fast-math flags so that the multiply we introduce can be folded 8429 // if Arg is already the result of a multiply by constant. 8430 auto Flags = Op->getFlags(); 8431 8432 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8433 8434 if (Subtarget->hasTrigReducedRange()) { 8435 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8436 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8437 } else { 8438 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8439 } 8440 8441 switch (Op.getOpcode()) { 8442 case ISD::FCOS: 8443 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8444 case ISD::FSIN: 8445 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8446 default: 8447 llvm_unreachable("Wrong trig opcode"); 8448 } 8449 } 8450 8451 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8452 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8453 assert(AtomicNode->isCompareAndSwap()); 8454 unsigned AS = AtomicNode->getAddressSpace(); 8455 8456 // No custom lowering required for local address space 8457 if (!isFlatGlobalAddrSpace(AS)) 8458 return Op; 8459 8460 // Non-local address space requires custom lowering for atomic compare 8461 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8462 SDLoc DL(Op); 8463 SDValue ChainIn = Op.getOperand(0); 8464 SDValue Addr = Op.getOperand(1); 8465 SDValue Old = Op.getOperand(2); 8466 SDValue New = Op.getOperand(3); 8467 EVT VT = Op.getValueType(); 8468 MVT SimpleVT = VT.getSimpleVT(); 8469 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8470 8471 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8472 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8473 8474 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8475 Ops, VT, AtomicNode->getMemOperand()); 8476 } 8477 8478 //===----------------------------------------------------------------------===// 8479 // Custom DAG optimizations 8480 //===----------------------------------------------------------------------===// 8481 8482 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8483 DAGCombinerInfo &DCI) const { 8484 EVT VT = N->getValueType(0); 8485 EVT ScalarVT = VT.getScalarType(); 8486 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8487 return SDValue(); 8488 8489 SelectionDAG &DAG = DCI.DAG; 8490 SDLoc DL(N); 8491 8492 SDValue Src = N->getOperand(0); 8493 EVT SrcVT = Src.getValueType(); 8494 8495 // TODO: We could try to match extracting the higher bytes, which would be 8496 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8497 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8498 // about in practice. 8499 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8500 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8501 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8502 DCI.AddToWorklist(Cvt.getNode()); 8503 8504 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8505 if (ScalarVT != MVT::f32) { 8506 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8507 DAG.getTargetConstant(0, DL, MVT::i32)); 8508 } 8509 return Cvt; 8510 } 8511 } 8512 8513 return SDValue(); 8514 } 8515 8516 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8517 8518 // This is a variant of 8519 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8520 // 8521 // The normal DAG combiner will do this, but only if the add has one use since 8522 // that would increase the number of instructions. 8523 // 8524 // This prevents us from seeing a constant offset that can be folded into a 8525 // memory instruction's addressing mode. If we know the resulting add offset of 8526 // a pointer can be folded into an addressing offset, we can replace the pointer 8527 // operand with the add of new constant offset. This eliminates one of the uses, 8528 // and may allow the remaining use to also be simplified. 8529 // 8530 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8531 unsigned AddrSpace, 8532 EVT MemVT, 8533 DAGCombinerInfo &DCI) const { 8534 SDValue N0 = N->getOperand(0); 8535 SDValue N1 = N->getOperand(1); 8536 8537 // We only do this to handle cases where it's profitable when there are 8538 // multiple uses of the add, so defer to the standard combine. 8539 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8540 N0->hasOneUse()) 8541 return SDValue(); 8542 8543 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8544 if (!CN1) 8545 return SDValue(); 8546 8547 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8548 if (!CAdd) 8549 return SDValue(); 8550 8551 // If the resulting offset is too large, we can't fold it into the addressing 8552 // mode offset. 8553 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8554 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8555 8556 AddrMode AM; 8557 AM.HasBaseReg = true; 8558 AM.BaseOffs = Offset.getSExtValue(); 8559 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8560 return SDValue(); 8561 8562 SelectionDAG &DAG = DCI.DAG; 8563 SDLoc SL(N); 8564 EVT VT = N->getValueType(0); 8565 8566 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8567 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8568 8569 SDNodeFlags Flags; 8570 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8571 (N0.getOpcode() == ISD::OR || 8572 N0->getFlags().hasNoUnsignedWrap())); 8573 8574 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8575 } 8576 8577 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8578 DAGCombinerInfo &DCI) const { 8579 SDValue Ptr = N->getBasePtr(); 8580 SelectionDAG &DAG = DCI.DAG; 8581 SDLoc SL(N); 8582 8583 // TODO: We could also do this for multiplies. 8584 if (Ptr.getOpcode() == ISD::SHL) { 8585 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8586 N->getMemoryVT(), DCI); 8587 if (NewPtr) { 8588 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8589 8590 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8591 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8592 } 8593 } 8594 8595 return SDValue(); 8596 } 8597 8598 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8599 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8600 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8601 (Opc == ISD::XOR && Val == 0); 8602 } 8603 8604 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8605 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8606 // integer combine opportunities since most 64-bit operations are decomposed 8607 // this way. TODO: We won't want this for SALU especially if it is an inline 8608 // immediate. 8609 SDValue SITargetLowering::splitBinaryBitConstantOp( 8610 DAGCombinerInfo &DCI, 8611 const SDLoc &SL, 8612 unsigned Opc, SDValue LHS, 8613 const ConstantSDNode *CRHS) const { 8614 uint64_t Val = CRHS->getZExtValue(); 8615 uint32_t ValLo = Lo_32(Val); 8616 uint32_t ValHi = Hi_32(Val); 8617 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8618 8619 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8620 bitOpWithConstantIsReducible(Opc, ValHi)) || 8621 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8622 // If we need to materialize a 64-bit immediate, it will be split up later 8623 // anyway. Avoid creating the harder to understand 64-bit immediate 8624 // materialization. 8625 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8626 } 8627 8628 return SDValue(); 8629 } 8630 8631 // Returns true if argument is a boolean value which is not serialized into 8632 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8633 static bool isBoolSGPR(SDValue V) { 8634 if (V.getValueType() != MVT::i1) 8635 return false; 8636 switch (V.getOpcode()) { 8637 default: break; 8638 case ISD::SETCC: 8639 case ISD::AND: 8640 case ISD::OR: 8641 case ISD::XOR: 8642 case AMDGPUISD::FP_CLASS: 8643 return true; 8644 } 8645 return false; 8646 } 8647 8648 // If a constant has all zeroes or all ones within each byte return it. 8649 // Otherwise return 0. 8650 static uint32_t getConstantPermuteMask(uint32_t C) { 8651 // 0xff for any zero byte in the mask 8652 uint32_t ZeroByteMask = 0; 8653 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8654 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8655 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8656 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8657 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8658 if ((NonZeroByteMask & C) != NonZeroByteMask) 8659 return 0; // Partial bytes selected. 8660 return C; 8661 } 8662 8663 // Check if a node selects whole bytes from its operand 0 starting at a byte 8664 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8665 // or -1 if not succeeded. 8666 // Note byte select encoding: 8667 // value 0-3 selects corresponding source byte; 8668 // value 0xc selects zero; 8669 // value 0xff selects 0xff. 8670 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8671 assert(V.getValueSizeInBits() == 32); 8672 8673 if (V.getNumOperands() != 2) 8674 return ~0; 8675 8676 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8677 if (!N1) 8678 return ~0; 8679 8680 uint32_t C = N1->getZExtValue(); 8681 8682 switch (V.getOpcode()) { 8683 default: 8684 break; 8685 case ISD::AND: 8686 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8687 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8688 } 8689 break; 8690 8691 case ISD::OR: 8692 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8693 return (0x03020100 & ~ConstMask) | ConstMask; 8694 } 8695 break; 8696 8697 case ISD::SHL: 8698 if (C % 8) 8699 return ~0; 8700 8701 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8702 8703 case ISD::SRL: 8704 if (C % 8) 8705 return ~0; 8706 8707 return uint32_t(0x0c0c0c0c03020100ull >> C); 8708 } 8709 8710 return ~0; 8711 } 8712 8713 SDValue SITargetLowering::performAndCombine(SDNode *N, 8714 DAGCombinerInfo &DCI) const { 8715 if (DCI.isBeforeLegalize()) 8716 return SDValue(); 8717 8718 SelectionDAG &DAG = DCI.DAG; 8719 EVT VT = N->getValueType(0); 8720 SDValue LHS = N->getOperand(0); 8721 SDValue RHS = N->getOperand(1); 8722 8723 8724 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8725 if (VT == MVT::i64 && CRHS) { 8726 if (SDValue Split 8727 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8728 return Split; 8729 } 8730 8731 if (CRHS && VT == MVT::i32) { 8732 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8733 // nb = number of trailing zeroes in mask 8734 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8735 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8736 uint64_t Mask = CRHS->getZExtValue(); 8737 unsigned Bits = countPopulation(Mask); 8738 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8739 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8740 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8741 unsigned Shift = CShift->getZExtValue(); 8742 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8743 unsigned Offset = NB + Shift; 8744 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8745 SDLoc SL(N); 8746 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8747 LHS->getOperand(0), 8748 DAG.getConstant(Offset, SL, MVT::i32), 8749 DAG.getConstant(Bits, SL, MVT::i32)); 8750 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8751 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8752 DAG.getValueType(NarrowVT)); 8753 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8754 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8755 return Shl; 8756 } 8757 } 8758 } 8759 8760 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8761 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8762 isa<ConstantSDNode>(LHS.getOperand(2))) { 8763 uint32_t Sel = getConstantPermuteMask(Mask); 8764 if (!Sel) 8765 return SDValue(); 8766 8767 // Select 0xc for all zero bytes 8768 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8769 SDLoc DL(N); 8770 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8771 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8772 } 8773 } 8774 8775 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8776 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8777 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8778 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8779 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8780 8781 SDValue X = LHS.getOperand(0); 8782 SDValue Y = RHS.getOperand(0); 8783 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8784 return SDValue(); 8785 8786 if (LCC == ISD::SETO) { 8787 if (X != LHS.getOperand(1)) 8788 return SDValue(); 8789 8790 if (RCC == ISD::SETUNE) { 8791 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8792 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8793 return SDValue(); 8794 8795 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8796 SIInstrFlags::N_SUBNORMAL | 8797 SIInstrFlags::N_ZERO | 8798 SIInstrFlags::P_ZERO | 8799 SIInstrFlags::P_SUBNORMAL | 8800 SIInstrFlags::P_NORMAL; 8801 8802 static_assert(((~(SIInstrFlags::S_NAN | 8803 SIInstrFlags::Q_NAN | 8804 SIInstrFlags::N_INFINITY | 8805 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8806 "mask not equal"); 8807 8808 SDLoc DL(N); 8809 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8810 X, DAG.getConstant(Mask, DL, MVT::i32)); 8811 } 8812 } 8813 } 8814 8815 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8816 std::swap(LHS, RHS); 8817 8818 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8819 RHS.hasOneUse()) { 8820 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8821 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8822 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8823 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8824 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8825 (RHS.getOperand(0) == LHS.getOperand(0) && 8826 LHS.getOperand(0) == LHS.getOperand(1))) { 8827 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8828 unsigned NewMask = LCC == ISD::SETO ? 8829 Mask->getZExtValue() & ~OrdMask : 8830 Mask->getZExtValue() & OrdMask; 8831 8832 SDLoc DL(N); 8833 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8834 DAG.getConstant(NewMask, DL, MVT::i32)); 8835 } 8836 } 8837 8838 if (VT == MVT::i32 && 8839 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8840 // and x, (sext cc from i1) => select cc, x, 0 8841 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8842 std::swap(LHS, RHS); 8843 if (isBoolSGPR(RHS.getOperand(0))) 8844 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8845 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8846 } 8847 8848 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8849 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8850 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8851 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8852 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8853 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8854 if (LHSMask != ~0u && RHSMask != ~0u) { 8855 // Canonicalize the expression in an attempt to have fewer unique masks 8856 // and therefore fewer registers used to hold the masks. 8857 if (LHSMask > RHSMask) { 8858 std::swap(LHSMask, RHSMask); 8859 std::swap(LHS, RHS); 8860 } 8861 8862 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8863 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8864 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8865 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8866 8867 // Check of we need to combine values from two sources within a byte. 8868 if (!(LHSUsedLanes & RHSUsedLanes) && 8869 // If we select high and lower word keep it for SDWA. 8870 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8871 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8872 // Each byte in each mask is either selector mask 0-3, or has higher 8873 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8874 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8875 // mask which is not 0xff wins. By anding both masks we have a correct 8876 // result except that 0x0c shall be corrected to give 0x0c only. 8877 uint32_t Mask = LHSMask & RHSMask; 8878 for (unsigned I = 0; I < 32; I += 8) { 8879 uint32_t ByteSel = 0xff << I; 8880 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8881 Mask &= (0x0c << I) & 0xffffffff; 8882 } 8883 8884 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8885 // or 0x0c. 8886 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8887 SDLoc DL(N); 8888 8889 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8890 LHS.getOperand(0), RHS.getOperand(0), 8891 DAG.getConstant(Sel, DL, MVT::i32)); 8892 } 8893 } 8894 } 8895 8896 return SDValue(); 8897 } 8898 8899 SDValue SITargetLowering::performOrCombine(SDNode *N, 8900 DAGCombinerInfo &DCI) const { 8901 SelectionDAG &DAG = DCI.DAG; 8902 SDValue LHS = N->getOperand(0); 8903 SDValue RHS = N->getOperand(1); 8904 8905 EVT VT = N->getValueType(0); 8906 if (VT == MVT::i1) { 8907 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8908 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8909 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8910 SDValue Src = LHS.getOperand(0); 8911 if (Src != RHS.getOperand(0)) 8912 return SDValue(); 8913 8914 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8915 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8916 if (!CLHS || !CRHS) 8917 return SDValue(); 8918 8919 // Only 10 bits are used. 8920 static const uint32_t MaxMask = 0x3ff; 8921 8922 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8923 SDLoc DL(N); 8924 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8925 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8926 } 8927 8928 return SDValue(); 8929 } 8930 8931 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8932 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8933 LHS.getOpcode() == AMDGPUISD::PERM && 8934 isa<ConstantSDNode>(LHS.getOperand(2))) { 8935 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8936 if (!Sel) 8937 return SDValue(); 8938 8939 Sel |= LHS.getConstantOperandVal(2); 8940 SDLoc DL(N); 8941 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8942 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8943 } 8944 8945 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8946 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8947 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8948 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8949 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8950 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8951 if (LHSMask != ~0u && RHSMask != ~0u) { 8952 // Canonicalize the expression in an attempt to have fewer unique masks 8953 // and therefore fewer registers used to hold the masks. 8954 if (LHSMask > RHSMask) { 8955 std::swap(LHSMask, RHSMask); 8956 std::swap(LHS, RHS); 8957 } 8958 8959 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8960 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8961 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8962 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8963 8964 // Check of we need to combine values from two sources within a byte. 8965 if (!(LHSUsedLanes & RHSUsedLanes) && 8966 // If we select high and lower word keep it for SDWA. 8967 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8968 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8969 // Kill zero bytes selected by other mask. Zero value is 0xc. 8970 LHSMask &= ~RHSUsedLanes; 8971 RHSMask &= ~LHSUsedLanes; 8972 // Add 4 to each active LHS lane 8973 LHSMask |= LHSUsedLanes & 0x04040404; 8974 // Combine masks 8975 uint32_t Sel = LHSMask | RHSMask; 8976 SDLoc DL(N); 8977 8978 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8979 LHS.getOperand(0), RHS.getOperand(0), 8980 DAG.getConstant(Sel, DL, MVT::i32)); 8981 } 8982 } 8983 } 8984 8985 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 8986 return SDValue(); 8987 8988 // TODO: This could be a generic combine with a predicate for extracting the 8989 // high half of an integer being free. 8990 8991 // (or i64:x, (zero_extend i32:y)) -> 8992 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8993 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8994 RHS.getOpcode() != ISD::ZERO_EXTEND) 8995 std::swap(LHS, RHS); 8996 8997 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8998 SDValue ExtSrc = RHS.getOperand(0); 8999 EVT SrcVT = ExtSrc.getValueType(); 9000 if (SrcVT == MVT::i32) { 9001 SDLoc SL(N); 9002 SDValue LowLHS, HiBits; 9003 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9004 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9005 9006 DCI.AddToWorklist(LowOr.getNode()); 9007 DCI.AddToWorklist(HiBits.getNode()); 9008 9009 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9010 LowOr, HiBits); 9011 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9012 } 9013 } 9014 9015 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9016 if (CRHS) { 9017 if (SDValue Split 9018 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9019 return Split; 9020 } 9021 9022 return SDValue(); 9023 } 9024 9025 SDValue SITargetLowering::performXorCombine(SDNode *N, 9026 DAGCombinerInfo &DCI) const { 9027 EVT VT = N->getValueType(0); 9028 if (VT != MVT::i64) 9029 return SDValue(); 9030 9031 SDValue LHS = N->getOperand(0); 9032 SDValue RHS = N->getOperand(1); 9033 9034 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9035 if (CRHS) { 9036 if (SDValue Split 9037 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9038 return Split; 9039 } 9040 9041 return SDValue(); 9042 } 9043 9044 // Instructions that will be lowered with a final instruction that zeros the 9045 // high result bits. 9046 // XXX - probably only need to list legal operations. 9047 static bool fp16SrcZerosHighBits(unsigned Opc) { 9048 switch (Opc) { 9049 case ISD::FADD: 9050 case ISD::FSUB: 9051 case ISD::FMUL: 9052 case ISD::FDIV: 9053 case ISD::FREM: 9054 case ISD::FMA: 9055 case ISD::FMAD: 9056 case ISD::FCANONICALIZE: 9057 case ISD::FP_ROUND: 9058 case ISD::UINT_TO_FP: 9059 case ISD::SINT_TO_FP: 9060 case ISD::FABS: 9061 // Fabs is lowered to a bit operation, but it's an and which will clear the 9062 // high bits anyway. 9063 case ISD::FSQRT: 9064 case ISD::FSIN: 9065 case ISD::FCOS: 9066 case ISD::FPOWI: 9067 case ISD::FPOW: 9068 case ISD::FLOG: 9069 case ISD::FLOG2: 9070 case ISD::FLOG10: 9071 case ISD::FEXP: 9072 case ISD::FEXP2: 9073 case ISD::FCEIL: 9074 case ISD::FTRUNC: 9075 case ISD::FRINT: 9076 case ISD::FNEARBYINT: 9077 case ISD::FROUND: 9078 case ISD::FFLOOR: 9079 case ISD::FMINNUM: 9080 case ISD::FMAXNUM: 9081 case AMDGPUISD::FRACT: 9082 case AMDGPUISD::CLAMP: 9083 case AMDGPUISD::COS_HW: 9084 case AMDGPUISD::SIN_HW: 9085 case AMDGPUISD::FMIN3: 9086 case AMDGPUISD::FMAX3: 9087 case AMDGPUISD::FMED3: 9088 case AMDGPUISD::FMAD_FTZ: 9089 case AMDGPUISD::RCP: 9090 case AMDGPUISD::RSQ: 9091 case AMDGPUISD::RCP_IFLAG: 9092 case AMDGPUISD::LDEXP: 9093 return true; 9094 default: 9095 // fcopysign, select and others may be lowered to 32-bit bit operations 9096 // which don't zero the high bits. 9097 return false; 9098 } 9099 } 9100 9101 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9102 DAGCombinerInfo &DCI) const { 9103 if (!Subtarget->has16BitInsts() || 9104 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9105 return SDValue(); 9106 9107 EVT VT = N->getValueType(0); 9108 if (VT != MVT::i32) 9109 return SDValue(); 9110 9111 SDValue Src = N->getOperand(0); 9112 if (Src.getValueType() != MVT::i16) 9113 return SDValue(); 9114 9115 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9116 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9117 if (Src.getOpcode() == ISD::BITCAST) { 9118 SDValue BCSrc = Src.getOperand(0); 9119 if (BCSrc.getValueType() == MVT::f16 && 9120 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9121 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9122 } 9123 9124 return SDValue(); 9125 } 9126 9127 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9128 DAGCombinerInfo &DCI) 9129 const { 9130 SDValue Src = N->getOperand(0); 9131 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9132 9133 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9134 VTSign->getVT() == MVT::i8) || 9135 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9136 VTSign->getVT() == MVT::i16)) && 9137 Src.hasOneUse()) { 9138 auto *M = cast<MemSDNode>(Src); 9139 SDValue Ops[] = { 9140 Src.getOperand(0), // Chain 9141 Src.getOperand(1), // rsrc 9142 Src.getOperand(2), // vindex 9143 Src.getOperand(3), // voffset 9144 Src.getOperand(4), // soffset 9145 Src.getOperand(5), // offset 9146 Src.getOperand(6), 9147 Src.getOperand(7) 9148 }; 9149 // replace with BUFFER_LOAD_BYTE/SHORT 9150 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9151 Src.getOperand(0).getValueType()); 9152 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9153 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9154 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9155 ResList, 9156 Ops, M->getMemoryVT(), 9157 M->getMemOperand()); 9158 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9159 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9160 } 9161 return SDValue(); 9162 } 9163 9164 SDValue SITargetLowering::performClassCombine(SDNode *N, 9165 DAGCombinerInfo &DCI) const { 9166 SelectionDAG &DAG = DCI.DAG; 9167 SDValue Mask = N->getOperand(1); 9168 9169 // fp_class x, 0 -> false 9170 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9171 if (CMask->isNullValue()) 9172 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9173 } 9174 9175 if (N->getOperand(0).isUndef()) 9176 return DAG.getUNDEF(MVT::i1); 9177 9178 return SDValue(); 9179 } 9180 9181 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9182 DAGCombinerInfo &DCI) const { 9183 EVT VT = N->getValueType(0); 9184 SDValue N0 = N->getOperand(0); 9185 9186 if (N0.isUndef()) 9187 return N0; 9188 9189 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9190 N0.getOpcode() == ISD::SINT_TO_FP)) { 9191 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9192 N->getFlags()); 9193 } 9194 9195 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9196 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9197 N0.getOperand(0), N->getFlags()); 9198 } 9199 9200 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9201 } 9202 9203 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9204 unsigned MaxDepth) const { 9205 unsigned Opcode = Op.getOpcode(); 9206 if (Opcode == ISD::FCANONICALIZE) 9207 return true; 9208 9209 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9210 auto F = CFP->getValueAPF(); 9211 if (F.isNaN() && F.isSignaling()) 9212 return false; 9213 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9214 } 9215 9216 // If source is a result of another standard FP operation it is already in 9217 // canonical form. 9218 if (MaxDepth == 0) 9219 return false; 9220 9221 switch (Opcode) { 9222 // These will flush denorms if required. 9223 case ISD::FADD: 9224 case ISD::FSUB: 9225 case ISD::FMUL: 9226 case ISD::FCEIL: 9227 case ISD::FFLOOR: 9228 case ISD::FMA: 9229 case ISD::FMAD: 9230 case ISD::FSQRT: 9231 case ISD::FDIV: 9232 case ISD::FREM: 9233 case ISD::FP_ROUND: 9234 case ISD::FP_EXTEND: 9235 case AMDGPUISD::FMUL_LEGACY: 9236 case AMDGPUISD::FMAD_FTZ: 9237 case AMDGPUISD::RCP: 9238 case AMDGPUISD::RSQ: 9239 case AMDGPUISD::RSQ_CLAMP: 9240 case AMDGPUISD::RCP_LEGACY: 9241 case AMDGPUISD::RCP_IFLAG: 9242 case AMDGPUISD::DIV_SCALE: 9243 case AMDGPUISD::DIV_FMAS: 9244 case AMDGPUISD::DIV_FIXUP: 9245 case AMDGPUISD::FRACT: 9246 case AMDGPUISD::LDEXP: 9247 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9248 case AMDGPUISD::CVT_F32_UBYTE0: 9249 case AMDGPUISD::CVT_F32_UBYTE1: 9250 case AMDGPUISD::CVT_F32_UBYTE2: 9251 case AMDGPUISD::CVT_F32_UBYTE3: 9252 return true; 9253 9254 // It can/will be lowered or combined as a bit operation. 9255 // Need to check their input recursively to handle. 9256 case ISD::FNEG: 9257 case ISD::FABS: 9258 case ISD::FCOPYSIGN: 9259 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9260 9261 case ISD::FSIN: 9262 case ISD::FCOS: 9263 case ISD::FSINCOS: 9264 return Op.getValueType().getScalarType() != MVT::f16; 9265 9266 case ISD::FMINNUM: 9267 case ISD::FMAXNUM: 9268 case ISD::FMINNUM_IEEE: 9269 case ISD::FMAXNUM_IEEE: 9270 case AMDGPUISD::CLAMP: 9271 case AMDGPUISD::FMED3: 9272 case AMDGPUISD::FMAX3: 9273 case AMDGPUISD::FMIN3: { 9274 // FIXME: Shouldn't treat the generic operations different based these. 9275 // However, we aren't really required to flush the result from 9276 // minnum/maxnum.. 9277 9278 // snans will be quieted, so we only need to worry about denormals. 9279 if (Subtarget->supportsMinMaxDenormModes() || 9280 denormalsEnabledForType(DAG, Op.getValueType())) 9281 return true; 9282 9283 // Flushing may be required. 9284 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9285 // targets need to check their input recursively. 9286 9287 // FIXME: Does this apply with clamp? It's implemented with max. 9288 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9289 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9290 return false; 9291 } 9292 9293 return true; 9294 } 9295 case ISD::SELECT: { 9296 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9297 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9298 } 9299 case ISD::BUILD_VECTOR: { 9300 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9301 SDValue SrcOp = Op.getOperand(i); 9302 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9303 return false; 9304 } 9305 9306 return true; 9307 } 9308 case ISD::EXTRACT_VECTOR_ELT: 9309 case ISD::EXTRACT_SUBVECTOR: { 9310 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9311 } 9312 case ISD::INSERT_VECTOR_ELT: { 9313 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9314 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9315 } 9316 case ISD::UNDEF: 9317 // Could be anything. 9318 return false; 9319 9320 case ISD::BITCAST: { 9321 // Hack round the mess we make when legalizing extract_vector_elt 9322 SDValue Src = Op.getOperand(0); 9323 if (Src.getValueType() == MVT::i16 && 9324 Src.getOpcode() == ISD::TRUNCATE) { 9325 SDValue TruncSrc = Src.getOperand(0); 9326 if (TruncSrc.getValueType() == MVT::i32 && 9327 TruncSrc.getOpcode() == ISD::BITCAST && 9328 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9329 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9330 } 9331 } 9332 9333 return false; 9334 } 9335 case ISD::INTRINSIC_WO_CHAIN: { 9336 unsigned IntrinsicID 9337 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9338 // TODO: Handle more intrinsics 9339 switch (IntrinsicID) { 9340 case Intrinsic::amdgcn_cvt_pkrtz: 9341 case Intrinsic::amdgcn_cubeid: 9342 case Intrinsic::amdgcn_frexp_mant: 9343 case Intrinsic::amdgcn_fdot2: 9344 case Intrinsic::amdgcn_rcp: 9345 case Intrinsic::amdgcn_rsq: 9346 case Intrinsic::amdgcn_rsq_clamp: 9347 case Intrinsic::amdgcn_rcp_legacy: 9348 case Intrinsic::amdgcn_rsq_legacy: 9349 case Intrinsic::amdgcn_trig_preop: 9350 return true; 9351 default: 9352 break; 9353 } 9354 9355 LLVM_FALLTHROUGH; 9356 } 9357 default: 9358 return denormalsEnabledForType(DAG, Op.getValueType()) && 9359 DAG.isKnownNeverSNaN(Op); 9360 } 9361 9362 llvm_unreachable("invalid operation"); 9363 } 9364 9365 // Constant fold canonicalize. 9366 SDValue SITargetLowering::getCanonicalConstantFP( 9367 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9368 // Flush denormals to 0 if not enabled. 9369 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9370 return DAG.getConstantFP(0.0, SL, VT); 9371 9372 if (C.isNaN()) { 9373 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9374 if (C.isSignaling()) { 9375 // Quiet a signaling NaN. 9376 // FIXME: Is this supposed to preserve payload bits? 9377 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9378 } 9379 9380 // Make sure it is the canonical NaN bitpattern. 9381 // 9382 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9383 // immediate? 9384 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9385 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9386 } 9387 9388 // Already canonical. 9389 return DAG.getConstantFP(C, SL, VT); 9390 } 9391 9392 static bool vectorEltWillFoldAway(SDValue Op) { 9393 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9394 } 9395 9396 SDValue SITargetLowering::performFCanonicalizeCombine( 9397 SDNode *N, 9398 DAGCombinerInfo &DCI) const { 9399 SelectionDAG &DAG = DCI.DAG; 9400 SDValue N0 = N->getOperand(0); 9401 EVT VT = N->getValueType(0); 9402 9403 // fcanonicalize undef -> qnan 9404 if (N0.isUndef()) { 9405 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9406 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9407 } 9408 9409 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9410 EVT VT = N->getValueType(0); 9411 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9412 } 9413 9414 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9415 // (fcanonicalize k) 9416 // 9417 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9418 9419 // TODO: This could be better with wider vectors that will be split to v2f16, 9420 // and to consider uses since there aren't that many packed operations. 9421 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9422 isTypeLegal(MVT::v2f16)) { 9423 SDLoc SL(N); 9424 SDValue NewElts[2]; 9425 SDValue Lo = N0.getOperand(0); 9426 SDValue Hi = N0.getOperand(1); 9427 EVT EltVT = Lo.getValueType(); 9428 9429 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9430 for (unsigned I = 0; I != 2; ++I) { 9431 SDValue Op = N0.getOperand(I); 9432 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9433 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9434 CFP->getValueAPF()); 9435 } else if (Op.isUndef()) { 9436 // Handled below based on what the other operand is. 9437 NewElts[I] = Op; 9438 } else { 9439 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9440 } 9441 } 9442 9443 // If one half is undef, and one is constant, perfer a splat vector rather 9444 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9445 // cheaper to use and may be free with a packed operation. 9446 if (NewElts[0].isUndef()) { 9447 if (isa<ConstantFPSDNode>(NewElts[1])) 9448 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9449 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9450 } 9451 9452 if (NewElts[1].isUndef()) { 9453 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9454 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9455 } 9456 9457 return DAG.getBuildVector(VT, SL, NewElts); 9458 } 9459 } 9460 9461 unsigned SrcOpc = N0.getOpcode(); 9462 9463 // If it's free to do so, push canonicalizes further up the source, which may 9464 // find a canonical source. 9465 // 9466 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9467 // sNaNs. 9468 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9469 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9470 if (CRHS && N0.hasOneUse()) { 9471 SDLoc SL(N); 9472 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9473 N0.getOperand(0)); 9474 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9475 DCI.AddToWorklist(Canon0.getNode()); 9476 9477 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9478 } 9479 } 9480 9481 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9482 } 9483 9484 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9485 switch (Opc) { 9486 case ISD::FMAXNUM: 9487 case ISD::FMAXNUM_IEEE: 9488 return AMDGPUISD::FMAX3; 9489 case ISD::SMAX: 9490 return AMDGPUISD::SMAX3; 9491 case ISD::UMAX: 9492 return AMDGPUISD::UMAX3; 9493 case ISD::FMINNUM: 9494 case ISD::FMINNUM_IEEE: 9495 return AMDGPUISD::FMIN3; 9496 case ISD::SMIN: 9497 return AMDGPUISD::SMIN3; 9498 case ISD::UMIN: 9499 return AMDGPUISD::UMIN3; 9500 default: 9501 llvm_unreachable("Not a min/max opcode"); 9502 } 9503 } 9504 9505 SDValue SITargetLowering::performIntMed3ImmCombine( 9506 SelectionDAG &DAG, const SDLoc &SL, 9507 SDValue Op0, SDValue Op1, bool Signed) const { 9508 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9509 if (!K1) 9510 return SDValue(); 9511 9512 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9513 if (!K0) 9514 return SDValue(); 9515 9516 if (Signed) { 9517 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9518 return SDValue(); 9519 } else { 9520 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9521 return SDValue(); 9522 } 9523 9524 EVT VT = K0->getValueType(0); 9525 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9526 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9527 return DAG.getNode(Med3Opc, SL, VT, 9528 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9529 } 9530 9531 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9532 MVT NVT = MVT::i32; 9533 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9534 9535 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9536 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9537 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9538 9539 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9540 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9541 } 9542 9543 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9544 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9545 return C; 9546 9547 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9548 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9549 return C; 9550 } 9551 9552 return nullptr; 9553 } 9554 9555 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9556 const SDLoc &SL, 9557 SDValue Op0, 9558 SDValue Op1) const { 9559 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9560 if (!K1) 9561 return SDValue(); 9562 9563 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9564 if (!K0) 9565 return SDValue(); 9566 9567 // Ordered >= (although NaN inputs should have folded away by now). 9568 if (K0->getValueAPF() > K1->getValueAPF()) 9569 return SDValue(); 9570 9571 const MachineFunction &MF = DAG.getMachineFunction(); 9572 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9573 9574 // TODO: Check IEEE bit enabled? 9575 EVT VT = Op0.getValueType(); 9576 if (Info->getMode().DX10Clamp) { 9577 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9578 // hardware fmed3 behavior converting to a min. 9579 // FIXME: Should this be allowing -0.0? 9580 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9581 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9582 } 9583 9584 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9585 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9586 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9587 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9588 // then give the other result, which is different from med3 with a NaN 9589 // input. 9590 SDValue Var = Op0.getOperand(0); 9591 if (!DAG.isKnownNeverSNaN(Var)) 9592 return SDValue(); 9593 9594 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9595 9596 if ((!K0->hasOneUse() || 9597 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9598 (!K1->hasOneUse() || 9599 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9600 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9601 Var, SDValue(K0, 0), SDValue(K1, 0)); 9602 } 9603 } 9604 9605 return SDValue(); 9606 } 9607 9608 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9609 DAGCombinerInfo &DCI) const { 9610 SelectionDAG &DAG = DCI.DAG; 9611 9612 EVT VT = N->getValueType(0); 9613 unsigned Opc = N->getOpcode(); 9614 SDValue Op0 = N->getOperand(0); 9615 SDValue Op1 = N->getOperand(1); 9616 9617 // Only do this if the inner op has one use since this will just increases 9618 // register pressure for no benefit. 9619 9620 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9621 !VT.isVector() && 9622 (VT == MVT::i32 || VT == MVT::f32 || 9623 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9624 // max(max(a, b), c) -> max3(a, b, c) 9625 // min(min(a, b), c) -> min3(a, b, c) 9626 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9627 SDLoc DL(N); 9628 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9629 DL, 9630 N->getValueType(0), 9631 Op0.getOperand(0), 9632 Op0.getOperand(1), 9633 Op1); 9634 } 9635 9636 // Try commuted. 9637 // max(a, max(b, c)) -> max3(a, b, c) 9638 // min(a, min(b, c)) -> min3(a, b, c) 9639 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9640 SDLoc DL(N); 9641 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9642 DL, 9643 N->getValueType(0), 9644 Op0, 9645 Op1.getOperand(0), 9646 Op1.getOperand(1)); 9647 } 9648 } 9649 9650 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9651 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9652 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9653 return Med3; 9654 } 9655 9656 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9657 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9658 return Med3; 9659 } 9660 9661 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9662 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9663 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9664 (Opc == AMDGPUISD::FMIN_LEGACY && 9665 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9666 (VT == MVT::f32 || VT == MVT::f64 || 9667 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9668 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9669 Op0.hasOneUse()) { 9670 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9671 return Res; 9672 } 9673 9674 return SDValue(); 9675 } 9676 9677 static bool isClampZeroToOne(SDValue A, SDValue B) { 9678 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9679 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9680 // FIXME: Should this be allowing -0.0? 9681 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9682 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9683 } 9684 } 9685 9686 return false; 9687 } 9688 9689 // FIXME: Should only worry about snans for version with chain. 9690 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9691 DAGCombinerInfo &DCI) const { 9692 EVT VT = N->getValueType(0); 9693 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9694 // NaNs. With a NaN input, the order of the operands may change the result. 9695 9696 SelectionDAG &DAG = DCI.DAG; 9697 SDLoc SL(N); 9698 9699 SDValue Src0 = N->getOperand(0); 9700 SDValue Src1 = N->getOperand(1); 9701 SDValue Src2 = N->getOperand(2); 9702 9703 if (isClampZeroToOne(Src0, Src1)) { 9704 // const_a, const_b, x -> clamp is safe in all cases including signaling 9705 // nans. 9706 // FIXME: Should this be allowing -0.0? 9707 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9708 } 9709 9710 const MachineFunction &MF = DAG.getMachineFunction(); 9711 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9712 9713 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9714 // handling no dx10-clamp? 9715 if (Info->getMode().DX10Clamp) { 9716 // If NaNs is clamped to 0, we are free to reorder the inputs. 9717 9718 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9719 std::swap(Src0, Src1); 9720 9721 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9722 std::swap(Src1, Src2); 9723 9724 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9725 std::swap(Src0, Src1); 9726 9727 if (isClampZeroToOne(Src1, Src2)) 9728 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9729 } 9730 9731 return SDValue(); 9732 } 9733 9734 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9735 DAGCombinerInfo &DCI) const { 9736 SDValue Src0 = N->getOperand(0); 9737 SDValue Src1 = N->getOperand(1); 9738 if (Src0.isUndef() && Src1.isUndef()) 9739 return DCI.DAG.getUNDEF(N->getValueType(0)); 9740 return SDValue(); 9741 } 9742 9743 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9744 // expanded into a set of cmp/select instructions. 9745 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9746 unsigned NumElem, 9747 bool IsDivergentIdx) { 9748 if (UseDivergentRegisterIndexing) 9749 return false; 9750 9751 unsigned VecSize = EltSize * NumElem; 9752 9753 // Sub-dword vectors of size 2 dword or less have better implementation. 9754 if (VecSize <= 64 && EltSize < 32) 9755 return false; 9756 9757 // Always expand the rest of sub-dword instructions, otherwise it will be 9758 // lowered via memory. 9759 if (EltSize < 32) 9760 return true; 9761 9762 // Always do this if var-idx is divergent, otherwise it will become a loop. 9763 if (IsDivergentIdx) 9764 return true; 9765 9766 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9767 unsigned NumInsts = NumElem /* Number of compares */ + 9768 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9769 return NumInsts <= 16; 9770 } 9771 9772 static bool shouldExpandVectorDynExt(SDNode *N) { 9773 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9774 if (isa<ConstantSDNode>(Idx)) 9775 return false; 9776 9777 SDValue Vec = N->getOperand(0); 9778 EVT VecVT = Vec.getValueType(); 9779 EVT EltVT = VecVT.getVectorElementType(); 9780 unsigned EltSize = EltVT.getSizeInBits(); 9781 unsigned NumElem = VecVT.getVectorNumElements(); 9782 9783 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9784 Idx->isDivergent()); 9785 } 9786 9787 SDValue SITargetLowering::performExtractVectorEltCombine( 9788 SDNode *N, DAGCombinerInfo &DCI) const { 9789 SDValue Vec = N->getOperand(0); 9790 SelectionDAG &DAG = DCI.DAG; 9791 9792 EVT VecVT = Vec.getValueType(); 9793 EVT EltVT = VecVT.getVectorElementType(); 9794 9795 if ((Vec.getOpcode() == ISD::FNEG || 9796 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9797 SDLoc SL(N); 9798 EVT EltVT = N->getValueType(0); 9799 SDValue Idx = N->getOperand(1); 9800 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9801 Vec.getOperand(0), Idx); 9802 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9803 } 9804 9805 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9806 // => 9807 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9808 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9809 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9810 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9811 SDLoc SL(N); 9812 EVT EltVT = N->getValueType(0); 9813 SDValue Idx = N->getOperand(1); 9814 unsigned Opc = Vec.getOpcode(); 9815 9816 switch(Opc) { 9817 default: 9818 break; 9819 // TODO: Support other binary operations. 9820 case ISD::FADD: 9821 case ISD::FSUB: 9822 case ISD::FMUL: 9823 case ISD::ADD: 9824 case ISD::UMIN: 9825 case ISD::UMAX: 9826 case ISD::SMIN: 9827 case ISD::SMAX: 9828 case ISD::FMAXNUM: 9829 case ISD::FMINNUM: 9830 case ISD::FMAXNUM_IEEE: 9831 case ISD::FMINNUM_IEEE: { 9832 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9833 Vec.getOperand(0), Idx); 9834 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9835 Vec.getOperand(1), Idx); 9836 9837 DCI.AddToWorklist(Elt0.getNode()); 9838 DCI.AddToWorklist(Elt1.getNode()); 9839 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9840 } 9841 } 9842 } 9843 9844 unsigned VecSize = VecVT.getSizeInBits(); 9845 unsigned EltSize = EltVT.getSizeInBits(); 9846 9847 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9848 if (::shouldExpandVectorDynExt(N)) { 9849 SDLoc SL(N); 9850 SDValue Idx = N->getOperand(1); 9851 SDValue V; 9852 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9853 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9854 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9855 if (I == 0) 9856 V = Elt; 9857 else 9858 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9859 } 9860 return V; 9861 } 9862 9863 if (!DCI.isBeforeLegalize()) 9864 return SDValue(); 9865 9866 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9867 // elements. This exposes more load reduction opportunities by replacing 9868 // multiple small extract_vector_elements with a single 32-bit extract. 9869 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9870 if (isa<MemSDNode>(Vec) && 9871 EltSize <= 16 && 9872 EltVT.isByteSized() && 9873 VecSize > 32 && 9874 VecSize % 32 == 0 && 9875 Idx) { 9876 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9877 9878 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9879 unsigned EltIdx = BitIndex / 32; 9880 unsigned LeftoverBitIdx = BitIndex % 32; 9881 SDLoc SL(N); 9882 9883 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9884 DCI.AddToWorklist(Cast.getNode()); 9885 9886 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9887 DAG.getConstant(EltIdx, SL, MVT::i32)); 9888 DCI.AddToWorklist(Elt.getNode()); 9889 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9890 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9891 DCI.AddToWorklist(Srl.getNode()); 9892 9893 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9894 DCI.AddToWorklist(Trunc.getNode()); 9895 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9896 } 9897 9898 return SDValue(); 9899 } 9900 9901 SDValue 9902 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9903 DAGCombinerInfo &DCI) const { 9904 SDValue Vec = N->getOperand(0); 9905 SDValue Idx = N->getOperand(2); 9906 EVT VecVT = Vec.getValueType(); 9907 EVT EltVT = VecVT.getVectorElementType(); 9908 9909 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9910 // => BUILD_VECTOR n x select (e, const-idx) 9911 if (!::shouldExpandVectorDynExt(N)) 9912 return SDValue(); 9913 9914 SelectionDAG &DAG = DCI.DAG; 9915 SDLoc SL(N); 9916 SDValue Ins = N->getOperand(1); 9917 EVT IdxVT = Idx.getValueType(); 9918 9919 SmallVector<SDValue, 16> Ops; 9920 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9921 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9922 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9923 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9924 Ops.push_back(V); 9925 } 9926 9927 return DAG.getBuildVector(VecVT, SL, Ops); 9928 } 9929 9930 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9931 const SDNode *N0, 9932 const SDNode *N1) const { 9933 EVT VT = N0->getValueType(0); 9934 9935 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9936 // support denormals ever. 9937 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9938 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9939 getSubtarget()->hasMadF16())) && 9940 isOperationLegal(ISD::FMAD, VT)) 9941 return ISD::FMAD; 9942 9943 const TargetOptions &Options = DAG.getTarget().Options; 9944 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9945 (N0->getFlags().hasAllowContract() && 9946 N1->getFlags().hasAllowContract())) && 9947 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9948 return ISD::FMA; 9949 } 9950 9951 return 0; 9952 } 9953 9954 // For a reassociatable opcode perform: 9955 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9956 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9957 SelectionDAG &DAG) const { 9958 EVT VT = N->getValueType(0); 9959 if (VT != MVT::i32 && VT != MVT::i64) 9960 return SDValue(); 9961 9962 unsigned Opc = N->getOpcode(); 9963 SDValue Op0 = N->getOperand(0); 9964 SDValue Op1 = N->getOperand(1); 9965 9966 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9967 return SDValue(); 9968 9969 if (Op0->isDivergent()) 9970 std::swap(Op0, Op1); 9971 9972 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9973 return SDValue(); 9974 9975 SDValue Op2 = Op1.getOperand(1); 9976 Op1 = Op1.getOperand(0); 9977 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9978 return SDValue(); 9979 9980 if (Op1->isDivergent()) 9981 std::swap(Op1, Op2); 9982 9983 // If either operand is constant this will conflict with 9984 // DAGCombiner::ReassociateOps(). 9985 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9986 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9987 return SDValue(); 9988 9989 SDLoc SL(N); 9990 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9991 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9992 } 9993 9994 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9995 EVT VT, 9996 SDValue N0, SDValue N1, SDValue N2, 9997 bool Signed) { 9998 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9999 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10000 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10001 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10002 } 10003 10004 SDValue SITargetLowering::performAddCombine(SDNode *N, 10005 DAGCombinerInfo &DCI) const { 10006 SelectionDAG &DAG = DCI.DAG; 10007 EVT VT = N->getValueType(0); 10008 SDLoc SL(N); 10009 SDValue LHS = N->getOperand(0); 10010 SDValue RHS = N->getOperand(1); 10011 10012 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10013 && Subtarget->hasMad64_32() && 10014 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10015 VT.getScalarSizeInBits() <= 64) { 10016 if (LHS.getOpcode() != ISD::MUL) 10017 std::swap(LHS, RHS); 10018 10019 SDValue MulLHS = LHS.getOperand(0); 10020 SDValue MulRHS = LHS.getOperand(1); 10021 SDValue AddRHS = RHS; 10022 10023 // TODO: Maybe restrict if SGPR inputs. 10024 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10025 numBitsUnsigned(MulRHS, DAG) <= 32) { 10026 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10027 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10028 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10029 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10030 } 10031 10032 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10033 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10034 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10035 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10036 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10037 } 10038 10039 return SDValue(); 10040 } 10041 10042 if (SDValue V = reassociateScalarOps(N, DAG)) { 10043 return V; 10044 } 10045 10046 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10047 return SDValue(); 10048 10049 // add x, zext (setcc) => addcarry x, 0, setcc 10050 // add x, sext (setcc) => subcarry x, 0, setcc 10051 unsigned Opc = LHS.getOpcode(); 10052 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10053 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10054 std::swap(RHS, LHS); 10055 10056 Opc = RHS.getOpcode(); 10057 switch (Opc) { 10058 default: break; 10059 case ISD::ZERO_EXTEND: 10060 case ISD::SIGN_EXTEND: 10061 case ISD::ANY_EXTEND: { 10062 auto Cond = RHS.getOperand(0); 10063 // If this won't be a real VOPC output, we would still need to insert an 10064 // extra instruction anyway. 10065 if (!isBoolSGPR(Cond)) 10066 break; 10067 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10068 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10069 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10070 return DAG.getNode(Opc, SL, VTList, Args); 10071 } 10072 case ISD::ADDCARRY: { 10073 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10074 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10075 if (!C || C->getZExtValue() != 0) break; 10076 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10077 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10078 } 10079 } 10080 return SDValue(); 10081 } 10082 10083 SDValue SITargetLowering::performSubCombine(SDNode *N, 10084 DAGCombinerInfo &DCI) const { 10085 SelectionDAG &DAG = DCI.DAG; 10086 EVT VT = N->getValueType(0); 10087 10088 if (VT != MVT::i32) 10089 return SDValue(); 10090 10091 SDLoc SL(N); 10092 SDValue LHS = N->getOperand(0); 10093 SDValue RHS = N->getOperand(1); 10094 10095 // sub x, zext (setcc) => subcarry x, 0, setcc 10096 // sub x, sext (setcc) => addcarry x, 0, setcc 10097 unsigned Opc = RHS.getOpcode(); 10098 switch (Opc) { 10099 default: break; 10100 case ISD::ZERO_EXTEND: 10101 case ISD::SIGN_EXTEND: 10102 case ISD::ANY_EXTEND: { 10103 auto Cond = RHS.getOperand(0); 10104 // If this won't be a real VOPC output, we would still need to insert an 10105 // extra instruction anyway. 10106 if (!isBoolSGPR(Cond)) 10107 break; 10108 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10109 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10110 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10111 return DAG.getNode(Opc, SL, VTList, Args); 10112 } 10113 } 10114 10115 if (LHS.getOpcode() == ISD::SUBCARRY) { 10116 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10117 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10118 if (!C || !C->isNullValue()) 10119 return SDValue(); 10120 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10121 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10122 } 10123 return SDValue(); 10124 } 10125 10126 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10127 DAGCombinerInfo &DCI) const { 10128 10129 if (N->getValueType(0) != MVT::i32) 10130 return SDValue(); 10131 10132 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10133 if (!C || C->getZExtValue() != 0) 10134 return SDValue(); 10135 10136 SelectionDAG &DAG = DCI.DAG; 10137 SDValue LHS = N->getOperand(0); 10138 10139 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10140 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10141 unsigned LHSOpc = LHS.getOpcode(); 10142 unsigned Opc = N->getOpcode(); 10143 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10144 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10145 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10146 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10147 } 10148 return SDValue(); 10149 } 10150 10151 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10152 DAGCombinerInfo &DCI) const { 10153 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10154 return SDValue(); 10155 10156 SelectionDAG &DAG = DCI.DAG; 10157 EVT VT = N->getValueType(0); 10158 10159 SDLoc SL(N); 10160 SDValue LHS = N->getOperand(0); 10161 SDValue RHS = N->getOperand(1); 10162 10163 // These should really be instruction patterns, but writing patterns with 10164 // source modiifiers is a pain. 10165 10166 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10167 if (LHS.getOpcode() == ISD::FADD) { 10168 SDValue A = LHS.getOperand(0); 10169 if (A == LHS.getOperand(1)) { 10170 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10171 if (FusedOp != 0) { 10172 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10173 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10174 } 10175 } 10176 } 10177 10178 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10179 if (RHS.getOpcode() == ISD::FADD) { 10180 SDValue A = RHS.getOperand(0); 10181 if (A == RHS.getOperand(1)) { 10182 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10183 if (FusedOp != 0) { 10184 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10185 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10186 } 10187 } 10188 } 10189 10190 return SDValue(); 10191 } 10192 10193 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10194 DAGCombinerInfo &DCI) const { 10195 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10196 return SDValue(); 10197 10198 SelectionDAG &DAG = DCI.DAG; 10199 SDLoc SL(N); 10200 EVT VT = N->getValueType(0); 10201 assert(!VT.isVector()); 10202 10203 // Try to get the fneg to fold into the source modifier. This undoes generic 10204 // DAG combines and folds them into the mad. 10205 // 10206 // Only do this if we are not trying to support denormals. v_mad_f32 does 10207 // not support denormals ever. 10208 SDValue LHS = N->getOperand(0); 10209 SDValue RHS = N->getOperand(1); 10210 if (LHS.getOpcode() == ISD::FADD) { 10211 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10212 SDValue A = LHS.getOperand(0); 10213 if (A == LHS.getOperand(1)) { 10214 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10215 if (FusedOp != 0){ 10216 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10217 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10218 10219 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10220 } 10221 } 10222 } 10223 10224 if (RHS.getOpcode() == ISD::FADD) { 10225 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10226 10227 SDValue A = RHS.getOperand(0); 10228 if (A == RHS.getOperand(1)) { 10229 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10230 if (FusedOp != 0){ 10231 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10232 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10233 } 10234 } 10235 } 10236 10237 return SDValue(); 10238 } 10239 10240 SDValue SITargetLowering::performFMACombine(SDNode *N, 10241 DAGCombinerInfo &DCI) const { 10242 SelectionDAG &DAG = DCI.DAG; 10243 EVT VT = N->getValueType(0); 10244 SDLoc SL(N); 10245 10246 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10247 return SDValue(); 10248 10249 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10250 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10251 SDValue Op1 = N->getOperand(0); 10252 SDValue Op2 = N->getOperand(1); 10253 SDValue FMA = N->getOperand(2); 10254 10255 if (FMA.getOpcode() != ISD::FMA || 10256 Op1.getOpcode() != ISD::FP_EXTEND || 10257 Op2.getOpcode() != ISD::FP_EXTEND) 10258 return SDValue(); 10259 10260 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10261 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10262 // is sufficient to allow generaing fdot2. 10263 const TargetOptions &Options = DAG.getTarget().Options; 10264 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10265 (N->getFlags().hasAllowContract() && 10266 FMA->getFlags().hasAllowContract())) { 10267 Op1 = Op1.getOperand(0); 10268 Op2 = Op2.getOperand(0); 10269 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10270 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10271 return SDValue(); 10272 10273 SDValue Vec1 = Op1.getOperand(0); 10274 SDValue Idx1 = Op1.getOperand(1); 10275 SDValue Vec2 = Op2.getOperand(0); 10276 10277 SDValue FMAOp1 = FMA.getOperand(0); 10278 SDValue FMAOp2 = FMA.getOperand(1); 10279 SDValue FMAAcc = FMA.getOperand(2); 10280 10281 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10282 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10283 return SDValue(); 10284 10285 FMAOp1 = FMAOp1.getOperand(0); 10286 FMAOp2 = FMAOp2.getOperand(0); 10287 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10288 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10289 return SDValue(); 10290 10291 SDValue Vec3 = FMAOp1.getOperand(0); 10292 SDValue Vec4 = FMAOp2.getOperand(0); 10293 SDValue Idx2 = FMAOp1.getOperand(1); 10294 10295 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10296 // Idx1 and Idx2 cannot be the same. 10297 Idx1 == Idx2) 10298 return SDValue(); 10299 10300 if (Vec1 == Vec2 || Vec3 == Vec4) 10301 return SDValue(); 10302 10303 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10304 return SDValue(); 10305 10306 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10307 (Vec1 == Vec4 && Vec2 == Vec3)) { 10308 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10309 DAG.getTargetConstant(0, SL, MVT::i1)); 10310 } 10311 } 10312 return SDValue(); 10313 } 10314 10315 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10316 DAGCombinerInfo &DCI) const { 10317 SelectionDAG &DAG = DCI.DAG; 10318 SDLoc SL(N); 10319 10320 SDValue LHS = N->getOperand(0); 10321 SDValue RHS = N->getOperand(1); 10322 EVT VT = LHS.getValueType(); 10323 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10324 10325 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10326 if (!CRHS) { 10327 CRHS = dyn_cast<ConstantSDNode>(LHS); 10328 if (CRHS) { 10329 std::swap(LHS, RHS); 10330 CC = getSetCCSwappedOperands(CC); 10331 } 10332 } 10333 10334 if (CRHS) { 10335 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10336 isBoolSGPR(LHS.getOperand(0))) { 10337 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10338 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10339 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10340 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10341 if ((CRHS->isAllOnesValue() && 10342 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10343 (CRHS->isNullValue() && 10344 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10345 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10346 DAG.getConstant(-1, SL, MVT::i1)); 10347 if ((CRHS->isAllOnesValue() && 10348 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10349 (CRHS->isNullValue() && 10350 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10351 return LHS.getOperand(0); 10352 } 10353 10354 uint64_t CRHSVal = CRHS->getZExtValue(); 10355 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10356 LHS.getOpcode() == ISD::SELECT && 10357 isa<ConstantSDNode>(LHS.getOperand(1)) && 10358 isa<ConstantSDNode>(LHS.getOperand(2)) && 10359 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10360 isBoolSGPR(LHS.getOperand(0))) { 10361 // Given CT != FT: 10362 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10363 // setcc (select cc, CT, CF), CF, ne => cc 10364 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10365 // setcc (select cc, CT, CF), CT, eq => cc 10366 uint64_t CT = LHS.getConstantOperandVal(1); 10367 uint64_t CF = LHS.getConstantOperandVal(2); 10368 10369 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10370 (CT == CRHSVal && CC == ISD::SETNE)) 10371 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10372 DAG.getConstant(-1, SL, MVT::i1)); 10373 if ((CF == CRHSVal && CC == ISD::SETNE) || 10374 (CT == CRHSVal && CC == ISD::SETEQ)) 10375 return LHS.getOperand(0); 10376 } 10377 } 10378 10379 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10380 VT != MVT::f16)) 10381 return SDValue(); 10382 10383 // Match isinf/isfinite pattern 10384 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10385 // (fcmp one (fabs x), inf) -> (fp_class x, 10386 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10387 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10388 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10389 if (!CRHS) 10390 return SDValue(); 10391 10392 const APFloat &APF = CRHS->getValueAPF(); 10393 if (APF.isInfinity() && !APF.isNegative()) { 10394 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10395 SIInstrFlags::N_INFINITY; 10396 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10397 SIInstrFlags::P_ZERO | 10398 SIInstrFlags::N_NORMAL | 10399 SIInstrFlags::P_NORMAL | 10400 SIInstrFlags::N_SUBNORMAL | 10401 SIInstrFlags::P_SUBNORMAL; 10402 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10403 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10404 DAG.getConstant(Mask, SL, MVT::i32)); 10405 } 10406 } 10407 10408 return SDValue(); 10409 } 10410 10411 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10412 DAGCombinerInfo &DCI) const { 10413 SelectionDAG &DAG = DCI.DAG; 10414 SDLoc SL(N); 10415 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10416 10417 SDValue Src = N->getOperand(0); 10418 SDValue Shift = N->getOperand(0); 10419 10420 // TODO: Extend type shouldn't matter (assuming legal types). 10421 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10422 Shift = Shift.getOperand(0); 10423 10424 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10425 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10426 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10427 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10428 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10429 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10430 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10431 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10432 SDLoc(Shift.getOperand(0)), MVT::i32); 10433 10434 unsigned ShiftOffset = 8 * Offset; 10435 if (Shift.getOpcode() == ISD::SHL) 10436 ShiftOffset -= C->getZExtValue(); 10437 else 10438 ShiftOffset += C->getZExtValue(); 10439 10440 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10441 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10442 MVT::f32, Shift); 10443 } 10444 } 10445 } 10446 10447 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10448 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10449 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10450 // We simplified Src. If this node is not dead, visit it again so it is 10451 // folded properly. 10452 if (N->getOpcode() != ISD::DELETED_NODE) 10453 DCI.AddToWorklist(N); 10454 return SDValue(N, 0); 10455 } 10456 10457 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10458 if (SDValue DemandedSrc = 10459 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10460 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10461 10462 return SDValue(); 10463 } 10464 10465 SDValue SITargetLowering::performClampCombine(SDNode *N, 10466 DAGCombinerInfo &DCI) const { 10467 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10468 if (!CSrc) 10469 return SDValue(); 10470 10471 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10472 const APFloat &F = CSrc->getValueAPF(); 10473 APFloat Zero = APFloat::getZero(F.getSemantics()); 10474 if (F < Zero || 10475 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10476 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10477 } 10478 10479 APFloat One(F.getSemantics(), "1.0"); 10480 if (F > One) 10481 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10482 10483 return SDValue(CSrc, 0); 10484 } 10485 10486 10487 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10488 DAGCombinerInfo &DCI) const { 10489 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10490 return SDValue(); 10491 switch (N->getOpcode()) { 10492 default: 10493 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10494 case ISD::ADD: 10495 return performAddCombine(N, DCI); 10496 case ISD::SUB: 10497 return performSubCombine(N, DCI); 10498 case ISD::ADDCARRY: 10499 case ISD::SUBCARRY: 10500 return performAddCarrySubCarryCombine(N, DCI); 10501 case ISD::FADD: 10502 return performFAddCombine(N, DCI); 10503 case ISD::FSUB: 10504 return performFSubCombine(N, DCI); 10505 case ISD::SETCC: 10506 return performSetCCCombine(N, DCI); 10507 case ISD::FMAXNUM: 10508 case ISD::FMINNUM: 10509 case ISD::FMAXNUM_IEEE: 10510 case ISD::FMINNUM_IEEE: 10511 case ISD::SMAX: 10512 case ISD::SMIN: 10513 case ISD::UMAX: 10514 case ISD::UMIN: 10515 case AMDGPUISD::FMIN_LEGACY: 10516 case AMDGPUISD::FMAX_LEGACY: 10517 return performMinMaxCombine(N, DCI); 10518 case ISD::FMA: 10519 return performFMACombine(N, DCI); 10520 case ISD::LOAD: { 10521 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10522 return Widended; 10523 LLVM_FALLTHROUGH; 10524 } 10525 case ISD::STORE: 10526 case ISD::ATOMIC_LOAD: 10527 case ISD::ATOMIC_STORE: 10528 case ISD::ATOMIC_CMP_SWAP: 10529 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10530 case ISD::ATOMIC_SWAP: 10531 case ISD::ATOMIC_LOAD_ADD: 10532 case ISD::ATOMIC_LOAD_SUB: 10533 case ISD::ATOMIC_LOAD_AND: 10534 case ISD::ATOMIC_LOAD_OR: 10535 case ISD::ATOMIC_LOAD_XOR: 10536 case ISD::ATOMIC_LOAD_NAND: 10537 case ISD::ATOMIC_LOAD_MIN: 10538 case ISD::ATOMIC_LOAD_MAX: 10539 case ISD::ATOMIC_LOAD_UMIN: 10540 case ISD::ATOMIC_LOAD_UMAX: 10541 case ISD::ATOMIC_LOAD_FADD: 10542 case AMDGPUISD::ATOMIC_INC: 10543 case AMDGPUISD::ATOMIC_DEC: 10544 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10545 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10546 if (DCI.isBeforeLegalize()) 10547 break; 10548 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10549 case ISD::AND: 10550 return performAndCombine(N, DCI); 10551 case ISD::OR: 10552 return performOrCombine(N, DCI); 10553 case ISD::XOR: 10554 return performXorCombine(N, DCI); 10555 case ISD::ZERO_EXTEND: 10556 return performZeroExtendCombine(N, DCI); 10557 case ISD::SIGN_EXTEND_INREG: 10558 return performSignExtendInRegCombine(N , DCI); 10559 case AMDGPUISD::FP_CLASS: 10560 return performClassCombine(N, DCI); 10561 case ISD::FCANONICALIZE: 10562 return performFCanonicalizeCombine(N, DCI); 10563 case AMDGPUISD::RCP: 10564 return performRcpCombine(N, DCI); 10565 case AMDGPUISD::FRACT: 10566 case AMDGPUISD::RSQ: 10567 case AMDGPUISD::RCP_LEGACY: 10568 case AMDGPUISD::RCP_IFLAG: 10569 case AMDGPUISD::RSQ_CLAMP: 10570 case AMDGPUISD::LDEXP: { 10571 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10572 SDValue Src = N->getOperand(0); 10573 if (Src.isUndef()) 10574 return Src; 10575 break; 10576 } 10577 case ISD::SINT_TO_FP: 10578 case ISD::UINT_TO_FP: 10579 return performUCharToFloatCombine(N, DCI); 10580 case AMDGPUISD::CVT_F32_UBYTE0: 10581 case AMDGPUISD::CVT_F32_UBYTE1: 10582 case AMDGPUISD::CVT_F32_UBYTE2: 10583 case AMDGPUISD::CVT_F32_UBYTE3: 10584 return performCvtF32UByteNCombine(N, DCI); 10585 case AMDGPUISD::FMED3: 10586 return performFMed3Combine(N, DCI); 10587 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10588 return performCvtPkRTZCombine(N, DCI); 10589 case AMDGPUISD::CLAMP: 10590 return performClampCombine(N, DCI); 10591 case ISD::SCALAR_TO_VECTOR: { 10592 SelectionDAG &DAG = DCI.DAG; 10593 EVT VT = N->getValueType(0); 10594 10595 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10596 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10597 SDLoc SL(N); 10598 SDValue Src = N->getOperand(0); 10599 EVT EltVT = Src.getValueType(); 10600 if (EltVT == MVT::f16) 10601 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10602 10603 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10604 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10605 } 10606 10607 break; 10608 } 10609 case ISD::EXTRACT_VECTOR_ELT: 10610 return performExtractVectorEltCombine(N, DCI); 10611 case ISD::INSERT_VECTOR_ELT: 10612 return performInsertVectorEltCombine(N, DCI); 10613 } 10614 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10615 } 10616 10617 /// Helper function for adjustWritemask 10618 static unsigned SubIdx2Lane(unsigned Idx) { 10619 switch (Idx) { 10620 default: return 0; 10621 case AMDGPU::sub0: return 0; 10622 case AMDGPU::sub1: return 1; 10623 case AMDGPU::sub2: return 2; 10624 case AMDGPU::sub3: return 3; 10625 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10626 } 10627 } 10628 10629 /// Adjust the writemask of MIMG instructions 10630 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10631 SelectionDAG &DAG) const { 10632 unsigned Opcode = Node->getMachineOpcode(); 10633 10634 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10635 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10636 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10637 return Node; // not implemented for D16 10638 10639 SDNode *Users[5] = { nullptr }; 10640 unsigned Lane = 0; 10641 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10642 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10643 unsigned NewDmask = 0; 10644 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10645 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10646 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10647 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10648 unsigned TFCLane = 0; 10649 bool HasChain = Node->getNumValues() > 1; 10650 10651 if (OldDmask == 0) { 10652 // These are folded out, but on the chance it happens don't assert. 10653 return Node; 10654 } 10655 10656 unsigned OldBitsSet = countPopulation(OldDmask); 10657 // Work out which is the TFE/LWE lane if that is enabled. 10658 if (UsesTFC) { 10659 TFCLane = OldBitsSet; 10660 } 10661 10662 // Try to figure out the used register components 10663 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10664 I != E; ++I) { 10665 10666 // Don't look at users of the chain. 10667 if (I.getUse().getResNo() != 0) 10668 continue; 10669 10670 // Abort if we can't understand the usage 10671 if (!I->isMachineOpcode() || 10672 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10673 return Node; 10674 10675 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10676 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10677 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10678 // set, etc. 10679 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10680 10681 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10682 if (UsesTFC && Lane == TFCLane) { 10683 Users[Lane] = *I; 10684 } else { 10685 // Set which texture component corresponds to the lane. 10686 unsigned Comp; 10687 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10688 Comp = countTrailingZeros(Dmask); 10689 Dmask &= ~(1 << Comp); 10690 } 10691 10692 // Abort if we have more than one user per component. 10693 if (Users[Lane]) 10694 return Node; 10695 10696 Users[Lane] = *I; 10697 NewDmask |= 1 << Comp; 10698 } 10699 } 10700 10701 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10702 bool NoChannels = !NewDmask; 10703 if (NoChannels) { 10704 if (!UsesTFC) { 10705 // No uses of the result and not using TFC. Then do nothing. 10706 return Node; 10707 } 10708 // If the original dmask has one channel - then nothing to do 10709 if (OldBitsSet == 1) 10710 return Node; 10711 // Use an arbitrary dmask - required for the instruction to work 10712 NewDmask = 1; 10713 } 10714 // Abort if there's no change 10715 if (NewDmask == OldDmask) 10716 return Node; 10717 10718 unsigned BitsSet = countPopulation(NewDmask); 10719 10720 // Check for TFE or LWE - increase the number of channels by one to account 10721 // for the extra return value 10722 // This will need adjustment for D16 if this is also included in 10723 // adjustWriteMask (this function) but at present D16 are excluded. 10724 unsigned NewChannels = BitsSet + UsesTFC; 10725 10726 int NewOpcode = 10727 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10728 assert(NewOpcode != -1 && 10729 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10730 "failed to find equivalent MIMG op"); 10731 10732 // Adjust the writemask in the node 10733 SmallVector<SDValue, 12> Ops; 10734 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10735 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10736 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10737 10738 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10739 10740 MVT ResultVT = NewChannels == 1 ? 10741 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10742 NewChannels == 5 ? 8 : NewChannels); 10743 SDVTList NewVTList = HasChain ? 10744 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10745 10746 10747 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10748 NewVTList, Ops); 10749 10750 if (HasChain) { 10751 // Update chain. 10752 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10753 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10754 } 10755 10756 if (NewChannels == 1) { 10757 assert(Node->hasNUsesOfValue(1, 0)); 10758 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10759 SDLoc(Node), Users[Lane]->getValueType(0), 10760 SDValue(NewNode, 0)); 10761 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10762 return nullptr; 10763 } 10764 10765 // Update the users of the node with the new indices 10766 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10767 SDNode *User = Users[i]; 10768 if (!User) { 10769 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10770 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10771 if (i || !NoChannels) 10772 continue; 10773 } else { 10774 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10775 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10776 } 10777 10778 switch (Idx) { 10779 default: break; 10780 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10781 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10782 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10783 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10784 } 10785 } 10786 10787 DAG.RemoveDeadNode(Node); 10788 return nullptr; 10789 } 10790 10791 static bool isFrameIndexOp(SDValue Op) { 10792 if (Op.getOpcode() == ISD::AssertZext) 10793 Op = Op.getOperand(0); 10794 10795 return isa<FrameIndexSDNode>(Op); 10796 } 10797 10798 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10799 /// with frame index operands. 10800 /// LLVM assumes that inputs are to these instructions are registers. 10801 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10802 SelectionDAG &DAG) const { 10803 if (Node->getOpcode() == ISD::CopyToReg) { 10804 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10805 SDValue SrcVal = Node->getOperand(2); 10806 10807 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10808 // to try understanding copies to physical registers. 10809 if (SrcVal.getValueType() == MVT::i1 && 10810 Register::isPhysicalRegister(DestReg->getReg())) { 10811 SDLoc SL(Node); 10812 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10813 SDValue VReg = DAG.getRegister( 10814 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10815 10816 SDNode *Glued = Node->getGluedNode(); 10817 SDValue ToVReg 10818 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10819 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10820 SDValue ToResultReg 10821 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10822 VReg, ToVReg.getValue(1)); 10823 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10824 DAG.RemoveDeadNode(Node); 10825 return ToResultReg.getNode(); 10826 } 10827 } 10828 10829 SmallVector<SDValue, 8> Ops; 10830 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10831 if (!isFrameIndexOp(Node->getOperand(i))) { 10832 Ops.push_back(Node->getOperand(i)); 10833 continue; 10834 } 10835 10836 SDLoc DL(Node); 10837 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10838 Node->getOperand(i).getValueType(), 10839 Node->getOperand(i)), 0)); 10840 } 10841 10842 return DAG.UpdateNodeOperands(Node, Ops); 10843 } 10844 10845 /// Fold the instructions after selecting them. 10846 /// Returns null if users were already updated. 10847 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10848 SelectionDAG &DAG) const { 10849 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10850 unsigned Opcode = Node->getMachineOpcode(); 10851 10852 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10853 !TII->isGather4(Opcode)) { 10854 return adjustWritemask(Node, DAG); 10855 } 10856 10857 if (Opcode == AMDGPU::INSERT_SUBREG || 10858 Opcode == AMDGPU::REG_SEQUENCE) { 10859 legalizeTargetIndependentNode(Node, DAG); 10860 return Node; 10861 } 10862 10863 switch (Opcode) { 10864 case AMDGPU::V_DIV_SCALE_F32: 10865 case AMDGPU::V_DIV_SCALE_F64: { 10866 // Satisfy the operand register constraint when one of the inputs is 10867 // undefined. Ordinarily each undef value will have its own implicit_def of 10868 // a vreg, so force these to use a single register. 10869 SDValue Src0 = Node->getOperand(0); 10870 SDValue Src1 = Node->getOperand(1); 10871 SDValue Src2 = Node->getOperand(2); 10872 10873 if ((Src0.isMachineOpcode() && 10874 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10875 (Src0 == Src1 || Src0 == Src2)) 10876 break; 10877 10878 MVT VT = Src0.getValueType().getSimpleVT(); 10879 const TargetRegisterClass *RC = 10880 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10881 10882 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10883 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10884 10885 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10886 UndefReg, Src0, SDValue()); 10887 10888 // src0 must be the same register as src1 or src2, even if the value is 10889 // undefined, so make sure we don't violate this constraint. 10890 if (Src0.isMachineOpcode() && 10891 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10892 if (Src1.isMachineOpcode() && 10893 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10894 Src0 = Src1; 10895 else if (Src2.isMachineOpcode() && 10896 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10897 Src0 = Src2; 10898 else { 10899 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10900 Src0 = UndefReg; 10901 Src1 = UndefReg; 10902 } 10903 } else 10904 break; 10905 10906 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10907 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10908 Ops.push_back(Node->getOperand(I)); 10909 10910 Ops.push_back(ImpDef.getValue(1)); 10911 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10912 } 10913 default: 10914 break; 10915 } 10916 10917 return Node; 10918 } 10919 10920 /// Assign the register class depending on the number of 10921 /// bits set in the writemask 10922 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10923 SDNode *Node) const { 10924 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10925 10926 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10927 10928 if (TII->isVOP3(MI.getOpcode())) { 10929 // Make sure constant bus requirements are respected. 10930 TII->legalizeOperandsVOP3(MRI, MI); 10931 10932 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10933 // This saves a chain-copy of registers and better ballance register 10934 // use between vgpr and agpr as agpr tuples tend to be big. 10935 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10936 unsigned Opc = MI.getOpcode(); 10937 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10938 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10939 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10940 if (I == -1) 10941 break; 10942 MachineOperand &Op = MI.getOperand(I); 10943 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10944 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10945 !Register::isVirtualRegister(Op.getReg()) || 10946 !TRI->isAGPR(MRI, Op.getReg())) 10947 continue; 10948 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10949 if (!Src || !Src->isCopy() || 10950 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10951 continue; 10952 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10953 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10954 // All uses of agpr64 and agpr32 can also accept vgpr except for 10955 // v_accvgpr_read, but we do not produce agpr reads during selection, 10956 // so no use checks are needed. 10957 MRI.setRegClass(Op.getReg(), NewRC); 10958 } 10959 } 10960 10961 return; 10962 } 10963 10964 // Replace unused atomics with the no return version. 10965 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10966 if (NoRetAtomicOp != -1) { 10967 if (!Node->hasAnyUseOfValue(0)) { 10968 MI.setDesc(TII->get(NoRetAtomicOp)); 10969 MI.RemoveOperand(0); 10970 return; 10971 } 10972 10973 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10974 // instruction, because the return type of these instructions is a vec2 of 10975 // the memory type, so it can be tied to the input operand. 10976 // This means these instructions always have a use, so we need to add a 10977 // special case to check if the atomic has only one extract_subreg use, 10978 // which itself has no uses. 10979 if ((Node->hasNUsesOfValue(1, 0) && 10980 Node->use_begin()->isMachineOpcode() && 10981 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10982 !Node->use_begin()->hasAnyUseOfValue(0))) { 10983 Register Def = MI.getOperand(0).getReg(); 10984 10985 // Change this into a noret atomic. 10986 MI.setDesc(TII->get(NoRetAtomicOp)); 10987 MI.RemoveOperand(0); 10988 10989 // If we only remove the def operand from the atomic instruction, the 10990 // extract_subreg will be left with a use of a vreg without a def. 10991 // So we need to insert an implicit_def to avoid machine verifier 10992 // errors. 10993 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10994 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10995 } 10996 return; 10997 } 10998 } 10999 11000 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11001 uint64_t Val) { 11002 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11003 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11004 } 11005 11006 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11007 const SDLoc &DL, 11008 SDValue Ptr) const { 11009 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11010 11011 // Build the half of the subregister with the constants before building the 11012 // full 128-bit register. If we are building multiple resource descriptors, 11013 // this will allow CSEing of the 2-component register. 11014 const SDValue Ops0[] = { 11015 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11016 buildSMovImm32(DAG, DL, 0), 11017 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11018 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11019 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11020 }; 11021 11022 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11023 MVT::v2i32, Ops0), 0); 11024 11025 // Combine the constants and the pointer. 11026 const SDValue Ops1[] = { 11027 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11028 Ptr, 11029 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11030 SubRegHi, 11031 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11032 }; 11033 11034 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11035 } 11036 11037 /// Return a resource descriptor with the 'Add TID' bit enabled 11038 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11039 /// of the resource descriptor) to create an offset, which is added to 11040 /// the resource pointer. 11041 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11042 SDValue Ptr, uint32_t RsrcDword1, 11043 uint64_t RsrcDword2And3) const { 11044 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11045 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11046 if (RsrcDword1) { 11047 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11048 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11049 0); 11050 } 11051 11052 SDValue DataLo = buildSMovImm32(DAG, DL, 11053 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11054 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11055 11056 const SDValue Ops[] = { 11057 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11058 PtrLo, 11059 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11060 PtrHi, 11061 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11062 DataLo, 11063 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11064 DataHi, 11065 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11066 }; 11067 11068 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11069 } 11070 11071 //===----------------------------------------------------------------------===// 11072 // SI Inline Assembly Support 11073 //===----------------------------------------------------------------------===// 11074 11075 std::pair<unsigned, const TargetRegisterClass *> 11076 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11077 StringRef Constraint, 11078 MVT VT) const { 11079 const TargetRegisterClass *RC = nullptr; 11080 if (Constraint.size() == 1) { 11081 const unsigned BitWidth = VT.getSizeInBits(); 11082 switch (Constraint[0]) { 11083 default: 11084 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11085 case 's': 11086 case 'r': 11087 switch (BitWidth) { 11088 case 16: 11089 RC = &AMDGPU::SReg_32RegClass; 11090 break; 11091 case 64: 11092 RC = &AMDGPU::SGPR_64RegClass; 11093 break; 11094 default: 11095 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11096 if (!RC) 11097 return std::make_pair(0U, nullptr); 11098 break; 11099 } 11100 break; 11101 case 'v': 11102 switch (BitWidth) { 11103 case 16: 11104 RC = &AMDGPU::VGPR_32RegClass; 11105 break; 11106 default: 11107 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11108 if (!RC) 11109 return std::make_pair(0U, nullptr); 11110 break; 11111 } 11112 break; 11113 case 'a': 11114 if (!Subtarget->hasMAIInsts()) 11115 break; 11116 switch (BitWidth) { 11117 case 16: 11118 RC = &AMDGPU::AGPR_32RegClass; 11119 break; 11120 default: 11121 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11122 if (!RC) 11123 return std::make_pair(0U, nullptr); 11124 break; 11125 } 11126 break; 11127 } 11128 // We actually support i128, i16 and f16 as inline parameters 11129 // even if they are not reported as legal 11130 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11131 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11132 return std::make_pair(0U, RC); 11133 } 11134 11135 if (Constraint.size() > 1) { 11136 if (Constraint[1] == 'v') { 11137 RC = &AMDGPU::VGPR_32RegClass; 11138 } else if (Constraint[1] == 's') { 11139 RC = &AMDGPU::SGPR_32RegClass; 11140 } else if (Constraint[1] == 'a') { 11141 RC = &AMDGPU::AGPR_32RegClass; 11142 } 11143 11144 if (RC) { 11145 uint32_t Idx; 11146 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11147 if (!Failed && Idx < RC->getNumRegs()) 11148 return std::make_pair(RC->getRegister(Idx), RC); 11149 } 11150 } 11151 11152 // FIXME: Returns VS_32 for physical SGPR constraints 11153 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11154 } 11155 11156 SITargetLowering::ConstraintType 11157 SITargetLowering::getConstraintType(StringRef Constraint) const { 11158 if (Constraint.size() == 1) { 11159 switch (Constraint[0]) { 11160 default: break; 11161 case 's': 11162 case 'v': 11163 case 'a': 11164 return C_RegisterClass; 11165 case 'A': 11166 return C_Other; 11167 } 11168 } 11169 return TargetLowering::getConstraintType(Constraint); 11170 } 11171 11172 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11173 std::string &Constraint, 11174 std::vector<SDValue> &Ops, 11175 SelectionDAG &DAG) const { 11176 if (Constraint.length() == 1 && Constraint[0] == 'A') { 11177 LowerAsmOperandForConstraintA(Op, Ops, DAG); 11178 } else { 11179 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11180 } 11181 } 11182 11183 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op, 11184 std::vector<SDValue> &Ops, 11185 SelectionDAG &DAG) const { 11186 unsigned Size = Op.getScalarValueSizeInBits(); 11187 if (Size > 64) 11188 return; 11189 11190 uint64_t Val; 11191 bool IsConst = false; 11192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11193 Val = C->getSExtValue(); 11194 IsConst = true; 11195 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11196 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11197 IsConst = true; 11198 } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11199 if (Size != 16 || Op.getNumOperands() != 2) 11200 return; 11201 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11202 return; 11203 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11204 Val = C->getSExtValue(); 11205 IsConst = true; 11206 } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11207 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11208 IsConst = true; 11209 } 11210 } 11211 11212 if (IsConst) { 11213 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11214 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11215 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11216 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11217 // Clear unused bits of fp constants 11218 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11219 unsigned UnusedBits = 64 - Size; 11220 Val = (Val << UnusedBits) >> UnusedBits; 11221 } 11222 auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64); 11223 Ops.push_back(Res); 11224 } 11225 } 11226 } 11227 11228 // Figure out which registers should be reserved for stack access. Only after 11229 // the function is legalized do we know all of the non-spill stack objects or if 11230 // calls are present. 11231 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11232 MachineRegisterInfo &MRI = MF.getRegInfo(); 11233 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11234 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11235 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11236 11237 if (Info->isEntryFunction()) { 11238 // Callable functions have fixed registers used for stack access. 11239 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11240 } 11241 11242 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11243 Info->getStackPtrOffsetReg())); 11244 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11245 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11246 11247 // We need to worry about replacing the default register with itself in case 11248 // of MIR testcases missing the MFI. 11249 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11250 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11251 11252 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11253 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11254 11255 Info->limitOccupancy(MF); 11256 11257 if (ST.isWave32() && !MF.empty()) { 11258 // Add VCC_HI def because many instructions marked as imp-use VCC where 11259 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11260 // having a use of undef. 11261 11262 const SIInstrInfo *TII = ST.getInstrInfo(); 11263 DebugLoc DL; 11264 11265 MachineBasicBlock &MBB = MF.front(); 11266 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11267 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11268 11269 for (auto &MBB : MF) { 11270 for (auto &MI : MBB) { 11271 TII->fixImplicitOperands(MI); 11272 } 11273 } 11274 } 11275 11276 TargetLoweringBase::finalizeLowering(MF); 11277 11278 // Allocate a VGPR for future SGPR Spill if 11279 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11280 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11281 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11282 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11283 Info->reserveVGPRforSGPRSpills(MF); 11284 } 11285 11286 void SITargetLowering::computeKnownBitsForFrameIndex( 11287 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11288 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11289 11290 // Set the high bits to zero based on the maximum allowed scratch size per 11291 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11292 // calculation won't overflow, so assume the sign bit is never set. 11293 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11294 } 11295 11296 Align SITargetLowering::computeKnownAlignForTargetInstr( 11297 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11298 unsigned Depth) const { 11299 const MachineInstr *MI = MRI.getVRegDef(R); 11300 switch (MI->getOpcode()) { 11301 case AMDGPU::G_INTRINSIC: 11302 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11303 // FIXME: Can this move to generic code? What about the case where the call 11304 // site specifies a lower alignment? 11305 Intrinsic::ID IID = MI->getIntrinsicID(); 11306 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11307 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11308 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11309 return *RetAlign; 11310 return Align(1); 11311 } 11312 default: 11313 return Align(1); 11314 } 11315 } 11316 11317 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11318 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11319 const Align CacheLineAlign = Align(64); 11320 11321 // Pre-GFX10 target did not benefit from loop alignment 11322 if (!ML || DisableLoopAlignment || 11323 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11324 getSubtarget()->hasInstFwdPrefetchBug()) 11325 return PrefAlign; 11326 11327 // On GFX10 I$ is 4 x 64 bytes cache lines. 11328 // By default prefetcher keeps one cache line behind and reads two ahead. 11329 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11330 // behind and one ahead. 11331 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11332 // If loop fits 64 bytes it always spans no more than two cache lines and 11333 // does not need an alignment. 11334 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11335 // Else if loop is less or equal 192 bytes we need two lines behind. 11336 11337 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11338 const MachineBasicBlock *Header = ML->getHeader(); 11339 if (Header->getAlignment() != PrefAlign) 11340 return Header->getAlignment(); // Already processed. 11341 11342 unsigned LoopSize = 0; 11343 for (const MachineBasicBlock *MBB : ML->blocks()) { 11344 // If inner loop block is aligned assume in average half of the alignment 11345 // size to be added as nops. 11346 if (MBB != Header) 11347 LoopSize += MBB->getAlignment().value() / 2; 11348 11349 for (const MachineInstr &MI : *MBB) { 11350 LoopSize += TII->getInstSizeInBytes(MI); 11351 if (LoopSize > 192) 11352 return PrefAlign; 11353 } 11354 } 11355 11356 if (LoopSize <= 64) 11357 return PrefAlign; 11358 11359 if (LoopSize <= 128) 11360 return CacheLineAlign; 11361 11362 // If any of parent loops is surrounded by prefetch instructions do not 11363 // insert new for inner loop, which would reset parent's settings. 11364 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11365 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11366 auto I = Exit->getFirstNonDebugInstr(); 11367 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11368 return CacheLineAlign; 11369 } 11370 } 11371 11372 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11373 MachineBasicBlock *Exit = ML->getExitBlock(); 11374 11375 if (Pre && Exit) { 11376 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11377 TII->get(AMDGPU::S_INST_PREFETCH)) 11378 .addImm(1); // prefetch 2 lines behind PC 11379 11380 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11381 TII->get(AMDGPU::S_INST_PREFETCH)) 11382 .addImm(2); // prefetch 1 line behind PC 11383 } 11384 11385 return CacheLineAlign; 11386 } 11387 11388 LLVM_ATTRIBUTE_UNUSED 11389 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11390 assert(N->getOpcode() == ISD::CopyFromReg); 11391 do { 11392 // Follow the chain until we find an INLINEASM node. 11393 N = N->getOperand(0).getNode(); 11394 if (N->getOpcode() == ISD::INLINEASM || 11395 N->getOpcode() == ISD::INLINEASM_BR) 11396 return true; 11397 } while (N->getOpcode() == ISD::CopyFromReg); 11398 return false; 11399 } 11400 11401 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11402 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11403 { 11404 switch (N->getOpcode()) { 11405 case ISD::CopyFromReg: 11406 { 11407 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11408 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11409 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11410 Register Reg = R->getReg(); 11411 11412 // FIXME: Why does this need to consider isLiveIn? 11413 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11414 return !TRI->isSGPRReg(MRI, Reg); 11415 11416 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11417 return KDA->isDivergent(V); 11418 11419 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11420 return !TRI->isSGPRReg(MRI, Reg); 11421 } 11422 break; 11423 case ISD::LOAD: { 11424 const LoadSDNode *L = cast<LoadSDNode>(N); 11425 unsigned AS = L->getAddressSpace(); 11426 // A flat load may access private memory. 11427 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11428 } break; 11429 case ISD::CALLSEQ_END: 11430 return true; 11431 break; 11432 case ISD::INTRINSIC_WO_CHAIN: 11433 { 11434 11435 } 11436 return AMDGPU::isIntrinsicSourceOfDivergence( 11437 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11438 case ISD::INTRINSIC_W_CHAIN: 11439 return AMDGPU::isIntrinsicSourceOfDivergence( 11440 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11441 } 11442 return false; 11443 } 11444 11445 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11446 EVT VT) const { 11447 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11448 case MVT::f32: 11449 return hasFP32Denormals(DAG.getMachineFunction()); 11450 case MVT::f64: 11451 case MVT::f16: 11452 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11453 default: 11454 return false; 11455 } 11456 } 11457 11458 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11459 const SelectionDAG &DAG, 11460 bool SNaN, 11461 unsigned Depth) const { 11462 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11463 const MachineFunction &MF = DAG.getMachineFunction(); 11464 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11465 11466 if (Info->getMode().DX10Clamp) 11467 return true; // Clamped to 0. 11468 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11469 } 11470 11471 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11472 SNaN, Depth); 11473 } 11474 11475 TargetLowering::AtomicExpansionKind 11476 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11477 switch (RMW->getOperation()) { 11478 case AtomicRMWInst::FAdd: { 11479 Type *Ty = RMW->getType(); 11480 11481 // We don't have a way to support 16-bit atomics now, so just leave them 11482 // as-is. 11483 if (Ty->isHalfTy()) 11484 return AtomicExpansionKind::None; 11485 11486 if (!Ty->isFloatTy()) 11487 return AtomicExpansionKind::CmpXChg; 11488 11489 // TODO: Do have these for flat. Older targets also had them for buffers. 11490 unsigned AS = RMW->getPointerAddressSpace(); 11491 11492 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11493 return RMW->use_empty() ? AtomicExpansionKind::None : 11494 AtomicExpansionKind::CmpXChg; 11495 } 11496 11497 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11498 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11499 } 11500 default: 11501 break; 11502 } 11503 11504 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11505 } 11506 11507 const TargetRegisterClass * 11508 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11509 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11510 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11511 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11512 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11513 : &AMDGPU::SReg_32RegClass; 11514 if (!TRI->isSGPRClass(RC) && !isDivergent) 11515 return TRI->getEquivalentSGPRClass(RC); 11516 else if (TRI->isSGPRClass(RC) && isDivergent) 11517 return TRI->getEquivalentVGPRClass(RC); 11518 11519 return RC; 11520 } 11521 11522 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11523 // uniform values (as produced by the mask results of control flow intrinsics) 11524 // used outside of divergent blocks. The phi users need to also be treated as 11525 // always uniform. 11526 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11527 unsigned WaveSize) { 11528 // FIXME: We asssume we never cast the mask results of a control flow 11529 // intrinsic. 11530 // Early exit if the type won't be consistent as a compile time hack. 11531 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11532 if (!IT || IT->getBitWidth() != WaveSize) 11533 return false; 11534 11535 if (!isa<Instruction>(V)) 11536 return false; 11537 if (!Visited.insert(V).second) 11538 return false; 11539 bool Result = false; 11540 for (auto U : V->users()) { 11541 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11542 if (V == U->getOperand(1)) { 11543 switch (Intrinsic->getIntrinsicID()) { 11544 default: 11545 Result = false; 11546 break; 11547 case Intrinsic::amdgcn_if_break: 11548 case Intrinsic::amdgcn_if: 11549 case Intrinsic::amdgcn_else: 11550 Result = true; 11551 break; 11552 } 11553 } 11554 if (V == U->getOperand(0)) { 11555 switch (Intrinsic->getIntrinsicID()) { 11556 default: 11557 Result = false; 11558 break; 11559 case Intrinsic::amdgcn_end_cf: 11560 case Intrinsic::amdgcn_loop: 11561 Result = true; 11562 break; 11563 } 11564 } 11565 } else { 11566 Result = hasCFUser(U, Visited, WaveSize); 11567 } 11568 if (Result) 11569 break; 11570 } 11571 return Result; 11572 } 11573 11574 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11575 const Value *V) const { 11576 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11577 if (CI->isInlineAsm()) { 11578 // FIXME: This cannot give a correct answer. This should only trigger in 11579 // the case where inline asm returns mixed SGPR and VGPR results, used 11580 // outside the defining block. We don't have a specific result to 11581 // consider, so this assumes if any value is SGPR, the overall register 11582 // also needs to be SGPR. 11583 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11584 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11585 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11586 for (auto &TC : TargetConstraints) { 11587 if (TC.Type == InlineAsm::isOutput) { 11588 ComputeConstraintToUse(TC, SDValue()); 11589 unsigned AssignedReg; 11590 const TargetRegisterClass *RC; 11591 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11592 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11593 if (RC) { 11594 MachineRegisterInfo &MRI = MF.getRegInfo(); 11595 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11596 return true; 11597 else if (SIRI->isSGPRClass(RC)) 11598 return true; 11599 } 11600 } 11601 } 11602 } 11603 } 11604 SmallPtrSet<const Value *, 16> Visited; 11605 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11606 } 11607