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/FunctionLoweringInfo.h" 38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetCallingConv.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/ValueTypes.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugLoc.h" 58 #include "llvm/IR/DerivedTypes.h" 59 #include "llvm/IR/DiagnosticInfo.h" 60 #include "llvm/IR/Function.h" 61 #include "llvm/IR/GlobalValue.h" 62 #include "llvm/IR/InstrTypes.h" 63 #include "llvm/IR/Instruction.h" 64 #include "llvm/IR/Instructions.h" 65 #include "llvm/IR/IntrinsicInst.h" 66 #include "llvm/IR/Type.h" 67 #include "llvm/Support/Casting.h" 68 #include "llvm/Support/CodeGen.h" 69 #include "llvm/Support/CommandLine.h" 70 #include "llvm/Support/Compiler.h" 71 #include "llvm/Support/ErrorHandling.h" 72 #include "llvm/Support/KnownBits.h" 73 #include "llvm/Support/MachineValueType.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Target/TargetOptions.h" 76 #include <cassert> 77 #include <cmath> 78 #include <cstdint> 79 #include <iterator> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 86 #define DEBUG_TYPE "si-lower" 87 88 STATISTIC(NumTailCalls, "Number of tail calls"); 89 90 static cl::opt<bool> DisableLoopAlignment( 91 "amdgpu-disable-loop-alignment", 92 cl::desc("Do not align and prefetch loops"), 93 cl::init(false)); 94 95 static cl::opt<bool> VGPRReserveforSGPRSpill( 96 "amdgpu-reserve-vgpr-for-sgpr-spill", 97 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 98 99 static cl::opt<bool> UseDivergentRegisterIndexing( 100 "amdgpu-use-divergent-register-indexing", 101 cl::Hidden, 102 cl::desc("Use indirect register addressing for divergent indexes"), 103 cl::init(false)); 104 105 static bool hasFP32Denormals(const MachineFunction &MF) { 106 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 107 return Info->getMode().allFP32Denormals(); 108 } 109 110 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 111 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 112 return Info->getMode().allFP64FP16Denormals(); 113 } 114 115 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 116 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 117 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 118 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 119 return AMDGPU::SGPR0 + Reg; 120 } 121 } 122 llvm_unreachable("Cannot allocate sgpr"); 123 } 124 125 SITargetLowering::SITargetLowering(const TargetMachine &TM, 126 const GCNSubtarget &STI) 127 : AMDGPUTargetLowering(TM, STI), 128 Subtarget(&STI) { 129 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 130 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 131 132 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 133 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 134 135 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 136 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 137 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 138 139 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 140 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 141 142 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 143 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 144 145 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 146 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 147 148 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 149 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 150 151 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 152 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 153 154 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 155 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 156 157 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 158 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 159 160 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 161 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 162 163 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 164 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 165 166 if (Subtarget->has16BitInsts()) { 167 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 168 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 169 170 // Unless there are also VOP3P operations, not operations are really legal. 171 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 172 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 173 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 174 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 175 } 176 177 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 178 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 179 180 computeRegisterProperties(Subtarget->getRegisterInfo()); 181 182 // The boolean content concept here is too inflexible. Compares only ever 183 // really produce a 1-bit result. Any copy/extend from these will turn into a 184 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 185 // it's what most targets use. 186 setBooleanContents(ZeroOrOneBooleanContent); 187 setBooleanVectorContents(ZeroOrOneBooleanContent); 188 189 // We need to custom lower vector stores from local memory 190 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 196 setOperationAction(ISD::LOAD, MVT::i1, Custom); 197 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 198 199 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 204 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 205 setOperationAction(ISD::STORE, MVT::i1, Custom); 206 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 207 208 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 209 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 210 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 211 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 212 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 213 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 214 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 215 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 216 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 217 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 218 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 219 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 220 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 221 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 222 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 223 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 224 225 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 227 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 228 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 229 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 230 231 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 232 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 233 234 setOperationAction(ISD::SELECT, MVT::i1, Promote); 235 setOperationAction(ISD::SELECT, MVT::i64, Custom); 236 setOperationAction(ISD::SELECT, MVT::f64, Promote); 237 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 238 239 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 242 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 243 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 244 245 setOperationAction(ISD::SETCC, MVT::i1, Promote); 246 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 247 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 248 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 249 250 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 251 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 252 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 253 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 254 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 255 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 256 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 257 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 258 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 267 268 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 269 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 270 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 271 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 272 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 273 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 274 275 setOperationAction(ISD::UADDO, MVT::i32, Legal); 276 setOperationAction(ISD::USUBO, MVT::i32, Legal); 277 278 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 279 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 280 281 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 282 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 283 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 284 285 #if 0 286 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 287 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 288 #endif 289 290 // We only support LOAD/STORE and vector manipulation ops for vectors 291 // with > 4 elements. 292 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 293 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 294 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 295 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 296 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 297 switch (Op) { 298 case ISD::LOAD: 299 case ISD::STORE: 300 case ISD::BUILD_VECTOR: 301 case ISD::BITCAST: 302 case ISD::EXTRACT_VECTOR_ELT: 303 case ISD::INSERT_VECTOR_ELT: 304 case ISD::INSERT_SUBVECTOR: 305 case ISD::EXTRACT_SUBVECTOR: 306 case ISD::SCALAR_TO_VECTOR: 307 break; 308 case ISD::CONCAT_VECTORS: 309 setOperationAction(Op, VT, Custom); 310 break; 311 default: 312 setOperationAction(Op, VT, Expand); 313 break; 314 } 315 } 316 } 317 318 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 319 320 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 321 // is expanded to avoid having two separate loops in case the index is a VGPR. 322 323 // Most operations are naturally 32-bit vector operations. We only support 324 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 325 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 326 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 327 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 328 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 330 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 331 332 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 333 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 334 335 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 336 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 337 } 338 339 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 340 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 341 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 344 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 345 346 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 347 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 348 349 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 350 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 351 } 352 353 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 354 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 355 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 358 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 359 360 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 361 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 362 363 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 364 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 365 } 366 367 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 368 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 369 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 372 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 373 374 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 375 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 376 377 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 378 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 379 } 380 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 383 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 384 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 385 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 387 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 388 389 // Avoid stack access for these. 390 // TODO: Generalize to more vector types. 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 395 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 401 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 404 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 405 406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 409 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 410 411 // Deal with vec3 vector operations when widened to vec4. 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 416 417 // Deal with vec5 vector operations when widened to vec8. 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 420 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 421 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 422 423 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 424 // and output demarshalling 425 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 426 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 427 428 // We can't return success/failure, only the old value, 429 // let LLVM add the comparison 430 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 431 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 432 433 if (Subtarget->hasFlatAddressSpace()) { 434 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 435 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 436 } 437 438 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 439 440 // FIXME: This should be narrowed to i32, but that only happens if i64 is 441 // illegal. 442 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 443 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 444 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 445 446 // On SI this is s_memtime and s_memrealtime on VI. 447 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 448 setOperationAction(ISD::TRAP, MVT::Other, Custom); 449 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 450 451 if (Subtarget->has16BitInsts()) { 452 setOperationAction(ISD::FPOW, MVT::f16, Promote); 453 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 454 setOperationAction(ISD::FLOG, MVT::f16, Custom); 455 setOperationAction(ISD::FEXP, MVT::f16, Custom); 456 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 457 } 458 459 if (Subtarget->hasMadMacF32Insts()) 460 setOperationAction(ISD::FMAD, MVT::f32, Legal); 461 462 if (!Subtarget->hasBFI()) { 463 // fcopysign can be done in a single instruction with BFI. 464 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 465 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 466 } 467 468 if (!Subtarget->hasBCNT(32)) 469 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 470 471 if (!Subtarget->hasBCNT(64)) 472 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 473 474 if (Subtarget->hasFFBH()) 475 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 476 477 if (Subtarget->hasFFBL()) 478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 479 480 // We only really have 32-bit BFE instructions (and 16-bit on VI). 481 // 482 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 483 // effort to match them now. We want this to be false for i64 cases when the 484 // extraction isn't restricted to the upper or lower half. Ideally we would 485 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 486 // span the midpoint are probably relatively rare, so don't worry about them 487 // for now. 488 if (Subtarget->hasBFE()) 489 setHasExtractBitsInsn(true); 490 491 // Clamp modifier on add/sub 492 if (Subtarget->hasIntClamp()) { 493 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 494 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 495 } 496 497 if (Subtarget->hasAddNoCarry()) { 498 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 502 } 503 504 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 508 509 510 // These are really only legal for ieee_mode functions. We should be avoiding 511 // them for functions that don't have ieee_mode enabled, so just say they are 512 // legal. 513 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 517 518 519 if (Subtarget->haveRoundOpsF64()) { 520 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 521 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 522 setOperationAction(ISD::FRINT, MVT::f64, Legal); 523 } else { 524 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 525 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 526 setOperationAction(ISD::FRINT, MVT::f64, Custom); 527 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 528 } 529 530 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 531 532 setOperationAction(ISD::FSIN, MVT::f32, Custom); 533 setOperationAction(ISD::FCOS, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f64, Custom); 536 537 if (Subtarget->has16BitInsts()) { 538 setOperationAction(ISD::Constant, MVT::i16, Legal); 539 540 setOperationAction(ISD::SMIN, MVT::i16, Legal); 541 setOperationAction(ISD::SMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::UMIN, MVT::i16, Legal); 544 setOperationAction(ISD::UMAX, MVT::i16, Legal); 545 546 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 547 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 548 549 setOperationAction(ISD::ROTR, MVT::i16, Expand); 550 setOperationAction(ISD::ROTL, MVT::i16, Expand); 551 552 setOperationAction(ISD::SDIV, MVT::i16, Promote); 553 setOperationAction(ISD::UDIV, MVT::i16, Promote); 554 setOperationAction(ISD::SREM, MVT::i16, Promote); 555 setOperationAction(ISD::UREM, MVT::i16, Promote); 556 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 557 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 558 559 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 560 561 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 566 567 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 568 569 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::LOAD, MVT::i16, Custom); 572 573 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 574 575 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 576 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 577 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 579 580 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 582 583 // F16 - Constant Actions. 584 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 585 586 // F16 - Load/Store Actions. 587 setOperationAction(ISD::LOAD, MVT::f16, Promote); 588 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 589 setOperationAction(ISD::STORE, MVT::f16, Promote); 590 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 591 592 // F16 - VOP1 Actions. 593 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 594 setOperationAction(ISD::FCOS, MVT::f16, Custom); 595 setOperationAction(ISD::FSIN, MVT::f16, Custom); 596 597 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 598 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 599 600 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 601 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 602 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 604 setOperationAction(ISD::FROUND, MVT::f16, Custom); 605 606 // F16 - VOP2 Actions. 607 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 608 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 609 610 setOperationAction(ISD::FDIV, MVT::f16, Custom); 611 612 // F16 - VOP3 Actions. 613 setOperationAction(ISD::FMA, MVT::f16, Legal); 614 if (STI.hasMadF16()) 615 setOperationAction(ISD::FMAD, MVT::f16, Legal); 616 617 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 618 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 619 switch (Op) { 620 case ISD::LOAD: 621 case ISD::STORE: 622 case ISD::BUILD_VECTOR: 623 case ISD::BITCAST: 624 case ISD::EXTRACT_VECTOR_ELT: 625 case ISD::INSERT_VECTOR_ELT: 626 case ISD::INSERT_SUBVECTOR: 627 case ISD::EXTRACT_SUBVECTOR: 628 case ISD::SCALAR_TO_VECTOR: 629 break; 630 case ISD::CONCAT_VECTORS: 631 setOperationAction(Op, VT, Custom); 632 break; 633 default: 634 setOperationAction(Op, VT, Expand); 635 break; 636 } 637 } 638 } 639 640 // v_perm_b32 can handle either of these. 641 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 643 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 644 645 // XXX - Do these do anything? Vector constants turn into build_vector. 646 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 647 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 648 649 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 650 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 653 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 654 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 655 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 656 657 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 658 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 659 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 660 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 661 662 setOperationAction(ISD::AND, MVT::v2i16, Promote); 663 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 664 setOperationAction(ISD::OR, MVT::v2i16, Promote); 665 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 666 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 668 669 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 670 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 671 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 672 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 673 674 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 675 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 676 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 677 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 678 679 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 682 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 683 684 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 686 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 687 688 if (!Subtarget->hasVOP3PInsts()) { 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 690 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 691 } 692 693 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 694 // This isn't really legal, but this avoids the legalizer unrolling it (and 695 // allows matching fneg (fabs x) patterns) 696 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 697 698 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 700 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 701 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 702 703 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 704 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 705 706 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 707 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 708 } 709 710 if (Subtarget->hasVOP3PInsts()) { 711 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 712 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 713 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 716 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 717 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 719 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 720 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 721 722 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 725 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 726 727 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 730 731 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 732 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 733 734 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 735 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 741 742 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 744 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 745 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 746 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 747 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 748 749 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 750 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 752 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 753 754 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 757 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 758 759 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 762 763 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 764 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 765 766 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 768 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 769 770 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 772 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 773 } 774 775 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 776 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 777 778 if (Subtarget->has16BitInsts()) { 779 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 780 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 781 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 782 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 783 } else { 784 // Legalization hack. 785 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 786 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 787 788 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 789 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 790 } 791 792 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 793 setOperationAction(ISD::SELECT, VT, Custom); 794 } 795 796 setOperationAction(ISD::SMULO, MVT::i64, Custom); 797 setOperationAction(ISD::UMULO, MVT::i64, Custom); 798 799 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 801 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 802 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 803 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 805 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 806 807 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 808 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 809 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 810 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 811 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 812 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 813 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 815 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 816 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 817 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 818 819 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 820 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 821 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 822 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 823 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 824 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 825 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 826 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 827 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 828 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 829 830 setTargetDAGCombine(ISD::ADD); 831 setTargetDAGCombine(ISD::ADDCARRY); 832 setTargetDAGCombine(ISD::SUB); 833 setTargetDAGCombine(ISD::SUBCARRY); 834 setTargetDAGCombine(ISD::FADD); 835 setTargetDAGCombine(ISD::FSUB); 836 setTargetDAGCombine(ISD::FMINNUM); 837 setTargetDAGCombine(ISD::FMAXNUM); 838 setTargetDAGCombine(ISD::FMINNUM_IEEE); 839 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 840 setTargetDAGCombine(ISD::FMA); 841 setTargetDAGCombine(ISD::SMIN); 842 setTargetDAGCombine(ISD::SMAX); 843 setTargetDAGCombine(ISD::UMIN); 844 setTargetDAGCombine(ISD::UMAX); 845 setTargetDAGCombine(ISD::SETCC); 846 setTargetDAGCombine(ISD::AND); 847 setTargetDAGCombine(ISD::OR); 848 setTargetDAGCombine(ISD::XOR); 849 setTargetDAGCombine(ISD::SINT_TO_FP); 850 setTargetDAGCombine(ISD::UINT_TO_FP); 851 setTargetDAGCombine(ISD::FCANONICALIZE); 852 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 853 setTargetDAGCombine(ISD::ZERO_EXTEND); 854 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 855 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 856 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 857 858 // All memory operations. Some folding on the pointer operand is done to help 859 // matching the constant offsets in the addressing modes. 860 setTargetDAGCombine(ISD::LOAD); 861 setTargetDAGCombine(ISD::STORE); 862 setTargetDAGCombine(ISD::ATOMIC_LOAD); 863 setTargetDAGCombine(ISD::ATOMIC_STORE); 864 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 865 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 866 setTargetDAGCombine(ISD::ATOMIC_SWAP); 867 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 868 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 870 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 871 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 872 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 873 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 874 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 875 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 876 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 877 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 878 setTargetDAGCombine(ISD::INTRINSIC_VOID); 879 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 880 881 // FIXME: In other contexts we pretend this is a per-function property. 882 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 883 884 setSchedulingPreference(Sched::RegPressure); 885 } 886 887 const GCNSubtarget *SITargetLowering::getSubtarget() const { 888 return Subtarget; 889 } 890 891 //===----------------------------------------------------------------------===// 892 // TargetLowering queries 893 //===----------------------------------------------------------------------===// 894 895 // v_mad_mix* support a conversion from f16 to f32. 896 // 897 // There is only one special case when denormals are enabled we don't currently, 898 // where this is OK to use. 899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 900 EVT DestVT, EVT SrcVT) const { 901 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 902 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 903 DestVT.getScalarType() == MVT::f32 && 904 SrcVT.getScalarType() == MVT::f16 && 905 // TODO: This probably only requires no input flushing? 906 !hasFP32Denormals(DAG.getMachineFunction()); 907 } 908 909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 910 // SI has some legal vector types, but no legal vector operations. Say no 911 // shuffles are legal in order to prefer scalarizing some vector operations. 912 return false; 913 } 914 915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 916 CallingConv::ID CC, 917 EVT VT) const { 918 if (CC == CallingConv::AMDGPU_KERNEL) 919 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 920 921 if (VT.isVector()) { 922 EVT ScalarVT = VT.getScalarType(); 923 unsigned Size = ScalarVT.getSizeInBits(); 924 if (Size == 16) { 925 if (Subtarget->has16BitInsts()) 926 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 927 return VT.isInteger() ? MVT::i32 : MVT::f32; 928 } 929 930 if (Size < 16) 931 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 932 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 933 } 934 935 if (VT.getSizeInBits() > 32) 936 return MVT::i32; 937 938 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 939 } 940 941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 942 CallingConv::ID CC, 943 EVT VT) const { 944 if (CC == CallingConv::AMDGPU_KERNEL) 945 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 946 947 if (VT.isVector()) { 948 unsigned NumElts = VT.getVectorNumElements(); 949 EVT ScalarVT = VT.getScalarType(); 950 unsigned Size = ScalarVT.getSizeInBits(); 951 952 // FIXME: Should probably promote 8-bit vectors to i16. 953 if (Size == 16 && Subtarget->has16BitInsts()) 954 return (NumElts + 1) / 2; 955 956 if (Size <= 32) 957 return NumElts; 958 959 if (Size > 32) 960 return NumElts * ((Size + 31) / 32); 961 } else if (VT.getSizeInBits() > 32) 962 return (VT.getSizeInBits() + 31) / 32; 963 964 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 965 } 966 967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 968 LLVMContext &Context, CallingConv::ID CC, 969 EVT VT, EVT &IntermediateVT, 970 unsigned &NumIntermediates, MVT &RegisterVT) const { 971 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 972 unsigned NumElts = VT.getVectorNumElements(); 973 EVT ScalarVT = VT.getScalarType(); 974 unsigned Size = ScalarVT.getSizeInBits(); 975 // FIXME: We should fix the ABI to be the same on targets without 16-bit 976 // support, but unless we can properly handle 3-vectors, it will be still be 977 // inconsistent. 978 if (Size == 16 && Subtarget->has16BitInsts()) { 979 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 980 IntermediateVT = RegisterVT; 981 NumIntermediates = (NumElts + 1) / 2; 982 return NumIntermediates; 983 } 984 985 if (Size == 32) { 986 RegisterVT = ScalarVT.getSimpleVT(); 987 IntermediateVT = RegisterVT; 988 NumIntermediates = NumElts; 989 return NumIntermediates; 990 } 991 992 if (Size < 16 && Subtarget->has16BitInsts()) { 993 // FIXME: Should probably form v2i16 pieces 994 RegisterVT = MVT::i16; 995 IntermediateVT = ScalarVT; 996 NumIntermediates = NumElts; 997 return NumIntermediates; 998 } 999 1000 1001 if (Size != 16 && Size <= 32) { 1002 RegisterVT = MVT::i32; 1003 IntermediateVT = ScalarVT; 1004 NumIntermediates = NumElts; 1005 return NumIntermediates; 1006 } 1007 1008 if (Size > 32) { 1009 RegisterVT = MVT::i32; 1010 IntermediateVT = RegisterVT; 1011 NumIntermediates = NumElts * ((Size + 31) / 32); 1012 return NumIntermediates; 1013 } 1014 } 1015 1016 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1017 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1018 } 1019 1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1021 assert(DMaskLanes != 0); 1022 1023 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1024 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1025 return EVT::getVectorVT(Ty->getContext(), 1026 EVT::getEVT(VT->getElementType()), 1027 NumElts); 1028 } 1029 1030 return EVT::getEVT(Ty); 1031 } 1032 1033 // Peek through TFE struct returns to only use the data size. 1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1035 auto *ST = dyn_cast<StructType>(Ty); 1036 if (!ST) 1037 return memVTFromImageData(Ty, DMaskLanes); 1038 1039 // Some intrinsics return an aggregate type - special case to work out the 1040 // correct memVT. 1041 // 1042 // Only limited forms of aggregate type currently expected. 1043 if (ST->getNumContainedTypes() != 2 || 1044 !ST->getContainedType(1)->isIntegerTy(32)) 1045 return EVT(); 1046 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1047 } 1048 1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1050 const CallInst &CI, 1051 MachineFunction &MF, 1052 unsigned IntrID) const { 1053 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1054 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1055 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1056 (Intrinsic::ID)IntrID); 1057 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1058 return false; 1059 1060 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1061 1062 if (RsrcIntr->IsImage) { 1063 Info.ptrVal = MFI->getImagePSV( 1064 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1065 CI.getArgOperand(RsrcIntr->RsrcArg)); 1066 Info.align.reset(); 1067 } else { 1068 Info.ptrVal = MFI->getBufferPSV( 1069 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1070 CI.getArgOperand(RsrcIntr->RsrcArg)); 1071 } 1072 1073 Info.flags = MachineMemOperand::MODereferenceable; 1074 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1075 unsigned DMaskLanes = 4; 1076 1077 if (RsrcIntr->IsImage) { 1078 const AMDGPU::ImageDimIntrinsicInfo *Intr 1079 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1080 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1081 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1082 1083 if (!BaseOpcode->Gather4) { 1084 // If this isn't a gather, we may have excess loaded elements in the 1085 // IR type. Check the dmask for the real number of elements loaded. 1086 unsigned DMask 1087 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1088 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1089 } 1090 1091 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1092 } else 1093 Info.memVT = EVT::getEVT(CI.getType()); 1094 1095 // FIXME: What does alignment mean for an image? 1096 Info.opc = ISD::INTRINSIC_W_CHAIN; 1097 Info.flags |= MachineMemOperand::MOLoad; 1098 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1099 Info.opc = ISD::INTRINSIC_VOID; 1100 1101 Type *DataTy = CI.getArgOperand(0)->getType(); 1102 if (RsrcIntr->IsImage) { 1103 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1104 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1105 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1106 } else 1107 Info.memVT = EVT::getEVT(DataTy); 1108 1109 Info.flags |= MachineMemOperand::MOStore; 1110 } else { 1111 // Atomic 1112 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1113 ISD::INTRINSIC_W_CHAIN; 1114 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1115 Info.flags = MachineMemOperand::MOLoad | 1116 MachineMemOperand::MOStore | 1117 MachineMemOperand::MODereferenceable; 1118 1119 // XXX - Should this be volatile without known ordering? 1120 Info.flags |= MachineMemOperand::MOVolatile; 1121 } 1122 return true; 1123 } 1124 1125 switch (IntrID) { 1126 case Intrinsic::amdgcn_atomic_inc: 1127 case Intrinsic::amdgcn_atomic_dec: 1128 case Intrinsic::amdgcn_ds_ordered_add: 1129 case Intrinsic::amdgcn_ds_ordered_swap: 1130 case Intrinsic::amdgcn_ds_fadd: 1131 case Intrinsic::amdgcn_ds_fmin: 1132 case Intrinsic::amdgcn_ds_fmax: { 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 | MachineMemOperand::MOStore; 1138 1139 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1140 if (!Vol->isZero()) 1141 Info.flags |= MachineMemOperand::MOVolatile; 1142 1143 return true; 1144 } 1145 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1146 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1147 1148 Info.opc = ISD::INTRINSIC_W_CHAIN; 1149 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1150 Info.ptrVal = MFI->getBufferPSV( 1151 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1152 CI.getArgOperand(1)); 1153 Info.align.reset(); 1154 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1155 1156 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1157 if (!Vol || !Vol->isZero()) 1158 Info.flags |= MachineMemOperand::MOVolatile; 1159 1160 return true; 1161 } 1162 case Intrinsic::amdgcn_ds_append: 1163 case Intrinsic::amdgcn_ds_consume: { 1164 Info.opc = ISD::INTRINSIC_W_CHAIN; 1165 Info.memVT = MVT::getVT(CI.getType()); 1166 Info.ptrVal = CI.getOperand(0); 1167 Info.align.reset(); 1168 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1169 1170 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1171 if (!Vol->isZero()) 1172 Info.flags |= MachineMemOperand::MOVolatile; 1173 1174 return true; 1175 } 1176 case Intrinsic::amdgcn_global_atomic_csub: { 1177 Info.opc = ISD::INTRINSIC_W_CHAIN; 1178 Info.memVT = MVT::getVT(CI.getType()); 1179 Info.ptrVal = CI.getOperand(0); 1180 Info.align.reset(); 1181 Info.flags = MachineMemOperand::MOLoad | 1182 MachineMemOperand::MOStore | 1183 MachineMemOperand::MOVolatile; 1184 return true; 1185 } 1186 case Intrinsic::amdgcn_global_atomic_fadd: { 1187 Info.opc = ISD::INTRINSIC_W_CHAIN; 1188 Info.memVT = MVT::getVT(CI.getType()); 1189 Info.ptrVal = CI.getOperand(0); 1190 Info.align.reset(); 1191 Info.flags = MachineMemOperand::MOLoad | 1192 MachineMemOperand::MOStore | 1193 MachineMemOperand::MODereferenceable | 1194 MachineMemOperand::MOVolatile; 1195 return true; 1196 } 1197 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1198 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1199 Info.opc = ISD::INTRINSIC_W_CHAIN; 1200 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1201 Info.ptrVal = MFI->getImagePSV( 1202 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5)); 1203 Info.align.reset(); 1204 Info.flags = MachineMemOperand::MOLoad | 1205 MachineMemOperand::MODereferenceable; 1206 return true; 1207 } 1208 case Intrinsic::amdgcn_ds_gws_init: 1209 case Intrinsic::amdgcn_ds_gws_barrier: 1210 case Intrinsic::amdgcn_ds_gws_sema_v: 1211 case Intrinsic::amdgcn_ds_gws_sema_br: 1212 case Intrinsic::amdgcn_ds_gws_sema_p: 1213 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1214 Info.opc = ISD::INTRINSIC_VOID; 1215 1216 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1217 Info.ptrVal = 1218 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1219 1220 // This is an abstract access, but we need to specify a type and size. 1221 Info.memVT = MVT::i32; 1222 Info.size = 4; 1223 Info.align = Align(4); 1224 1225 Info.flags = MachineMemOperand::MOStore; 1226 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1227 Info.flags = MachineMemOperand::MOLoad; 1228 return true; 1229 } 1230 default: 1231 return false; 1232 } 1233 } 1234 1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1236 SmallVectorImpl<Value*> &Ops, 1237 Type *&AccessTy) const { 1238 switch (II->getIntrinsicID()) { 1239 case Intrinsic::amdgcn_atomic_inc: 1240 case Intrinsic::amdgcn_atomic_dec: 1241 case Intrinsic::amdgcn_ds_ordered_add: 1242 case Intrinsic::amdgcn_ds_ordered_swap: 1243 case Intrinsic::amdgcn_ds_append: 1244 case Intrinsic::amdgcn_ds_consume: 1245 case Intrinsic::amdgcn_ds_fadd: 1246 case Intrinsic::amdgcn_ds_fmin: 1247 case Intrinsic::amdgcn_ds_fmax: 1248 case Intrinsic::amdgcn_global_atomic_fadd: 1249 case Intrinsic::amdgcn_global_atomic_csub: { 1250 Value *Ptr = II->getArgOperand(0); 1251 AccessTy = II->getType(); 1252 Ops.push_back(Ptr); 1253 return true; 1254 } 1255 default: 1256 return false; 1257 } 1258 } 1259 1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1261 if (!Subtarget->hasFlatInstOffsets()) { 1262 // Flat instructions do not have offsets, and only have the register 1263 // address. 1264 return AM.BaseOffs == 0 && AM.Scale == 0; 1265 } 1266 1267 return AM.Scale == 0 && 1268 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1269 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1270 /*Signed=*/false)); 1271 } 1272 1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1274 if (Subtarget->hasFlatGlobalInsts()) 1275 return AM.Scale == 0 && 1276 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1277 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1278 /*Signed=*/true)); 1279 1280 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1281 // Assume the we will use FLAT for all global memory accesses 1282 // on VI. 1283 // FIXME: This assumption is currently wrong. On VI we still use 1284 // MUBUF instructions for the r + i addressing mode. As currently 1285 // implemented, the MUBUF instructions only work on buffer < 4GB. 1286 // It may be possible to support > 4GB buffers with MUBUF instructions, 1287 // by setting the stride value in the resource descriptor which would 1288 // increase the size limit to (stride * 4GB). However, this is risky, 1289 // because it has never been validated. 1290 return isLegalFlatAddressingMode(AM); 1291 } 1292 1293 return isLegalMUBUFAddressingMode(AM); 1294 } 1295 1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1297 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1298 // additionally can do r + r + i with addr64. 32-bit has more addressing 1299 // mode options. Depending on the resource constant, it can also do 1300 // (i64 r0) + (i32 r1) * (i14 i). 1301 // 1302 // Private arrays end up using a scratch buffer most of the time, so also 1303 // assume those use MUBUF instructions. Scratch loads / stores are currently 1304 // implemented as mubuf instructions with offen bit set, so slightly 1305 // different than the normal addr64. 1306 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1307 return false; 1308 1309 // FIXME: Since we can split immediate into soffset and immediate offset, 1310 // would it make sense to allow any immediate? 1311 1312 switch (AM.Scale) { 1313 case 0: // r + i or just i, depending on HasBaseReg. 1314 return true; 1315 case 1: 1316 return true; // We have r + r or r + i. 1317 case 2: 1318 if (AM.HasBaseReg) { 1319 // Reject 2 * r + r. 1320 return false; 1321 } 1322 1323 // Allow 2 * r as r + r 1324 // Or 2 * r + i is allowed as r + r + i. 1325 return true; 1326 default: // Don't allow n * r 1327 return false; 1328 } 1329 } 1330 1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1332 const AddrMode &AM, Type *Ty, 1333 unsigned AS, Instruction *I) const { 1334 // No global is ever allowed as a base. 1335 if (AM.BaseGV) 1336 return false; 1337 1338 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1339 return isLegalGlobalAddressingMode(AM); 1340 1341 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1342 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1343 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1344 // If the offset isn't a multiple of 4, it probably isn't going to be 1345 // correctly aligned. 1346 // FIXME: Can we get the real alignment here? 1347 if (AM.BaseOffs % 4 != 0) 1348 return isLegalMUBUFAddressingMode(AM); 1349 1350 // There are no SMRD extloads, so if we have to do a small type access we 1351 // will use a MUBUF load. 1352 // FIXME?: We also need to do this if unaligned, but we don't know the 1353 // alignment here. 1354 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1355 return isLegalGlobalAddressingMode(AM); 1356 1357 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1358 // SMRD instructions have an 8-bit, dword offset on SI. 1359 if (!isUInt<8>(AM.BaseOffs / 4)) 1360 return false; 1361 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1362 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1363 // in 8-bits, it can use a smaller encoding. 1364 if (!isUInt<32>(AM.BaseOffs / 4)) 1365 return false; 1366 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1367 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1368 if (!isUInt<20>(AM.BaseOffs)) 1369 return false; 1370 } else 1371 llvm_unreachable("unhandled generation"); 1372 1373 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1374 return true; 1375 1376 if (AM.Scale == 1 && AM.HasBaseReg) 1377 return true; 1378 1379 return false; 1380 1381 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1382 return isLegalMUBUFAddressingMode(AM); 1383 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1384 AS == AMDGPUAS::REGION_ADDRESS) { 1385 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1386 // field. 1387 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1388 // an 8-bit dword offset but we don't know the alignment here. 1389 if (!isUInt<16>(AM.BaseOffs)) 1390 return false; 1391 1392 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1393 return true; 1394 1395 if (AM.Scale == 1 && AM.HasBaseReg) 1396 return true; 1397 1398 return false; 1399 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1400 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1401 // For an unknown address space, this usually means that this is for some 1402 // reason being used for pure arithmetic, and not based on some addressing 1403 // computation. We don't have instructions that compute pointers with any 1404 // addressing modes, so treat them as having no offset like flat 1405 // instructions. 1406 return isLegalFlatAddressingMode(AM); 1407 } 1408 1409 // Assume a user alias of global for unknown address spaces. 1410 return isLegalGlobalAddressingMode(AM); 1411 } 1412 1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1414 const SelectionDAG &DAG) const { 1415 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1416 return (MemVT.getSizeInBits() <= 4 * 32); 1417 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1418 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1419 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1420 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1421 return (MemVT.getSizeInBits() <= 2 * 32); 1422 } 1423 return true; 1424 } 1425 1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1427 unsigned Size, unsigned AddrSpace, Align Alignment, 1428 MachineMemOperand::Flags Flags, bool *IsFast) const { 1429 if (IsFast) 1430 *IsFast = false; 1431 1432 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1433 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1434 // Check if alignment requirements for ds_read/write instructions are 1435 // disabled. 1436 if (Subtarget->hasUnalignedDSAccess() && 1437 Subtarget->hasUnalignedAccessMode() && 1438 !Subtarget->hasLDSMisalignedBug()) { 1439 if (IsFast) 1440 *IsFast = Alignment != Align(2); 1441 return true; 1442 } 1443 1444 if (Size == 64) { 1445 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1446 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1447 // with adjacent offsets. 1448 bool AlignedBy4 = Alignment >= Align(4); 1449 if (IsFast) 1450 *IsFast = AlignedBy4; 1451 1452 return AlignedBy4; 1453 } 1454 if (Size == 96) { 1455 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1456 bool Aligned = Alignment >= Align(16); 1457 if (IsFast) 1458 *IsFast = Aligned; 1459 1460 return Aligned; 1461 } 1462 if (Size == 128) { 1463 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1464 // can do a 8 byte aligned, 16 byte access in a single operation using 1465 // ds_read2/write2_b64. 1466 bool Aligned = Alignment >= Align(8); 1467 if (IsFast) 1468 *IsFast = Aligned; 1469 1470 return Aligned; 1471 } 1472 } 1473 1474 // FIXME: We have to be conservative here and assume that flat operations 1475 // will access scratch. If we had access to the IR function, then we 1476 // could determine if any private memory was used in the function. 1477 if (!Subtarget->hasUnalignedScratchAccess() && 1478 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1479 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1480 bool AlignedBy4 = Alignment >= Align(4); 1481 if (IsFast) 1482 *IsFast = AlignedBy4; 1483 1484 return AlignedBy4; 1485 } 1486 1487 if (Subtarget->hasUnalignedBufferAccess() && 1488 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1489 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1490 // If we have an uniform constant load, it still requires using a slow 1491 // buffer instruction if unaligned. 1492 if (IsFast) { 1493 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1494 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1495 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1496 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1497 Alignment >= Align(4) : Alignment != Align(2); 1498 } 1499 1500 return true; 1501 } 1502 1503 // Smaller than dword value must be aligned. 1504 if (Size < 32) 1505 return false; 1506 1507 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1508 // byte-address are ignored, thus forcing Dword alignment. 1509 // This applies to private, global, and constant memory. 1510 if (IsFast) 1511 *IsFast = true; 1512 1513 return Size >= 32 && Alignment >= Align(4); 1514 } 1515 1516 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1517 EVT VT, unsigned AddrSpace, unsigned Alignment, 1518 MachineMemOperand::Flags Flags, bool *IsFast) const { 1519 if (IsFast) 1520 *IsFast = false; 1521 1522 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1523 // which isn't a simple VT. 1524 // Until MVT is extended to handle this, simply check for the size and 1525 // rely on the condition below: allow accesses if the size is a multiple of 4. 1526 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1527 VT.getStoreSize() > 16)) { 1528 return false; 1529 } 1530 1531 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1532 Align(Alignment), Flags, IsFast); 1533 } 1534 1535 EVT SITargetLowering::getOptimalMemOpType( 1536 const MemOp &Op, const AttributeList &FuncAttributes) const { 1537 // FIXME: Should account for address space here. 1538 1539 // The default fallback uses the private pointer size as a guess for a type to 1540 // use. Make sure we switch these to 64-bit accesses. 1541 1542 if (Op.size() >= 16 && 1543 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1544 return MVT::v4i32; 1545 1546 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1547 return MVT::v2i32; 1548 1549 // Use the default. 1550 return MVT::Other; 1551 } 1552 1553 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1554 const MemSDNode *MemNode = cast<MemSDNode>(N); 1555 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1556 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1557 return I && I->getMetadata("amdgpu.noclobber"); 1558 } 1559 1560 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1561 unsigned DestAS) const { 1562 // Flat -> private/local is a simple truncate. 1563 // Flat -> global is no-op 1564 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1565 return true; 1566 1567 const GCNTargetMachine &TM = 1568 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1569 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1570 } 1571 1572 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1573 const MemSDNode *MemNode = cast<MemSDNode>(N); 1574 1575 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1576 } 1577 1578 TargetLoweringBase::LegalizeTypeAction 1579 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1580 int NumElts = VT.getVectorNumElements(); 1581 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1582 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1583 return TargetLoweringBase::getPreferredVectorAction(VT); 1584 } 1585 1586 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1587 Type *Ty) const { 1588 // FIXME: Could be smarter if called for vector constants. 1589 return true; 1590 } 1591 1592 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1593 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1594 switch (Op) { 1595 case ISD::LOAD: 1596 case ISD::STORE: 1597 1598 // These operations are done with 32-bit instructions anyway. 1599 case ISD::AND: 1600 case ISD::OR: 1601 case ISD::XOR: 1602 case ISD::SELECT: 1603 // TODO: Extensions? 1604 return true; 1605 default: 1606 return false; 1607 } 1608 } 1609 1610 // SimplifySetCC uses this function to determine whether or not it should 1611 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1612 if (VT == MVT::i1 && Op == ISD::SETCC) 1613 return false; 1614 1615 return TargetLowering::isTypeDesirableForOp(Op, VT); 1616 } 1617 1618 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1619 const SDLoc &SL, 1620 SDValue Chain, 1621 uint64_t Offset) const { 1622 const DataLayout &DL = DAG.getDataLayout(); 1623 MachineFunction &MF = DAG.getMachineFunction(); 1624 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1625 1626 const ArgDescriptor *InputPtrReg; 1627 const TargetRegisterClass *RC; 1628 LLT ArgTy; 1629 1630 std::tie(InputPtrReg, RC, ArgTy) = 1631 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1632 1633 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1634 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1635 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1636 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1637 1638 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1639 } 1640 1641 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1642 const SDLoc &SL) const { 1643 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1644 FIRST_IMPLICIT); 1645 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1646 } 1647 1648 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1649 const SDLoc &SL, SDValue Val, 1650 bool Signed, 1651 const ISD::InputArg *Arg) const { 1652 // First, if it is a widened vector, narrow it. 1653 if (VT.isVector() && 1654 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1655 EVT NarrowedVT = 1656 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1657 VT.getVectorNumElements()); 1658 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1659 DAG.getConstant(0, SL, MVT::i32)); 1660 } 1661 1662 // Then convert the vector elements or scalar value. 1663 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1664 VT.bitsLT(MemVT)) { 1665 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1666 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1667 } 1668 1669 if (MemVT.isFloatingPoint()) 1670 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1671 else if (Signed) 1672 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1673 else 1674 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1675 1676 return Val; 1677 } 1678 1679 SDValue SITargetLowering::lowerKernargMemParameter( 1680 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1681 uint64_t Offset, Align Alignment, bool Signed, 1682 const ISD::InputArg *Arg) const { 1683 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1684 1685 // Try to avoid using an extload by loading earlier than the argument address, 1686 // and extracting the relevant bits. The load should hopefully be merged with 1687 // the previous argument. 1688 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1689 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1690 int64_t AlignDownOffset = alignDown(Offset, 4); 1691 int64_t OffsetDiff = Offset - AlignDownOffset; 1692 1693 EVT IntVT = MemVT.changeTypeToInteger(); 1694 1695 // TODO: If we passed in the base kernel offset we could have a better 1696 // alignment than 4, but we don't really need it. 1697 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1698 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1699 MachineMemOperand::MODereferenceable | 1700 MachineMemOperand::MOInvariant); 1701 1702 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1703 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1704 1705 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1706 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1707 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1708 1709 1710 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1711 } 1712 1713 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1714 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1715 MachineMemOperand::MODereferenceable | 1716 MachineMemOperand::MOInvariant); 1717 1718 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1719 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1720 } 1721 1722 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1723 const SDLoc &SL, SDValue Chain, 1724 const ISD::InputArg &Arg) const { 1725 MachineFunction &MF = DAG.getMachineFunction(); 1726 MachineFrameInfo &MFI = MF.getFrameInfo(); 1727 1728 if (Arg.Flags.isByVal()) { 1729 unsigned Size = Arg.Flags.getByValSize(); 1730 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1731 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1732 } 1733 1734 unsigned ArgOffset = VA.getLocMemOffset(); 1735 unsigned ArgSize = VA.getValVT().getStoreSize(); 1736 1737 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1738 1739 // Create load nodes to retrieve arguments from the stack. 1740 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1741 SDValue ArgValue; 1742 1743 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1744 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1745 MVT MemVT = VA.getValVT(); 1746 1747 switch (VA.getLocInfo()) { 1748 default: 1749 break; 1750 case CCValAssign::BCvt: 1751 MemVT = VA.getLocVT(); 1752 break; 1753 case CCValAssign::SExt: 1754 ExtType = ISD::SEXTLOAD; 1755 break; 1756 case CCValAssign::ZExt: 1757 ExtType = ISD::ZEXTLOAD; 1758 break; 1759 case CCValAssign::AExt: 1760 ExtType = ISD::EXTLOAD; 1761 break; 1762 } 1763 1764 ArgValue = DAG.getExtLoad( 1765 ExtType, SL, VA.getLocVT(), Chain, FIN, 1766 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1767 MemVT); 1768 return ArgValue; 1769 } 1770 1771 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1772 const SIMachineFunctionInfo &MFI, 1773 EVT VT, 1774 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1775 const ArgDescriptor *Reg; 1776 const TargetRegisterClass *RC; 1777 LLT Ty; 1778 1779 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1780 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1781 } 1782 1783 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1784 CallingConv::ID CallConv, 1785 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1786 FunctionType *FType, 1787 SIMachineFunctionInfo *Info) { 1788 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1789 const ISD::InputArg *Arg = &Ins[I]; 1790 1791 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1792 "vector type argument should have been split"); 1793 1794 // First check if it's a PS input addr. 1795 if (CallConv == CallingConv::AMDGPU_PS && 1796 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1797 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1798 1799 // Inconveniently only the first part of the split is marked as isSplit, 1800 // so skip to the end. We only want to increment PSInputNum once for the 1801 // entire split argument. 1802 if (Arg->Flags.isSplit()) { 1803 while (!Arg->Flags.isSplitEnd()) { 1804 assert((!Arg->VT.isVector() || 1805 Arg->VT.getScalarSizeInBits() == 16) && 1806 "unexpected vector split in ps argument type"); 1807 if (!SkipArg) 1808 Splits.push_back(*Arg); 1809 Arg = &Ins[++I]; 1810 } 1811 } 1812 1813 if (SkipArg) { 1814 // We can safely skip PS inputs. 1815 Skipped.set(Arg->getOrigArgIndex()); 1816 ++PSInputNum; 1817 continue; 1818 } 1819 1820 Info->markPSInputAllocated(PSInputNum); 1821 if (Arg->Used) 1822 Info->markPSInputEnabled(PSInputNum); 1823 1824 ++PSInputNum; 1825 } 1826 1827 Splits.push_back(*Arg); 1828 } 1829 } 1830 1831 // Allocate special inputs passed in VGPRs. 1832 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1833 MachineFunction &MF, 1834 const SIRegisterInfo &TRI, 1835 SIMachineFunctionInfo &Info) const { 1836 const LLT S32 = LLT::scalar(32); 1837 MachineRegisterInfo &MRI = MF.getRegInfo(); 1838 1839 if (Info.hasWorkItemIDX()) { 1840 Register Reg = AMDGPU::VGPR0; 1841 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1842 1843 CCInfo.AllocateReg(Reg); 1844 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1845 } 1846 1847 if (Info.hasWorkItemIDY()) { 1848 Register Reg = AMDGPU::VGPR1; 1849 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1850 1851 CCInfo.AllocateReg(Reg); 1852 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1853 } 1854 1855 if (Info.hasWorkItemIDZ()) { 1856 Register Reg = AMDGPU::VGPR2; 1857 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1858 1859 CCInfo.AllocateReg(Reg); 1860 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1861 } 1862 } 1863 1864 // Try to allocate a VGPR at the end of the argument list, or if no argument 1865 // VGPRs are left allocating a stack slot. 1866 // If \p Mask is is given it indicates bitfield position in the register. 1867 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1868 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1869 ArgDescriptor Arg = ArgDescriptor()) { 1870 if (Arg.isSet()) 1871 return ArgDescriptor::createArg(Arg, Mask); 1872 1873 ArrayRef<MCPhysReg> ArgVGPRs 1874 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1875 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1876 if (RegIdx == ArgVGPRs.size()) { 1877 // Spill to stack required. 1878 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1879 1880 return ArgDescriptor::createStack(Offset, Mask); 1881 } 1882 1883 unsigned Reg = ArgVGPRs[RegIdx]; 1884 Reg = CCInfo.AllocateReg(Reg); 1885 assert(Reg != AMDGPU::NoRegister); 1886 1887 MachineFunction &MF = CCInfo.getMachineFunction(); 1888 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1889 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1890 return ArgDescriptor::createRegister(Reg, Mask); 1891 } 1892 1893 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1894 const TargetRegisterClass *RC, 1895 unsigned NumArgRegs) { 1896 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1897 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1898 if (RegIdx == ArgSGPRs.size()) 1899 report_fatal_error("ran out of SGPRs for arguments"); 1900 1901 unsigned Reg = ArgSGPRs[RegIdx]; 1902 Reg = CCInfo.AllocateReg(Reg); 1903 assert(Reg != AMDGPU::NoRegister); 1904 1905 MachineFunction &MF = CCInfo.getMachineFunction(); 1906 MF.addLiveIn(Reg, RC); 1907 return ArgDescriptor::createRegister(Reg); 1908 } 1909 1910 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1911 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1912 } 1913 1914 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1915 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1916 } 1917 1918 /// Allocate implicit function VGPR arguments at the end of allocated user 1919 /// arguments. 1920 void SITargetLowering::allocateSpecialInputVGPRs( 1921 CCState &CCInfo, MachineFunction &MF, 1922 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1923 const unsigned Mask = 0x3ff; 1924 ArgDescriptor Arg; 1925 1926 if (Info.hasWorkItemIDX()) { 1927 Arg = allocateVGPR32Input(CCInfo, Mask); 1928 Info.setWorkItemIDX(Arg); 1929 } 1930 1931 if (Info.hasWorkItemIDY()) { 1932 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1933 Info.setWorkItemIDY(Arg); 1934 } 1935 1936 if (Info.hasWorkItemIDZ()) 1937 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1938 } 1939 1940 /// Allocate implicit function VGPR arguments in fixed registers. 1941 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1942 CCState &CCInfo, MachineFunction &MF, 1943 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1944 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1945 if (!Reg) 1946 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1947 1948 const unsigned Mask = 0x3ff; 1949 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1950 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1951 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1952 } 1953 1954 void SITargetLowering::allocateSpecialInputSGPRs( 1955 CCState &CCInfo, 1956 MachineFunction &MF, 1957 const SIRegisterInfo &TRI, 1958 SIMachineFunctionInfo &Info) const { 1959 auto &ArgInfo = Info.getArgInfo(); 1960 1961 // TODO: Unify handling with private memory pointers. 1962 1963 if (Info.hasDispatchPtr()) 1964 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1965 1966 if (Info.hasQueuePtr()) 1967 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1968 1969 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1970 // constant offset from the kernarg segment. 1971 if (Info.hasImplicitArgPtr()) 1972 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1973 1974 if (Info.hasDispatchID()) 1975 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1976 1977 // flat_scratch_init is not applicable for non-kernel functions. 1978 1979 if (Info.hasWorkGroupIDX()) 1980 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1981 1982 if (Info.hasWorkGroupIDY()) 1983 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1984 1985 if (Info.hasWorkGroupIDZ()) 1986 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1987 } 1988 1989 // Allocate special inputs passed in user SGPRs. 1990 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1991 MachineFunction &MF, 1992 const SIRegisterInfo &TRI, 1993 SIMachineFunctionInfo &Info) const { 1994 if (Info.hasImplicitBufferPtr()) { 1995 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1996 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1997 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1998 } 1999 2000 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2001 if (Info.hasPrivateSegmentBuffer()) { 2002 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2003 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2004 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2005 } 2006 2007 if (Info.hasDispatchPtr()) { 2008 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2009 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2010 CCInfo.AllocateReg(DispatchPtrReg); 2011 } 2012 2013 if (Info.hasQueuePtr()) { 2014 Register QueuePtrReg = Info.addQueuePtr(TRI); 2015 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2016 CCInfo.AllocateReg(QueuePtrReg); 2017 } 2018 2019 if (Info.hasKernargSegmentPtr()) { 2020 MachineRegisterInfo &MRI = MF.getRegInfo(); 2021 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2022 CCInfo.AllocateReg(InputPtrReg); 2023 2024 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2025 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2026 } 2027 2028 if (Info.hasDispatchID()) { 2029 Register DispatchIDReg = Info.addDispatchID(TRI); 2030 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2031 CCInfo.AllocateReg(DispatchIDReg); 2032 } 2033 2034 if (Info.hasFlatScratchInit()) { 2035 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2036 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2037 CCInfo.AllocateReg(FlatScratchInitReg); 2038 } 2039 2040 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2041 // these from the dispatch pointer. 2042 } 2043 2044 // Allocate special input registers that are initialized per-wave. 2045 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2046 MachineFunction &MF, 2047 SIMachineFunctionInfo &Info, 2048 CallingConv::ID CallConv, 2049 bool IsShader) const { 2050 if (Info.hasWorkGroupIDX()) { 2051 Register Reg = Info.addWorkGroupIDX(); 2052 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2053 CCInfo.AllocateReg(Reg); 2054 } 2055 2056 if (Info.hasWorkGroupIDY()) { 2057 Register Reg = Info.addWorkGroupIDY(); 2058 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2059 CCInfo.AllocateReg(Reg); 2060 } 2061 2062 if (Info.hasWorkGroupIDZ()) { 2063 Register Reg = Info.addWorkGroupIDZ(); 2064 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2065 CCInfo.AllocateReg(Reg); 2066 } 2067 2068 if (Info.hasWorkGroupInfo()) { 2069 Register Reg = Info.addWorkGroupInfo(); 2070 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2071 CCInfo.AllocateReg(Reg); 2072 } 2073 2074 if (Info.hasPrivateSegmentWaveByteOffset()) { 2075 // Scratch wave offset passed in system SGPR. 2076 unsigned PrivateSegmentWaveByteOffsetReg; 2077 2078 if (IsShader) { 2079 PrivateSegmentWaveByteOffsetReg = 2080 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2081 2082 // This is true if the scratch wave byte offset doesn't have a fixed 2083 // location. 2084 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2085 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2086 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2087 } 2088 } else 2089 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2090 2091 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2092 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2093 } 2094 } 2095 2096 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2097 MachineFunction &MF, 2098 const SIRegisterInfo &TRI, 2099 SIMachineFunctionInfo &Info) { 2100 // Now that we've figured out where the scratch register inputs are, see if 2101 // should reserve the arguments and use them directly. 2102 MachineFrameInfo &MFI = MF.getFrameInfo(); 2103 bool HasStackObjects = MFI.hasStackObjects(); 2104 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2105 2106 // Record that we know we have non-spill stack objects so we don't need to 2107 // check all stack objects later. 2108 if (HasStackObjects) 2109 Info.setHasNonSpillStackObjects(true); 2110 2111 // Everything live out of a block is spilled with fast regalloc, so it's 2112 // almost certain that spilling will be required. 2113 if (TM.getOptLevel() == CodeGenOpt::None) 2114 HasStackObjects = true; 2115 2116 // For now assume stack access is needed in any callee functions, so we need 2117 // the scratch registers to pass in. 2118 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2119 2120 if (!ST.enableFlatScratch()) { 2121 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2122 // If we have stack objects, we unquestionably need the private buffer 2123 // resource. For the Code Object V2 ABI, this will be the first 4 user 2124 // SGPR inputs. We can reserve those and use them directly. 2125 2126 Register PrivateSegmentBufferReg = 2127 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2128 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2129 } else { 2130 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2131 // We tentatively reserve the last registers (skipping the last registers 2132 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2133 // we'll replace these with the ones immediately after those which were 2134 // really allocated. In the prologue copies will be inserted from the 2135 // argument to these reserved registers. 2136 2137 // Without HSA, relocations are used for the scratch pointer and the 2138 // buffer resource setup is always inserted in the prologue. Scratch wave 2139 // offset is still in an input SGPR. 2140 Info.setScratchRSrcReg(ReservedBufferReg); 2141 } 2142 } 2143 2144 MachineRegisterInfo &MRI = MF.getRegInfo(); 2145 2146 // For entry functions we have to set up the stack pointer if we use it, 2147 // whereas non-entry functions get this "for free". This means there is no 2148 // intrinsic advantage to using S32 over S34 in cases where we do not have 2149 // calls but do need a frame pointer (i.e. if we are requested to have one 2150 // because frame pointer elimination is disabled). To keep things simple we 2151 // only ever use S32 as the call ABI stack pointer, and so using it does not 2152 // imply we need a separate frame pointer. 2153 // 2154 // Try to use s32 as the SP, but move it if it would interfere with input 2155 // arguments. This won't work with calls though. 2156 // 2157 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2158 // registers. 2159 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2160 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2161 } else { 2162 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2163 2164 if (MFI.hasCalls()) 2165 report_fatal_error("call in graphics shader with too many input SGPRs"); 2166 2167 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2168 if (!MRI.isLiveIn(Reg)) { 2169 Info.setStackPtrOffsetReg(Reg); 2170 break; 2171 } 2172 } 2173 2174 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2175 report_fatal_error("failed to find register for SP"); 2176 } 2177 2178 // hasFP should be accurate for entry functions even before the frame is 2179 // finalized, because it does not rely on the known stack size, only 2180 // properties like whether variable sized objects are present. 2181 if (ST.getFrameLowering()->hasFP(MF)) { 2182 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2183 } 2184 } 2185 2186 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2187 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2188 return !Info->isEntryFunction(); 2189 } 2190 2191 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2192 2193 } 2194 2195 void SITargetLowering::insertCopiesSplitCSR( 2196 MachineBasicBlock *Entry, 2197 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2198 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2199 2200 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2201 if (!IStart) 2202 return; 2203 2204 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2205 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2206 MachineBasicBlock::iterator MBBI = Entry->begin(); 2207 for (const MCPhysReg *I = IStart; *I; ++I) { 2208 const TargetRegisterClass *RC = nullptr; 2209 if (AMDGPU::SReg_64RegClass.contains(*I)) 2210 RC = &AMDGPU::SGPR_64RegClass; 2211 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2212 RC = &AMDGPU::SGPR_32RegClass; 2213 else 2214 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2215 2216 Register NewVR = MRI->createVirtualRegister(RC); 2217 // Create copy from CSR to a virtual register. 2218 Entry->addLiveIn(*I); 2219 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2220 .addReg(*I); 2221 2222 // Insert the copy-back instructions right before the terminator. 2223 for (auto *Exit : Exits) 2224 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2225 TII->get(TargetOpcode::COPY), *I) 2226 .addReg(NewVR); 2227 } 2228 } 2229 2230 SDValue SITargetLowering::LowerFormalArguments( 2231 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2232 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2233 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2234 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2235 2236 MachineFunction &MF = DAG.getMachineFunction(); 2237 const Function &Fn = MF.getFunction(); 2238 FunctionType *FType = MF.getFunction().getFunctionType(); 2239 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2240 2241 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2242 DiagnosticInfoUnsupported NoGraphicsHSA( 2243 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2244 DAG.getContext()->diagnose(NoGraphicsHSA); 2245 return DAG.getEntryNode(); 2246 } 2247 2248 SmallVector<ISD::InputArg, 16> Splits; 2249 SmallVector<CCValAssign, 16> ArgLocs; 2250 BitVector Skipped(Ins.size()); 2251 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2252 *DAG.getContext()); 2253 2254 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2255 bool IsKernel = AMDGPU::isKernel(CallConv); 2256 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2257 2258 if (IsGraphics) { 2259 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2260 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2261 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2262 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2263 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2264 !Info->hasWorkItemIDZ()); 2265 } 2266 2267 if (CallConv == CallingConv::AMDGPU_PS) { 2268 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2269 2270 // At least one interpolation mode must be enabled or else the GPU will 2271 // hang. 2272 // 2273 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2274 // set PSInputAddr, the user wants to enable some bits after the compilation 2275 // based on run-time states. Since we can't know what the final PSInputEna 2276 // will look like, so we shouldn't do anything here and the user should take 2277 // responsibility for the correct programming. 2278 // 2279 // Otherwise, the following restrictions apply: 2280 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2281 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2282 // enabled too. 2283 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2284 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2285 CCInfo.AllocateReg(AMDGPU::VGPR0); 2286 CCInfo.AllocateReg(AMDGPU::VGPR1); 2287 Info->markPSInputAllocated(0); 2288 Info->markPSInputEnabled(0); 2289 } 2290 if (Subtarget->isAmdPalOS()) { 2291 // For isAmdPalOS, the user does not enable some bits after compilation 2292 // based on run-time states; the register values being generated here are 2293 // the final ones set in hardware. Therefore we need to apply the 2294 // workaround to PSInputAddr and PSInputEnable together. (The case where 2295 // a bit is set in PSInputAddr but not PSInputEnable is where the 2296 // frontend set up an input arg for a particular interpolation mode, but 2297 // nothing uses that input arg. Really we should have an earlier pass 2298 // that removes such an arg.) 2299 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2300 if ((PsInputBits & 0x7F) == 0 || 2301 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2302 Info->markPSInputEnabled( 2303 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2304 } 2305 } else if (IsKernel) { 2306 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2307 } else { 2308 Splits.append(Ins.begin(), Ins.end()); 2309 } 2310 2311 if (IsEntryFunc) { 2312 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2313 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2314 } else { 2315 // For the fixed ABI, pass workitem IDs in the last argument register. 2316 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2317 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2318 } 2319 2320 if (IsKernel) { 2321 analyzeFormalArgumentsCompute(CCInfo, Ins); 2322 } else { 2323 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2324 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2325 } 2326 2327 SmallVector<SDValue, 16> Chains; 2328 2329 // FIXME: This is the minimum kernel argument alignment. We should improve 2330 // this to the maximum alignment of the arguments. 2331 // 2332 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2333 // kern arg offset. 2334 const Align KernelArgBaseAlign = Align(16); 2335 2336 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2337 const ISD::InputArg &Arg = Ins[i]; 2338 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2339 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2340 continue; 2341 } 2342 2343 CCValAssign &VA = ArgLocs[ArgIdx++]; 2344 MVT VT = VA.getLocVT(); 2345 2346 if (IsEntryFunc && VA.isMemLoc()) { 2347 VT = Ins[i].VT; 2348 EVT MemVT = VA.getLocVT(); 2349 2350 const uint64_t Offset = VA.getLocMemOffset(); 2351 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2352 2353 if (Arg.Flags.isByRef()) { 2354 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2355 2356 const GCNTargetMachine &TM = 2357 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2358 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2359 Arg.Flags.getPointerAddrSpace())) { 2360 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2361 Arg.Flags.getPointerAddrSpace()); 2362 } 2363 2364 InVals.push_back(Ptr); 2365 continue; 2366 } 2367 2368 SDValue Arg = lowerKernargMemParameter( 2369 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2370 Chains.push_back(Arg.getValue(1)); 2371 2372 auto *ParamTy = 2373 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2374 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2375 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2376 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2377 // On SI local pointers are just offsets into LDS, so they are always 2378 // less than 16-bits. On CI and newer they could potentially be 2379 // real pointers, so we can't guarantee their size. 2380 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2381 DAG.getValueType(MVT::i16)); 2382 } 2383 2384 InVals.push_back(Arg); 2385 continue; 2386 } else if (!IsEntryFunc && VA.isMemLoc()) { 2387 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2388 InVals.push_back(Val); 2389 if (!Arg.Flags.isByVal()) 2390 Chains.push_back(Val.getValue(1)); 2391 continue; 2392 } 2393 2394 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2395 2396 Register Reg = VA.getLocReg(); 2397 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2398 EVT ValVT = VA.getValVT(); 2399 2400 Reg = MF.addLiveIn(Reg, RC); 2401 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2402 2403 if (Arg.Flags.isSRet()) { 2404 // The return object should be reasonably addressable. 2405 2406 // FIXME: This helps when the return is a real sret. If it is a 2407 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2408 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2409 unsigned NumBits 2410 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2411 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2412 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2413 } 2414 2415 // If this is an 8 or 16-bit value, it is really passed promoted 2416 // to 32 bits. Insert an assert[sz]ext to capture this, then 2417 // truncate to the right size. 2418 switch (VA.getLocInfo()) { 2419 case CCValAssign::Full: 2420 break; 2421 case CCValAssign::BCvt: 2422 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2423 break; 2424 case CCValAssign::SExt: 2425 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2426 DAG.getValueType(ValVT)); 2427 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2428 break; 2429 case CCValAssign::ZExt: 2430 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2431 DAG.getValueType(ValVT)); 2432 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2433 break; 2434 case CCValAssign::AExt: 2435 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2436 break; 2437 default: 2438 llvm_unreachable("Unknown loc info!"); 2439 } 2440 2441 InVals.push_back(Val); 2442 } 2443 2444 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2445 // Special inputs come after user arguments. 2446 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2447 } 2448 2449 // Start adding system SGPRs. 2450 if (IsEntryFunc) { 2451 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2452 } else { 2453 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2454 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2455 } 2456 2457 auto &ArgUsageInfo = 2458 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2459 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2460 2461 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2462 Info->setBytesInStackArgArea(StackArgSize); 2463 2464 return Chains.empty() ? Chain : 2465 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2466 } 2467 2468 // TODO: If return values can't fit in registers, we should return as many as 2469 // possible in registers before passing on stack. 2470 bool SITargetLowering::CanLowerReturn( 2471 CallingConv::ID CallConv, 2472 MachineFunction &MF, bool IsVarArg, 2473 const SmallVectorImpl<ISD::OutputArg> &Outs, 2474 LLVMContext &Context) const { 2475 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2476 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2477 // for shaders. Vector types should be explicitly handled by CC. 2478 if (AMDGPU::isEntryFunctionCC(CallConv)) 2479 return true; 2480 2481 SmallVector<CCValAssign, 16> RVLocs; 2482 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2483 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2484 } 2485 2486 SDValue 2487 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2488 bool isVarArg, 2489 const SmallVectorImpl<ISD::OutputArg> &Outs, 2490 const SmallVectorImpl<SDValue> &OutVals, 2491 const SDLoc &DL, SelectionDAG &DAG) const { 2492 MachineFunction &MF = DAG.getMachineFunction(); 2493 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2494 2495 if (AMDGPU::isKernel(CallConv)) { 2496 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2497 OutVals, DL, DAG); 2498 } 2499 2500 bool IsShader = AMDGPU::isShader(CallConv); 2501 2502 Info->setIfReturnsVoid(Outs.empty()); 2503 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2504 2505 // CCValAssign - represent the assignment of the return value to a location. 2506 SmallVector<CCValAssign, 48> RVLocs; 2507 SmallVector<ISD::OutputArg, 48> Splits; 2508 2509 // CCState - Info about the registers and stack slots. 2510 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2511 *DAG.getContext()); 2512 2513 // Analyze outgoing return values. 2514 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2515 2516 SDValue Flag; 2517 SmallVector<SDValue, 48> RetOps; 2518 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2519 2520 // Add return address for callable functions. 2521 if (!Info->isEntryFunction()) { 2522 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2523 SDValue ReturnAddrReg = CreateLiveInRegister( 2524 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2525 2526 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2527 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2528 MVT::i64); 2529 Chain = 2530 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2531 Flag = Chain.getValue(1); 2532 RetOps.push_back(ReturnAddrVirtualReg); 2533 } 2534 2535 // Copy the result values into the output registers. 2536 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2537 ++I, ++RealRVLocIdx) { 2538 CCValAssign &VA = RVLocs[I]; 2539 assert(VA.isRegLoc() && "Can only return in registers!"); 2540 // TODO: Partially return in registers if return values don't fit. 2541 SDValue Arg = OutVals[RealRVLocIdx]; 2542 2543 // Copied from other backends. 2544 switch (VA.getLocInfo()) { 2545 case CCValAssign::Full: 2546 break; 2547 case CCValAssign::BCvt: 2548 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2549 break; 2550 case CCValAssign::SExt: 2551 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2552 break; 2553 case CCValAssign::ZExt: 2554 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2555 break; 2556 case CCValAssign::AExt: 2557 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2558 break; 2559 default: 2560 llvm_unreachable("Unknown loc info!"); 2561 } 2562 2563 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2564 Flag = Chain.getValue(1); 2565 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2566 } 2567 2568 // FIXME: Does sret work properly? 2569 if (!Info->isEntryFunction()) { 2570 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2571 const MCPhysReg *I = 2572 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2573 if (I) { 2574 for (; *I; ++I) { 2575 if (AMDGPU::SReg_64RegClass.contains(*I)) 2576 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2577 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2578 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2579 else 2580 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2581 } 2582 } 2583 } 2584 2585 // Update chain and glue. 2586 RetOps[0] = Chain; 2587 if (Flag.getNode()) 2588 RetOps.push_back(Flag); 2589 2590 unsigned Opc = AMDGPUISD::ENDPGM; 2591 if (!IsWaveEnd) 2592 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2593 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2594 } 2595 2596 SDValue SITargetLowering::LowerCallResult( 2597 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2598 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2599 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2600 SDValue ThisVal) const { 2601 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2602 2603 // Assign locations to each value returned by this call. 2604 SmallVector<CCValAssign, 16> RVLocs; 2605 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2606 *DAG.getContext()); 2607 CCInfo.AnalyzeCallResult(Ins, RetCC); 2608 2609 // Copy all of the result registers out of their specified physreg. 2610 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2611 CCValAssign VA = RVLocs[i]; 2612 SDValue Val; 2613 2614 if (VA.isRegLoc()) { 2615 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2616 Chain = Val.getValue(1); 2617 InFlag = Val.getValue(2); 2618 } else if (VA.isMemLoc()) { 2619 report_fatal_error("TODO: return values in memory"); 2620 } else 2621 llvm_unreachable("unknown argument location type"); 2622 2623 switch (VA.getLocInfo()) { 2624 case CCValAssign::Full: 2625 break; 2626 case CCValAssign::BCvt: 2627 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2628 break; 2629 case CCValAssign::ZExt: 2630 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2631 DAG.getValueType(VA.getValVT())); 2632 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2633 break; 2634 case CCValAssign::SExt: 2635 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2636 DAG.getValueType(VA.getValVT())); 2637 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2638 break; 2639 case CCValAssign::AExt: 2640 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2641 break; 2642 default: 2643 llvm_unreachable("Unknown loc info!"); 2644 } 2645 2646 InVals.push_back(Val); 2647 } 2648 2649 return Chain; 2650 } 2651 2652 // Add code to pass special inputs required depending on used features separate 2653 // from the explicit user arguments present in the IR. 2654 void SITargetLowering::passSpecialInputs( 2655 CallLoweringInfo &CLI, 2656 CCState &CCInfo, 2657 const SIMachineFunctionInfo &Info, 2658 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2659 SmallVectorImpl<SDValue> &MemOpChains, 2660 SDValue Chain) const { 2661 // If we don't have a call site, this was a call inserted by 2662 // legalization. These can never use special inputs. 2663 if (!CLI.CB) 2664 return; 2665 2666 SelectionDAG &DAG = CLI.DAG; 2667 const SDLoc &DL = CLI.DL; 2668 2669 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2670 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2671 2672 const AMDGPUFunctionArgInfo *CalleeArgInfo 2673 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2674 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2675 auto &ArgUsageInfo = 2676 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2677 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2678 } 2679 2680 // TODO: Unify with private memory register handling. This is complicated by 2681 // the fact that at least in kernels, the input argument is not necessarily 2682 // in the same location as the input. 2683 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2684 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2685 AMDGPUFunctionArgInfo::QUEUE_PTR, 2686 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2687 AMDGPUFunctionArgInfo::DISPATCH_ID, 2688 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2689 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2690 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2691 }; 2692 2693 for (auto InputID : InputRegs) { 2694 const ArgDescriptor *OutgoingArg; 2695 const TargetRegisterClass *ArgRC; 2696 LLT ArgTy; 2697 2698 std::tie(OutgoingArg, ArgRC, ArgTy) = 2699 CalleeArgInfo->getPreloadedValue(InputID); 2700 if (!OutgoingArg) 2701 continue; 2702 2703 const ArgDescriptor *IncomingArg; 2704 const TargetRegisterClass *IncomingArgRC; 2705 LLT Ty; 2706 std::tie(IncomingArg, IncomingArgRC, Ty) = 2707 CallerArgInfo.getPreloadedValue(InputID); 2708 assert(IncomingArgRC == ArgRC); 2709 2710 // All special arguments are ints for now. 2711 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2712 SDValue InputReg; 2713 2714 if (IncomingArg) { 2715 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2716 } else { 2717 // The implicit arg ptr is special because it doesn't have a corresponding 2718 // input for kernels, and is computed from the kernarg segment pointer. 2719 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2720 InputReg = getImplicitArgPtr(DAG, DL); 2721 } 2722 2723 if (OutgoingArg->isRegister()) { 2724 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2725 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2726 report_fatal_error("failed to allocate implicit input argument"); 2727 } else { 2728 unsigned SpecialArgOffset = 2729 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2730 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2731 SpecialArgOffset); 2732 MemOpChains.push_back(ArgStore); 2733 } 2734 } 2735 2736 // Pack workitem IDs into a single register or pass it as is if already 2737 // packed. 2738 const ArgDescriptor *OutgoingArg; 2739 const TargetRegisterClass *ArgRC; 2740 LLT Ty; 2741 2742 std::tie(OutgoingArg, ArgRC, Ty) = 2743 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2744 if (!OutgoingArg) 2745 std::tie(OutgoingArg, ArgRC, Ty) = 2746 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2747 if (!OutgoingArg) 2748 std::tie(OutgoingArg, ArgRC, Ty) = 2749 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2750 if (!OutgoingArg) 2751 return; 2752 2753 const ArgDescriptor *IncomingArgX = std::get<0>( 2754 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2755 const ArgDescriptor *IncomingArgY = std::get<0>( 2756 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2757 const ArgDescriptor *IncomingArgZ = std::get<0>( 2758 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2759 2760 SDValue InputReg; 2761 SDLoc SL; 2762 2763 // If incoming ids are not packed we need to pack them. 2764 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2765 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2766 2767 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2768 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2769 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2770 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2771 InputReg = InputReg.getNode() ? 2772 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2773 } 2774 2775 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2776 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2777 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2778 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2779 InputReg = InputReg.getNode() ? 2780 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2781 } 2782 2783 if (!InputReg.getNode()) { 2784 // Workitem ids are already packed, any of present incoming arguments 2785 // will carry all required fields. 2786 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2787 IncomingArgX ? *IncomingArgX : 2788 IncomingArgY ? *IncomingArgY : 2789 *IncomingArgZ, ~0u); 2790 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2791 } 2792 2793 if (OutgoingArg->isRegister()) { 2794 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2795 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2796 } else { 2797 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2798 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2799 SpecialArgOffset); 2800 MemOpChains.push_back(ArgStore); 2801 } 2802 } 2803 2804 static bool canGuaranteeTCO(CallingConv::ID CC) { 2805 return CC == CallingConv::Fast; 2806 } 2807 2808 /// Return true if we might ever do TCO for calls with this calling convention. 2809 static bool mayTailCallThisCC(CallingConv::ID CC) { 2810 switch (CC) { 2811 case CallingConv::C: 2812 return true; 2813 default: 2814 return canGuaranteeTCO(CC); 2815 } 2816 } 2817 2818 bool SITargetLowering::isEligibleForTailCallOptimization( 2819 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2820 const SmallVectorImpl<ISD::OutputArg> &Outs, 2821 const SmallVectorImpl<SDValue> &OutVals, 2822 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2823 if (!mayTailCallThisCC(CalleeCC)) 2824 return false; 2825 2826 MachineFunction &MF = DAG.getMachineFunction(); 2827 const Function &CallerF = MF.getFunction(); 2828 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2829 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2830 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2831 2832 // Kernels aren't callable, and don't have a live in return address so it 2833 // doesn't make sense to do a tail call with entry functions. 2834 if (!CallerPreserved) 2835 return false; 2836 2837 bool CCMatch = CallerCC == CalleeCC; 2838 2839 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2840 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2841 return true; 2842 return false; 2843 } 2844 2845 // TODO: Can we handle var args? 2846 if (IsVarArg) 2847 return false; 2848 2849 for (const Argument &Arg : CallerF.args()) { 2850 if (Arg.hasByValAttr()) 2851 return false; 2852 } 2853 2854 LLVMContext &Ctx = *DAG.getContext(); 2855 2856 // Check that the call results are passed in the same way. 2857 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2858 CCAssignFnForCall(CalleeCC, IsVarArg), 2859 CCAssignFnForCall(CallerCC, IsVarArg))) 2860 return false; 2861 2862 // The callee has to preserve all registers the caller needs to preserve. 2863 if (!CCMatch) { 2864 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2865 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2866 return false; 2867 } 2868 2869 // Nothing more to check if the callee is taking no arguments. 2870 if (Outs.empty()) 2871 return true; 2872 2873 SmallVector<CCValAssign, 16> ArgLocs; 2874 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2875 2876 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2877 2878 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2879 // If the stack arguments for this call do not fit into our own save area then 2880 // the call cannot be made tail. 2881 // TODO: Is this really necessary? 2882 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2883 return false; 2884 2885 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2886 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2887 } 2888 2889 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2890 if (!CI->isTailCall()) 2891 return false; 2892 2893 const Function *ParentFn = CI->getParent()->getParent(); 2894 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2895 return false; 2896 return true; 2897 } 2898 2899 // The wave scratch offset register is used as the global base pointer. 2900 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2901 SmallVectorImpl<SDValue> &InVals) const { 2902 SelectionDAG &DAG = CLI.DAG; 2903 const SDLoc &DL = CLI.DL; 2904 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2905 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2906 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2907 SDValue Chain = CLI.Chain; 2908 SDValue Callee = CLI.Callee; 2909 bool &IsTailCall = CLI.IsTailCall; 2910 CallingConv::ID CallConv = CLI.CallConv; 2911 bool IsVarArg = CLI.IsVarArg; 2912 bool IsSibCall = false; 2913 bool IsThisReturn = false; 2914 MachineFunction &MF = DAG.getMachineFunction(); 2915 2916 if (Callee.isUndef() || isNullConstant(Callee)) { 2917 if (!CLI.IsTailCall) { 2918 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2919 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2920 } 2921 2922 return Chain; 2923 } 2924 2925 if (IsVarArg) { 2926 return lowerUnhandledCall(CLI, InVals, 2927 "unsupported call to variadic function "); 2928 } 2929 2930 if (!CLI.CB) 2931 report_fatal_error("unsupported libcall legalization"); 2932 2933 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2934 !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) { 2935 return lowerUnhandledCall(CLI, InVals, 2936 "unsupported indirect call to function "); 2937 } 2938 2939 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2940 return lowerUnhandledCall(CLI, InVals, 2941 "unsupported required tail call to function "); 2942 } 2943 2944 if (AMDGPU::isShader(CallConv)) { 2945 // Note the issue is with the CC of the called function, not of the call 2946 // itself. 2947 return lowerUnhandledCall(CLI, InVals, 2948 "unsupported call to a shader function "); 2949 } 2950 2951 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2952 CallConv != CallingConv::AMDGPU_Gfx) { 2953 // Only allow calls with specific calling conventions. 2954 return lowerUnhandledCall(CLI, InVals, 2955 "unsupported calling convention for call from " 2956 "graphics shader of function "); 2957 } 2958 2959 if (IsTailCall) { 2960 IsTailCall = isEligibleForTailCallOptimization( 2961 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2962 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2963 report_fatal_error("failed to perform tail call elimination on a call " 2964 "site marked musttail"); 2965 } 2966 2967 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2968 2969 // A sibling call is one where we're under the usual C ABI and not planning 2970 // to change that but can still do a tail call: 2971 if (!TailCallOpt && IsTailCall) 2972 IsSibCall = true; 2973 2974 if (IsTailCall) 2975 ++NumTailCalls; 2976 } 2977 2978 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2979 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2980 SmallVector<SDValue, 8> MemOpChains; 2981 2982 // Analyze operands of the call, assigning locations to each operand. 2983 SmallVector<CCValAssign, 16> ArgLocs; 2984 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2985 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2986 2987 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 2988 CallConv != CallingConv::AMDGPU_Gfx) { 2989 // With a fixed ABI, allocate fixed registers before user arguments. 2990 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2991 } 2992 2993 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2994 2995 // Get a count of how many bytes are to be pushed on the stack. 2996 unsigned NumBytes = CCInfo.getNextStackOffset(); 2997 2998 if (IsSibCall) { 2999 // Since we're not changing the ABI to make this a tail call, the memory 3000 // operands are already available in the caller's incoming argument space. 3001 NumBytes = 0; 3002 } 3003 3004 // FPDiff is the byte offset of the call's argument area from the callee's. 3005 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3006 // by this amount for a tail call. In a sibling call it must be 0 because the 3007 // caller will deallocate the entire stack and the callee still expects its 3008 // arguments to begin at SP+0. Completely unused for non-tail calls. 3009 int32_t FPDiff = 0; 3010 MachineFrameInfo &MFI = MF.getFrameInfo(); 3011 3012 // Adjust the stack pointer for the new arguments... 3013 // These operations are automatically eliminated by the prolog/epilog pass 3014 if (!IsSibCall) { 3015 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3016 3017 if (!Subtarget->enableFlatScratch()) { 3018 SmallVector<SDValue, 4> CopyFromChains; 3019 3020 // In the HSA case, this should be an identity copy. 3021 SDValue ScratchRSrcReg 3022 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3023 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3024 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3025 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3026 } 3027 } 3028 3029 MVT PtrVT = MVT::i32; 3030 3031 // Walk the register/memloc assignments, inserting copies/loads. 3032 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3033 CCValAssign &VA = ArgLocs[i]; 3034 SDValue Arg = OutVals[i]; 3035 3036 // Promote the value if needed. 3037 switch (VA.getLocInfo()) { 3038 case CCValAssign::Full: 3039 break; 3040 case CCValAssign::BCvt: 3041 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3042 break; 3043 case CCValAssign::ZExt: 3044 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3045 break; 3046 case CCValAssign::SExt: 3047 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3048 break; 3049 case CCValAssign::AExt: 3050 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3051 break; 3052 case CCValAssign::FPExt: 3053 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3054 break; 3055 default: 3056 llvm_unreachable("Unknown loc info!"); 3057 } 3058 3059 if (VA.isRegLoc()) { 3060 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3061 } else { 3062 assert(VA.isMemLoc()); 3063 3064 SDValue DstAddr; 3065 MachinePointerInfo DstInfo; 3066 3067 unsigned LocMemOffset = VA.getLocMemOffset(); 3068 int32_t Offset = LocMemOffset; 3069 3070 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3071 MaybeAlign Alignment; 3072 3073 if (IsTailCall) { 3074 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3075 unsigned OpSize = Flags.isByVal() ? 3076 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3077 3078 // FIXME: We can have better than the minimum byval required alignment. 3079 Alignment = 3080 Flags.isByVal() 3081 ? Flags.getNonZeroByValAlign() 3082 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3083 3084 Offset = Offset + FPDiff; 3085 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3086 3087 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3088 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3089 3090 // Make sure any stack arguments overlapping with where we're storing 3091 // are loaded before this eventual operation. Otherwise they'll be 3092 // clobbered. 3093 3094 // FIXME: Why is this really necessary? This seems to just result in a 3095 // lot of code to copy the stack and write them back to the same 3096 // locations, which are supposed to be immutable? 3097 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3098 } else { 3099 DstAddr = PtrOff; 3100 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3101 Alignment = 3102 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3103 } 3104 3105 if (Outs[i].Flags.isByVal()) { 3106 SDValue SizeNode = 3107 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3108 SDValue Cpy = 3109 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3110 Outs[i].Flags.getNonZeroByValAlign(), 3111 /*isVol = */ false, /*AlwaysInline = */ true, 3112 /*isTailCall = */ false, DstInfo, 3113 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3114 3115 MemOpChains.push_back(Cpy); 3116 } else { 3117 SDValue Store = 3118 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3119 MemOpChains.push_back(Store); 3120 } 3121 } 3122 } 3123 3124 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3125 CallConv != CallingConv::AMDGPU_Gfx) { 3126 // Copy special input registers after user input arguments. 3127 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3128 } 3129 3130 if (!MemOpChains.empty()) 3131 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3132 3133 // Build a sequence of copy-to-reg nodes chained together with token chain 3134 // and flag operands which copy the outgoing args into the appropriate regs. 3135 SDValue InFlag; 3136 for (auto &RegToPass : RegsToPass) { 3137 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3138 RegToPass.second, InFlag); 3139 InFlag = Chain.getValue(1); 3140 } 3141 3142 3143 SDValue PhysReturnAddrReg; 3144 if (IsTailCall) { 3145 // Since the return is being combined with the call, we need to pass on the 3146 // return address. 3147 3148 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3149 SDValue ReturnAddrReg = CreateLiveInRegister( 3150 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3151 3152 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3153 MVT::i64); 3154 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3155 InFlag = Chain.getValue(1); 3156 } 3157 3158 // We don't usually want to end the call-sequence here because we would tidy 3159 // the frame up *after* the call, however in the ABI-changing tail-call case 3160 // we've carefully laid out the parameters so that when sp is reset they'll be 3161 // in the correct location. 3162 if (IsTailCall && !IsSibCall) { 3163 Chain = DAG.getCALLSEQ_END(Chain, 3164 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3165 DAG.getTargetConstant(0, DL, MVT::i32), 3166 InFlag, DL); 3167 InFlag = Chain.getValue(1); 3168 } 3169 3170 std::vector<SDValue> Ops; 3171 Ops.push_back(Chain); 3172 Ops.push_back(Callee); 3173 // Add a redundant copy of the callee global which will not be legalized, as 3174 // we need direct access to the callee later. 3175 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3176 const GlobalValue *GV = GSD->getGlobal(); 3177 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3178 } else { 3179 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3180 } 3181 3182 if (IsTailCall) { 3183 // Each tail call may have to adjust the stack by a different amount, so 3184 // this information must travel along with the operation for eventual 3185 // consumption by emitEpilogue. 3186 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3187 3188 Ops.push_back(PhysReturnAddrReg); 3189 } 3190 3191 // Add argument registers to the end of the list so that they are known live 3192 // into the call. 3193 for (auto &RegToPass : RegsToPass) { 3194 Ops.push_back(DAG.getRegister(RegToPass.first, 3195 RegToPass.second.getValueType())); 3196 } 3197 3198 // Add a register mask operand representing the call-preserved registers. 3199 3200 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3201 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3202 assert(Mask && "Missing call preserved mask for calling convention"); 3203 Ops.push_back(DAG.getRegisterMask(Mask)); 3204 3205 if (InFlag.getNode()) 3206 Ops.push_back(InFlag); 3207 3208 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3209 3210 // If we're doing a tall call, use a TC_RETURN here rather than an 3211 // actual call instruction. 3212 if (IsTailCall) { 3213 MFI.setHasTailCall(); 3214 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3215 } 3216 3217 // Returns a chain and a flag for retval copy to use. 3218 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3219 Chain = Call.getValue(0); 3220 InFlag = Call.getValue(1); 3221 3222 uint64_t CalleePopBytes = NumBytes; 3223 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3224 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3225 InFlag, DL); 3226 if (!Ins.empty()) 3227 InFlag = Chain.getValue(1); 3228 3229 // Handle result values, copying them out of physregs into vregs that we 3230 // return. 3231 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3232 InVals, IsThisReturn, 3233 IsThisReturn ? OutVals[0] : SDValue()); 3234 } 3235 3236 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3237 // except for applying the wave size scale to the increment amount. 3238 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3239 SDValue Op, SelectionDAG &DAG) const { 3240 const MachineFunction &MF = DAG.getMachineFunction(); 3241 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3242 3243 SDLoc dl(Op); 3244 EVT VT = Op.getValueType(); 3245 SDValue Tmp1 = Op; 3246 SDValue Tmp2 = Op.getValue(1); 3247 SDValue Tmp3 = Op.getOperand(2); 3248 SDValue Chain = Tmp1.getOperand(0); 3249 3250 Register SPReg = Info->getStackPtrOffsetReg(); 3251 3252 // Chain the dynamic stack allocation so that it doesn't modify the stack 3253 // pointer when other instructions are using the stack. 3254 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3255 3256 SDValue Size = Tmp2.getOperand(1); 3257 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3258 Chain = SP.getValue(1); 3259 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3260 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3261 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3262 unsigned Opc = 3263 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3264 ISD::ADD : ISD::SUB; 3265 3266 SDValue ScaledSize = DAG.getNode( 3267 ISD::SHL, dl, VT, Size, 3268 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3269 3270 Align StackAlign = TFL->getStackAlign(); 3271 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3272 if (Alignment && *Alignment > StackAlign) { 3273 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3274 DAG.getConstant(-(uint64_t)Alignment->value() 3275 << ST.getWavefrontSizeLog2(), 3276 dl, VT)); 3277 } 3278 3279 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3280 Tmp2 = DAG.getCALLSEQ_END( 3281 Chain, DAG.getIntPtrConstant(0, dl, true), 3282 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3283 3284 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3285 } 3286 3287 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3288 SelectionDAG &DAG) const { 3289 // We only handle constant sizes here to allow non-entry block, static sized 3290 // allocas. A truly dynamic value is more difficult to support because we 3291 // don't know if the size value is uniform or not. If the size isn't uniform, 3292 // we would need to do a wave reduction to get the maximum size to know how 3293 // much to increment the uniform stack pointer. 3294 SDValue Size = Op.getOperand(1); 3295 if (isa<ConstantSDNode>(Size)) 3296 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3297 3298 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3299 } 3300 3301 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3302 const MachineFunction &MF) const { 3303 Register Reg = StringSwitch<Register>(RegName) 3304 .Case("m0", AMDGPU::M0) 3305 .Case("exec", AMDGPU::EXEC) 3306 .Case("exec_lo", AMDGPU::EXEC_LO) 3307 .Case("exec_hi", AMDGPU::EXEC_HI) 3308 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3309 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3310 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3311 .Default(Register()); 3312 3313 if (Reg == AMDGPU::NoRegister) { 3314 report_fatal_error(Twine("invalid register name \"" 3315 + StringRef(RegName) + "\".")); 3316 3317 } 3318 3319 if (!Subtarget->hasFlatScrRegister() && 3320 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3321 report_fatal_error(Twine("invalid register \"" 3322 + StringRef(RegName) + "\" for subtarget.")); 3323 } 3324 3325 switch (Reg) { 3326 case AMDGPU::M0: 3327 case AMDGPU::EXEC_LO: 3328 case AMDGPU::EXEC_HI: 3329 case AMDGPU::FLAT_SCR_LO: 3330 case AMDGPU::FLAT_SCR_HI: 3331 if (VT.getSizeInBits() == 32) 3332 return Reg; 3333 break; 3334 case AMDGPU::EXEC: 3335 case AMDGPU::FLAT_SCR: 3336 if (VT.getSizeInBits() == 64) 3337 return Reg; 3338 break; 3339 default: 3340 llvm_unreachable("missing register type checking"); 3341 } 3342 3343 report_fatal_error(Twine("invalid type for register \"" 3344 + StringRef(RegName) + "\".")); 3345 } 3346 3347 // If kill is not the last instruction, split the block so kill is always a 3348 // proper terminator. 3349 MachineBasicBlock * 3350 SITargetLowering::splitKillBlock(MachineInstr &MI, 3351 MachineBasicBlock *BB) const { 3352 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3353 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3354 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3355 return SplitBB; 3356 } 3357 3358 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3359 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3360 // be the first instruction in the remainder block. 3361 // 3362 /// \returns { LoopBody, Remainder } 3363 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3364 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3365 MachineFunction *MF = MBB.getParent(); 3366 MachineBasicBlock::iterator I(&MI); 3367 3368 // To insert the loop we need to split the block. Move everything after this 3369 // point to a new block, and insert a new empty block between the two. 3370 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3371 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3372 MachineFunction::iterator MBBI(MBB); 3373 ++MBBI; 3374 3375 MF->insert(MBBI, LoopBB); 3376 MF->insert(MBBI, RemainderBB); 3377 3378 LoopBB->addSuccessor(LoopBB); 3379 LoopBB->addSuccessor(RemainderBB); 3380 3381 // Move the rest of the block into a new block. 3382 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3383 3384 if (InstInLoop) { 3385 auto Next = std::next(I); 3386 3387 // Move instruction to loop body. 3388 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3389 3390 // Move the rest of the block. 3391 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3392 } else { 3393 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3394 } 3395 3396 MBB.addSuccessor(LoopBB); 3397 3398 return std::make_pair(LoopBB, RemainderBB); 3399 } 3400 3401 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3402 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3403 MachineBasicBlock *MBB = MI.getParent(); 3404 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3405 auto I = MI.getIterator(); 3406 auto E = std::next(I); 3407 3408 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3409 .addImm(0); 3410 3411 MIBundleBuilder Bundler(*MBB, I, E); 3412 finalizeBundle(*MBB, Bundler.begin()); 3413 } 3414 3415 MachineBasicBlock * 3416 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3417 MachineBasicBlock *BB) const { 3418 const DebugLoc &DL = MI.getDebugLoc(); 3419 3420 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3421 3422 MachineBasicBlock *LoopBB; 3423 MachineBasicBlock *RemainderBB; 3424 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3425 3426 // Apparently kill flags are only valid if the def is in the same block? 3427 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3428 Src->setIsKill(false); 3429 3430 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3431 3432 MachineBasicBlock::iterator I = LoopBB->end(); 3433 3434 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3435 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3436 3437 // Clear TRAP_STS.MEM_VIOL 3438 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3439 .addImm(0) 3440 .addImm(EncodedReg); 3441 3442 bundleInstWithWaitcnt(MI); 3443 3444 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3445 3446 // Load and check TRAP_STS.MEM_VIOL 3447 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3448 .addImm(EncodedReg); 3449 3450 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3451 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3452 .addReg(Reg, RegState::Kill) 3453 .addImm(0); 3454 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3455 .addMBB(LoopBB); 3456 3457 return RemainderBB; 3458 } 3459 3460 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3461 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3462 // will only do one iteration. In the worst case, this will loop 64 times. 3463 // 3464 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3465 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3466 const SIInstrInfo *TII, 3467 MachineRegisterInfo &MRI, 3468 MachineBasicBlock &OrigBB, 3469 MachineBasicBlock &LoopBB, 3470 const DebugLoc &DL, 3471 const MachineOperand &IdxReg, 3472 unsigned InitReg, 3473 unsigned ResultReg, 3474 unsigned PhiReg, 3475 unsigned InitSaveExecReg, 3476 int Offset, 3477 bool UseGPRIdxMode, 3478 bool IsIndirectSrc) { 3479 MachineFunction *MF = OrigBB.getParent(); 3480 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3481 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3482 MachineBasicBlock::iterator I = LoopBB.begin(); 3483 3484 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3485 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3486 Register NewExec = MRI.createVirtualRegister(BoolRC); 3487 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3488 Register CondReg = MRI.createVirtualRegister(BoolRC); 3489 3490 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3491 .addReg(InitReg) 3492 .addMBB(&OrigBB) 3493 .addReg(ResultReg) 3494 .addMBB(&LoopBB); 3495 3496 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3497 .addReg(InitSaveExecReg) 3498 .addMBB(&OrigBB) 3499 .addReg(NewExec) 3500 .addMBB(&LoopBB); 3501 3502 // Read the next variant <- also loop target. 3503 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3504 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3505 3506 // Compare the just read M0 value to all possible Idx values. 3507 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3508 .addReg(CurrentIdxReg) 3509 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3510 3511 // Update EXEC, save the original EXEC value to VCC. 3512 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3513 : AMDGPU::S_AND_SAVEEXEC_B64), 3514 NewExec) 3515 .addReg(CondReg, RegState::Kill); 3516 3517 MRI.setSimpleHint(NewExec, CondReg); 3518 3519 if (UseGPRIdxMode) { 3520 unsigned IdxReg; 3521 if (Offset == 0) { 3522 IdxReg = CurrentIdxReg; 3523 } else { 3524 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3525 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3526 .addReg(CurrentIdxReg, RegState::Kill) 3527 .addImm(Offset); 3528 } 3529 unsigned IdxMode = IsIndirectSrc ? 3530 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3531 MachineInstr *SetOn = 3532 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3533 .addReg(IdxReg, RegState::Kill) 3534 .addImm(IdxMode); 3535 SetOn->getOperand(3).setIsUndef(); 3536 } else { 3537 // Move index from VCC into M0 3538 if (Offset == 0) { 3539 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3540 .addReg(CurrentIdxReg, RegState::Kill); 3541 } else { 3542 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3543 .addReg(CurrentIdxReg, RegState::Kill) 3544 .addImm(Offset); 3545 } 3546 } 3547 3548 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3549 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3550 MachineInstr *InsertPt = 3551 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3552 : AMDGPU::S_XOR_B64_term), Exec) 3553 .addReg(Exec) 3554 .addReg(NewExec); 3555 3556 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3557 // s_cbranch_scc0? 3558 3559 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3560 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3561 .addMBB(&LoopBB); 3562 3563 return InsertPt->getIterator(); 3564 } 3565 3566 // This has slightly sub-optimal regalloc when the source vector is killed by 3567 // the read. The register allocator does not understand that the kill is 3568 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3569 // subregister from it, using 1 more VGPR than necessary. This was saved when 3570 // this was expanded after register allocation. 3571 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3572 MachineBasicBlock &MBB, 3573 MachineInstr &MI, 3574 unsigned InitResultReg, 3575 unsigned PhiReg, 3576 int Offset, 3577 bool UseGPRIdxMode, 3578 bool IsIndirectSrc) { 3579 MachineFunction *MF = MBB.getParent(); 3580 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3581 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3582 MachineRegisterInfo &MRI = MF->getRegInfo(); 3583 const DebugLoc &DL = MI.getDebugLoc(); 3584 MachineBasicBlock::iterator I(&MI); 3585 3586 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3587 Register DstReg = MI.getOperand(0).getReg(); 3588 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3589 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3590 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3591 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3592 3593 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3594 3595 // Save the EXEC mask 3596 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3597 .addReg(Exec); 3598 3599 MachineBasicBlock *LoopBB; 3600 MachineBasicBlock *RemainderBB; 3601 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3602 3603 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3604 3605 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3606 InitResultReg, DstReg, PhiReg, TmpExec, 3607 Offset, UseGPRIdxMode, IsIndirectSrc); 3608 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3609 MachineFunction::iterator MBBI(LoopBB); 3610 ++MBBI; 3611 MF->insert(MBBI, LandingPad); 3612 LoopBB->removeSuccessor(RemainderBB); 3613 LandingPad->addSuccessor(RemainderBB); 3614 LoopBB->addSuccessor(LandingPad); 3615 MachineBasicBlock::iterator First = LandingPad->begin(); 3616 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3617 .addReg(SaveExec); 3618 3619 return InsPt; 3620 } 3621 3622 // Returns subreg index, offset 3623 static std::pair<unsigned, int> 3624 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3625 const TargetRegisterClass *SuperRC, 3626 unsigned VecReg, 3627 int Offset) { 3628 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3629 3630 // Skip out of bounds offsets, or else we would end up using an undefined 3631 // register. 3632 if (Offset >= NumElts || Offset < 0) 3633 return std::make_pair(AMDGPU::sub0, Offset); 3634 3635 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3636 } 3637 3638 // Return true if the index is an SGPR and was set. 3639 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3640 MachineRegisterInfo &MRI, 3641 MachineInstr &MI, 3642 int Offset, 3643 bool UseGPRIdxMode, 3644 bool IsIndirectSrc) { 3645 MachineBasicBlock *MBB = MI.getParent(); 3646 const DebugLoc &DL = MI.getDebugLoc(); 3647 MachineBasicBlock::iterator I(&MI); 3648 3649 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3650 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3651 3652 assert(Idx->getReg() != AMDGPU::NoRegister); 3653 3654 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3655 return false; 3656 3657 if (UseGPRIdxMode) { 3658 unsigned IdxMode = IsIndirectSrc ? 3659 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3660 if (Offset == 0) { 3661 MachineInstr *SetOn = 3662 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3663 .add(*Idx) 3664 .addImm(IdxMode); 3665 3666 SetOn->getOperand(3).setIsUndef(); 3667 } else { 3668 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3669 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3670 .add(*Idx) 3671 .addImm(Offset); 3672 MachineInstr *SetOn = 3673 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3674 .addReg(Tmp, RegState::Kill) 3675 .addImm(IdxMode); 3676 3677 SetOn->getOperand(3).setIsUndef(); 3678 } 3679 3680 return true; 3681 } 3682 3683 if (Offset == 0) { 3684 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3685 .add(*Idx); 3686 } else { 3687 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3688 .add(*Idx) 3689 .addImm(Offset); 3690 } 3691 3692 return true; 3693 } 3694 3695 // Control flow needs to be inserted if indexing with a VGPR. 3696 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3697 MachineBasicBlock &MBB, 3698 const GCNSubtarget &ST) { 3699 const SIInstrInfo *TII = ST.getInstrInfo(); 3700 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3701 MachineFunction *MF = MBB.getParent(); 3702 MachineRegisterInfo &MRI = MF->getRegInfo(); 3703 3704 Register Dst = MI.getOperand(0).getReg(); 3705 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3706 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3707 3708 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3709 3710 unsigned SubReg; 3711 std::tie(SubReg, Offset) 3712 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3713 3714 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3715 3716 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3717 MachineBasicBlock::iterator I(&MI); 3718 const DebugLoc &DL = MI.getDebugLoc(); 3719 3720 if (UseGPRIdxMode) { 3721 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3722 // to avoid interfering with other uses, so probably requires a new 3723 // optimization pass. 3724 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3725 .addReg(SrcReg, 0, SubReg) 3726 .addReg(SrcReg, RegState::Implicit) 3727 .addReg(AMDGPU::M0, RegState::Implicit); 3728 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3729 } else { 3730 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3731 .addReg(SrcReg, 0, SubReg) 3732 .addReg(SrcReg, RegState::Implicit); 3733 } 3734 3735 MI.eraseFromParent(); 3736 3737 return &MBB; 3738 } 3739 3740 const DebugLoc &DL = MI.getDebugLoc(); 3741 MachineBasicBlock::iterator I(&MI); 3742 3743 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3744 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3745 3746 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3747 3748 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3749 Offset, UseGPRIdxMode, true); 3750 MachineBasicBlock *LoopBB = InsPt->getParent(); 3751 3752 if (UseGPRIdxMode) { 3753 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3754 .addReg(SrcReg, 0, SubReg) 3755 .addReg(SrcReg, RegState::Implicit) 3756 .addReg(AMDGPU::M0, RegState::Implicit); 3757 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3758 } else { 3759 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3760 .addReg(SrcReg, 0, SubReg) 3761 .addReg(SrcReg, RegState::Implicit); 3762 } 3763 3764 MI.eraseFromParent(); 3765 3766 return LoopBB; 3767 } 3768 3769 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3770 MachineBasicBlock &MBB, 3771 const GCNSubtarget &ST) { 3772 const SIInstrInfo *TII = ST.getInstrInfo(); 3773 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3774 MachineFunction *MF = MBB.getParent(); 3775 MachineRegisterInfo &MRI = MF->getRegInfo(); 3776 3777 Register Dst = MI.getOperand(0).getReg(); 3778 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3779 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3780 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3781 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3782 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3783 3784 // This can be an immediate, but will be folded later. 3785 assert(Val->getReg()); 3786 3787 unsigned SubReg; 3788 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3789 SrcVec->getReg(), 3790 Offset); 3791 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3792 3793 if (Idx->getReg() == AMDGPU::NoRegister) { 3794 MachineBasicBlock::iterator I(&MI); 3795 const DebugLoc &DL = MI.getDebugLoc(); 3796 3797 assert(Offset == 0); 3798 3799 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3800 .add(*SrcVec) 3801 .add(*Val) 3802 .addImm(SubReg); 3803 3804 MI.eraseFromParent(); 3805 return &MBB; 3806 } 3807 3808 const MCInstrDesc &MovRelDesc 3809 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3810 3811 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3812 MachineBasicBlock::iterator I(&MI); 3813 const DebugLoc &DL = MI.getDebugLoc(); 3814 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3815 .addReg(SrcVec->getReg()) 3816 .add(*Val) 3817 .addImm(SubReg); 3818 if (UseGPRIdxMode) 3819 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3820 3821 MI.eraseFromParent(); 3822 return &MBB; 3823 } 3824 3825 if (Val->isReg()) 3826 MRI.clearKillFlags(Val->getReg()); 3827 3828 const DebugLoc &DL = MI.getDebugLoc(); 3829 3830 Register PhiReg = MRI.createVirtualRegister(VecRC); 3831 3832 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3833 Offset, UseGPRIdxMode, false); 3834 MachineBasicBlock *LoopBB = InsPt->getParent(); 3835 3836 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3837 .addReg(PhiReg) 3838 .add(*Val) 3839 .addImm(AMDGPU::sub0); 3840 if (UseGPRIdxMode) 3841 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3842 3843 MI.eraseFromParent(); 3844 return LoopBB; 3845 } 3846 3847 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3848 MachineInstr &MI, MachineBasicBlock *BB) const { 3849 3850 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3851 MachineFunction *MF = BB->getParent(); 3852 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3853 3854 switch (MI.getOpcode()) { 3855 case AMDGPU::S_UADDO_PSEUDO: 3856 case AMDGPU::S_USUBO_PSEUDO: { 3857 const DebugLoc &DL = MI.getDebugLoc(); 3858 MachineOperand &Dest0 = MI.getOperand(0); 3859 MachineOperand &Dest1 = MI.getOperand(1); 3860 MachineOperand &Src0 = MI.getOperand(2); 3861 MachineOperand &Src1 = MI.getOperand(3); 3862 3863 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3864 ? AMDGPU::S_ADD_I32 3865 : AMDGPU::S_SUB_I32; 3866 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3867 3868 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3869 .addImm(1) 3870 .addImm(0); 3871 3872 MI.eraseFromParent(); 3873 return BB; 3874 } 3875 case AMDGPU::S_ADD_U64_PSEUDO: 3876 case AMDGPU::S_SUB_U64_PSEUDO: { 3877 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3878 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3879 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3880 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3881 const DebugLoc &DL = MI.getDebugLoc(); 3882 3883 MachineOperand &Dest = MI.getOperand(0); 3884 MachineOperand &Src0 = MI.getOperand(1); 3885 MachineOperand &Src1 = MI.getOperand(2); 3886 3887 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3888 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3889 3890 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3891 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3892 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3893 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3894 3895 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3896 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3897 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3898 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3899 3900 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3901 3902 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3903 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3904 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3905 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3906 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3907 .addReg(DestSub0) 3908 .addImm(AMDGPU::sub0) 3909 .addReg(DestSub1) 3910 .addImm(AMDGPU::sub1); 3911 MI.eraseFromParent(); 3912 return BB; 3913 } 3914 case AMDGPU::V_ADD_U64_PSEUDO: 3915 case AMDGPU::V_SUB_U64_PSEUDO: { 3916 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3917 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3918 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3919 const DebugLoc &DL = MI.getDebugLoc(); 3920 3921 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3922 3923 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3924 3925 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3926 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3927 3928 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3929 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3930 3931 MachineOperand &Dest = MI.getOperand(0); 3932 MachineOperand &Src0 = MI.getOperand(1); 3933 MachineOperand &Src1 = MI.getOperand(2); 3934 3935 const TargetRegisterClass *Src0RC = Src0.isReg() 3936 ? MRI.getRegClass(Src0.getReg()) 3937 : &AMDGPU::VReg_64RegClass; 3938 const TargetRegisterClass *Src1RC = Src1.isReg() 3939 ? MRI.getRegClass(Src1.getReg()) 3940 : &AMDGPU::VReg_64RegClass; 3941 3942 const TargetRegisterClass *Src0SubRC = 3943 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3944 const TargetRegisterClass *Src1SubRC = 3945 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3946 3947 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3948 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3949 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3950 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3951 3952 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3953 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3954 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3955 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3956 3957 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3958 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3959 .addReg(CarryReg, RegState::Define) 3960 .add(SrcReg0Sub0) 3961 .add(SrcReg1Sub0) 3962 .addImm(0); // clamp bit 3963 3964 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3965 MachineInstr *HiHalf = 3966 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3967 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3968 .add(SrcReg0Sub1) 3969 .add(SrcReg1Sub1) 3970 .addReg(CarryReg, RegState::Kill) 3971 .addImm(0); // clamp bit 3972 3973 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3974 .addReg(DestSub0) 3975 .addImm(AMDGPU::sub0) 3976 .addReg(DestSub1) 3977 .addImm(AMDGPU::sub1); 3978 TII->legalizeOperands(*LoHalf); 3979 TII->legalizeOperands(*HiHalf); 3980 MI.eraseFromParent(); 3981 return BB; 3982 } 3983 case AMDGPU::S_ADD_CO_PSEUDO: 3984 case AMDGPU::S_SUB_CO_PSEUDO: { 3985 // This pseudo has a chance to be selected 3986 // only from uniform add/subcarry node. All the VGPR operands 3987 // therefore assumed to be splat vectors. 3988 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3989 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3990 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3991 MachineBasicBlock::iterator MII = MI; 3992 const DebugLoc &DL = MI.getDebugLoc(); 3993 MachineOperand &Dest = MI.getOperand(0); 3994 MachineOperand &CarryDest = MI.getOperand(1); 3995 MachineOperand &Src0 = MI.getOperand(2); 3996 MachineOperand &Src1 = MI.getOperand(3); 3997 MachineOperand &Src2 = MI.getOperand(4); 3998 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3999 ? AMDGPU::S_ADDC_U32 4000 : AMDGPU::S_SUBB_U32; 4001 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4002 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4003 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4004 .addReg(Src0.getReg()); 4005 Src0.setReg(RegOp0); 4006 } 4007 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4008 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4009 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4010 .addReg(Src1.getReg()); 4011 Src1.setReg(RegOp1); 4012 } 4013 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4014 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4015 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4016 .addReg(Src2.getReg()); 4017 Src2.setReg(RegOp2); 4018 } 4019 4020 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4021 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4022 if (ST.hasScalarCompareEq64()) { 4023 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4024 .addReg(Src2.getReg()) 4025 .addImm(0); 4026 } else { 4027 const TargetRegisterClass *SubRC = 4028 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4029 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4030 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4031 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4032 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4033 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4034 4035 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4036 .add(Src2Sub0) 4037 .add(Src2Sub1); 4038 4039 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4040 .addReg(Src2_32, RegState::Kill) 4041 .addImm(0); 4042 } 4043 } else { 4044 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4045 .addReg(Src2.getReg()) 4046 .addImm(0); 4047 } 4048 4049 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4050 4051 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4052 .addReg(AMDGPU::SCC); 4053 MI.eraseFromParent(); 4054 return BB; 4055 } 4056 case AMDGPU::SI_INIT_M0: { 4057 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4058 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4059 .add(MI.getOperand(0)); 4060 MI.eraseFromParent(); 4061 return BB; 4062 } 4063 case AMDGPU::SI_INIT_EXEC: 4064 // This should be before all vector instructions. 4065 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4066 AMDGPU::EXEC) 4067 .addImm(MI.getOperand(0).getImm()); 4068 MI.eraseFromParent(); 4069 return BB; 4070 4071 case AMDGPU::SI_INIT_EXEC_LO: 4072 // This should be before all vector instructions. 4073 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4074 AMDGPU::EXEC_LO) 4075 .addImm(MI.getOperand(0).getImm()); 4076 MI.eraseFromParent(); 4077 return BB; 4078 4079 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4080 // Extract the thread count from an SGPR input and set EXEC accordingly. 4081 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4082 // 4083 // S_BFE_U32 count, input, {shift, 7} 4084 // S_BFM_B64 exec, count, 0 4085 // S_CMP_EQ_U32 count, 64 4086 // S_CMOV_B64 exec, -1 4087 MachineInstr *FirstMI = &*BB->begin(); 4088 MachineRegisterInfo &MRI = MF->getRegInfo(); 4089 Register InputReg = MI.getOperand(0).getReg(); 4090 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4091 bool Found = false; 4092 4093 // Move the COPY of the input reg to the beginning, so that we can use it. 4094 for (auto I = BB->begin(); I != &MI; I++) { 4095 if (I->getOpcode() != TargetOpcode::COPY || 4096 I->getOperand(0).getReg() != InputReg) 4097 continue; 4098 4099 if (I == FirstMI) { 4100 FirstMI = &*++BB->begin(); 4101 } else { 4102 I->removeFromParent(); 4103 BB->insert(FirstMI, &*I); 4104 } 4105 Found = true; 4106 break; 4107 } 4108 assert(Found); 4109 (void)Found; 4110 4111 // This should be before all vector instructions. 4112 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4113 bool isWave32 = getSubtarget()->isWave32(); 4114 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4115 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4116 .addReg(InputReg) 4117 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4118 BuildMI(*BB, FirstMI, DebugLoc(), 4119 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4120 Exec) 4121 .addReg(CountReg) 4122 .addImm(0); 4123 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4124 .addReg(CountReg, RegState::Kill) 4125 .addImm(getSubtarget()->getWavefrontSize()); 4126 BuildMI(*BB, FirstMI, DebugLoc(), 4127 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4128 Exec) 4129 .addImm(-1); 4130 MI.eraseFromParent(); 4131 return BB; 4132 } 4133 4134 case AMDGPU::GET_GROUPSTATICSIZE: { 4135 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4136 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4137 DebugLoc DL = MI.getDebugLoc(); 4138 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4139 .add(MI.getOperand(0)) 4140 .addImm(MFI->getLDSSize()); 4141 MI.eraseFromParent(); 4142 return BB; 4143 } 4144 case AMDGPU::SI_INDIRECT_SRC_V1: 4145 case AMDGPU::SI_INDIRECT_SRC_V2: 4146 case AMDGPU::SI_INDIRECT_SRC_V4: 4147 case AMDGPU::SI_INDIRECT_SRC_V8: 4148 case AMDGPU::SI_INDIRECT_SRC_V16: 4149 case AMDGPU::SI_INDIRECT_SRC_V32: 4150 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4151 case AMDGPU::SI_INDIRECT_DST_V1: 4152 case AMDGPU::SI_INDIRECT_DST_V2: 4153 case AMDGPU::SI_INDIRECT_DST_V4: 4154 case AMDGPU::SI_INDIRECT_DST_V8: 4155 case AMDGPU::SI_INDIRECT_DST_V16: 4156 case AMDGPU::SI_INDIRECT_DST_V32: 4157 return emitIndirectDst(MI, *BB, *getSubtarget()); 4158 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4159 case AMDGPU::SI_KILL_I1_PSEUDO: 4160 return splitKillBlock(MI, BB); 4161 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4162 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4163 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4164 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4165 4166 Register Dst = MI.getOperand(0).getReg(); 4167 Register Src0 = MI.getOperand(1).getReg(); 4168 Register Src1 = MI.getOperand(2).getReg(); 4169 const DebugLoc &DL = MI.getDebugLoc(); 4170 Register SrcCond = MI.getOperand(3).getReg(); 4171 4172 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4173 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4174 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4175 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4176 4177 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4178 .addReg(SrcCond); 4179 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4180 .addImm(0) 4181 .addReg(Src0, 0, AMDGPU::sub0) 4182 .addImm(0) 4183 .addReg(Src1, 0, AMDGPU::sub0) 4184 .addReg(SrcCondCopy); 4185 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4186 .addImm(0) 4187 .addReg(Src0, 0, AMDGPU::sub1) 4188 .addImm(0) 4189 .addReg(Src1, 0, AMDGPU::sub1) 4190 .addReg(SrcCondCopy); 4191 4192 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4193 .addReg(DstLo) 4194 .addImm(AMDGPU::sub0) 4195 .addReg(DstHi) 4196 .addImm(AMDGPU::sub1); 4197 MI.eraseFromParent(); 4198 return BB; 4199 } 4200 case AMDGPU::SI_BR_UNDEF: { 4201 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4202 const DebugLoc &DL = MI.getDebugLoc(); 4203 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4204 .add(MI.getOperand(0)); 4205 Br->getOperand(1).setIsUndef(true); // read undef SCC 4206 MI.eraseFromParent(); 4207 return BB; 4208 } 4209 case AMDGPU::ADJCALLSTACKUP: 4210 case AMDGPU::ADJCALLSTACKDOWN: { 4211 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4212 MachineInstrBuilder MIB(*MF, &MI); 4213 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4214 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4215 return BB; 4216 } 4217 case AMDGPU::SI_CALL_ISEL: { 4218 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4219 const DebugLoc &DL = MI.getDebugLoc(); 4220 4221 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4222 4223 MachineInstrBuilder MIB; 4224 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4225 4226 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4227 MIB.add(MI.getOperand(I)); 4228 4229 MIB.cloneMemRefs(MI); 4230 MI.eraseFromParent(); 4231 return BB; 4232 } 4233 case AMDGPU::V_ADD_CO_U32_e32: 4234 case AMDGPU::V_SUB_CO_U32_e32: 4235 case AMDGPU::V_SUBREV_CO_U32_e32: { 4236 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4237 const DebugLoc &DL = MI.getDebugLoc(); 4238 unsigned Opc = MI.getOpcode(); 4239 4240 bool NeedClampOperand = false; 4241 if (TII->pseudoToMCOpcode(Opc) == -1) { 4242 Opc = AMDGPU::getVOPe64(Opc); 4243 NeedClampOperand = true; 4244 } 4245 4246 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4247 if (TII->isVOP3(*I)) { 4248 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4249 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4250 I.addReg(TRI->getVCC(), RegState::Define); 4251 } 4252 I.add(MI.getOperand(1)) 4253 .add(MI.getOperand(2)); 4254 if (NeedClampOperand) 4255 I.addImm(0); // clamp bit for e64 encoding 4256 4257 TII->legalizeOperands(*I); 4258 4259 MI.eraseFromParent(); 4260 return BB; 4261 } 4262 case AMDGPU::DS_GWS_INIT: 4263 case AMDGPU::DS_GWS_SEMA_V: 4264 case AMDGPU::DS_GWS_SEMA_BR: 4265 case AMDGPU::DS_GWS_SEMA_P: 4266 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4267 case AMDGPU::DS_GWS_BARRIER: 4268 // A s_waitcnt 0 is required to be the instruction immediately following. 4269 if (getSubtarget()->hasGWSAutoReplay()) { 4270 bundleInstWithWaitcnt(MI); 4271 return BB; 4272 } 4273 4274 return emitGWSMemViolTestLoop(MI, BB); 4275 case AMDGPU::S_SETREG_B32: { 4276 // Try to optimize cases that only set the denormal mode or rounding mode. 4277 // 4278 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4279 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4280 // instead. 4281 // 4282 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4283 // allow you to have a no side effect instruction in the output of a 4284 // sideeffecting pattern. 4285 unsigned ID, Offset, Width; 4286 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4287 if (ID != AMDGPU::Hwreg::ID_MODE) 4288 return BB; 4289 4290 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4291 const unsigned SetMask = WidthMask << Offset; 4292 4293 if (getSubtarget()->hasDenormModeInst()) { 4294 unsigned SetDenormOp = 0; 4295 unsigned SetRoundOp = 0; 4296 4297 // The dedicated instructions can only set the whole denorm or round mode 4298 // at once, not a subset of bits in either. 4299 if (SetMask == 4300 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4301 // If this fully sets both the round and denorm mode, emit the two 4302 // dedicated instructions for these. 4303 SetRoundOp = AMDGPU::S_ROUND_MODE; 4304 SetDenormOp = AMDGPU::S_DENORM_MODE; 4305 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4306 SetRoundOp = AMDGPU::S_ROUND_MODE; 4307 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4308 SetDenormOp = AMDGPU::S_DENORM_MODE; 4309 } 4310 4311 if (SetRoundOp || SetDenormOp) { 4312 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4313 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4314 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4315 unsigned ImmVal = Def->getOperand(1).getImm(); 4316 if (SetRoundOp) { 4317 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4318 .addImm(ImmVal & 0xf); 4319 4320 // If we also have the denorm mode, get just the denorm mode bits. 4321 ImmVal >>= 4; 4322 } 4323 4324 if (SetDenormOp) { 4325 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4326 .addImm(ImmVal & 0xf); 4327 } 4328 4329 MI.eraseFromParent(); 4330 return BB; 4331 } 4332 } 4333 } 4334 4335 // If only FP bits are touched, used the no side effects pseudo. 4336 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4337 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4338 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4339 4340 return BB; 4341 } 4342 default: 4343 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4344 } 4345 } 4346 4347 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4348 return isTypeLegal(VT.getScalarType()); 4349 } 4350 4351 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4352 // This currently forces unfolding various combinations of fsub into fma with 4353 // free fneg'd operands. As long as we have fast FMA (controlled by 4354 // isFMAFasterThanFMulAndFAdd), we should perform these. 4355 4356 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4357 // most of these combines appear to be cycle neutral but save on instruction 4358 // count / code size. 4359 return true; 4360 } 4361 4362 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4363 EVT VT) const { 4364 if (!VT.isVector()) { 4365 return MVT::i1; 4366 } 4367 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4368 } 4369 4370 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4371 // TODO: Should i16 be used always if legal? For now it would force VALU 4372 // shifts. 4373 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4374 } 4375 4376 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4377 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4378 ? Ty.changeElementSize(16) 4379 : Ty.changeElementSize(32); 4380 } 4381 4382 // Answering this is somewhat tricky and depends on the specific device which 4383 // have different rates for fma or all f64 operations. 4384 // 4385 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4386 // regardless of which device (although the number of cycles differs between 4387 // devices), so it is always profitable for f64. 4388 // 4389 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4390 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4391 // which we can always do even without fused FP ops since it returns the same 4392 // result as the separate operations and since it is always full 4393 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4394 // however does not support denormals, so we do report fma as faster if we have 4395 // a fast fma device and require denormals. 4396 // 4397 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4398 EVT VT) const { 4399 VT = VT.getScalarType(); 4400 4401 switch (VT.getSimpleVT().SimpleTy) { 4402 case MVT::f32: { 4403 // If mad is not available this depends only on if f32 fma is full rate. 4404 if (!Subtarget->hasMadMacF32Insts()) 4405 return Subtarget->hasFastFMAF32(); 4406 4407 // Otherwise f32 mad is always full rate and returns the same result as 4408 // the separate operations so should be preferred over fma. 4409 // However does not support denomals. 4410 if (hasFP32Denormals(MF)) 4411 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4412 4413 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4414 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4415 } 4416 case MVT::f64: 4417 return true; 4418 case MVT::f16: 4419 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4420 default: 4421 break; 4422 } 4423 4424 return false; 4425 } 4426 4427 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4428 const SDNode *N) const { 4429 // TODO: Check future ftz flag 4430 // v_mad_f32/v_mac_f32 do not support denormals. 4431 EVT VT = N->getValueType(0); 4432 if (VT == MVT::f32) 4433 return Subtarget->hasMadMacF32Insts() && 4434 !hasFP32Denormals(DAG.getMachineFunction()); 4435 if (VT == MVT::f16) { 4436 return Subtarget->hasMadF16() && 4437 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4438 } 4439 4440 return false; 4441 } 4442 4443 //===----------------------------------------------------------------------===// 4444 // Custom DAG Lowering Operations 4445 //===----------------------------------------------------------------------===// 4446 4447 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4448 // wider vector type is legal. 4449 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4450 SelectionDAG &DAG) const { 4451 unsigned Opc = Op.getOpcode(); 4452 EVT VT = Op.getValueType(); 4453 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4454 4455 SDValue Lo, Hi; 4456 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4457 4458 SDLoc SL(Op); 4459 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4460 Op->getFlags()); 4461 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4462 Op->getFlags()); 4463 4464 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4465 } 4466 4467 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4468 // wider vector type is legal. 4469 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4470 SelectionDAG &DAG) const { 4471 unsigned Opc = Op.getOpcode(); 4472 EVT VT = Op.getValueType(); 4473 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4474 4475 SDValue Lo0, Hi0; 4476 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4477 SDValue Lo1, Hi1; 4478 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4479 4480 SDLoc SL(Op); 4481 4482 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4483 Op->getFlags()); 4484 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4485 Op->getFlags()); 4486 4487 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4488 } 4489 4490 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4491 SelectionDAG &DAG) const { 4492 unsigned Opc = Op.getOpcode(); 4493 EVT VT = Op.getValueType(); 4494 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4495 4496 SDValue Lo0, Hi0; 4497 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4498 SDValue Lo1, Hi1; 4499 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4500 SDValue Lo2, Hi2; 4501 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4502 4503 SDLoc SL(Op); 4504 4505 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4506 Op->getFlags()); 4507 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4508 Op->getFlags()); 4509 4510 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4511 } 4512 4513 4514 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4515 switch (Op.getOpcode()) { 4516 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4517 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4518 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4519 case ISD::LOAD: { 4520 SDValue Result = LowerLOAD(Op, DAG); 4521 assert((!Result.getNode() || 4522 Result.getNode()->getNumValues() == 2) && 4523 "Load should return a value and a chain"); 4524 return Result; 4525 } 4526 4527 case ISD::FSIN: 4528 case ISD::FCOS: 4529 return LowerTrig(Op, DAG); 4530 case ISD::SELECT: return LowerSELECT(Op, DAG); 4531 case ISD::FDIV: return LowerFDIV(Op, DAG); 4532 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4533 case ISD::STORE: return LowerSTORE(Op, DAG); 4534 case ISD::GlobalAddress: { 4535 MachineFunction &MF = DAG.getMachineFunction(); 4536 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4537 return LowerGlobalAddress(MFI, Op, DAG); 4538 } 4539 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4540 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4541 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4542 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4543 case ISD::INSERT_SUBVECTOR: 4544 return lowerINSERT_SUBVECTOR(Op, DAG); 4545 case ISD::INSERT_VECTOR_ELT: 4546 return lowerINSERT_VECTOR_ELT(Op, DAG); 4547 case ISD::EXTRACT_VECTOR_ELT: 4548 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4549 case ISD::VECTOR_SHUFFLE: 4550 return lowerVECTOR_SHUFFLE(Op, DAG); 4551 case ISD::BUILD_VECTOR: 4552 return lowerBUILD_VECTOR(Op, DAG); 4553 case ISD::FP_ROUND: 4554 return lowerFP_ROUND(Op, DAG); 4555 case ISD::TRAP: 4556 return lowerTRAP(Op, DAG); 4557 case ISD::DEBUGTRAP: 4558 return lowerDEBUGTRAP(Op, DAG); 4559 case ISD::FABS: 4560 case ISD::FNEG: 4561 case ISD::FCANONICALIZE: 4562 case ISD::BSWAP: 4563 return splitUnaryVectorOp(Op, DAG); 4564 case ISD::FMINNUM: 4565 case ISD::FMAXNUM: 4566 return lowerFMINNUM_FMAXNUM(Op, DAG); 4567 case ISD::FMA: 4568 return splitTernaryVectorOp(Op, DAG); 4569 case ISD::SHL: 4570 case ISD::SRA: 4571 case ISD::SRL: 4572 case ISD::ADD: 4573 case ISD::SUB: 4574 case ISD::MUL: 4575 case ISD::SMIN: 4576 case ISD::SMAX: 4577 case ISD::UMIN: 4578 case ISD::UMAX: 4579 case ISD::FADD: 4580 case ISD::FMUL: 4581 case ISD::FMINNUM_IEEE: 4582 case ISD::FMAXNUM_IEEE: 4583 case ISD::UADDSAT: 4584 case ISD::USUBSAT: 4585 case ISD::SADDSAT: 4586 case ISD::SSUBSAT: 4587 return splitBinaryVectorOp(Op, DAG); 4588 case ISD::SMULO: 4589 case ISD::UMULO: 4590 return lowerXMULO(Op, DAG); 4591 case ISD::DYNAMIC_STACKALLOC: 4592 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4593 } 4594 return SDValue(); 4595 } 4596 4597 // Used for D16: Casts the result of an instruction into the right vector, 4598 // packs values if loads return unpacked values. 4599 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4600 const SDLoc &DL, 4601 SelectionDAG &DAG, bool Unpacked) { 4602 if (!LoadVT.isVector()) 4603 return Result; 4604 4605 // Cast back to the original packed type or to a larger type that is a 4606 // multiple of 32 bit for D16. Widening the return type is a required for 4607 // legalization. 4608 EVT FittingLoadVT = LoadVT; 4609 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4610 FittingLoadVT = 4611 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4612 LoadVT.getVectorNumElements() + 1); 4613 } 4614 4615 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4616 // Truncate to v2i16/v4i16. 4617 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4618 4619 // Workaround legalizer not scalarizing truncate after vector op 4620 // legalization but not creating intermediate vector trunc. 4621 SmallVector<SDValue, 4> Elts; 4622 DAG.ExtractVectorElements(Result, Elts); 4623 for (SDValue &Elt : Elts) 4624 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4625 4626 // Pad illegal v1i16/v3fi6 to v4i16 4627 if ((LoadVT.getVectorNumElements() % 2) == 1) 4628 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4629 4630 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4631 4632 // Bitcast to original type (v2f16/v4f16). 4633 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4634 } 4635 4636 // Cast back to the original packed type. 4637 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4638 } 4639 4640 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4641 MemSDNode *M, 4642 SelectionDAG &DAG, 4643 ArrayRef<SDValue> Ops, 4644 bool IsIntrinsic) const { 4645 SDLoc DL(M); 4646 4647 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4648 EVT LoadVT = M->getValueType(0); 4649 4650 EVT EquivLoadVT = LoadVT; 4651 if (LoadVT.isVector()) { 4652 if (Unpacked) { 4653 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4654 LoadVT.getVectorNumElements()); 4655 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4656 // Widen v3f16 to legal type 4657 EquivLoadVT = 4658 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4659 LoadVT.getVectorNumElements() + 1); 4660 } 4661 } 4662 4663 // Change from v4f16/v2f16 to EquivLoadVT. 4664 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4665 4666 SDValue Load 4667 = DAG.getMemIntrinsicNode( 4668 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4669 VTList, Ops, M->getMemoryVT(), 4670 M->getMemOperand()); 4671 4672 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4673 4674 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4675 } 4676 4677 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4678 SelectionDAG &DAG, 4679 ArrayRef<SDValue> Ops) const { 4680 SDLoc DL(M); 4681 EVT LoadVT = M->getValueType(0); 4682 EVT EltType = LoadVT.getScalarType(); 4683 EVT IntVT = LoadVT.changeTypeToInteger(); 4684 4685 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4686 4687 unsigned Opc = 4688 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4689 4690 if (IsD16) { 4691 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4692 } 4693 4694 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4695 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4696 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4697 4698 if (isTypeLegal(LoadVT)) { 4699 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4700 M->getMemOperand(), DAG); 4701 } 4702 4703 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4704 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4705 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4706 M->getMemOperand(), DAG); 4707 return DAG.getMergeValues( 4708 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4709 DL); 4710 } 4711 4712 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4713 SDNode *N, SelectionDAG &DAG) { 4714 EVT VT = N->getValueType(0); 4715 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4716 unsigned CondCode = CD->getZExtValue(); 4717 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4718 return DAG.getUNDEF(VT); 4719 4720 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4721 4722 SDValue LHS = N->getOperand(1); 4723 SDValue RHS = N->getOperand(2); 4724 4725 SDLoc DL(N); 4726 4727 EVT CmpVT = LHS.getValueType(); 4728 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4729 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4730 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4731 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4732 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4733 } 4734 4735 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4736 4737 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4738 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4739 4740 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4741 DAG.getCondCode(CCOpcode)); 4742 if (VT.bitsEq(CCVT)) 4743 return SetCC; 4744 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4745 } 4746 4747 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4748 SDNode *N, SelectionDAG &DAG) { 4749 EVT VT = N->getValueType(0); 4750 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4751 4752 unsigned CondCode = CD->getZExtValue(); 4753 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4754 return DAG.getUNDEF(VT); 4755 4756 SDValue Src0 = N->getOperand(1); 4757 SDValue Src1 = N->getOperand(2); 4758 EVT CmpVT = Src0.getValueType(); 4759 SDLoc SL(N); 4760 4761 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4762 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4763 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4764 } 4765 4766 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4767 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4768 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4769 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4770 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4771 Src1, DAG.getCondCode(CCOpcode)); 4772 if (VT.bitsEq(CCVT)) 4773 return SetCC; 4774 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4775 } 4776 4777 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4778 SelectionDAG &DAG) { 4779 EVT VT = N->getValueType(0); 4780 SDValue Src = N->getOperand(1); 4781 SDLoc SL(N); 4782 4783 if (Src.getOpcode() == ISD::SETCC) { 4784 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4785 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4786 Src.getOperand(1), Src.getOperand(2)); 4787 } 4788 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4789 // (ballot 0) -> 0 4790 if (Arg->isNullValue()) 4791 return DAG.getConstant(0, SL, VT); 4792 4793 // (ballot 1) -> EXEC/EXEC_LO 4794 if (Arg->isOne()) { 4795 Register Exec; 4796 if (VT.getScalarSizeInBits() == 32) 4797 Exec = AMDGPU::EXEC_LO; 4798 else if (VT.getScalarSizeInBits() == 64) 4799 Exec = AMDGPU::EXEC; 4800 else 4801 return SDValue(); 4802 4803 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4804 } 4805 } 4806 4807 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4808 // ISD::SETNE) 4809 return DAG.getNode( 4810 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4811 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4812 } 4813 4814 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4815 SmallVectorImpl<SDValue> &Results, 4816 SelectionDAG &DAG) const { 4817 switch (N->getOpcode()) { 4818 case ISD::INSERT_VECTOR_ELT: { 4819 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4820 Results.push_back(Res); 4821 return; 4822 } 4823 case ISD::EXTRACT_VECTOR_ELT: { 4824 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4825 Results.push_back(Res); 4826 return; 4827 } 4828 case ISD::INTRINSIC_WO_CHAIN: { 4829 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4830 switch (IID) { 4831 case Intrinsic::amdgcn_cvt_pkrtz: { 4832 SDValue Src0 = N->getOperand(1); 4833 SDValue Src1 = N->getOperand(2); 4834 SDLoc SL(N); 4835 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4836 Src0, Src1); 4837 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4838 return; 4839 } 4840 case Intrinsic::amdgcn_cvt_pknorm_i16: 4841 case Intrinsic::amdgcn_cvt_pknorm_u16: 4842 case Intrinsic::amdgcn_cvt_pk_i16: 4843 case Intrinsic::amdgcn_cvt_pk_u16: { 4844 SDValue Src0 = N->getOperand(1); 4845 SDValue Src1 = N->getOperand(2); 4846 SDLoc SL(N); 4847 unsigned Opcode; 4848 4849 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4850 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4851 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4852 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4853 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4854 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4855 else 4856 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4857 4858 EVT VT = N->getValueType(0); 4859 if (isTypeLegal(VT)) 4860 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4861 else { 4862 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4863 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4864 } 4865 return; 4866 } 4867 } 4868 break; 4869 } 4870 case ISD::INTRINSIC_W_CHAIN: { 4871 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4872 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4873 // FIXME: Hacky 4874 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4875 Results.push_back(Res.getOperand(I)); 4876 } 4877 } else { 4878 Results.push_back(Res); 4879 Results.push_back(Res.getValue(1)); 4880 } 4881 return; 4882 } 4883 4884 break; 4885 } 4886 case ISD::SELECT: { 4887 SDLoc SL(N); 4888 EVT VT = N->getValueType(0); 4889 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4890 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4891 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4892 4893 EVT SelectVT = NewVT; 4894 if (NewVT.bitsLT(MVT::i32)) { 4895 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4896 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4897 SelectVT = MVT::i32; 4898 } 4899 4900 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4901 N->getOperand(0), LHS, RHS); 4902 4903 if (NewVT != SelectVT) 4904 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4905 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4906 return; 4907 } 4908 case ISD::FNEG: { 4909 if (N->getValueType(0) != MVT::v2f16) 4910 break; 4911 4912 SDLoc SL(N); 4913 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4914 4915 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4916 BC, 4917 DAG.getConstant(0x80008000, SL, MVT::i32)); 4918 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4919 return; 4920 } 4921 case ISD::FABS: { 4922 if (N->getValueType(0) != MVT::v2f16) 4923 break; 4924 4925 SDLoc SL(N); 4926 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4927 4928 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4929 BC, 4930 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4931 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4932 return; 4933 } 4934 default: 4935 break; 4936 } 4937 } 4938 4939 /// Helper function for LowerBRCOND 4940 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4941 4942 SDNode *Parent = Value.getNode(); 4943 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4944 I != E; ++I) { 4945 4946 if (I.getUse().get() != Value) 4947 continue; 4948 4949 if (I->getOpcode() == Opcode) 4950 return *I; 4951 } 4952 return nullptr; 4953 } 4954 4955 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4956 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4957 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4958 case Intrinsic::amdgcn_if: 4959 return AMDGPUISD::IF; 4960 case Intrinsic::amdgcn_else: 4961 return AMDGPUISD::ELSE; 4962 case Intrinsic::amdgcn_loop: 4963 return AMDGPUISD::LOOP; 4964 case Intrinsic::amdgcn_end_cf: 4965 llvm_unreachable("should not occur"); 4966 default: 4967 return 0; 4968 } 4969 } 4970 4971 // break, if_break, else_break are all only used as inputs to loop, not 4972 // directly as branch conditions. 4973 return 0; 4974 } 4975 4976 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4977 const Triple &TT = getTargetMachine().getTargetTriple(); 4978 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4979 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4980 AMDGPU::shouldEmitConstantsToTextSection(TT); 4981 } 4982 4983 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4984 // FIXME: Either avoid relying on address space here or change the default 4985 // address space for functions to avoid the explicit check. 4986 return (GV->getValueType()->isFunctionTy() || 4987 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4988 !shouldEmitFixup(GV) && 4989 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4990 } 4991 4992 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4993 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4994 } 4995 4996 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4997 if (!GV->hasExternalLinkage()) 4998 return true; 4999 5000 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5001 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5002 } 5003 5004 /// This transforms the control flow intrinsics to get the branch destination as 5005 /// last parameter, also switches branch target with BR if the need arise 5006 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5007 SelectionDAG &DAG) const { 5008 SDLoc DL(BRCOND); 5009 5010 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5011 SDValue Target = BRCOND.getOperand(2); 5012 SDNode *BR = nullptr; 5013 SDNode *SetCC = nullptr; 5014 5015 if (Intr->getOpcode() == ISD::SETCC) { 5016 // As long as we negate the condition everything is fine 5017 SetCC = Intr; 5018 Intr = SetCC->getOperand(0).getNode(); 5019 5020 } else { 5021 // Get the target from BR if we don't negate the condition 5022 BR = findUser(BRCOND, ISD::BR); 5023 assert(BR && "brcond missing unconditional branch user"); 5024 Target = BR->getOperand(1); 5025 } 5026 5027 unsigned CFNode = isCFIntrinsic(Intr); 5028 if (CFNode == 0) { 5029 // This is a uniform branch so we don't need to legalize. 5030 return BRCOND; 5031 } 5032 5033 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5034 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5035 5036 assert(!SetCC || 5037 (SetCC->getConstantOperandVal(1) == 1 && 5038 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5039 ISD::SETNE)); 5040 5041 // operands of the new intrinsic call 5042 SmallVector<SDValue, 4> Ops; 5043 if (HaveChain) 5044 Ops.push_back(BRCOND.getOperand(0)); 5045 5046 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5047 Ops.push_back(Target); 5048 5049 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5050 5051 // build the new intrinsic call 5052 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5053 5054 if (!HaveChain) { 5055 SDValue Ops[] = { 5056 SDValue(Result, 0), 5057 BRCOND.getOperand(0) 5058 }; 5059 5060 Result = DAG.getMergeValues(Ops, DL).getNode(); 5061 } 5062 5063 if (BR) { 5064 // Give the branch instruction our target 5065 SDValue Ops[] = { 5066 BR->getOperand(0), 5067 BRCOND.getOperand(2) 5068 }; 5069 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5070 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5071 } 5072 5073 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5074 5075 // Copy the intrinsic results to registers 5076 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5077 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5078 if (!CopyToReg) 5079 continue; 5080 5081 Chain = DAG.getCopyToReg( 5082 Chain, DL, 5083 CopyToReg->getOperand(1), 5084 SDValue(Result, i - 1), 5085 SDValue()); 5086 5087 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5088 } 5089 5090 // Remove the old intrinsic from the chain 5091 DAG.ReplaceAllUsesOfValueWith( 5092 SDValue(Intr, Intr->getNumValues() - 1), 5093 Intr->getOperand(0)); 5094 5095 return Chain; 5096 } 5097 5098 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5099 SelectionDAG &DAG) const { 5100 MVT VT = Op.getSimpleValueType(); 5101 SDLoc DL(Op); 5102 // Checking the depth 5103 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5104 return DAG.getConstant(0, DL, VT); 5105 5106 MachineFunction &MF = DAG.getMachineFunction(); 5107 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5108 // Check for kernel and shader functions 5109 if (Info->isEntryFunction()) 5110 return DAG.getConstant(0, DL, VT); 5111 5112 MachineFrameInfo &MFI = MF.getFrameInfo(); 5113 // There is a call to @llvm.returnaddress in this function 5114 MFI.setReturnAddressIsTaken(true); 5115 5116 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5117 // Get the return address reg and mark it as an implicit live-in 5118 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5119 5120 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5121 } 5122 5123 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5124 SDValue Op, 5125 const SDLoc &DL, 5126 EVT VT) const { 5127 return Op.getValueType().bitsLE(VT) ? 5128 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5129 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5130 DAG.getTargetConstant(0, DL, MVT::i32)); 5131 } 5132 5133 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5134 assert(Op.getValueType() == MVT::f16 && 5135 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5136 5137 SDValue Src = Op.getOperand(0); 5138 EVT SrcVT = Src.getValueType(); 5139 if (SrcVT != MVT::f64) 5140 return Op; 5141 5142 SDLoc DL(Op); 5143 5144 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5145 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5146 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5147 } 5148 5149 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5150 SelectionDAG &DAG) const { 5151 EVT VT = Op.getValueType(); 5152 const MachineFunction &MF = DAG.getMachineFunction(); 5153 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5154 bool IsIEEEMode = Info->getMode().IEEE; 5155 5156 // FIXME: Assert during selection that this is only selected for 5157 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5158 // mode functions, but this happens to be OK since it's only done in cases 5159 // where there is known no sNaN. 5160 if (IsIEEEMode) 5161 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5162 5163 if (VT == MVT::v4f16) 5164 return splitBinaryVectorOp(Op, DAG); 5165 return Op; 5166 } 5167 5168 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5169 EVT VT = Op.getValueType(); 5170 SDLoc SL(Op); 5171 SDValue LHS = Op.getOperand(0); 5172 SDValue RHS = Op.getOperand(1); 5173 bool isSigned = Op.getOpcode() == ISD::SMULO; 5174 5175 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5176 const APInt &C = RHSC->getAPIntValue(); 5177 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5178 if (C.isPowerOf2()) { 5179 // smulo(x, signed_min) is same as umulo(x, signed_min). 5180 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5181 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5182 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5183 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5184 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5185 SL, VT, Result, ShiftAmt), 5186 LHS, ISD::SETNE); 5187 return DAG.getMergeValues({ Result, Overflow }, SL); 5188 } 5189 } 5190 5191 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5192 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5193 SL, VT, LHS, RHS); 5194 5195 SDValue Sign = isSigned 5196 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5197 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5198 : DAG.getConstant(0, SL, VT); 5199 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5200 5201 return DAG.getMergeValues({ Result, Overflow }, SL); 5202 } 5203 5204 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5205 SDLoc SL(Op); 5206 SDValue Chain = Op.getOperand(0); 5207 5208 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5209 !Subtarget->isTrapHandlerEnabled()) 5210 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5211 5212 MachineFunction &MF = DAG.getMachineFunction(); 5213 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5214 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5215 assert(UserSGPR != AMDGPU::NoRegister); 5216 SDValue QueuePtr = CreateLiveInRegister( 5217 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5218 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5219 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5220 QueuePtr, SDValue()); 5221 SDValue Ops[] = { 5222 ToReg, 5223 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5224 SGPR01, 5225 ToReg.getValue(1) 5226 }; 5227 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5228 } 5229 5230 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5231 SDLoc SL(Op); 5232 SDValue Chain = Op.getOperand(0); 5233 MachineFunction &MF = DAG.getMachineFunction(); 5234 5235 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5236 !Subtarget->isTrapHandlerEnabled()) { 5237 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5238 "debugtrap handler not supported", 5239 Op.getDebugLoc(), 5240 DS_Warning); 5241 LLVMContext &Ctx = MF.getFunction().getContext(); 5242 Ctx.diagnose(NoTrap); 5243 return Chain; 5244 } 5245 5246 SDValue Ops[] = { 5247 Chain, 5248 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5249 }; 5250 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5251 } 5252 5253 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5254 SelectionDAG &DAG) const { 5255 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5256 if (Subtarget->hasApertureRegs()) { 5257 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5258 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5259 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5260 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5261 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5262 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5263 unsigned Encoding = 5264 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5265 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5266 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5267 5268 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5269 SDValue ApertureReg = SDValue( 5270 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5271 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5272 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5273 } 5274 5275 MachineFunction &MF = DAG.getMachineFunction(); 5276 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5277 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5278 assert(UserSGPR != AMDGPU::NoRegister); 5279 5280 SDValue QueuePtr = CreateLiveInRegister( 5281 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5282 5283 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5284 // private_segment_aperture_base_hi. 5285 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5286 5287 SDValue Ptr = 5288 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5289 5290 // TODO: Use custom target PseudoSourceValue. 5291 // TODO: We should use the value from the IR intrinsic call, but it might not 5292 // be available and how do we get it? 5293 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5294 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5295 commonAlignment(Align(64), StructOffset), 5296 MachineMemOperand::MODereferenceable | 5297 MachineMemOperand::MOInvariant); 5298 } 5299 5300 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5301 SelectionDAG &DAG) const { 5302 SDLoc SL(Op); 5303 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5304 5305 SDValue Src = ASC->getOperand(0); 5306 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5307 5308 const AMDGPUTargetMachine &TM = 5309 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5310 5311 // flat -> local/private 5312 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5313 unsigned DestAS = ASC->getDestAddressSpace(); 5314 5315 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5316 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5317 unsigned NullVal = TM.getNullPointerValue(DestAS); 5318 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5319 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5320 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5321 5322 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5323 NonNull, Ptr, SegmentNullPtr); 5324 } 5325 } 5326 5327 // local/private -> flat 5328 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5329 unsigned SrcAS = ASC->getSrcAddressSpace(); 5330 5331 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5332 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5333 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5334 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5335 5336 SDValue NonNull 5337 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5338 5339 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5340 SDValue CvtPtr 5341 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5342 5343 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5344 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5345 FlatNullPtr); 5346 } 5347 } 5348 5349 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5350 Src.getValueType() == MVT::i64) 5351 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5352 5353 // global <-> flat are no-ops and never emitted. 5354 5355 const MachineFunction &MF = DAG.getMachineFunction(); 5356 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5357 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5358 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5359 5360 return DAG.getUNDEF(ASC->getValueType(0)); 5361 } 5362 5363 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5364 // the small vector and inserting them into the big vector. That is better than 5365 // the default expansion of doing it via a stack slot. Even though the use of 5366 // the stack slot would be optimized away afterwards, the stack slot itself 5367 // remains. 5368 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5369 SelectionDAG &DAG) const { 5370 SDValue Vec = Op.getOperand(0); 5371 SDValue Ins = Op.getOperand(1); 5372 SDValue Idx = Op.getOperand(2); 5373 EVT VecVT = Vec.getValueType(); 5374 EVT InsVT = Ins.getValueType(); 5375 EVT EltVT = VecVT.getVectorElementType(); 5376 unsigned InsNumElts = InsVT.getVectorNumElements(); 5377 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5378 SDLoc SL(Op); 5379 5380 for (unsigned I = 0; I != InsNumElts; ++I) { 5381 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5382 DAG.getConstant(I, SL, MVT::i32)); 5383 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5384 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5385 } 5386 return Vec; 5387 } 5388 5389 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5390 SelectionDAG &DAG) const { 5391 SDValue Vec = Op.getOperand(0); 5392 SDValue InsVal = Op.getOperand(1); 5393 SDValue Idx = Op.getOperand(2); 5394 EVT VecVT = Vec.getValueType(); 5395 EVT EltVT = VecVT.getVectorElementType(); 5396 unsigned VecSize = VecVT.getSizeInBits(); 5397 unsigned EltSize = EltVT.getSizeInBits(); 5398 5399 5400 assert(VecSize <= 64); 5401 5402 unsigned NumElts = VecVT.getVectorNumElements(); 5403 SDLoc SL(Op); 5404 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5405 5406 if (NumElts == 4 && EltSize == 16 && KIdx) { 5407 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5408 5409 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5410 DAG.getConstant(0, SL, MVT::i32)); 5411 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5412 DAG.getConstant(1, SL, MVT::i32)); 5413 5414 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5415 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5416 5417 unsigned Idx = KIdx->getZExtValue(); 5418 bool InsertLo = Idx < 2; 5419 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5420 InsertLo ? LoVec : HiVec, 5421 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5422 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5423 5424 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5425 5426 SDValue Concat = InsertLo ? 5427 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5428 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5429 5430 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5431 } 5432 5433 if (isa<ConstantSDNode>(Idx)) 5434 return SDValue(); 5435 5436 MVT IntVT = MVT::getIntegerVT(VecSize); 5437 5438 // Avoid stack access for dynamic indexing. 5439 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5440 5441 // Create a congruent vector with the target value in each element so that 5442 // the required element can be masked and ORed into the target vector. 5443 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5444 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5445 5446 assert(isPowerOf2_32(EltSize)); 5447 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5448 5449 // Convert vector index to bit-index. 5450 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5451 5452 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5453 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5454 DAG.getConstant(0xffff, SL, IntVT), 5455 ScaledIdx); 5456 5457 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5458 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5459 DAG.getNOT(SL, BFM, IntVT), BCVec); 5460 5461 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5462 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5463 } 5464 5465 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5466 SelectionDAG &DAG) const { 5467 SDLoc SL(Op); 5468 5469 EVT ResultVT = Op.getValueType(); 5470 SDValue Vec = Op.getOperand(0); 5471 SDValue Idx = Op.getOperand(1); 5472 EVT VecVT = Vec.getValueType(); 5473 unsigned VecSize = VecVT.getSizeInBits(); 5474 EVT EltVT = VecVT.getVectorElementType(); 5475 assert(VecSize <= 64); 5476 5477 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5478 5479 // Make sure we do any optimizations that will make it easier to fold 5480 // source modifiers before obscuring it with bit operations. 5481 5482 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5483 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5484 return Combined; 5485 5486 unsigned EltSize = EltVT.getSizeInBits(); 5487 assert(isPowerOf2_32(EltSize)); 5488 5489 MVT IntVT = MVT::getIntegerVT(VecSize); 5490 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5491 5492 // Convert vector index to bit-index (* EltSize) 5493 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5494 5495 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5496 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5497 5498 if (ResultVT == MVT::f16) { 5499 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5500 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5501 } 5502 5503 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5504 } 5505 5506 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5507 assert(Elt % 2 == 0); 5508 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5509 } 5510 5511 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5512 SelectionDAG &DAG) const { 5513 SDLoc SL(Op); 5514 EVT ResultVT = Op.getValueType(); 5515 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5516 5517 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5518 EVT EltVT = PackVT.getVectorElementType(); 5519 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5520 5521 // vector_shuffle <0,1,6,7> lhs, rhs 5522 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5523 // 5524 // vector_shuffle <6,7,2,3> lhs, rhs 5525 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5526 // 5527 // vector_shuffle <6,7,0,1> lhs, rhs 5528 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5529 5530 // Avoid scalarizing when both halves are reading from consecutive elements. 5531 SmallVector<SDValue, 4> Pieces; 5532 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5533 if (elementPairIsContiguous(SVN->getMask(), I)) { 5534 const int Idx = SVN->getMaskElt(I); 5535 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5536 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5537 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5538 PackVT, SVN->getOperand(VecIdx), 5539 DAG.getConstant(EltIdx, SL, MVT::i32)); 5540 Pieces.push_back(SubVec); 5541 } else { 5542 const int Idx0 = SVN->getMaskElt(I); 5543 const int Idx1 = SVN->getMaskElt(I + 1); 5544 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5545 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5546 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5547 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5548 5549 SDValue Vec0 = SVN->getOperand(VecIdx0); 5550 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5551 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5552 5553 SDValue Vec1 = SVN->getOperand(VecIdx1); 5554 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5555 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5556 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5557 } 5558 } 5559 5560 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5561 } 5562 5563 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5564 SelectionDAG &DAG) const { 5565 SDLoc SL(Op); 5566 EVT VT = Op.getValueType(); 5567 5568 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5569 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5570 5571 // Turn into pair of packed build_vectors. 5572 // TODO: Special case for constants that can be materialized with s_mov_b64. 5573 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5574 { Op.getOperand(0), Op.getOperand(1) }); 5575 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5576 { Op.getOperand(2), Op.getOperand(3) }); 5577 5578 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5579 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5580 5581 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5582 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5583 } 5584 5585 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5586 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5587 5588 SDValue Lo = Op.getOperand(0); 5589 SDValue Hi = Op.getOperand(1); 5590 5591 // Avoid adding defined bits with the zero_extend. 5592 if (Hi.isUndef()) { 5593 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5594 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5595 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5596 } 5597 5598 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5599 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5600 5601 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5602 DAG.getConstant(16, SL, MVT::i32)); 5603 if (Lo.isUndef()) 5604 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5605 5606 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5607 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5608 5609 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5610 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5611 } 5612 5613 bool 5614 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5615 // We can fold offsets for anything that doesn't require a GOT relocation. 5616 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5617 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5618 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5619 !shouldEmitGOTReloc(GA->getGlobal()); 5620 } 5621 5622 static SDValue 5623 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5624 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5625 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5626 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5627 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5628 // lowered to the following code sequence: 5629 // 5630 // For constant address space: 5631 // s_getpc_b64 s[0:1] 5632 // s_add_u32 s0, s0, $symbol 5633 // s_addc_u32 s1, s1, 0 5634 // 5635 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5636 // a fixup or relocation is emitted to replace $symbol with a literal 5637 // constant, which is a pc-relative offset from the encoding of the $symbol 5638 // operand to the global variable. 5639 // 5640 // For global address space: 5641 // s_getpc_b64 s[0:1] 5642 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5643 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5644 // 5645 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5646 // fixups or relocations are emitted to replace $symbol@*@lo and 5647 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5648 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5649 // operand to the global variable. 5650 // 5651 // What we want here is an offset from the value returned by s_getpc 5652 // (which is the address of the s_add_u32 instruction) to the global 5653 // variable, but since the encoding of $symbol starts 4 bytes after the start 5654 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5655 // small. This requires us to add 4 to the global variable offset in order to 5656 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5657 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5658 // instruction. 5659 SDValue PtrLo = 5660 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5661 SDValue PtrHi; 5662 if (GAFlags == SIInstrInfo::MO_NONE) { 5663 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5664 } else { 5665 PtrHi = 5666 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5667 } 5668 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5669 } 5670 5671 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5672 SDValue Op, 5673 SelectionDAG &DAG) const { 5674 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5675 SDLoc DL(GSD); 5676 EVT PtrVT = Op.getValueType(); 5677 5678 const GlobalValue *GV = GSD->getGlobal(); 5679 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5680 shouldUseLDSConstAddress(GV)) || 5681 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5682 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5683 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5684 GV->hasExternalLinkage()) { 5685 Type *Ty = GV->getValueType(); 5686 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5687 // zero-sized type in other languages to declare the dynamic shared 5688 // memory which size is not known at the compile time. They will be 5689 // allocated by the runtime and placed directly after the static 5690 // allocated ones. They all share the same offset. 5691 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5692 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5693 // Adjust alignment for that dynamic shared memory array. 5694 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5695 return SDValue( 5696 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5697 } 5698 } 5699 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5700 } 5701 5702 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5703 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5704 SIInstrInfo::MO_ABS32_LO); 5705 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5706 } 5707 5708 if (shouldEmitFixup(GV)) 5709 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5710 else if (shouldEmitPCReloc(GV)) 5711 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5712 SIInstrInfo::MO_REL32); 5713 5714 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5715 SIInstrInfo::MO_GOTPCREL32); 5716 5717 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5718 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5719 const DataLayout &DataLayout = DAG.getDataLayout(); 5720 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5721 MachinePointerInfo PtrInfo 5722 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5723 5724 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5725 MachineMemOperand::MODereferenceable | 5726 MachineMemOperand::MOInvariant); 5727 } 5728 5729 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5730 const SDLoc &DL, SDValue V) const { 5731 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5732 // the destination register. 5733 // 5734 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5735 // so we will end up with redundant moves to m0. 5736 // 5737 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5738 5739 // A Null SDValue creates a glue result. 5740 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5741 V, Chain); 5742 return SDValue(M0, 0); 5743 } 5744 5745 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5746 SDValue Op, 5747 MVT VT, 5748 unsigned Offset) const { 5749 SDLoc SL(Op); 5750 SDValue Param = lowerKernargMemParameter( 5751 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5752 // The local size values will have the hi 16-bits as zero. 5753 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5754 DAG.getValueType(VT)); 5755 } 5756 5757 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5758 EVT VT) { 5759 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5760 "non-hsa intrinsic with hsa target", 5761 DL.getDebugLoc()); 5762 DAG.getContext()->diagnose(BadIntrin); 5763 return DAG.getUNDEF(VT); 5764 } 5765 5766 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5767 EVT VT) { 5768 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5769 "intrinsic not supported on subtarget", 5770 DL.getDebugLoc()); 5771 DAG.getContext()->diagnose(BadIntrin); 5772 return DAG.getUNDEF(VT); 5773 } 5774 5775 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5776 ArrayRef<SDValue> Elts) { 5777 assert(!Elts.empty()); 5778 MVT Type; 5779 unsigned NumElts; 5780 5781 if (Elts.size() == 1) { 5782 Type = MVT::f32; 5783 NumElts = 1; 5784 } else if (Elts.size() == 2) { 5785 Type = MVT::v2f32; 5786 NumElts = 2; 5787 } else if (Elts.size() == 3) { 5788 Type = MVT::v3f32; 5789 NumElts = 3; 5790 } else if (Elts.size() <= 4) { 5791 Type = MVT::v4f32; 5792 NumElts = 4; 5793 } else if (Elts.size() <= 8) { 5794 Type = MVT::v8f32; 5795 NumElts = 8; 5796 } else { 5797 assert(Elts.size() <= 16); 5798 Type = MVT::v16f32; 5799 NumElts = 16; 5800 } 5801 5802 SmallVector<SDValue, 16> VecElts(NumElts); 5803 for (unsigned i = 0; i < Elts.size(); ++i) { 5804 SDValue Elt = Elts[i]; 5805 if (Elt.getValueType() != MVT::f32) 5806 Elt = DAG.getBitcast(MVT::f32, Elt); 5807 VecElts[i] = Elt; 5808 } 5809 for (unsigned i = Elts.size(); i < NumElts; ++i) 5810 VecElts[i] = DAG.getUNDEF(MVT::f32); 5811 5812 if (NumElts == 1) 5813 return VecElts[0]; 5814 return DAG.getBuildVector(Type, DL, VecElts); 5815 } 5816 5817 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5818 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5819 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5820 5821 uint64_t Value = CachePolicyConst->getZExtValue(); 5822 SDLoc DL(CachePolicy); 5823 if (GLC) { 5824 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5825 Value &= ~(uint64_t)0x1; 5826 } 5827 if (SLC) { 5828 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5829 Value &= ~(uint64_t)0x2; 5830 } 5831 if (DLC) { 5832 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5833 Value &= ~(uint64_t)0x4; 5834 } 5835 5836 return Value == 0; 5837 } 5838 5839 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5840 SDValue Src, int ExtraElts) { 5841 EVT SrcVT = Src.getValueType(); 5842 5843 SmallVector<SDValue, 8> Elts; 5844 5845 if (SrcVT.isVector()) 5846 DAG.ExtractVectorElements(Src, Elts); 5847 else 5848 Elts.push_back(Src); 5849 5850 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5851 while (ExtraElts--) 5852 Elts.push_back(Undef); 5853 5854 return DAG.getBuildVector(CastVT, DL, Elts); 5855 } 5856 5857 // Re-construct the required return value for a image load intrinsic. 5858 // This is more complicated due to the optional use TexFailCtrl which means the required 5859 // return type is an aggregate 5860 static SDValue constructRetValue(SelectionDAG &DAG, 5861 MachineSDNode *Result, 5862 ArrayRef<EVT> ResultTypes, 5863 bool IsTexFail, bool Unpacked, bool IsD16, 5864 int DMaskPop, int NumVDataDwords, 5865 const SDLoc &DL, LLVMContext &Context) { 5866 // Determine the required return type. This is the same regardless of IsTexFail flag 5867 EVT ReqRetVT = ResultTypes[0]; 5868 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5869 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5870 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5871 5872 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5873 DMaskPop : (DMaskPop + 1) / 2; 5874 5875 MVT DataDwordVT = NumDataDwords == 1 ? 5876 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5877 5878 MVT MaskPopVT = MaskPopDwords == 1 ? 5879 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5880 5881 SDValue Data(Result, 0); 5882 SDValue TexFail; 5883 5884 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5885 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5886 if (MaskPopVT.isVector()) { 5887 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5888 SDValue(Result, 0), ZeroIdx); 5889 } else { 5890 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5891 SDValue(Result, 0), ZeroIdx); 5892 } 5893 } 5894 5895 if (DataDwordVT.isVector()) 5896 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5897 NumDataDwords - MaskPopDwords); 5898 5899 if (IsD16) 5900 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5901 5902 EVT LegalReqRetVT = ReqRetVT; 5903 if (!ReqRetVT.isVector()) { 5904 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5905 } else { 5906 // We need to widen the return vector to a legal type 5907 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5908 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5909 LegalReqRetVT = 5910 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5911 ReqRetVT.getVectorNumElements() + 1); 5912 } 5913 } 5914 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5915 5916 if (IsTexFail) { 5917 TexFail = 5918 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5919 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5920 5921 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5922 } 5923 5924 if (Result->getNumValues() == 1) 5925 return Data; 5926 5927 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5928 } 5929 5930 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5931 SDValue *LWE, bool &IsTexFail) { 5932 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5933 5934 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5935 if (Value) { 5936 IsTexFail = true; 5937 } 5938 5939 SDLoc DL(TexFailCtrlConst); 5940 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5941 Value &= ~(uint64_t)0x1; 5942 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5943 Value &= ~(uint64_t)0x2; 5944 5945 return Value == 0; 5946 } 5947 5948 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5949 MVT PackVectorVT, 5950 SmallVectorImpl<SDValue> &PackedAddrs, 5951 unsigned DimIdx, unsigned EndIdx, 5952 unsigned NumGradients) { 5953 SDLoc DL(Op); 5954 for (unsigned I = DimIdx; I < EndIdx; I++) { 5955 SDValue Addr = Op.getOperand(I); 5956 5957 // Gradients are packed with undef for each coordinate. 5958 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5959 // 1D: undef,dx/dh; undef,dx/dv 5960 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5961 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5962 if (((I + 1) >= EndIdx) || 5963 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5964 I == DimIdx + NumGradients - 1))) { 5965 if (Addr.getValueType() != MVT::i16) 5966 Addr = DAG.getBitcast(MVT::i16, Addr); 5967 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5968 } else { 5969 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5970 I++; 5971 } 5972 Addr = DAG.getBitcast(MVT::f32, Addr); 5973 PackedAddrs.push_back(Addr); 5974 } 5975 } 5976 5977 SDValue SITargetLowering::lowerImage(SDValue Op, 5978 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5979 SelectionDAG &DAG, bool WithChain) const { 5980 SDLoc DL(Op); 5981 MachineFunction &MF = DAG.getMachineFunction(); 5982 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5983 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5984 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5985 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5986 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5987 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5988 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5989 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5990 unsigned IntrOpcode = Intr->BaseOpcode; 5991 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5992 5993 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5994 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5995 bool IsD16 = false; 5996 bool IsG16 = false; 5997 bool IsA16 = false; 5998 SDValue VData; 5999 int NumVDataDwords; 6000 bool AdjustRetType = false; 6001 6002 // Offset of intrinsic arguments 6003 const unsigned ArgOffset = WithChain ? 2 : 1; 6004 6005 unsigned DMask; 6006 unsigned DMaskLanes = 0; 6007 6008 if (BaseOpcode->Atomic) { 6009 VData = Op.getOperand(2); 6010 6011 bool Is64Bit = VData.getValueType() == MVT::i64; 6012 if (BaseOpcode->AtomicX2) { 6013 SDValue VData2 = Op.getOperand(3); 6014 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6015 {VData, VData2}); 6016 if (Is64Bit) 6017 VData = DAG.getBitcast(MVT::v4i32, VData); 6018 6019 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6020 DMask = Is64Bit ? 0xf : 0x3; 6021 NumVDataDwords = Is64Bit ? 4 : 2; 6022 } else { 6023 DMask = Is64Bit ? 0x3 : 0x1; 6024 NumVDataDwords = Is64Bit ? 2 : 1; 6025 } 6026 } else { 6027 auto *DMaskConst = 6028 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6029 DMask = DMaskConst->getZExtValue(); 6030 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6031 6032 if (BaseOpcode->Store) { 6033 VData = Op.getOperand(2); 6034 6035 MVT StoreVT = VData.getSimpleValueType(); 6036 if (StoreVT.getScalarType() == MVT::f16) { 6037 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6038 return Op; // D16 is unsupported for this instruction 6039 6040 IsD16 = true; 6041 VData = handleD16VData(VData, DAG, true); 6042 } 6043 6044 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6045 } else { 6046 // Work out the num dwords based on the dmask popcount and underlying type 6047 // and whether packing is supported. 6048 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6049 if (LoadVT.getScalarType() == MVT::f16) { 6050 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6051 return Op; // D16 is unsupported for this instruction 6052 6053 IsD16 = true; 6054 } 6055 6056 // Confirm that the return type is large enough for the dmask specified 6057 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6058 (!LoadVT.isVector() && DMaskLanes > 1)) 6059 return Op; 6060 6061 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6062 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6063 // instructions. 6064 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6065 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6066 NumVDataDwords = (DMaskLanes + 1) / 2; 6067 else 6068 NumVDataDwords = DMaskLanes; 6069 6070 AdjustRetType = true; 6071 } 6072 } 6073 6074 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6075 SmallVector<SDValue, 4> VAddrs; 6076 6077 // Optimize _L to _LZ when _L is zero 6078 if (LZMappingInfo) { 6079 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6080 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6081 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6082 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6083 VAddrEnd--; // remove 'lod' 6084 } 6085 } 6086 } 6087 6088 // Optimize _mip away, when 'lod' is zero 6089 if (MIPMappingInfo) { 6090 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6091 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6092 if (ConstantLod->isNullValue()) { 6093 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6094 VAddrEnd--; // remove 'mip' 6095 } 6096 } 6097 } 6098 6099 // Push back extra arguments. 6100 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6101 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6102 6103 // Check for 16 bit addresses or derivatives and pack if true. 6104 MVT VAddrVT = 6105 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6106 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6107 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6108 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6109 6110 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6111 VAddrScalarVT = VAddrVT.getScalarType(); 6112 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6113 if (IsA16 || IsG16) { 6114 if (IsA16) { 6115 if (!ST->hasA16()) { 6116 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6117 "support 16 bit addresses\n"); 6118 return Op; 6119 } 6120 if (!IsG16) { 6121 LLVM_DEBUG( 6122 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6123 "need 16 bit derivatives but got 32 bit derivatives\n"); 6124 return Op; 6125 } 6126 } else if (!ST->hasG16()) { 6127 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6128 "support 16 bit derivatives\n"); 6129 return Op; 6130 } 6131 6132 if (BaseOpcode->Gradients && !IsA16) { 6133 if (!ST->hasG16()) { 6134 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6135 "support 16 bit derivatives\n"); 6136 return Op; 6137 } 6138 // Activate g16 6139 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6140 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6141 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6142 } 6143 6144 // Don't compress addresses for G16 6145 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6146 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6147 ArgOffset + Intr->GradientStart, PackEndIdx, 6148 Intr->NumGradients); 6149 6150 if (!IsA16) { 6151 // Add uncompressed address 6152 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6153 VAddrs.push_back(Op.getOperand(I)); 6154 } 6155 } else { 6156 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6157 VAddrs.push_back(Op.getOperand(I)); 6158 } 6159 6160 // If the register allocator cannot place the address registers contiguously 6161 // without introducing moves, then using the non-sequential address encoding 6162 // is always preferable, since it saves VALU instructions and is usually a 6163 // wash in terms of code size or even better. 6164 // 6165 // However, we currently have no way of hinting to the register allocator that 6166 // MIMG addresses should be placed contiguously when it is possible to do so, 6167 // so force non-NSA for the common 2-address case as a heuristic. 6168 // 6169 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6170 // allocation when possible. 6171 bool UseNSA = 6172 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6173 SDValue VAddr; 6174 if (!UseNSA) 6175 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6176 6177 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6178 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6179 SDValue Unorm; 6180 if (!BaseOpcode->Sampler) { 6181 Unorm = True; 6182 } else { 6183 auto UnormConst = 6184 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6185 6186 Unorm = UnormConst->getZExtValue() ? True : False; 6187 } 6188 6189 SDValue TFE; 6190 SDValue LWE; 6191 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6192 bool IsTexFail = false; 6193 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6194 return Op; 6195 6196 if (IsTexFail) { 6197 if (!DMaskLanes) { 6198 // Expecting to get an error flag since TFC is on - and dmask is 0 6199 // Force dmask to be at least 1 otherwise the instruction will fail 6200 DMask = 0x1; 6201 DMaskLanes = 1; 6202 NumVDataDwords = 1; 6203 } 6204 NumVDataDwords += 1; 6205 AdjustRetType = true; 6206 } 6207 6208 // Has something earlier tagged that the return type needs adjusting 6209 // This happens if the instruction is a load or has set TexFailCtrl flags 6210 if (AdjustRetType) { 6211 // NumVDataDwords reflects the true number of dwords required in the return type 6212 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6213 // This is a no-op load. This can be eliminated 6214 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6215 if (isa<MemSDNode>(Op)) 6216 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6217 return Undef; 6218 } 6219 6220 EVT NewVT = NumVDataDwords > 1 ? 6221 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6222 : MVT::i32; 6223 6224 ResultTypes[0] = NewVT; 6225 if (ResultTypes.size() == 3) { 6226 // Original result was aggregate type used for TexFailCtrl results 6227 // The actual instruction returns as a vector type which has now been 6228 // created. Remove the aggregate result. 6229 ResultTypes.erase(&ResultTypes[1]); 6230 } 6231 } 6232 6233 SDValue GLC; 6234 SDValue SLC; 6235 SDValue DLC; 6236 if (BaseOpcode->Atomic) { 6237 GLC = True; // TODO no-return optimization 6238 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6239 DAG, nullptr, &SLC, IsGFX10 ? &DLC : nullptr)) 6240 return Op; 6241 } else { 6242 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6243 DAG, &GLC, &SLC, IsGFX10 ? &DLC : nullptr)) 6244 return Op; 6245 } 6246 6247 SmallVector<SDValue, 26> Ops; 6248 if (BaseOpcode->Store || BaseOpcode->Atomic) 6249 Ops.push_back(VData); // vdata 6250 if (UseNSA) { 6251 for (const SDValue &Addr : VAddrs) 6252 Ops.push_back(Addr); 6253 } else { 6254 Ops.push_back(VAddr); 6255 } 6256 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6257 if (BaseOpcode->Sampler) 6258 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6259 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6260 if (IsGFX10) 6261 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6262 Ops.push_back(Unorm); 6263 if (IsGFX10) 6264 Ops.push_back(DLC); 6265 Ops.push_back(GLC); 6266 Ops.push_back(SLC); 6267 Ops.push_back(IsA16 && // r128, a16 for gfx9 6268 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6269 if (IsGFX10) 6270 Ops.push_back(IsA16 ? True : False); 6271 Ops.push_back(TFE); 6272 Ops.push_back(LWE); 6273 if (!IsGFX10) 6274 Ops.push_back(DimInfo->DA ? True : False); 6275 if (BaseOpcode->HasD16) 6276 Ops.push_back(IsD16 ? True : False); 6277 if (isa<MemSDNode>(Op)) 6278 Ops.push_back(Op.getOperand(0)); // chain 6279 6280 int NumVAddrDwords = 6281 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6282 int Opcode = -1; 6283 6284 if (IsGFX10) { 6285 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6286 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6287 : AMDGPU::MIMGEncGfx10Default, 6288 NumVDataDwords, NumVAddrDwords); 6289 } else { 6290 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6291 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6292 NumVDataDwords, NumVAddrDwords); 6293 if (Opcode == -1) 6294 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6295 NumVDataDwords, NumVAddrDwords); 6296 } 6297 assert(Opcode != -1); 6298 6299 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6300 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6301 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6302 DAG.setNodeMemRefs(NewNode, {MemRef}); 6303 } 6304 6305 if (BaseOpcode->AtomicX2) { 6306 SmallVector<SDValue, 1> Elt; 6307 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6308 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6309 } else if (!BaseOpcode->Store) { 6310 return constructRetValue(DAG, NewNode, 6311 OrigResultTypes, IsTexFail, 6312 Subtarget->hasUnpackedD16VMem(), IsD16, 6313 DMaskLanes, NumVDataDwords, DL, 6314 *DAG.getContext()); 6315 } 6316 6317 return SDValue(NewNode, 0); 6318 } 6319 6320 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6321 SDValue Offset, SDValue CachePolicy, 6322 SelectionDAG &DAG) const { 6323 MachineFunction &MF = DAG.getMachineFunction(); 6324 6325 const DataLayout &DataLayout = DAG.getDataLayout(); 6326 Align Alignment = 6327 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6328 6329 MachineMemOperand *MMO = MF.getMachineMemOperand( 6330 MachinePointerInfo(), 6331 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6332 MachineMemOperand::MOInvariant, 6333 VT.getStoreSize(), Alignment); 6334 6335 if (!Offset->isDivergent()) { 6336 SDValue Ops[] = { 6337 Rsrc, 6338 Offset, // Offset 6339 CachePolicy 6340 }; 6341 6342 // Widen vec3 load to vec4. 6343 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6344 EVT WidenedVT = 6345 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6346 auto WidenedOp = DAG.getMemIntrinsicNode( 6347 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6348 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6349 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6350 DAG.getVectorIdxConstant(0, DL)); 6351 return Subvector; 6352 } 6353 6354 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6355 DAG.getVTList(VT), Ops, VT, MMO); 6356 } 6357 6358 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6359 // assume that the buffer is unswizzled. 6360 SmallVector<SDValue, 4> Loads; 6361 unsigned NumLoads = 1; 6362 MVT LoadVT = VT.getSimpleVT(); 6363 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6364 assert((LoadVT.getScalarType() == MVT::i32 || 6365 LoadVT.getScalarType() == MVT::f32)); 6366 6367 if (NumElts == 8 || NumElts == 16) { 6368 NumLoads = NumElts / 4; 6369 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6370 } 6371 6372 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6373 SDValue Ops[] = { 6374 DAG.getEntryNode(), // Chain 6375 Rsrc, // rsrc 6376 DAG.getConstant(0, DL, MVT::i32), // vindex 6377 {}, // voffset 6378 {}, // soffset 6379 {}, // offset 6380 CachePolicy, // cachepolicy 6381 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6382 }; 6383 6384 // Use the alignment to ensure that the required offsets will fit into the 6385 // immediate offsets. 6386 setBufferOffsets(Offset, DAG, &Ops[3], 6387 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6388 6389 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6390 for (unsigned i = 0; i < NumLoads; ++i) { 6391 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6392 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6393 LoadVT, MMO, DAG)); 6394 } 6395 6396 if (NumElts == 8 || NumElts == 16) 6397 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6398 6399 return Loads[0]; 6400 } 6401 6402 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6403 SelectionDAG &DAG) const { 6404 MachineFunction &MF = DAG.getMachineFunction(); 6405 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6406 6407 EVT VT = Op.getValueType(); 6408 SDLoc DL(Op); 6409 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6410 6411 // TODO: Should this propagate fast-math-flags? 6412 6413 switch (IntrinsicID) { 6414 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6415 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6416 return emitNonHSAIntrinsicError(DAG, DL, VT); 6417 return getPreloadedValue(DAG, *MFI, VT, 6418 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6419 } 6420 case Intrinsic::amdgcn_dispatch_ptr: 6421 case Intrinsic::amdgcn_queue_ptr: { 6422 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6423 DiagnosticInfoUnsupported BadIntrin( 6424 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6425 DL.getDebugLoc()); 6426 DAG.getContext()->diagnose(BadIntrin); 6427 return DAG.getUNDEF(VT); 6428 } 6429 6430 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6431 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6432 return getPreloadedValue(DAG, *MFI, VT, RegID); 6433 } 6434 case Intrinsic::amdgcn_implicitarg_ptr: { 6435 if (MFI->isEntryFunction()) 6436 return getImplicitArgPtr(DAG, DL); 6437 return getPreloadedValue(DAG, *MFI, VT, 6438 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6439 } 6440 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6441 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6442 // This only makes sense to call in a kernel, so just lower to null. 6443 return DAG.getConstant(0, DL, VT); 6444 } 6445 6446 return getPreloadedValue(DAG, *MFI, VT, 6447 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6448 } 6449 case Intrinsic::amdgcn_dispatch_id: { 6450 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6451 } 6452 case Intrinsic::amdgcn_rcp: 6453 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6454 case Intrinsic::amdgcn_rsq: 6455 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6456 case Intrinsic::amdgcn_rsq_legacy: 6457 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6458 return emitRemovedIntrinsicError(DAG, DL, VT); 6459 return SDValue(); 6460 case Intrinsic::amdgcn_rcp_legacy: 6461 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6462 return emitRemovedIntrinsicError(DAG, DL, VT); 6463 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6464 case Intrinsic::amdgcn_rsq_clamp: { 6465 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6466 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6467 6468 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6469 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6470 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6471 6472 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6473 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6474 DAG.getConstantFP(Max, DL, VT)); 6475 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6476 DAG.getConstantFP(Min, DL, VT)); 6477 } 6478 case Intrinsic::r600_read_ngroups_x: 6479 if (Subtarget->isAmdHsaOS()) 6480 return emitNonHSAIntrinsicError(DAG, DL, VT); 6481 6482 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6483 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6484 false); 6485 case Intrinsic::r600_read_ngroups_y: 6486 if (Subtarget->isAmdHsaOS()) 6487 return emitNonHSAIntrinsicError(DAG, DL, VT); 6488 6489 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6490 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6491 false); 6492 case Intrinsic::r600_read_ngroups_z: 6493 if (Subtarget->isAmdHsaOS()) 6494 return emitNonHSAIntrinsicError(DAG, DL, VT); 6495 6496 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6497 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6498 false); 6499 case Intrinsic::r600_read_global_size_x: 6500 if (Subtarget->isAmdHsaOS()) 6501 return emitNonHSAIntrinsicError(DAG, DL, VT); 6502 6503 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6504 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6505 Align(4), false); 6506 case Intrinsic::r600_read_global_size_y: 6507 if (Subtarget->isAmdHsaOS()) 6508 return emitNonHSAIntrinsicError(DAG, DL, VT); 6509 6510 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6511 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6512 Align(4), false); 6513 case Intrinsic::r600_read_global_size_z: 6514 if (Subtarget->isAmdHsaOS()) 6515 return emitNonHSAIntrinsicError(DAG, DL, VT); 6516 6517 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6518 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6519 Align(4), false); 6520 case Intrinsic::r600_read_local_size_x: 6521 if (Subtarget->isAmdHsaOS()) 6522 return emitNonHSAIntrinsicError(DAG, DL, VT); 6523 6524 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6525 SI::KernelInputOffsets::LOCAL_SIZE_X); 6526 case Intrinsic::r600_read_local_size_y: 6527 if (Subtarget->isAmdHsaOS()) 6528 return emitNonHSAIntrinsicError(DAG, DL, VT); 6529 6530 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6531 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6532 case Intrinsic::r600_read_local_size_z: 6533 if (Subtarget->isAmdHsaOS()) 6534 return emitNonHSAIntrinsicError(DAG, DL, VT); 6535 6536 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6537 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6538 case Intrinsic::amdgcn_workgroup_id_x: 6539 return getPreloadedValue(DAG, *MFI, VT, 6540 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6541 case Intrinsic::amdgcn_workgroup_id_y: 6542 return getPreloadedValue(DAG, *MFI, VT, 6543 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6544 case Intrinsic::amdgcn_workgroup_id_z: 6545 return getPreloadedValue(DAG, *MFI, VT, 6546 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6547 case Intrinsic::amdgcn_workitem_id_x: 6548 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6549 SDLoc(DAG.getEntryNode()), 6550 MFI->getArgInfo().WorkItemIDX); 6551 case Intrinsic::amdgcn_workitem_id_y: 6552 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6553 SDLoc(DAG.getEntryNode()), 6554 MFI->getArgInfo().WorkItemIDY); 6555 case Intrinsic::amdgcn_workitem_id_z: 6556 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6557 SDLoc(DAG.getEntryNode()), 6558 MFI->getArgInfo().WorkItemIDZ); 6559 case Intrinsic::amdgcn_wavefrontsize: 6560 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6561 SDLoc(Op), MVT::i32); 6562 case Intrinsic::amdgcn_s_buffer_load: { 6563 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6564 SDValue GLC; 6565 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6566 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6567 IsGFX10 ? &DLC : nullptr)) 6568 return Op; 6569 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6570 DAG); 6571 } 6572 case Intrinsic::amdgcn_fdiv_fast: 6573 return lowerFDIV_FAST(Op, DAG); 6574 case Intrinsic::amdgcn_sin: 6575 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6576 6577 case Intrinsic::amdgcn_cos: 6578 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6579 6580 case Intrinsic::amdgcn_mul_u24: 6581 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6582 case Intrinsic::amdgcn_mul_i24: 6583 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6584 6585 case Intrinsic::amdgcn_log_clamp: { 6586 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6587 return SDValue(); 6588 6589 DiagnosticInfoUnsupported BadIntrin( 6590 MF.getFunction(), "intrinsic not supported on subtarget", 6591 DL.getDebugLoc()); 6592 DAG.getContext()->diagnose(BadIntrin); 6593 return DAG.getUNDEF(VT); 6594 } 6595 case Intrinsic::amdgcn_ldexp: 6596 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6597 Op.getOperand(1), Op.getOperand(2)); 6598 6599 case Intrinsic::amdgcn_fract: 6600 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6601 6602 case Intrinsic::amdgcn_class: 6603 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6604 Op.getOperand(1), Op.getOperand(2)); 6605 case Intrinsic::amdgcn_div_fmas: 6606 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6607 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6608 Op.getOperand(4)); 6609 6610 case Intrinsic::amdgcn_div_fixup: 6611 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6612 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6613 6614 case Intrinsic::amdgcn_div_scale: { 6615 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6616 6617 // Translate to the operands expected by the machine instruction. The 6618 // first parameter must be the same as the first instruction. 6619 SDValue Numerator = Op.getOperand(1); 6620 SDValue Denominator = Op.getOperand(2); 6621 6622 // Note this order is opposite of the machine instruction's operations, 6623 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6624 // intrinsic has the numerator as the first operand to match a normal 6625 // division operation. 6626 6627 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6628 6629 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6630 Denominator, Numerator); 6631 } 6632 case Intrinsic::amdgcn_icmp: { 6633 // There is a Pat that handles this variant, so return it as-is. 6634 if (Op.getOperand(1).getValueType() == MVT::i1 && 6635 Op.getConstantOperandVal(2) == 0 && 6636 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6637 return Op; 6638 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6639 } 6640 case Intrinsic::amdgcn_fcmp: { 6641 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6642 } 6643 case Intrinsic::amdgcn_ballot: 6644 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6645 case Intrinsic::amdgcn_fmed3: 6646 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6647 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6648 case Intrinsic::amdgcn_fdot2: 6649 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6650 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6651 Op.getOperand(4)); 6652 case Intrinsic::amdgcn_fmul_legacy: 6653 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6654 Op.getOperand(1), Op.getOperand(2)); 6655 case Intrinsic::amdgcn_sffbh: 6656 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6657 case Intrinsic::amdgcn_sbfe: 6658 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6659 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6660 case Intrinsic::amdgcn_ubfe: 6661 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6662 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6663 case Intrinsic::amdgcn_cvt_pkrtz: 6664 case Intrinsic::amdgcn_cvt_pknorm_i16: 6665 case Intrinsic::amdgcn_cvt_pknorm_u16: 6666 case Intrinsic::amdgcn_cvt_pk_i16: 6667 case Intrinsic::amdgcn_cvt_pk_u16: { 6668 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6669 EVT VT = Op.getValueType(); 6670 unsigned Opcode; 6671 6672 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6673 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6674 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6675 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6676 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6677 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6678 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6679 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6680 else 6681 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6682 6683 if (isTypeLegal(VT)) 6684 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6685 6686 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6687 Op.getOperand(1), Op.getOperand(2)); 6688 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6689 } 6690 case Intrinsic::amdgcn_fmad_ftz: 6691 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6692 Op.getOperand(2), Op.getOperand(3)); 6693 6694 case Intrinsic::amdgcn_if_break: 6695 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6696 Op->getOperand(1), Op->getOperand(2)), 0); 6697 6698 case Intrinsic::amdgcn_groupstaticsize: { 6699 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6700 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6701 return Op; 6702 6703 const Module *M = MF.getFunction().getParent(); 6704 const GlobalValue *GV = 6705 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6706 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6707 SIInstrInfo::MO_ABS32_LO); 6708 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6709 } 6710 case Intrinsic::amdgcn_is_shared: 6711 case Intrinsic::amdgcn_is_private: { 6712 SDLoc SL(Op); 6713 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6714 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6715 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6716 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6717 Op.getOperand(1)); 6718 6719 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6720 DAG.getConstant(1, SL, MVT::i32)); 6721 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6722 } 6723 case Intrinsic::amdgcn_alignbit: 6724 return DAG.getNode(ISD::FSHR, DL, VT, 6725 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6726 case Intrinsic::amdgcn_reloc_constant: { 6727 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6728 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6729 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6730 auto RelocSymbol = cast<GlobalVariable>( 6731 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6732 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6733 SIInstrInfo::MO_ABS32_LO); 6734 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6735 } 6736 default: 6737 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6738 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6739 return lowerImage(Op, ImageDimIntr, DAG, false); 6740 6741 return Op; 6742 } 6743 } 6744 6745 // This function computes an appropriate offset to pass to 6746 // MachineMemOperand::setOffset() based on the offset inputs to 6747 // an intrinsic. If any of the offsets are non-contstant or 6748 // if VIndex is non-zero then this function returns 0. Otherwise, 6749 // it returns the sum of VOffset, SOffset, and Offset. 6750 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6751 SDValue SOffset, 6752 SDValue Offset, 6753 SDValue VIndex = SDValue()) { 6754 6755 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6756 !isa<ConstantSDNode>(Offset)) 6757 return 0; 6758 6759 if (VIndex) { 6760 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6761 return 0; 6762 } 6763 6764 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6765 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6766 cast<ConstantSDNode>(Offset)->getSExtValue(); 6767 } 6768 6769 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6770 SelectionDAG &DAG, 6771 unsigned NewOpcode) const { 6772 SDLoc DL(Op); 6773 6774 SDValue VData = Op.getOperand(2); 6775 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6776 SDValue Ops[] = { 6777 Op.getOperand(0), // Chain 6778 VData, // vdata 6779 Op.getOperand(3), // rsrc 6780 DAG.getConstant(0, DL, MVT::i32), // vindex 6781 Offsets.first, // voffset 6782 Op.getOperand(5), // soffset 6783 Offsets.second, // offset 6784 Op.getOperand(6), // cachepolicy 6785 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6786 }; 6787 6788 auto *M = cast<MemSDNode>(Op); 6789 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6790 6791 EVT MemVT = VData.getValueType(); 6792 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6793 M->getMemOperand()); 6794 } 6795 6796 SDValue 6797 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6798 unsigned NewOpcode) const { 6799 SDLoc DL(Op); 6800 6801 SDValue VData = Op.getOperand(2); 6802 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6803 SDValue Ops[] = { 6804 Op.getOperand(0), // Chain 6805 VData, // vdata 6806 Op.getOperand(3), // rsrc 6807 Op.getOperand(4), // vindex 6808 Offsets.first, // voffset 6809 Op.getOperand(6), // soffset 6810 Offsets.second, // offset 6811 Op.getOperand(7), // cachepolicy 6812 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6813 }; 6814 6815 auto *M = cast<MemSDNode>(Op); 6816 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6817 Ops[3])); 6818 6819 EVT MemVT = VData.getValueType(); 6820 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6821 M->getMemOperand()); 6822 } 6823 6824 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6825 SelectionDAG &DAG) const { 6826 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6827 SDLoc DL(Op); 6828 6829 switch (IntrID) { 6830 case Intrinsic::amdgcn_ds_ordered_add: 6831 case Intrinsic::amdgcn_ds_ordered_swap: { 6832 MemSDNode *M = cast<MemSDNode>(Op); 6833 SDValue Chain = M->getOperand(0); 6834 SDValue M0 = M->getOperand(2); 6835 SDValue Value = M->getOperand(3); 6836 unsigned IndexOperand = M->getConstantOperandVal(7); 6837 unsigned WaveRelease = M->getConstantOperandVal(8); 6838 unsigned WaveDone = M->getConstantOperandVal(9); 6839 6840 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6841 IndexOperand &= ~0x3f; 6842 unsigned CountDw = 0; 6843 6844 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6845 CountDw = (IndexOperand >> 24) & 0xf; 6846 IndexOperand &= ~(0xf << 24); 6847 6848 if (CountDw < 1 || CountDw > 4) { 6849 report_fatal_error( 6850 "ds_ordered_count: dword count must be between 1 and 4"); 6851 } 6852 } 6853 6854 if (IndexOperand) 6855 report_fatal_error("ds_ordered_count: bad index operand"); 6856 6857 if (WaveDone && !WaveRelease) 6858 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6859 6860 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6861 unsigned ShaderType = 6862 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6863 unsigned Offset0 = OrderedCountIndex << 2; 6864 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6865 (Instruction << 4); 6866 6867 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6868 Offset1 |= (CountDw - 1) << 6; 6869 6870 unsigned Offset = Offset0 | (Offset1 << 8); 6871 6872 SDValue Ops[] = { 6873 Chain, 6874 Value, 6875 DAG.getTargetConstant(Offset, DL, MVT::i16), 6876 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6877 }; 6878 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6879 M->getVTList(), Ops, M->getMemoryVT(), 6880 M->getMemOperand()); 6881 } 6882 case Intrinsic::amdgcn_ds_fadd: { 6883 MemSDNode *M = cast<MemSDNode>(Op); 6884 unsigned Opc; 6885 switch (IntrID) { 6886 case Intrinsic::amdgcn_ds_fadd: 6887 Opc = ISD::ATOMIC_LOAD_FADD; 6888 break; 6889 } 6890 6891 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6892 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6893 M->getMemOperand()); 6894 } 6895 case Intrinsic::amdgcn_atomic_inc: 6896 case Intrinsic::amdgcn_atomic_dec: 6897 case Intrinsic::amdgcn_ds_fmin: 6898 case Intrinsic::amdgcn_ds_fmax: { 6899 MemSDNode *M = cast<MemSDNode>(Op); 6900 unsigned Opc; 6901 switch (IntrID) { 6902 case Intrinsic::amdgcn_atomic_inc: 6903 Opc = AMDGPUISD::ATOMIC_INC; 6904 break; 6905 case Intrinsic::amdgcn_atomic_dec: 6906 Opc = AMDGPUISD::ATOMIC_DEC; 6907 break; 6908 case Intrinsic::amdgcn_ds_fmin: 6909 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6910 break; 6911 case Intrinsic::amdgcn_ds_fmax: 6912 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6913 break; 6914 default: 6915 llvm_unreachable("Unknown intrinsic!"); 6916 } 6917 SDValue Ops[] = { 6918 M->getOperand(0), // Chain 6919 M->getOperand(2), // Ptr 6920 M->getOperand(3) // Value 6921 }; 6922 6923 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6924 M->getMemoryVT(), M->getMemOperand()); 6925 } 6926 case Intrinsic::amdgcn_buffer_load: 6927 case Intrinsic::amdgcn_buffer_load_format: { 6928 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6929 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6930 unsigned IdxEn = 1; 6931 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6932 IdxEn = Idx->getZExtValue() != 0; 6933 SDValue Ops[] = { 6934 Op.getOperand(0), // Chain 6935 Op.getOperand(2), // rsrc 6936 Op.getOperand(3), // vindex 6937 SDValue(), // voffset -- will be set by setBufferOffsets 6938 SDValue(), // soffset -- will be set by setBufferOffsets 6939 SDValue(), // offset -- will be set by setBufferOffsets 6940 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6941 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6942 }; 6943 6944 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6945 // We don't know the offset if vindex is non-zero, so clear it. 6946 if (IdxEn) 6947 Offset = 0; 6948 6949 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6950 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6951 6952 EVT VT = Op.getValueType(); 6953 EVT IntVT = VT.changeTypeToInteger(); 6954 auto *M = cast<MemSDNode>(Op); 6955 M->getMemOperand()->setOffset(Offset); 6956 EVT LoadVT = Op.getValueType(); 6957 6958 if (LoadVT.getScalarType() == MVT::f16) 6959 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6960 M, DAG, Ops); 6961 6962 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6963 if (LoadVT.getScalarType() == MVT::i8 || 6964 LoadVT.getScalarType() == MVT::i16) 6965 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6966 6967 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6968 M->getMemOperand(), DAG); 6969 } 6970 case Intrinsic::amdgcn_raw_buffer_load: 6971 case Intrinsic::amdgcn_raw_buffer_load_format: { 6972 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6973 6974 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6975 SDValue Ops[] = { 6976 Op.getOperand(0), // Chain 6977 Op.getOperand(2), // rsrc 6978 DAG.getConstant(0, DL, MVT::i32), // vindex 6979 Offsets.first, // voffset 6980 Op.getOperand(4), // soffset 6981 Offsets.second, // offset 6982 Op.getOperand(5), // cachepolicy, swizzled buffer 6983 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6984 }; 6985 6986 auto *M = cast<MemSDNode>(Op); 6987 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6988 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6989 } 6990 case Intrinsic::amdgcn_struct_buffer_load: 6991 case Intrinsic::amdgcn_struct_buffer_load_format: { 6992 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6993 6994 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6995 SDValue Ops[] = { 6996 Op.getOperand(0), // Chain 6997 Op.getOperand(2), // rsrc 6998 Op.getOperand(3), // vindex 6999 Offsets.first, // voffset 7000 Op.getOperand(5), // soffset 7001 Offsets.second, // offset 7002 Op.getOperand(6), // cachepolicy, swizzled buffer 7003 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7004 }; 7005 7006 auto *M = cast<MemSDNode>(Op); 7007 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 7008 Ops[2])); 7009 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7010 } 7011 case Intrinsic::amdgcn_tbuffer_load: { 7012 MemSDNode *M = cast<MemSDNode>(Op); 7013 EVT LoadVT = Op.getValueType(); 7014 7015 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7016 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7017 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7018 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7019 unsigned IdxEn = 1; 7020 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 7021 IdxEn = Idx->getZExtValue() != 0; 7022 SDValue Ops[] = { 7023 Op.getOperand(0), // Chain 7024 Op.getOperand(2), // rsrc 7025 Op.getOperand(3), // vindex 7026 Op.getOperand(4), // voffset 7027 Op.getOperand(5), // soffset 7028 Op.getOperand(6), // offset 7029 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7030 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7031 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7032 }; 7033 7034 if (LoadVT.getScalarType() == MVT::f16) 7035 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7036 M, DAG, Ops); 7037 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7038 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7039 DAG); 7040 } 7041 case Intrinsic::amdgcn_raw_tbuffer_load: { 7042 MemSDNode *M = cast<MemSDNode>(Op); 7043 EVT LoadVT = Op.getValueType(); 7044 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7045 7046 SDValue Ops[] = { 7047 Op.getOperand(0), // Chain 7048 Op.getOperand(2), // rsrc 7049 DAG.getConstant(0, DL, MVT::i32), // vindex 7050 Offsets.first, // voffset 7051 Op.getOperand(4), // soffset 7052 Offsets.second, // offset 7053 Op.getOperand(5), // format 7054 Op.getOperand(6), // cachepolicy, swizzled buffer 7055 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7056 }; 7057 7058 if (LoadVT.getScalarType() == MVT::f16) 7059 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7060 M, DAG, Ops); 7061 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7062 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7063 DAG); 7064 } 7065 case Intrinsic::amdgcn_struct_tbuffer_load: { 7066 MemSDNode *M = cast<MemSDNode>(Op); 7067 EVT LoadVT = Op.getValueType(); 7068 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7069 7070 SDValue Ops[] = { 7071 Op.getOperand(0), // Chain 7072 Op.getOperand(2), // rsrc 7073 Op.getOperand(3), // vindex 7074 Offsets.first, // voffset 7075 Op.getOperand(5), // soffset 7076 Offsets.second, // offset 7077 Op.getOperand(6), // format 7078 Op.getOperand(7), // cachepolicy, swizzled buffer 7079 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7080 }; 7081 7082 if (LoadVT.getScalarType() == MVT::f16) 7083 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7084 M, DAG, Ops); 7085 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7086 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7087 DAG); 7088 } 7089 case Intrinsic::amdgcn_buffer_atomic_swap: 7090 case Intrinsic::amdgcn_buffer_atomic_add: 7091 case Intrinsic::amdgcn_buffer_atomic_sub: 7092 case Intrinsic::amdgcn_buffer_atomic_csub: 7093 case Intrinsic::amdgcn_buffer_atomic_smin: 7094 case Intrinsic::amdgcn_buffer_atomic_umin: 7095 case Intrinsic::amdgcn_buffer_atomic_smax: 7096 case Intrinsic::amdgcn_buffer_atomic_umax: 7097 case Intrinsic::amdgcn_buffer_atomic_and: 7098 case Intrinsic::amdgcn_buffer_atomic_or: 7099 case Intrinsic::amdgcn_buffer_atomic_xor: 7100 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7101 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7102 unsigned IdxEn = 1; 7103 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7104 IdxEn = Idx->getZExtValue() != 0; 7105 SDValue Ops[] = { 7106 Op.getOperand(0), // Chain 7107 Op.getOperand(2), // vdata 7108 Op.getOperand(3), // rsrc 7109 Op.getOperand(4), // vindex 7110 SDValue(), // voffset -- will be set by setBufferOffsets 7111 SDValue(), // soffset -- will be set by setBufferOffsets 7112 SDValue(), // offset -- will be set by setBufferOffsets 7113 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7114 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7115 }; 7116 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7117 // We don't know the offset if vindex is non-zero, so clear it. 7118 if (IdxEn) 7119 Offset = 0; 7120 EVT VT = Op.getValueType(); 7121 7122 auto *M = cast<MemSDNode>(Op); 7123 M->getMemOperand()->setOffset(Offset); 7124 unsigned Opcode = 0; 7125 7126 switch (IntrID) { 7127 case Intrinsic::amdgcn_buffer_atomic_swap: 7128 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7129 break; 7130 case Intrinsic::amdgcn_buffer_atomic_add: 7131 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7132 break; 7133 case Intrinsic::amdgcn_buffer_atomic_sub: 7134 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7135 break; 7136 case Intrinsic::amdgcn_buffer_atomic_csub: 7137 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7138 break; 7139 case Intrinsic::amdgcn_buffer_atomic_smin: 7140 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7141 break; 7142 case Intrinsic::amdgcn_buffer_atomic_umin: 7143 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7144 break; 7145 case Intrinsic::amdgcn_buffer_atomic_smax: 7146 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7147 break; 7148 case Intrinsic::amdgcn_buffer_atomic_umax: 7149 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7150 break; 7151 case Intrinsic::amdgcn_buffer_atomic_and: 7152 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7153 break; 7154 case Intrinsic::amdgcn_buffer_atomic_or: 7155 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7156 break; 7157 case Intrinsic::amdgcn_buffer_atomic_xor: 7158 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7159 break; 7160 case Intrinsic::amdgcn_buffer_atomic_fadd: 7161 if (!Op.getValue(0).use_empty()) { 7162 DiagnosticInfoUnsupported 7163 NoFpRet(DAG.getMachineFunction().getFunction(), 7164 "return versions of fp atomics not supported", 7165 DL.getDebugLoc(), DS_Error); 7166 DAG.getContext()->diagnose(NoFpRet); 7167 return SDValue(); 7168 } 7169 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7170 break; 7171 default: 7172 llvm_unreachable("unhandled atomic opcode"); 7173 } 7174 7175 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7176 M->getMemOperand()); 7177 } 7178 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7179 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7180 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7181 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7182 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7183 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7184 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7185 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7186 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7187 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7188 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7189 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7190 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7191 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7192 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7193 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7194 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7195 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7196 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7197 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7198 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7199 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7200 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7201 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7202 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7203 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7204 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7205 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7206 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7207 return lowerStructBufferAtomicIntrin(Op, DAG, 7208 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7209 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7210 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7211 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7212 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7213 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7214 return lowerStructBufferAtomicIntrin(Op, DAG, 7215 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7216 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7217 return lowerStructBufferAtomicIntrin(Op, DAG, 7218 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7219 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7220 return lowerStructBufferAtomicIntrin(Op, DAG, 7221 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7222 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7223 return lowerStructBufferAtomicIntrin(Op, DAG, 7224 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7225 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7226 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7227 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7228 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7229 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7230 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7231 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7232 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7233 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7234 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7235 7236 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7237 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7238 unsigned IdxEn = 1; 7239 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7240 IdxEn = Idx->getZExtValue() != 0; 7241 SDValue Ops[] = { 7242 Op.getOperand(0), // Chain 7243 Op.getOperand(2), // src 7244 Op.getOperand(3), // cmp 7245 Op.getOperand(4), // rsrc 7246 Op.getOperand(5), // vindex 7247 SDValue(), // voffset -- will be set by setBufferOffsets 7248 SDValue(), // soffset -- will be set by setBufferOffsets 7249 SDValue(), // offset -- will be set by setBufferOffsets 7250 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7251 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7252 }; 7253 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7254 // We don't know the offset if vindex is non-zero, so clear it. 7255 if (IdxEn) 7256 Offset = 0; 7257 EVT VT = Op.getValueType(); 7258 auto *M = cast<MemSDNode>(Op); 7259 M->getMemOperand()->setOffset(Offset); 7260 7261 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7262 Op->getVTList(), Ops, VT, M->getMemOperand()); 7263 } 7264 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7265 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7266 SDValue Ops[] = { 7267 Op.getOperand(0), // Chain 7268 Op.getOperand(2), // src 7269 Op.getOperand(3), // cmp 7270 Op.getOperand(4), // rsrc 7271 DAG.getConstant(0, DL, MVT::i32), // vindex 7272 Offsets.first, // voffset 7273 Op.getOperand(6), // soffset 7274 Offsets.second, // offset 7275 Op.getOperand(7), // cachepolicy 7276 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7277 }; 7278 EVT VT = Op.getValueType(); 7279 auto *M = cast<MemSDNode>(Op); 7280 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7281 7282 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7283 Op->getVTList(), Ops, VT, M->getMemOperand()); 7284 } 7285 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7286 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7287 SDValue Ops[] = { 7288 Op.getOperand(0), // Chain 7289 Op.getOperand(2), // src 7290 Op.getOperand(3), // cmp 7291 Op.getOperand(4), // rsrc 7292 Op.getOperand(5), // vindex 7293 Offsets.first, // voffset 7294 Op.getOperand(7), // soffset 7295 Offsets.second, // offset 7296 Op.getOperand(8), // cachepolicy 7297 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7298 }; 7299 EVT VT = Op.getValueType(); 7300 auto *M = cast<MemSDNode>(Op); 7301 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7302 Ops[4])); 7303 7304 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7305 Op->getVTList(), Ops, VT, M->getMemOperand()); 7306 } 7307 case Intrinsic::amdgcn_global_atomic_fadd: { 7308 if (!Op.getValue(0).use_empty()) { 7309 DiagnosticInfoUnsupported 7310 NoFpRet(DAG.getMachineFunction().getFunction(), 7311 "return versions of fp atomics not supported", 7312 DL.getDebugLoc(), DS_Error); 7313 DAG.getContext()->diagnose(NoFpRet); 7314 return SDValue(); 7315 } 7316 MemSDNode *M = cast<MemSDNode>(Op); 7317 SDValue Ops[] = { 7318 M->getOperand(0), // Chain 7319 M->getOperand(2), // Ptr 7320 M->getOperand(3) // Value 7321 }; 7322 7323 EVT VT = Op.getOperand(3).getValueType(); 7324 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7325 DAG.getVTList(VT, MVT::Other), Ops, 7326 M->getMemOperand()); 7327 } 7328 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7329 SDLoc DL(Op); 7330 MemSDNode *M = cast<MemSDNode>(Op); 7331 SDValue NodePtr = M->getOperand(2); 7332 SDValue RayExtent = M->getOperand(3); 7333 SDValue RayOrigin = M->getOperand(4); 7334 SDValue RayDir = M->getOperand(5); 7335 SDValue RayInvDir = M->getOperand(6); 7336 SDValue TDescr = M->getOperand(7); 7337 7338 assert(NodePtr.getValueType() == MVT::i32 || 7339 NodePtr.getValueType() == MVT::i64); 7340 assert(RayDir.getValueType() == MVT::v4f16 || 7341 RayDir.getValueType() == MVT::v4f32); 7342 7343 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7344 bool Is64 = NodePtr.getValueType() == MVT::i64; 7345 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7346 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7347 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7348 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7349 7350 SmallVector<SDValue, 16> Ops; 7351 7352 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7353 SmallVector<SDValue, 3> Lanes; 7354 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7355 if (Lanes[0].getValueSizeInBits() == 32) { 7356 for (unsigned I = 0; I < 3; ++I) 7357 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7358 } else { 7359 if (IsAligned) { 7360 Ops.push_back( 7361 DAG.getBitcast(MVT::i32, 7362 DAG.getBuildVector(MVT::v2f16, DL, 7363 { Lanes[0], Lanes[1] }))); 7364 Ops.push_back(Lanes[2]); 7365 } else { 7366 SDValue Elt0 = Ops.pop_back_val(); 7367 Ops.push_back( 7368 DAG.getBitcast(MVT::i32, 7369 DAG.getBuildVector(MVT::v2f16, DL, 7370 { Elt0, Lanes[0] }))); 7371 Ops.push_back( 7372 DAG.getBitcast(MVT::i32, 7373 DAG.getBuildVector(MVT::v2f16, DL, 7374 { Lanes[1], Lanes[2] }))); 7375 } 7376 } 7377 }; 7378 7379 if (Is64) 7380 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7381 else 7382 Ops.push_back(NodePtr); 7383 7384 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7385 packLanes(RayOrigin, true); 7386 packLanes(RayDir, true); 7387 packLanes(RayInvDir, false); 7388 Ops.push_back(TDescr); 7389 if (IsA16) 7390 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7391 Ops.push_back(M->getChain()); 7392 7393 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7394 MachineMemOperand *MemRef = M->getMemOperand(); 7395 DAG.setNodeMemRefs(NewNode, {MemRef}); 7396 return SDValue(NewNode, 0); 7397 } 7398 default: 7399 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7400 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7401 return lowerImage(Op, ImageDimIntr, DAG, true); 7402 7403 return SDValue(); 7404 } 7405 } 7406 7407 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7408 // dwordx4 if on SI. 7409 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7410 SDVTList VTList, 7411 ArrayRef<SDValue> Ops, EVT MemVT, 7412 MachineMemOperand *MMO, 7413 SelectionDAG &DAG) const { 7414 EVT VT = VTList.VTs[0]; 7415 EVT WidenedVT = VT; 7416 EVT WidenedMemVT = MemVT; 7417 if (!Subtarget->hasDwordx3LoadStores() && 7418 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7419 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7420 WidenedVT.getVectorElementType(), 4); 7421 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7422 WidenedMemVT.getVectorElementType(), 4); 7423 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7424 } 7425 7426 assert(VTList.NumVTs == 2); 7427 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7428 7429 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7430 WidenedMemVT, MMO); 7431 if (WidenedVT != VT) { 7432 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7433 DAG.getVectorIdxConstant(0, DL)); 7434 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7435 } 7436 return NewOp; 7437 } 7438 7439 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7440 bool ImageStore) const { 7441 EVT StoreVT = VData.getValueType(); 7442 7443 // No change for f16 and legal vector D16 types. 7444 if (!StoreVT.isVector()) 7445 return VData; 7446 7447 SDLoc DL(VData); 7448 unsigned NumElements = StoreVT.getVectorNumElements(); 7449 7450 if (Subtarget->hasUnpackedD16VMem()) { 7451 // We need to unpack the packed data to store. 7452 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7453 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7454 7455 EVT EquivStoreVT = 7456 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7457 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7458 return DAG.UnrollVectorOp(ZExt.getNode()); 7459 } else if (NumElements == 3) { 7460 EVT IntStoreVT = 7461 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7462 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7463 7464 EVT WidenedStoreVT = EVT::getVectorVT( 7465 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7466 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7467 WidenedStoreVT.getStoreSizeInBits()); 7468 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7469 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7470 } 7471 7472 // The sq block of gfx8.1 does not estimate register use correctly for d16 7473 // image store instructions. The data operand is computed as if it were not a 7474 // d16 image instruction. 7475 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7476 // Bitcast to i16 7477 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7478 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7479 7480 // Decompose into scalars 7481 SmallVector<SDValue, 4> Elts; 7482 DAG.ExtractVectorElements(IntVData, Elts); 7483 7484 // Group pairs of i16 into v2i16 and bitcast to i32 7485 SmallVector<SDValue, 4> PackedElts; 7486 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7487 SDValue Pair = 7488 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7489 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7490 PackedElts.push_back(IntPair); 7491 } 7492 7493 // Pad using UNDEF 7494 PackedElts.resize(PackedElts.size() * 2, DAG.getUNDEF(MVT::i32)); 7495 7496 // Build final vector 7497 EVT VecVT = 7498 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7499 return DAG.getBuildVector(VecVT, DL, PackedElts); 7500 } 7501 7502 assert(isTypeLegal(StoreVT)); 7503 return VData; 7504 } 7505 7506 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7507 SelectionDAG &DAG) const { 7508 SDLoc DL(Op); 7509 SDValue Chain = Op.getOperand(0); 7510 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7511 MachineFunction &MF = DAG.getMachineFunction(); 7512 7513 switch (IntrinsicID) { 7514 case Intrinsic::amdgcn_exp_compr: { 7515 SDValue Src0 = Op.getOperand(4); 7516 SDValue Src1 = Op.getOperand(5); 7517 // Hack around illegal type on SI by directly selecting it. 7518 if (isTypeLegal(Src0.getValueType())) 7519 return SDValue(); 7520 7521 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7522 SDValue Undef = DAG.getUNDEF(MVT::f32); 7523 const SDValue Ops[] = { 7524 Op.getOperand(2), // tgt 7525 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7526 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7527 Undef, // src2 7528 Undef, // src3 7529 Op.getOperand(7), // vm 7530 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7531 Op.getOperand(3), // en 7532 Op.getOperand(0) // Chain 7533 }; 7534 7535 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7536 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7537 } 7538 case Intrinsic::amdgcn_s_barrier: { 7539 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7540 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7541 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7542 if (WGSize <= ST.getWavefrontSize()) 7543 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7544 Op.getOperand(0)), 0); 7545 } 7546 return SDValue(); 7547 }; 7548 case Intrinsic::amdgcn_tbuffer_store: { 7549 SDValue VData = Op.getOperand(2); 7550 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7551 if (IsD16) 7552 VData = handleD16VData(VData, DAG); 7553 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7554 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7555 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7556 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7557 unsigned IdxEn = 1; 7558 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7559 IdxEn = Idx->getZExtValue() != 0; 7560 SDValue Ops[] = { 7561 Chain, 7562 VData, // vdata 7563 Op.getOperand(3), // rsrc 7564 Op.getOperand(4), // vindex 7565 Op.getOperand(5), // voffset 7566 Op.getOperand(6), // soffset 7567 Op.getOperand(7), // offset 7568 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7569 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7570 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7571 }; 7572 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7573 AMDGPUISD::TBUFFER_STORE_FORMAT; 7574 MemSDNode *M = cast<MemSDNode>(Op); 7575 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7576 M->getMemoryVT(), M->getMemOperand()); 7577 } 7578 7579 case Intrinsic::amdgcn_struct_tbuffer_store: { 7580 SDValue VData = Op.getOperand(2); 7581 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7582 if (IsD16) 7583 VData = handleD16VData(VData, DAG); 7584 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7585 SDValue Ops[] = { 7586 Chain, 7587 VData, // vdata 7588 Op.getOperand(3), // rsrc 7589 Op.getOperand(4), // vindex 7590 Offsets.first, // voffset 7591 Op.getOperand(6), // soffset 7592 Offsets.second, // offset 7593 Op.getOperand(7), // format 7594 Op.getOperand(8), // cachepolicy, swizzled buffer 7595 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7596 }; 7597 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7598 AMDGPUISD::TBUFFER_STORE_FORMAT; 7599 MemSDNode *M = cast<MemSDNode>(Op); 7600 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7601 M->getMemoryVT(), M->getMemOperand()); 7602 } 7603 7604 case Intrinsic::amdgcn_raw_tbuffer_store: { 7605 SDValue VData = Op.getOperand(2); 7606 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7607 if (IsD16) 7608 VData = handleD16VData(VData, DAG); 7609 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7610 SDValue Ops[] = { 7611 Chain, 7612 VData, // vdata 7613 Op.getOperand(3), // rsrc 7614 DAG.getConstant(0, DL, MVT::i32), // vindex 7615 Offsets.first, // voffset 7616 Op.getOperand(5), // soffset 7617 Offsets.second, // offset 7618 Op.getOperand(6), // format 7619 Op.getOperand(7), // cachepolicy, swizzled buffer 7620 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7621 }; 7622 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7623 AMDGPUISD::TBUFFER_STORE_FORMAT; 7624 MemSDNode *M = cast<MemSDNode>(Op); 7625 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7626 M->getMemoryVT(), M->getMemOperand()); 7627 } 7628 7629 case Intrinsic::amdgcn_buffer_store: 7630 case Intrinsic::amdgcn_buffer_store_format: { 7631 SDValue VData = Op.getOperand(2); 7632 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7633 if (IsD16) 7634 VData = handleD16VData(VData, DAG); 7635 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7636 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7637 unsigned IdxEn = 1; 7638 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7639 IdxEn = Idx->getZExtValue() != 0; 7640 SDValue Ops[] = { 7641 Chain, 7642 VData, 7643 Op.getOperand(3), // rsrc 7644 Op.getOperand(4), // vindex 7645 SDValue(), // voffset -- will be set by setBufferOffsets 7646 SDValue(), // soffset -- will be set by setBufferOffsets 7647 SDValue(), // offset -- will be set by setBufferOffsets 7648 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7649 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7650 }; 7651 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7652 // We don't know the offset if vindex is non-zero, so clear it. 7653 if (IdxEn) 7654 Offset = 0; 7655 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7656 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7657 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7658 MemSDNode *M = cast<MemSDNode>(Op); 7659 M->getMemOperand()->setOffset(Offset); 7660 7661 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7662 EVT VDataType = VData.getValueType().getScalarType(); 7663 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7664 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7665 7666 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7667 M->getMemoryVT(), M->getMemOperand()); 7668 } 7669 7670 case Intrinsic::amdgcn_raw_buffer_store: 7671 case Intrinsic::amdgcn_raw_buffer_store_format: { 7672 const bool IsFormat = 7673 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7674 7675 SDValue VData = Op.getOperand(2); 7676 EVT VDataVT = VData.getValueType(); 7677 EVT EltType = VDataVT.getScalarType(); 7678 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7679 if (IsD16) { 7680 VData = handleD16VData(VData, DAG); 7681 VDataVT = VData.getValueType(); 7682 } 7683 7684 if (!isTypeLegal(VDataVT)) { 7685 VData = 7686 DAG.getNode(ISD::BITCAST, DL, 7687 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7688 } 7689 7690 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7691 SDValue Ops[] = { 7692 Chain, 7693 VData, 7694 Op.getOperand(3), // rsrc 7695 DAG.getConstant(0, DL, MVT::i32), // vindex 7696 Offsets.first, // voffset 7697 Op.getOperand(5), // soffset 7698 Offsets.second, // offset 7699 Op.getOperand(6), // cachepolicy, swizzled buffer 7700 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7701 }; 7702 unsigned Opc = 7703 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7704 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7705 MemSDNode *M = cast<MemSDNode>(Op); 7706 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7707 7708 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7709 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7710 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7711 7712 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7713 M->getMemoryVT(), M->getMemOperand()); 7714 } 7715 7716 case Intrinsic::amdgcn_struct_buffer_store: 7717 case Intrinsic::amdgcn_struct_buffer_store_format: { 7718 const bool IsFormat = 7719 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7720 7721 SDValue VData = Op.getOperand(2); 7722 EVT VDataVT = VData.getValueType(); 7723 EVT EltType = VDataVT.getScalarType(); 7724 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7725 7726 if (IsD16) { 7727 VData = handleD16VData(VData, DAG); 7728 VDataVT = VData.getValueType(); 7729 } 7730 7731 if (!isTypeLegal(VDataVT)) { 7732 VData = 7733 DAG.getNode(ISD::BITCAST, DL, 7734 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7735 } 7736 7737 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7738 SDValue Ops[] = { 7739 Chain, 7740 VData, 7741 Op.getOperand(3), // rsrc 7742 Op.getOperand(4), // vindex 7743 Offsets.first, // voffset 7744 Op.getOperand(6), // soffset 7745 Offsets.second, // offset 7746 Op.getOperand(7), // cachepolicy, swizzled buffer 7747 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7748 }; 7749 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7750 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7751 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7752 MemSDNode *M = cast<MemSDNode>(Op); 7753 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7754 Ops[3])); 7755 7756 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7757 EVT VDataType = VData.getValueType().getScalarType(); 7758 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7759 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7760 7761 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7762 M->getMemoryVT(), M->getMemOperand()); 7763 } 7764 case Intrinsic::amdgcn_end_cf: 7765 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7766 Op->getOperand(2), Chain), 0); 7767 7768 default: { 7769 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7770 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7771 return lowerImage(Op, ImageDimIntr, DAG, true); 7772 7773 return Op; 7774 } 7775 } 7776 } 7777 7778 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7779 // offset (the offset that is included in bounds checking and swizzling, to be 7780 // split between the instruction's voffset and immoffset fields) and soffset 7781 // (the offset that is excluded from bounds checking and swizzling, to go in 7782 // the instruction's soffset field). This function takes the first kind of 7783 // offset and figures out how to split it between voffset and immoffset. 7784 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7785 SDValue Offset, SelectionDAG &DAG) const { 7786 SDLoc DL(Offset); 7787 const unsigned MaxImm = 4095; 7788 SDValue N0 = Offset; 7789 ConstantSDNode *C1 = nullptr; 7790 7791 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7792 N0 = SDValue(); 7793 else if (DAG.isBaseWithConstantOffset(N0)) { 7794 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7795 N0 = N0.getOperand(0); 7796 } 7797 7798 if (C1) { 7799 unsigned ImmOffset = C1->getZExtValue(); 7800 // If the immediate value is too big for the immoffset field, put the value 7801 // and -4096 into the immoffset field so that the value that is copied/added 7802 // for the voffset field is a multiple of 4096, and it stands more chance 7803 // of being CSEd with the copy/add for another similar load/store. 7804 // However, do not do that rounding down to a multiple of 4096 if that is a 7805 // negative number, as it appears to be illegal to have a negative offset 7806 // in the vgpr, even if adding the immediate offset makes it positive. 7807 unsigned Overflow = ImmOffset & ~MaxImm; 7808 ImmOffset -= Overflow; 7809 if ((int32_t)Overflow < 0) { 7810 Overflow += ImmOffset; 7811 ImmOffset = 0; 7812 } 7813 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7814 if (Overflow) { 7815 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7816 if (!N0) 7817 N0 = OverflowVal; 7818 else { 7819 SDValue Ops[] = { N0, OverflowVal }; 7820 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7821 } 7822 } 7823 } 7824 if (!N0) 7825 N0 = DAG.getConstant(0, DL, MVT::i32); 7826 if (!C1) 7827 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7828 return {N0, SDValue(C1, 0)}; 7829 } 7830 7831 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7832 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7833 // pointed to by Offsets. 7834 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7835 SelectionDAG &DAG, SDValue *Offsets, 7836 Align Alignment) const { 7837 SDLoc DL(CombinedOffset); 7838 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7839 uint32_t Imm = C->getZExtValue(); 7840 uint32_t SOffset, ImmOffset; 7841 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7842 Alignment)) { 7843 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7844 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7845 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7846 return SOffset + ImmOffset; 7847 } 7848 } 7849 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7850 SDValue N0 = CombinedOffset.getOperand(0); 7851 SDValue N1 = CombinedOffset.getOperand(1); 7852 uint32_t SOffset, ImmOffset; 7853 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7854 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7855 Subtarget, Alignment)) { 7856 Offsets[0] = N0; 7857 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7858 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7859 return 0; 7860 } 7861 } 7862 Offsets[0] = CombinedOffset; 7863 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7864 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7865 return 0; 7866 } 7867 7868 // Handle 8 bit and 16 bit buffer loads 7869 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7870 EVT LoadVT, SDLoc DL, 7871 ArrayRef<SDValue> Ops, 7872 MemSDNode *M) const { 7873 EVT IntVT = LoadVT.changeTypeToInteger(); 7874 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7875 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7876 7877 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7878 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7879 Ops, IntVT, 7880 M->getMemOperand()); 7881 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7882 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7883 7884 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7885 } 7886 7887 // Handle 8 bit and 16 bit buffer stores 7888 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7889 EVT VDataType, SDLoc DL, 7890 SDValue Ops[], 7891 MemSDNode *M) const { 7892 if (VDataType == MVT::f16) 7893 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7894 7895 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7896 Ops[1] = BufferStoreExt; 7897 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7898 AMDGPUISD::BUFFER_STORE_SHORT; 7899 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7900 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7901 M->getMemOperand()); 7902 } 7903 7904 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7905 ISD::LoadExtType ExtType, SDValue Op, 7906 const SDLoc &SL, EVT VT) { 7907 if (VT.bitsLT(Op.getValueType())) 7908 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7909 7910 switch (ExtType) { 7911 case ISD::SEXTLOAD: 7912 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7913 case ISD::ZEXTLOAD: 7914 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7915 case ISD::EXTLOAD: 7916 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7917 case ISD::NON_EXTLOAD: 7918 return Op; 7919 } 7920 7921 llvm_unreachable("invalid ext type"); 7922 } 7923 7924 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7925 SelectionDAG &DAG = DCI.DAG; 7926 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7927 return SDValue(); 7928 7929 // FIXME: Constant loads should all be marked invariant. 7930 unsigned AS = Ld->getAddressSpace(); 7931 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7932 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7933 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7934 return SDValue(); 7935 7936 // Don't do this early, since it may interfere with adjacent load merging for 7937 // illegal types. We can avoid losing alignment information for exotic types 7938 // pre-legalize. 7939 EVT MemVT = Ld->getMemoryVT(); 7940 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7941 MemVT.getSizeInBits() >= 32) 7942 return SDValue(); 7943 7944 SDLoc SL(Ld); 7945 7946 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7947 "unexpected vector extload"); 7948 7949 // TODO: Drop only high part of range. 7950 SDValue Ptr = Ld->getBasePtr(); 7951 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7952 MVT::i32, SL, Ld->getChain(), Ptr, 7953 Ld->getOffset(), 7954 Ld->getPointerInfo(), MVT::i32, 7955 Ld->getAlignment(), 7956 Ld->getMemOperand()->getFlags(), 7957 Ld->getAAInfo(), 7958 nullptr); // Drop ranges 7959 7960 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7961 if (MemVT.isFloatingPoint()) { 7962 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7963 "unexpected fp extload"); 7964 TruncVT = MemVT.changeTypeToInteger(); 7965 } 7966 7967 SDValue Cvt = NewLoad; 7968 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7969 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7970 DAG.getValueType(TruncVT)); 7971 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7972 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7973 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7974 } else { 7975 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7976 } 7977 7978 EVT VT = Ld->getValueType(0); 7979 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7980 7981 DCI.AddToWorklist(Cvt.getNode()); 7982 7983 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7984 // the appropriate extension from the 32-bit load. 7985 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7986 DCI.AddToWorklist(Cvt.getNode()); 7987 7988 // Handle conversion back to floating point if necessary. 7989 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7990 7991 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7992 } 7993 7994 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7995 SDLoc DL(Op); 7996 LoadSDNode *Load = cast<LoadSDNode>(Op); 7997 ISD::LoadExtType ExtType = Load->getExtensionType(); 7998 EVT MemVT = Load->getMemoryVT(); 7999 8000 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8001 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8002 return SDValue(); 8003 8004 // FIXME: Copied from PPC 8005 // First, load into 32 bits, then truncate to 1 bit. 8006 8007 SDValue Chain = Load->getChain(); 8008 SDValue BasePtr = Load->getBasePtr(); 8009 MachineMemOperand *MMO = Load->getMemOperand(); 8010 8011 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8012 8013 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8014 BasePtr, RealMemVT, MMO); 8015 8016 if (!MemVT.isVector()) { 8017 SDValue Ops[] = { 8018 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8019 NewLD.getValue(1) 8020 }; 8021 8022 return DAG.getMergeValues(Ops, DL); 8023 } 8024 8025 SmallVector<SDValue, 3> Elts; 8026 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8027 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8028 DAG.getConstant(I, DL, MVT::i32)); 8029 8030 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8031 } 8032 8033 SDValue Ops[] = { 8034 DAG.getBuildVector(MemVT, DL, Elts), 8035 NewLD.getValue(1) 8036 }; 8037 8038 return DAG.getMergeValues(Ops, DL); 8039 } 8040 8041 if (!MemVT.isVector()) 8042 return SDValue(); 8043 8044 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8045 "Custom lowering for non-i32 vectors hasn't been implemented."); 8046 8047 unsigned Alignment = Load->getAlignment(); 8048 unsigned AS = Load->getAddressSpace(); 8049 if (Subtarget->hasLDSMisalignedBug() && 8050 AS == AMDGPUAS::FLAT_ADDRESS && 8051 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8052 return SplitVectorLoad(Op, DAG); 8053 } 8054 8055 MachineFunction &MF = DAG.getMachineFunction(); 8056 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8057 // If there is a possibilty that flat instruction access scratch memory 8058 // then we need to use the same legalization rules we use for private. 8059 if (AS == AMDGPUAS::FLAT_ADDRESS && 8060 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8061 AS = MFI->hasFlatScratchInit() ? 8062 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8063 8064 unsigned NumElements = MemVT.getVectorNumElements(); 8065 8066 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8067 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8068 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8069 if (MemVT.isPow2VectorType()) 8070 return SDValue(); 8071 return WidenOrSplitVectorLoad(Op, DAG); 8072 } 8073 // Non-uniform loads will be selected to MUBUF instructions, so they 8074 // have the same legalization requirements as global and private 8075 // loads. 8076 // 8077 } 8078 8079 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8080 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8081 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8082 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8083 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8084 Alignment >= 4 && NumElements < 32) { 8085 if (MemVT.isPow2VectorType()) 8086 return SDValue(); 8087 return WidenOrSplitVectorLoad(Op, DAG); 8088 } 8089 // Non-uniform loads will be selected to MUBUF instructions, so they 8090 // have the same legalization requirements as global and private 8091 // loads. 8092 // 8093 } 8094 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8095 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8096 AS == AMDGPUAS::GLOBAL_ADDRESS || 8097 AS == AMDGPUAS::FLAT_ADDRESS) { 8098 if (NumElements > 4) 8099 return SplitVectorLoad(Op, DAG); 8100 // v3 loads not supported on SI. 8101 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8102 return WidenOrSplitVectorLoad(Op, DAG); 8103 8104 // v3 and v4 loads are supported for private and global memory. 8105 return SDValue(); 8106 } 8107 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8108 // Depending on the setting of the private_element_size field in the 8109 // resource descriptor, we can only make private accesses up to a certain 8110 // size. 8111 switch (Subtarget->getMaxPrivateElementSize()) { 8112 case 4: { 8113 SDValue Ops[2]; 8114 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8115 return DAG.getMergeValues(Ops, DL); 8116 } 8117 case 8: 8118 if (NumElements > 2) 8119 return SplitVectorLoad(Op, DAG); 8120 return SDValue(); 8121 case 16: 8122 // Same as global/flat 8123 if (NumElements > 4) 8124 return SplitVectorLoad(Op, DAG); 8125 // v3 loads not supported on SI. 8126 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8127 return WidenOrSplitVectorLoad(Op, DAG); 8128 8129 return SDValue(); 8130 default: 8131 llvm_unreachable("unsupported private_element_size"); 8132 } 8133 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8134 // Use ds_read_b128 or ds_read_b96 when possible. 8135 if (Subtarget->hasDS96AndDS128() && 8136 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8137 MemVT.getStoreSize() == 12) && 8138 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8139 Load->getAlign())) 8140 return SDValue(); 8141 8142 if (NumElements > 2) 8143 return SplitVectorLoad(Op, DAG); 8144 8145 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8146 // address is negative, then the instruction is incorrectly treated as 8147 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8148 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8149 // load later in the SILoadStoreOptimizer. 8150 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8151 NumElements == 2 && MemVT.getStoreSize() == 8 && 8152 Load->getAlignment() < 8) { 8153 return SplitVectorLoad(Op, DAG); 8154 } 8155 } 8156 8157 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8158 MemVT, *Load->getMemOperand())) { 8159 SDValue Ops[2]; 8160 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8161 return DAG.getMergeValues(Ops, DL); 8162 } 8163 8164 return SDValue(); 8165 } 8166 8167 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8168 EVT VT = Op.getValueType(); 8169 assert(VT.getSizeInBits() == 64); 8170 8171 SDLoc DL(Op); 8172 SDValue Cond = Op.getOperand(0); 8173 8174 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8175 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8176 8177 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8178 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8179 8180 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8181 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8182 8183 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8184 8185 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8186 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8187 8188 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8189 8190 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8191 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8192 } 8193 8194 // Catch division cases where we can use shortcuts with rcp and rsq 8195 // instructions. 8196 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8197 SelectionDAG &DAG) const { 8198 SDLoc SL(Op); 8199 SDValue LHS = Op.getOperand(0); 8200 SDValue RHS = Op.getOperand(1); 8201 EVT VT = Op.getValueType(); 8202 const SDNodeFlags Flags = Op->getFlags(); 8203 8204 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8205 Flags.hasApproximateFuncs(); 8206 8207 // Without !fpmath accuracy information, we can't do more because we don't 8208 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8209 if (!AllowInaccurateRcp) 8210 return SDValue(); 8211 8212 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8213 if (CLHS->isExactlyValue(1.0)) { 8214 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8215 // the CI documentation has a worst case error of 1 ulp. 8216 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8217 // use it as long as we aren't trying to use denormals. 8218 // 8219 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8220 8221 // 1.0 / sqrt(x) -> rsq(x) 8222 8223 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8224 // error seems really high at 2^29 ULP. 8225 if (RHS.getOpcode() == ISD::FSQRT) 8226 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8227 8228 // 1.0 / x -> rcp(x) 8229 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8230 } 8231 8232 // Same as for 1.0, but expand the sign out of the constant. 8233 if (CLHS->isExactlyValue(-1.0)) { 8234 // -1.0 / x -> rcp (fneg x) 8235 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8236 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8237 } 8238 } 8239 8240 // Turn into multiply by the reciprocal. 8241 // x / y -> x * (1.0 / y) 8242 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8243 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8244 } 8245 8246 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8247 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8248 SDNodeFlags Flags) { 8249 if (GlueChain->getNumValues() <= 1) { 8250 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8251 } 8252 8253 assert(GlueChain->getNumValues() == 3); 8254 8255 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8256 switch (Opcode) { 8257 default: llvm_unreachable("no chain equivalent for opcode"); 8258 case ISD::FMUL: 8259 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8260 break; 8261 } 8262 8263 return DAG.getNode(Opcode, SL, VTList, 8264 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8265 Flags); 8266 } 8267 8268 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8269 EVT VT, SDValue A, SDValue B, SDValue C, 8270 SDValue GlueChain, SDNodeFlags Flags) { 8271 if (GlueChain->getNumValues() <= 1) { 8272 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8273 } 8274 8275 assert(GlueChain->getNumValues() == 3); 8276 8277 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8278 switch (Opcode) { 8279 default: llvm_unreachable("no chain equivalent for opcode"); 8280 case ISD::FMA: 8281 Opcode = AMDGPUISD::FMA_W_CHAIN; 8282 break; 8283 } 8284 8285 return DAG.getNode(Opcode, SL, VTList, 8286 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8287 Flags); 8288 } 8289 8290 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8291 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8292 return FastLowered; 8293 8294 SDLoc SL(Op); 8295 SDValue Src0 = Op.getOperand(0); 8296 SDValue Src1 = Op.getOperand(1); 8297 8298 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8299 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8300 8301 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8302 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8303 8304 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8305 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8306 8307 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8308 } 8309 8310 // Faster 2.5 ULP division that does not support denormals. 8311 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8312 SDLoc SL(Op); 8313 SDValue LHS = Op.getOperand(1); 8314 SDValue RHS = Op.getOperand(2); 8315 8316 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8317 8318 const APFloat K0Val(BitsToFloat(0x6f800000)); 8319 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8320 8321 const APFloat K1Val(BitsToFloat(0x2f800000)); 8322 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8323 8324 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8325 8326 EVT SetCCVT = 8327 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8328 8329 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8330 8331 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8332 8333 // TODO: Should this propagate fast-math-flags? 8334 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8335 8336 // rcp does not support denormals. 8337 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8338 8339 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8340 8341 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8342 } 8343 8344 // Returns immediate value for setting the F32 denorm mode when using the 8345 // S_DENORM_MODE instruction. 8346 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8347 const SDLoc &SL, const GCNSubtarget *ST) { 8348 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8349 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8350 ? FP_DENORM_FLUSH_NONE 8351 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8352 8353 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8354 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8355 } 8356 8357 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8358 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8359 return FastLowered; 8360 8361 // The selection matcher assumes anything with a chain selecting to a 8362 // mayRaiseFPException machine instruction. Since we're introducing a chain 8363 // here, we need to explicitly report nofpexcept for the regular fdiv 8364 // lowering. 8365 SDNodeFlags Flags = Op->getFlags(); 8366 Flags.setNoFPExcept(true); 8367 8368 SDLoc SL(Op); 8369 SDValue LHS = Op.getOperand(0); 8370 SDValue RHS = Op.getOperand(1); 8371 8372 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8373 8374 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8375 8376 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8377 {RHS, RHS, LHS}, Flags); 8378 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8379 {LHS, RHS, LHS}, Flags); 8380 8381 // Denominator is scaled to not be denormal, so using rcp is ok. 8382 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8383 DenominatorScaled, Flags); 8384 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8385 DenominatorScaled, Flags); 8386 8387 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8388 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8389 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8390 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8391 8392 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8393 8394 if (!HasFP32Denormals) { 8395 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8396 // lowering. The chain dependence is insufficient, and we need glue. We do 8397 // not need the glue variants in a strictfp function. 8398 8399 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8400 8401 SDNode *EnableDenorm; 8402 if (Subtarget->hasDenormModeInst()) { 8403 const SDValue EnableDenormValue = 8404 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8405 8406 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8407 DAG.getEntryNode(), EnableDenormValue).getNode(); 8408 } else { 8409 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8410 SL, MVT::i32); 8411 EnableDenorm = 8412 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8413 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8414 } 8415 8416 SDValue Ops[3] = { 8417 NegDivScale0, 8418 SDValue(EnableDenorm, 0), 8419 SDValue(EnableDenorm, 1) 8420 }; 8421 8422 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8423 } 8424 8425 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8426 ApproxRcp, One, NegDivScale0, Flags); 8427 8428 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8429 ApproxRcp, Fma0, Flags); 8430 8431 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8432 Fma1, Fma1, Flags); 8433 8434 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8435 NumeratorScaled, Mul, Flags); 8436 8437 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8438 Fma2, Fma1, Mul, Fma2, Flags); 8439 8440 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8441 NumeratorScaled, Fma3, Flags); 8442 8443 if (!HasFP32Denormals) { 8444 SDNode *DisableDenorm; 8445 if (Subtarget->hasDenormModeInst()) { 8446 const SDValue DisableDenormValue = 8447 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8448 8449 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8450 Fma4.getValue(1), DisableDenormValue, 8451 Fma4.getValue(2)).getNode(); 8452 } else { 8453 const SDValue DisableDenormValue = 8454 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8455 8456 DisableDenorm = DAG.getMachineNode( 8457 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8458 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8459 } 8460 8461 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8462 SDValue(DisableDenorm, 0), DAG.getRoot()); 8463 DAG.setRoot(OutputChain); 8464 } 8465 8466 SDValue Scale = NumeratorScaled.getValue(1); 8467 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8468 {Fma4, Fma1, Fma3, Scale}, Flags); 8469 8470 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8471 } 8472 8473 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8474 if (DAG.getTarget().Options.UnsafeFPMath) 8475 return lowerFastUnsafeFDIV(Op, DAG); 8476 8477 SDLoc SL(Op); 8478 SDValue X = Op.getOperand(0); 8479 SDValue Y = Op.getOperand(1); 8480 8481 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8482 8483 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8484 8485 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8486 8487 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8488 8489 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8490 8491 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8492 8493 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8494 8495 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8496 8497 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8498 8499 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8500 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8501 8502 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8503 NegDivScale0, Mul, DivScale1); 8504 8505 SDValue Scale; 8506 8507 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8508 // Workaround a hardware bug on SI where the condition output from div_scale 8509 // is not usable. 8510 8511 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8512 8513 // Figure out if the scale to use for div_fmas. 8514 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8515 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8516 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8517 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8518 8519 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8520 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8521 8522 SDValue Scale0Hi 8523 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8524 SDValue Scale1Hi 8525 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8526 8527 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8528 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8529 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8530 } else { 8531 Scale = DivScale1.getValue(1); 8532 } 8533 8534 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8535 Fma4, Fma3, Mul, Scale); 8536 8537 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8538 } 8539 8540 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8541 EVT VT = Op.getValueType(); 8542 8543 if (VT == MVT::f32) 8544 return LowerFDIV32(Op, DAG); 8545 8546 if (VT == MVT::f64) 8547 return LowerFDIV64(Op, DAG); 8548 8549 if (VT == MVT::f16) 8550 return LowerFDIV16(Op, DAG); 8551 8552 llvm_unreachable("Unexpected type for fdiv"); 8553 } 8554 8555 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8556 SDLoc DL(Op); 8557 StoreSDNode *Store = cast<StoreSDNode>(Op); 8558 EVT VT = Store->getMemoryVT(); 8559 8560 if (VT == MVT::i1) { 8561 return DAG.getTruncStore(Store->getChain(), DL, 8562 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8563 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8564 } 8565 8566 assert(VT.isVector() && 8567 Store->getValue().getValueType().getScalarType() == MVT::i32); 8568 8569 unsigned AS = Store->getAddressSpace(); 8570 if (Subtarget->hasLDSMisalignedBug() && 8571 AS == AMDGPUAS::FLAT_ADDRESS && 8572 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8573 return SplitVectorStore(Op, DAG); 8574 } 8575 8576 MachineFunction &MF = DAG.getMachineFunction(); 8577 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8578 // If there is a possibilty that flat instruction access scratch memory 8579 // then we need to use the same legalization rules we use for private. 8580 if (AS == AMDGPUAS::FLAT_ADDRESS && 8581 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8582 AS = MFI->hasFlatScratchInit() ? 8583 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8584 8585 unsigned NumElements = VT.getVectorNumElements(); 8586 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8587 AS == AMDGPUAS::FLAT_ADDRESS) { 8588 if (NumElements > 4) 8589 return SplitVectorStore(Op, DAG); 8590 // v3 stores not supported on SI. 8591 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8592 return SplitVectorStore(Op, DAG); 8593 8594 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8595 VT, *Store->getMemOperand())) 8596 return expandUnalignedStore(Store, DAG); 8597 8598 return SDValue(); 8599 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8600 switch (Subtarget->getMaxPrivateElementSize()) { 8601 case 4: 8602 return scalarizeVectorStore(Store, DAG); 8603 case 8: 8604 if (NumElements > 2) 8605 return SplitVectorStore(Op, DAG); 8606 return SDValue(); 8607 case 16: 8608 if (NumElements > 4 || NumElements == 3) 8609 return SplitVectorStore(Op, DAG); 8610 return SDValue(); 8611 default: 8612 llvm_unreachable("unsupported private_element_size"); 8613 } 8614 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8615 // Use ds_write_b128 or ds_write_b96 when possible. 8616 if (Subtarget->hasDS96AndDS128() && 8617 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8618 (VT.getStoreSize() == 12)) && 8619 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8620 Store->getAlign())) 8621 return SDValue(); 8622 8623 if (NumElements > 2) 8624 return SplitVectorStore(Op, DAG); 8625 8626 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8627 // address is negative, then the instruction is incorrectly treated as 8628 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8629 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8630 // store later in the SILoadStoreOptimizer. 8631 if (!Subtarget->hasUsableDSOffset() && 8632 NumElements == 2 && VT.getStoreSize() == 8 && 8633 Store->getAlignment() < 8) { 8634 return SplitVectorStore(Op, DAG); 8635 } 8636 8637 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8638 VT, *Store->getMemOperand())) { 8639 if (VT.isVector()) 8640 return SplitVectorStore(Op, DAG); 8641 return expandUnalignedStore(Store, DAG); 8642 } 8643 8644 return SDValue(); 8645 } else { 8646 llvm_unreachable("unhandled address space"); 8647 } 8648 } 8649 8650 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8651 SDLoc DL(Op); 8652 EVT VT = Op.getValueType(); 8653 SDValue Arg = Op.getOperand(0); 8654 SDValue TrigVal; 8655 8656 // Propagate fast-math flags so that the multiply we introduce can be folded 8657 // if Arg is already the result of a multiply by constant. 8658 auto Flags = Op->getFlags(); 8659 8660 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8661 8662 if (Subtarget->hasTrigReducedRange()) { 8663 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8664 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8665 } else { 8666 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8667 } 8668 8669 switch (Op.getOpcode()) { 8670 case ISD::FCOS: 8671 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8672 case ISD::FSIN: 8673 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8674 default: 8675 llvm_unreachable("Wrong trig opcode"); 8676 } 8677 } 8678 8679 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8680 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8681 assert(AtomicNode->isCompareAndSwap()); 8682 unsigned AS = AtomicNode->getAddressSpace(); 8683 8684 // No custom lowering required for local address space 8685 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8686 return Op; 8687 8688 // Non-local address space requires custom lowering for atomic compare 8689 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8690 SDLoc DL(Op); 8691 SDValue ChainIn = Op.getOperand(0); 8692 SDValue Addr = Op.getOperand(1); 8693 SDValue Old = Op.getOperand(2); 8694 SDValue New = Op.getOperand(3); 8695 EVT VT = Op.getValueType(); 8696 MVT SimpleVT = VT.getSimpleVT(); 8697 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8698 8699 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8700 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8701 8702 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8703 Ops, VT, AtomicNode->getMemOperand()); 8704 } 8705 8706 //===----------------------------------------------------------------------===// 8707 // Custom DAG optimizations 8708 //===----------------------------------------------------------------------===// 8709 8710 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8711 DAGCombinerInfo &DCI) const { 8712 EVT VT = N->getValueType(0); 8713 EVT ScalarVT = VT.getScalarType(); 8714 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8715 return SDValue(); 8716 8717 SelectionDAG &DAG = DCI.DAG; 8718 SDLoc DL(N); 8719 8720 SDValue Src = N->getOperand(0); 8721 EVT SrcVT = Src.getValueType(); 8722 8723 // TODO: We could try to match extracting the higher bytes, which would be 8724 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8725 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8726 // about in practice. 8727 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8728 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8729 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8730 DCI.AddToWorklist(Cvt.getNode()); 8731 8732 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8733 if (ScalarVT != MVT::f32) { 8734 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8735 DAG.getTargetConstant(0, DL, MVT::i32)); 8736 } 8737 return Cvt; 8738 } 8739 } 8740 8741 return SDValue(); 8742 } 8743 8744 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8745 8746 // This is a variant of 8747 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8748 // 8749 // The normal DAG combiner will do this, but only if the add has one use since 8750 // that would increase the number of instructions. 8751 // 8752 // This prevents us from seeing a constant offset that can be folded into a 8753 // memory instruction's addressing mode. If we know the resulting add offset of 8754 // a pointer can be folded into an addressing offset, we can replace the pointer 8755 // operand with the add of new constant offset. This eliminates one of the uses, 8756 // and may allow the remaining use to also be simplified. 8757 // 8758 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8759 unsigned AddrSpace, 8760 EVT MemVT, 8761 DAGCombinerInfo &DCI) const { 8762 SDValue N0 = N->getOperand(0); 8763 SDValue N1 = N->getOperand(1); 8764 8765 // We only do this to handle cases where it's profitable when there are 8766 // multiple uses of the add, so defer to the standard combine. 8767 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8768 N0->hasOneUse()) 8769 return SDValue(); 8770 8771 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8772 if (!CN1) 8773 return SDValue(); 8774 8775 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8776 if (!CAdd) 8777 return SDValue(); 8778 8779 // If the resulting offset is too large, we can't fold it into the addressing 8780 // mode offset. 8781 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8782 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8783 8784 AddrMode AM; 8785 AM.HasBaseReg = true; 8786 AM.BaseOffs = Offset.getSExtValue(); 8787 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8788 return SDValue(); 8789 8790 SelectionDAG &DAG = DCI.DAG; 8791 SDLoc SL(N); 8792 EVT VT = N->getValueType(0); 8793 8794 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8795 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8796 8797 SDNodeFlags Flags; 8798 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8799 (N0.getOpcode() == ISD::OR || 8800 N0->getFlags().hasNoUnsignedWrap())); 8801 8802 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8803 } 8804 8805 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8806 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8807 /// specific intrinsic, but they all place the pointer operand first. 8808 static unsigned getBasePtrIndex(const MemSDNode *N) { 8809 switch (N->getOpcode()) { 8810 case ISD::STORE: 8811 case ISD::INTRINSIC_W_CHAIN: 8812 case ISD::INTRINSIC_VOID: 8813 return 2; 8814 default: 8815 return 1; 8816 } 8817 } 8818 8819 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8820 DAGCombinerInfo &DCI) const { 8821 SelectionDAG &DAG = DCI.DAG; 8822 SDLoc SL(N); 8823 8824 unsigned PtrIdx = getBasePtrIndex(N); 8825 SDValue Ptr = N->getOperand(PtrIdx); 8826 8827 // TODO: We could also do this for multiplies. 8828 if (Ptr.getOpcode() == ISD::SHL) { 8829 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8830 N->getMemoryVT(), DCI); 8831 if (NewPtr) { 8832 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8833 8834 NewOps[PtrIdx] = NewPtr; 8835 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8836 } 8837 } 8838 8839 return SDValue(); 8840 } 8841 8842 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8843 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8844 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8845 (Opc == ISD::XOR && Val == 0); 8846 } 8847 8848 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8849 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8850 // integer combine opportunities since most 64-bit operations are decomposed 8851 // this way. TODO: We won't want this for SALU especially if it is an inline 8852 // immediate. 8853 SDValue SITargetLowering::splitBinaryBitConstantOp( 8854 DAGCombinerInfo &DCI, 8855 const SDLoc &SL, 8856 unsigned Opc, SDValue LHS, 8857 const ConstantSDNode *CRHS) const { 8858 uint64_t Val = CRHS->getZExtValue(); 8859 uint32_t ValLo = Lo_32(Val); 8860 uint32_t ValHi = Hi_32(Val); 8861 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8862 8863 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8864 bitOpWithConstantIsReducible(Opc, ValHi)) || 8865 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8866 // If we need to materialize a 64-bit immediate, it will be split up later 8867 // anyway. Avoid creating the harder to understand 64-bit immediate 8868 // materialization. 8869 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8870 } 8871 8872 return SDValue(); 8873 } 8874 8875 // Returns true if argument is a boolean value which is not serialized into 8876 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8877 static bool isBoolSGPR(SDValue V) { 8878 if (V.getValueType() != MVT::i1) 8879 return false; 8880 switch (V.getOpcode()) { 8881 default: break; 8882 case ISD::SETCC: 8883 case ISD::AND: 8884 case ISD::OR: 8885 case ISD::XOR: 8886 case AMDGPUISD::FP_CLASS: 8887 return true; 8888 } 8889 return false; 8890 } 8891 8892 // If a constant has all zeroes or all ones within each byte return it. 8893 // Otherwise return 0. 8894 static uint32_t getConstantPermuteMask(uint32_t C) { 8895 // 0xff for any zero byte in the mask 8896 uint32_t ZeroByteMask = 0; 8897 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8898 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8899 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8900 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8901 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8902 if ((NonZeroByteMask & C) != NonZeroByteMask) 8903 return 0; // Partial bytes selected. 8904 return C; 8905 } 8906 8907 // Check if a node selects whole bytes from its operand 0 starting at a byte 8908 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8909 // or -1 if not succeeded. 8910 // Note byte select encoding: 8911 // value 0-3 selects corresponding source byte; 8912 // value 0xc selects zero; 8913 // value 0xff selects 0xff. 8914 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8915 assert(V.getValueSizeInBits() == 32); 8916 8917 if (V.getNumOperands() != 2) 8918 return ~0; 8919 8920 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8921 if (!N1) 8922 return ~0; 8923 8924 uint32_t C = N1->getZExtValue(); 8925 8926 switch (V.getOpcode()) { 8927 default: 8928 break; 8929 case ISD::AND: 8930 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8931 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8932 } 8933 break; 8934 8935 case ISD::OR: 8936 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8937 return (0x03020100 & ~ConstMask) | ConstMask; 8938 } 8939 break; 8940 8941 case ISD::SHL: 8942 if (C % 8) 8943 return ~0; 8944 8945 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8946 8947 case ISD::SRL: 8948 if (C % 8) 8949 return ~0; 8950 8951 return uint32_t(0x0c0c0c0c03020100ull >> C); 8952 } 8953 8954 return ~0; 8955 } 8956 8957 SDValue SITargetLowering::performAndCombine(SDNode *N, 8958 DAGCombinerInfo &DCI) const { 8959 if (DCI.isBeforeLegalize()) 8960 return SDValue(); 8961 8962 SelectionDAG &DAG = DCI.DAG; 8963 EVT VT = N->getValueType(0); 8964 SDValue LHS = N->getOperand(0); 8965 SDValue RHS = N->getOperand(1); 8966 8967 8968 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8969 if (VT == MVT::i64 && CRHS) { 8970 if (SDValue Split 8971 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8972 return Split; 8973 } 8974 8975 if (CRHS && VT == MVT::i32) { 8976 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8977 // nb = number of trailing zeroes in mask 8978 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8979 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8980 uint64_t Mask = CRHS->getZExtValue(); 8981 unsigned Bits = countPopulation(Mask); 8982 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8983 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8984 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8985 unsigned Shift = CShift->getZExtValue(); 8986 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8987 unsigned Offset = NB + Shift; 8988 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8989 SDLoc SL(N); 8990 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8991 LHS->getOperand(0), 8992 DAG.getConstant(Offset, SL, MVT::i32), 8993 DAG.getConstant(Bits, SL, MVT::i32)); 8994 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8995 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8996 DAG.getValueType(NarrowVT)); 8997 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8998 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8999 return Shl; 9000 } 9001 } 9002 } 9003 9004 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9005 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9006 isa<ConstantSDNode>(LHS.getOperand(2))) { 9007 uint32_t Sel = getConstantPermuteMask(Mask); 9008 if (!Sel) 9009 return SDValue(); 9010 9011 // Select 0xc for all zero bytes 9012 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9013 SDLoc DL(N); 9014 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9015 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9016 } 9017 } 9018 9019 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9020 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9021 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9022 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9023 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9024 9025 SDValue X = LHS.getOperand(0); 9026 SDValue Y = RHS.getOperand(0); 9027 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9028 return SDValue(); 9029 9030 if (LCC == ISD::SETO) { 9031 if (X != LHS.getOperand(1)) 9032 return SDValue(); 9033 9034 if (RCC == ISD::SETUNE) { 9035 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9036 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9037 return SDValue(); 9038 9039 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9040 SIInstrFlags::N_SUBNORMAL | 9041 SIInstrFlags::N_ZERO | 9042 SIInstrFlags::P_ZERO | 9043 SIInstrFlags::P_SUBNORMAL | 9044 SIInstrFlags::P_NORMAL; 9045 9046 static_assert(((~(SIInstrFlags::S_NAN | 9047 SIInstrFlags::Q_NAN | 9048 SIInstrFlags::N_INFINITY | 9049 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9050 "mask not equal"); 9051 9052 SDLoc DL(N); 9053 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9054 X, DAG.getConstant(Mask, DL, MVT::i32)); 9055 } 9056 } 9057 } 9058 9059 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9060 std::swap(LHS, RHS); 9061 9062 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9063 RHS.hasOneUse()) { 9064 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9065 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9066 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9067 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9068 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9069 (RHS.getOperand(0) == LHS.getOperand(0) && 9070 LHS.getOperand(0) == LHS.getOperand(1))) { 9071 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9072 unsigned NewMask = LCC == ISD::SETO ? 9073 Mask->getZExtValue() & ~OrdMask : 9074 Mask->getZExtValue() & OrdMask; 9075 9076 SDLoc DL(N); 9077 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9078 DAG.getConstant(NewMask, DL, MVT::i32)); 9079 } 9080 } 9081 9082 if (VT == MVT::i32 && 9083 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9084 // and x, (sext cc from i1) => select cc, x, 0 9085 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9086 std::swap(LHS, RHS); 9087 if (isBoolSGPR(RHS.getOperand(0))) 9088 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9089 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9090 } 9091 9092 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9093 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9094 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9095 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9096 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9097 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9098 if (LHSMask != ~0u && RHSMask != ~0u) { 9099 // Canonicalize the expression in an attempt to have fewer unique masks 9100 // and therefore fewer registers used to hold the masks. 9101 if (LHSMask > RHSMask) { 9102 std::swap(LHSMask, RHSMask); 9103 std::swap(LHS, RHS); 9104 } 9105 9106 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9107 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9108 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9109 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9110 9111 // Check of we need to combine values from two sources within a byte. 9112 if (!(LHSUsedLanes & RHSUsedLanes) && 9113 // If we select high and lower word keep it for SDWA. 9114 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9115 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9116 // Each byte in each mask is either selector mask 0-3, or has higher 9117 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9118 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9119 // mask which is not 0xff wins. By anding both masks we have a correct 9120 // result except that 0x0c shall be corrected to give 0x0c only. 9121 uint32_t Mask = LHSMask & RHSMask; 9122 for (unsigned I = 0; I < 32; I += 8) { 9123 uint32_t ByteSel = 0xff << I; 9124 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9125 Mask &= (0x0c << I) & 0xffffffff; 9126 } 9127 9128 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9129 // or 0x0c. 9130 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9131 SDLoc DL(N); 9132 9133 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9134 LHS.getOperand(0), RHS.getOperand(0), 9135 DAG.getConstant(Sel, DL, MVT::i32)); 9136 } 9137 } 9138 } 9139 9140 return SDValue(); 9141 } 9142 9143 SDValue SITargetLowering::performOrCombine(SDNode *N, 9144 DAGCombinerInfo &DCI) const { 9145 SelectionDAG &DAG = DCI.DAG; 9146 SDValue LHS = N->getOperand(0); 9147 SDValue RHS = N->getOperand(1); 9148 9149 EVT VT = N->getValueType(0); 9150 if (VT == MVT::i1) { 9151 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9152 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9153 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9154 SDValue Src = LHS.getOperand(0); 9155 if (Src != RHS.getOperand(0)) 9156 return SDValue(); 9157 9158 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9159 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9160 if (!CLHS || !CRHS) 9161 return SDValue(); 9162 9163 // Only 10 bits are used. 9164 static const uint32_t MaxMask = 0x3ff; 9165 9166 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9167 SDLoc DL(N); 9168 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9169 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9170 } 9171 9172 return SDValue(); 9173 } 9174 9175 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9176 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9177 LHS.getOpcode() == AMDGPUISD::PERM && 9178 isa<ConstantSDNode>(LHS.getOperand(2))) { 9179 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9180 if (!Sel) 9181 return SDValue(); 9182 9183 Sel |= LHS.getConstantOperandVal(2); 9184 SDLoc DL(N); 9185 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9186 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9187 } 9188 9189 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9190 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9191 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9192 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9193 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9194 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9195 if (LHSMask != ~0u && RHSMask != ~0u) { 9196 // Canonicalize the expression in an attempt to have fewer unique masks 9197 // and therefore fewer registers used to hold the masks. 9198 if (LHSMask > RHSMask) { 9199 std::swap(LHSMask, RHSMask); 9200 std::swap(LHS, RHS); 9201 } 9202 9203 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9204 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9205 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9206 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9207 9208 // Check of we need to combine values from two sources within a byte. 9209 if (!(LHSUsedLanes & RHSUsedLanes) && 9210 // If we select high and lower word keep it for SDWA. 9211 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9212 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9213 // Kill zero bytes selected by other mask. Zero value is 0xc. 9214 LHSMask &= ~RHSUsedLanes; 9215 RHSMask &= ~LHSUsedLanes; 9216 // Add 4 to each active LHS lane 9217 LHSMask |= LHSUsedLanes & 0x04040404; 9218 // Combine masks 9219 uint32_t Sel = LHSMask | RHSMask; 9220 SDLoc DL(N); 9221 9222 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9223 LHS.getOperand(0), RHS.getOperand(0), 9224 DAG.getConstant(Sel, DL, MVT::i32)); 9225 } 9226 } 9227 } 9228 9229 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9230 return SDValue(); 9231 9232 // TODO: This could be a generic combine with a predicate for extracting the 9233 // high half of an integer being free. 9234 9235 // (or i64:x, (zero_extend i32:y)) -> 9236 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9237 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9238 RHS.getOpcode() != ISD::ZERO_EXTEND) 9239 std::swap(LHS, RHS); 9240 9241 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9242 SDValue ExtSrc = RHS.getOperand(0); 9243 EVT SrcVT = ExtSrc.getValueType(); 9244 if (SrcVT == MVT::i32) { 9245 SDLoc SL(N); 9246 SDValue LowLHS, HiBits; 9247 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9248 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9249 9250 DCI.AddToWorklist(LowOr.getNode()); 9251 DCI.AddToWorklist(HiBits.getNode()); 9252 9253 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9254 LowOr, HiBits); 9255 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9256 } 9257 } 9258 9259 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9260 if (CRHS) { 9261 if (SDValue Split 9262 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9263 return Split; 9264 } 9265 9266 return SDValue(); 9267 } 9268 9269 SDValue SITargetLowering::performXorCombine(SDNode *N, 9270 DAGCombinerInfo &DCI) const { 9271 EVT VT = N->getValueType(0); 9272 if (VT != MVT::i64) 9273 return SDValue(); 9274 9275 SDValue LHS = N->getOperand(0); 9276 SDValue RHS = N->getOperand(1); 9277 9278 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9279 if (CRHS) { 9280 if (SDValue Split 9281 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9282 return Split; 9283 } 9284 9285 return SDValue(); 9286 } 9287 9288 // Instructions that will be lowered with a final instruction that zeros the 9289 // high result bits. 9290 // XXX - probably only need to list legal operations. 9291 static bool fp16SrcZerosHighBits(unsigned Opc) { 9292 switch (Opc) { 9293 case ISD::FADD: 9294 case ISD::FSUB: 9295 case ISD::FMUL: 9296 case ISD::FDIV: 9297 case ISD::FREM: 9298 case ISD::FMA: 9299 case ISD::FMAD: 9300 case ISD::FCANONICALIZE: 9301 case ISD::FP_ROUND: 9302 case ISD::UINT_TO_FP: 9303 case ISD::SINT_TO_FP: 9304 case ISD::FABS: 9305 // Fabs is lowered to a bit operation, but it's an and which will clear the 9306 // high bits anyway. 9307 case ISD::FSQRT: 9308 case ISD::FSIN: 9309 case ISD::FCOS: 9310 case ISD::FPOWI: 9311 case ISD::FPOW: 9312 case ISD::FLOG: 9313 case ISD::FLOG2: 9314 case ISD::FLOG10: 9315 case ISD::FEXP: 9316 case ISD::FEXP2: 9317 case ISD::FCEIL: 9318 case ISD::FTRUNC: 9319 case ISD::FRINT: 9320 case ISD::FNEARBYINT: 9321 case ISD::FROUND: 9322 case ISD::FFLOOR: 9323 case ISD::FMINNUM: 9324 case ISD::FMAXNUM: 9325 case AMDGPUISD::FRACT: 9326 case AMDGPUISD::CLAMP: 9327 case AMDGPUISD::COS_HW: 9328 case AMDGPUISD::SIN_HW: 9329 case AMDGPUISD::FMIN3: 9330 case AMDGPUISD::FMAX3: 9331 case AMDGPUISD::FMED3: 9332 case AMDGPUISD::FMAD_FTZ: 9333 case AMDGPUISD::RCP: 9334 case AMDGPUISD::RSQ: 9335 case AMDGPUISD::RCP_IFLAG: 9336 case AMDGPUISD::LDEXP: 9337 return true; 9338 default: 9339 // fcopysign, select and others may be lowered to 32-bit bit operations 9340 // which don't zero the high bits. 9341 return false; 9342 } 9343 } 9344 9345 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9346 DAGCombinerInfo &DCI) const { 9347 if (!Subtarget->has16BitInsts() || 9348 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9349 return SDValue(); 9350 9351 EVT VT = N->getValueType(0); 9352 if (VT != MVT::i32) 9353 return SDValue(); 9354 9355 SDValue Src = N->getOperand(0); 9356 if (Src.getValueType() != MVT::i16) 9357 return SDValue(); 9358 9359 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9360 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9361 if (Src.getOpcode() == ISD::BITCAST) { 9362 SDValue BCSrc = Src.getOperand(0); 9363 if (BCSrc.getValueType() == MVT::f16 && 9364 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9365 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9366 } 9367 9368 return SDValue(); 9369 } 9370 9371 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9372 DAGCombinerInfo &DCI) 9373 const { 9374 SDValue Src = N->getOperand(0); 9375 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9376 9377 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9378 VTSign->getVT() == MVT::i8) || 9379 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9380 VTSign->getVT() == MVT::i16)) && 9381 Src.hasOneUse()) { 9382 auto *M = cast<MemSDNode>(Src); 9383 SDValue Ops[] = { 9384 Src.getOperand(0), // Chain 9385 Src.getOperand(1), // rsrc 9386 Src.getOperand(2), // vindex 9387 Src.getOperand(3), // voffset 9388 Src.getOperand(4), // soffset 9389 Src.getOperand(5), // offset 9390 Src.getOperand(6), 9391 Src.getOperand(7) 9392 }; 9393 // replace with BUFFER_LOAD_BYTE/SHORT 9394 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9395 Src.getOperand(0).getValueType()); 9396 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9397 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9398 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9399 ResList, 9400 Ops, M->getMemoryVT(), 9401 M->getMemOperand()); 9402 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9403 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9404 } 9405 return SDValue(); 9406 } 9407 9408 SDValue SITargetLowering::performClassCombine(SDNode *N, 9409 DAGCombinerInfo &DCI) const { 9410 SelectionDAG &DAG = DCI.DAG; 9411 SDValue Mask = N->getOperand(1); 9412 9413 // fp_class x, 0 -> false 9414 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9415 if (CMask->isNullValue()) 9416 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9417 } 9418 9419 if (N->getOperand(0).isUndef()) 9420 return DAG.getUNDEF(MVT::i1); 9421 9422 return SDValue(); 9423 } 9424 9425 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9426 DAGCombinerInfo &DCI) const { 9427 EVT VT = N->getValueType(0); 9428 SDValue N0 = N->getOperand(0); 9429 9430 if (N0.isUndef()) 9431 return N0; 9432 9433 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9434 N0.getOpcode() == ISD::SINT_TO_FP)) { 9435 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9436 N->getFlags()); 9437 } 9438 9439 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9440 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9441 N0.getOperand(0), N->getFlags()); 9442 } 9443 9444 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9445 } 9446 9447 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9448 unsigned MaxDepth) const { 9449 unsigned Opcode = Op.getOpcode(); 9450 if (Opcode == ISD::FCANONICALIZE) 9451 return true; 9452 9453 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9454 auto F = CFP->getValueAPF(); 9455 if (F.isNaN() && F.isSignaling()) 9456 return false; 9457 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9458 } 9459 9460 // If source is a result of another standard FP operation it is already in 9461 // canonical form. 9462 if (MaxDepth == 0) 9463 return false; 9464 9465 switch (Opcode) { 9466 // These will flush denorms if required. 9467 case ISD::FADD: 9468 case ISD::FSUB: 9469 case ISD::FMUL: 9470 case ISD::FCEIL: 9471 case ISD::FFLOOR: 9472 case ISD::FMA: 9473 case ISD::FMAD: 9474 case ISD::FSQRT: 9475 case ISD::FDIV: 9476 case ISD::FREM: 9477 case ISD::FP_ROUND: 9478 case ISD::FP_EXTEND: 9479 case AMDGPUISD::FMUL_LEGACY: 9480 case AMDGPUISD::FMAD_FTZ: 9481 case AMDGPUISD::RCP: 9482 case AMDGPUISD::RSQ: 9483 case AMDGPUISD::RSQ_CLAMP: 9484 case AMDGPUISD::RCP_LEGACY: 9485 case AMDGPUISD::RCP_IFLAG: 9486 case AMDGPUISD::DIV_SCALE: 9487 case AMDGPUISD::DIV_FMAS: 9488 case AMDGPUISD::DIV_FIXUP: 9489 case AMDGPUISD::FRACT: 9490 case AMDGPUISD::LDEXP: 9491 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9492 case AMDGPUISD::CVT_F32_UBYTE0: 9493 case AMDGPUISD::CVT_F32_UBYTE1: 9494 case AMDGPUISD::CVT_F32_UBYTE2: 9495 case AMDGPUISD::CVT_F32_UBYTE3: 9496 return true; 9497 9498 // It can/will be lowered or combined as a bit operation. 9499 // Need to check their input recursively to handle. 9500 case ISD::FNEG: 9501 case ISD::FABS: 9502 case ISD::FCOPYSIGN: 9503 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9504 9505 case ISD::FSIN: 9506 case ISD::FCOS: 9507 case ISD::FSINCOS: 9508 return Op.getValueType().getScalarType() != MVT::f16; 9509 9510 case ISD::FMINNUM: 9511 case ISD::FMAXNUM: 9512 case ISD::FMINNUM_IEEE: 9513 case ISD::FMAXNUM_IEEE: 9514 case AMDGPUISD::CLAMP: 9515 case AMDGPUISD::FMED3: 9516 case AMDGPUISD::FMAX3: 9517 case AMDGPUISD::FMIN3: { 9518 // FIXME: Shouldn't treat the generic operations different based these. 9519 // However, we aren't really required to flush the result from 9520 // minnum/maxnum.. 9521 9522 // snans will be quieted, so we only need to worry about denormals. 9523 if (Subtarget->supportsMinMaxDenormModes() || 9524 denormalsEnabledForType(DAG, Op.getValueType())) 9525 return true; 9526 9527 // Flushing may be required. 9528 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9529 // targets need to check their input recursively. 9530 9531 // FIXME: Does this apply with clamp? It's implemented with max. 9532 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9533 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9534 return false; 9535 } 9536 9537 return true; 9538 } 9539 case ISD::SELECT: { 9540 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9541 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9542 } 9543 case ISD::BUILD_VECTOR: { 9544 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9545 SDValue SrcOp = Op.getOperand(i); 9546 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9547 return false; 9548 } 9549 9550 return true; 9551 } 9552 case ISD::EXTRACT_VECTOR_ELT: 9553 case ISD::EXTRACT_SUBVECTOR: { 9554 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9555 } 9556 case ISD::INSERT_VECTOR_ELT: { 9557 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9558 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9559 } 9560 case ISD::UNDEF: 9561 // Could be anything. 9562 return false; 9563 9564 case ISD::BITCAST: { 9565 // Hack round the mess we make when legalizing extract_vector_elt 9566 SDValue Src = Op.getOperand(0); 9567 if (Src.getValueType() == MVT::i16 && 9568 Src.getOpcode() == ISD::TRUNCATE) { 9569 SDValue TruncSrc = Src.getOperand(0); 9570 if (TruncSrc.getValueType() == MVT::i32 && 9571 TruncSrc.getOpcode() == ISD::BITCAST && 9572 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9573 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9574 } 9575 } 9576 9577 return false; 9578 } 9579 case ISD::INTRINSIC_WO_CHAIN: { 9580 unsigned IntrinsicID 9581 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9582 // TODO: Handle more intrinsics 9583 switch (IntrinsicID) { 9584 case Intrinsic::amdgcn_cvt_pkrtz: 9585 case Intrinsic::amdgcn_cubeid: 9586 case Intrinsic::amdgcn_frexp_mant: 9587 case Intrinsic::amdgcn_fdot2: 9588 case Intrinsic::amdgcn_rcp: 9589 case Intrinsic::amdgcn_rsq: 9590 case Intrinsic::amdgcn_rsq_clamp: 9591 case Intrinsic::amdgcn_rcp_legacy: 9592 case Intrinsic::amdgcn_rsq_legacy: 9593 case Intrinsic::amdgcn_trig_preop: 9594 return true; 9595 default: 9596 break; 9597 } 9598 9599 LLVM_FALLTHROUGH; 9600 } 9601 default: 9602 return denormalsEnabledForType(DAG, Op.getValueType()) && 9603 DAG.isKnownNeverSNaN(Op); 9604 } 9605 9606 llvm_unreachable("invalid operation"); 9607 } 9608 9609 // Constant fold canonicalize. 9610 SDValue SITargetLowering::getCanonicalConstantFP( 9611 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9612 // Flush denormals to 0 if not enabled. 9613 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9614 return DAG.getConstantFP(0.0, SL, VT); 9615 9616 if (C.isNaN()) { 9617 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9618 if (C.isSignaling()) { 9619 // Quiet a signaling NaN. 9620 // FIXME: Is this supposed to preserve payload bits? 9621 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9622 } 9623 9624 // Make sure it is the canonical NaN bitpattern. 9625 // 9626 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9627 // immediate? 9628 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9629 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9630 } 9631 9632 // Already canonical. 9633 return DAG.getConstantFP(C, SL, VT); 9634 } 9635 9636 static bool vectorEltWillFoldAway(SDValue Op) { 9637 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9638 } 9639 9640 SDValue SITargetLowering::performFCanonicalizeCombine( 9641 SDNode *N, 9642 DAGCombinerInfo &DCI) const { 9643 SelectionDAG &DAG = DCI.DAG; 9644 SDValue N0 = N->getOperand(0); 9645 EVT VT = N->getValueType(0); 9646 9647 // fcanonicalize undef -> qnan 9648 if (N0.isUndef()) { 9649 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9650 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9651 } 9652 9653 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9654 EVT VT = N->getValueType(0); 9655 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9656 } 9657 9658 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9659 // (fcanonicalize k) 9660 // 9661 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9662 9663 // TODO: This could be better with wider vectors that will be split to v2f16, 9664 // and to consider uses since there aren't that many packed operations. 9665 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9666 isTypeLegal(MVT::v2f16)) { 9667 SDLoc SL(N); 9668 SDValue NewElts[2]; 9669 SDValue Lo = N0.getOperand(0); 9670 SDValue Hi = N0.getOperand(1); 9671 EVT EltVT = Lo.getValueType(); 9672 9673 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9674 for (unsigned I = 0; I != 2; ++I) { 9675 SDValue Op = N0.getOperand(I); 9676 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9677 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9678 CFP->getValueAPF()); 9679 } else if (Op.isUndef()) { 9680 // Handled below based on what the other operand is. 9681 NewElts[I] = Op; 9682 } else { 9683 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9684 } 9685 } 9686 9687 // If one half is undef, and one is constant, perfer a splat vector rather 9688 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9689 // cheaper to use and may be free with a packed operation. 9690 if (NewElts[0].isUndef()) { 9691 if (isa<ConstantFPSDNode>(NewElts[1])) 9692 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9693 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9694 } 9695 9696 if (NewElts[1].isUndef()) { 9697 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9698 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9699 } 9700 9701 return DAG.getBuildVector(VT, SL, NewElts); 9702 } 9703 } 9704 9705 unsigned SrcOpc = N0.getOpcode(); 9706 9707 // If it's free to do so, push canonicalizes further up the source, which may 9708 // find a canonical source. 9709 // 9710 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9711 // sNaNs. 9712 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9713 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9714 if (CRHS && N0.hasOneUse()) { 9715 SDLoc SL(N); 9716 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9717 N0.getOperand(0)); 9718 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9719 DCI.AddToWorklist(Canon0.getNode()); 9720 9721 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9722 } 9723 } 9724 9725 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9726 } 9727 9728 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9729 switch (Opc) { 9730 case ISD::FMAXNUM: 9731 case ISD::FMAXNUM_IEEE: 9732 return AMDGPUISD::FMAX3; 9733 case ISD::SMAX: 9734 return AMDGPUISD::SMAX3; 9735 case ISD::UMAX: 9736 return AMDGPUISD::UMAX3; 9737 case ISD::FMINNUM: 9738 case ISD::FMINNUM_IEEE: 9739 return AMDGPUISD::FMIN3; 9740 case ISD::SMIN: 9741 return AMDGPUISD::SMIN3; 9742 case ISD::UMIN: 9743 return AMDGPUISD::UMIN3; 9744 default: 9745 llvm_unreachable("Not a min/max opcode"); 9746 } 9747 } 9748 9749 SDValue SITargetLowering::performIntMed3ImmCombine( 9750 SelectionDAG &DAG, const SDLoc &SL, 9751 SDValue Op0, SDValue Op1, bool Signed) const { 9752 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9753 if (!K1) 9754 return SDValue(); 9755 9756 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9757 if (!K0) 9758 return SDValue(); 9759 9760 if (Signed) { 9761 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9762 return SDValue(); 9763 } else { 9764 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9765 return SDValue(); 9766 } 9767 9768 EVT VT = K0->getValueType(0); 9769 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9770 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9771 return DAG.getNode(Med3Opc, SL, VT, 9772 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9773 } 9774 9775 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9776 MVT NVT = MVT::i32; 9777 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9778 9779 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9780 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9781 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9782 9783 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9784 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9785 } 9786 9787 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9788 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9789 return C; 9790 9791 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9792 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9793 return C; 9794 } 9795 9796 return nullptr; 9797 } 9798 9799 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9800 const SDLoc &SL, 9801 SDValue Op0, 9802 SDValue Op1) const { 9803 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9804 if (!K1) 9805 return SDValue(); 9806 9807 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9808 if (!K0) 9809 return SDValue(); 9810 9811 // Ordered >= (although NaN inputs should have folded away by now). 9812 if (K0->getValueAPF() > K1->getValueAPF()) 9813 return SDValue(); 9814 9815 const MachineFunction &MF = DAG.getMachineFunction(); 9816 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9817 9818 // TODO: Check IEEE bit enabled? 9819 EVT VT = Op0.getValueType(); 9820 if (Info->getMode().DX10Clamp) { 9821 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9822 // hardware fmed3 behavior converting to a min. 9823 // FIXME: Should this be allowing -0.0? 9824 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9825 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9826 } 9827 9828 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9829 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9830 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9831 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9832 // then give the other result, which is different from med3 with a NaN 9833 // input. 9834 SDValue Var = Op0.getOperand(0); 9835 if (!DAG.isKnownNeverSNaN(Var)) 9836 return SDValue(); 9837 9838 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9839 9840 if ((!K0->hasOneUse() || 9841 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9842 (!K1->hasOneUse() || 9843 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9844 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9845 Var, SDValue(K0, 0), SDValue(K1, 0)); 9846 } 9847 } 9848 9849 return SDValue(); 9850 } 9851 9852 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9853 DAGCombinerInfo &DCI) const { 9854 SelectionDAG &DAG = DCI.DAG; 9855 9856 EVT VT = N->getValueType(0); 9857 unsigned Opc = N->getOpcode(); 9858 SDValue Op0 = N->getOperand(0); 9859 SDValue Op1 = N->getOperand(1); 9860 9861 // Only do this if the inner op has one use since this will just increases 9862 // register pressure for no benefit. 9863 9864 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9865 !VT.isVector() && 9866 (VT == MVT::i32 || VT == MVT::f32 || 9867 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9868 // max(max(a, b), c) -> max3(a, b, c) 9869 // min(min(a, b), c) -> min3(a, b, c) 9870 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9871 SDLoc DL(N); 9872 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9873 DL, 9874 N->getValueType(0), 9875 Op0.getOperand(0), 9876 Op0.getOperand(1), 9877 Op1); 9878 } 9879 9880 // Try commuted. 9881 // max(a, max(b, c)) -> max3(a, b, c) 9882 // min(a, min(b, c)) -> min3(a, b, c) 9883 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9884 SDLoc DL(N); 9885 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9886 DL, 9887 N->getValueType(0), 9888 Op0, 9889 Op1.getOperand(0), 9890 Op1.getOperand(1)); 9891 } 9892 } 9893 9894 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9895 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9896 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9897 return Med3; 9898 } 9899 9900 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9901 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9902 return Med3; 9903 } 9904 9905 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9906 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9907 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9908 (Opc == AMDGPUISD::FMIN_LEGACY && 9909 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9910 (VT == MVT::f32 || VT == MVT::f64 || 9911 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9912 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9913 Op0.hasOneUse()) { 9914 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9915 return Res; 9916 } 9917 9918 return SDValue(); 9919 } 9920 9921 static bool isClampZeroToOne(SDValue A, SDValue B) { 9922 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9923 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9924 // FIXME: Should this be allowing -0.0? 9925 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9926 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9927 } 9928 } 9929 9930 return false; 9931 } 9932 9933 // FIXME: Should only worry about snans for version with chain. 9934 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9935 DAGCombinerInfo &DCI) const { 9936 EVT VT = N->getValueType(0); 9937 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9938 // NaNs. With a NaN input, the order of the operands may change the result. 9939 9940 SelectionDAG &DAG = DCI.DAG; 9941 SDLoc SL(N); 9942 9943 SDValue Src0 = N->getOperand(0); 9944 SDValue Src1 = N->getOperand(1); 9945 SDValue Src2 = N->getOperand(2); 9946 9947 if (isClampZeroToOne(Src0, Src1)) { 9948 // const_a, const_b, x -> clamp is safe in all cases including signaling 9949 // nans. 9950 // FIXME: Should this be allowing -0.0? 9951 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9952 } 9953 9954 const MachineFunction &MF = DAG.getMachineFunction(); 9955 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9956 9957 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9958 // handling no dx10-clamp? 9959 if (Info->getMode().DX10Clamp) { 9960 // If NaNs is clamped to 0, we are free to reorder the inputs. 9961 9962 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9963 std::swap(Src0, Src1); 9964 9965 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9966 std::swap(Src1, Src2); 9967 9968 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9969 std::swap(Src0, Src1); 9970 9971 if (isClampZeroToOne(Src1, Src2)) 9972 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9973 } 9974 9975 return SDValue(); 9976 } 9977 9978 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9979 DAGCombinerInfo &DCI) const { 9980 SDValue Src0 = N->getOperand(0); 9981 SDValue Src1 = N->getOperand(1); 9982 if (Src0.isUndef() && Src1.isUndef()) 9983 return DCI.DAG.getUNDEF(N->getValueType(0)); 9984 return SDValue(); 9985 } 9986 9987 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9988 // expanded into a set of cmp/select instructions. 9989 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9990 unsigned NumElem, 9991 bool IsDivergentIdx) { 9992 if (UseDivergentRegisterIndexing) 9993 return false; 9994 9995 unsigned VecSize = EltSize * NumElem; 9996 9997 // Sub-dword vectors of size 2 dword or less have better implementation. 9998 if (VecSize <= 64 && EltSize < 32) 9999 return false; 10000 10001 // Always expand the rest of sub-dword instructions, otherwise it will be 10002 // lowered via memory. 10003 if (EltSize < 32) 10004 return true; 10005 10006 // Always do this if var-idx is divergent, otherwise it will become a loop. 10007 if (IsDivergentIdx) 10008 return true; 10009 10010 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10011 unsigned NumInsts = NumElem /* Number of compares */ + 10012 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10013 return NumInsts <= 16; 10014 } 10015 10016 static bool shouldExpandVectorDynExt(SDNode *N) { 10017 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10018 if (isa<ConstantSDNode>(Idx)) 10019 return false; 10020 10021 SDValue Vec = N->getOperand(0); 10022 EVT VecVT = Vec.getValueType(); 10023 EVT EltVT = VecVT.getVectorElementType(); 10024 unsigned EltSize = EltVT.getSizeInBits(); 10025 unsigned NumElem = VecVT.getVectorNumElements(); 10026 10027 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10028 Idx->isDivergent()); 10029 } 10030 10031 SDValue SITargetLowering::performExtractVectorEltCombine( 10032 SDNode *N, DAGCombinerInfo &DCI) const { 10033 SDValue Vec = N->getOperand(0); 10034 SelectionDAG &DAG = DCI.DAG; 10035 10036 EVT VecVT = Vec.getValueType(); 10037 EVT EltVT = VecVT.getVectorElementType(); 10038 10039 if ((Vec.getOpcode() == ISD::FNEG || 10040 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10041 SDLoc SL(N); 10042 EVT EltVT = N->getValueType(0); 10043 SDValue Idx = N->getOperand(1); 10044 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10045 Vec.getOperand(0), Idx); 10046 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10047 } 10048 10049 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10050 // => 10051 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10052 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10053 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10054 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10055 SDLoc SL(N); 10056 EVT EltVT = N->getValueType(0); 10057 SDValue Idx = N->getOperand(1); 10058 unsigned Opc = Vec.getOpcode(); 10059 10060 switch(Opc) { 10061 default: 10062 break; 10063 // TODO: Support other binary operations. 10064 case ISD::FADD: 10065 case ISD::FSUB: 10066 case ISD::FMUL: 10067 case ISD::ADD: 10068 case ISD::UMIN: 10069 case ISD::UMAX: 10070 case ISD::SMIN: 10071 case ISD::SMAX: 10072 case ISD::FMAXNUM: 10073 case ISD::FMINNUM: 10074 case ISD::FMAXNUM_IEEE: 10075 case ISD::FMINNUM_IEEE: { 10076 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10077 Vec.getOperand(0), Idx); 10078 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10079 Vec.getOperand(1), Idx); 10080 10081 DCI.AddToWorklist(Elt0.getNode()); 10082 DCI.AddToWorklist(Elt1.getNode()); 10083 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10084 } 10085 } 10086 } 10087 10088 unsigned VecSize = VecVT.getSizeInBits(); 10089 unsigned EltSize = EltVT.getSizeInBits(); 10090 10091 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10092 if (::shouldExpandVectorDynExt(N)) { 10093 SDLoc SL(N); 10094 SDValue Idx = N->getOperand(1); 10095 SDValue V; 10096 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10097 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10098 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10099 if (I == 0) 10100 V = Elt; 10101 else 10102 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10103 } 10104 return V; 10105 } 10106 10107 if (!DCI.isBeforeLegalize()) 10108 return SDValue(); 10109 10110 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10111 // elements. This exposes more load reduction opportunities by replacing 10112 // multiple small extract_vector_elements with a single 32-bit extract. 10113 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10114 if (isa<MemSDNode>(Vec) && 10115 EltSize <= 16 && 10116 EltVT.isByteSized() && 10117 VecSize > 32 && 10118 VecSize % 32 == 0 && 10119 Idx) { 10120 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10121 10122 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10123 unsigned EltIdx = BitIndex / 32; 10124 unsigned LeftoverBitIdx = BitIndex % 32; 10125 SDLoc SL(N); 10126 10127 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10128 DCI.AddToWorklist(Cast.getNode()); 10129 10130 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10131 DAG.getConstant(EltIdx, SL, MVT::i32)); 10132 DCI.AddToWorklist(Elt.getNode()); 10133 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10134 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10135 DCI.AddToWorklist(Srl.getNode()); 10136 10137 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10138 DCI.AddToWorklist(Trunc.getNode()); 10139 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10140 } 10141 10142 return SDValue(); 10143 } 10144 10145 SDValue 10146 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10147 DAGCombinerInfo &DCI) const { 10148 SDValue Vec = N->getOperand(0); 10149 SDValue Idx = N->getOperand(2); 10150 EVT VecVT = Vec.getValueType(); 10151 EVT EltVT = VecVT.getVectorElementType(); 10152 10153 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10154 // => BUILD_VECTOR n x select (e, const-idx) 10155 if (!::shouldExpandVectorDynExt(N)) 10156 return SDValue(); 10157 10158 SelectionDAG &DAG = DCI.DAG; 10159 SDLoc SL(N); 10160 SDValue Ins = N->getOperand(1); 10161 EVT IdxVT = Idx.getValueType(); 10162 10163 SmallVector<SDValue, 16> Ops; 10164 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10165 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10166 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10167 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10168 Ops.push_back(V); 10169 } 10170 10171 return DAG.getBuildVector(VecVT, SL, Ops); 10172 } 10173 10174 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10175 const SDNode *N0, 10176 const SDNode *N1) const { 10177 EVT VT = N0->getValueType(0); 10178 10179 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10180 // support denormals ever. 10181 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10182 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10183 getSubtarget()->hasMadF16())) && 10184 isOperationLegal(ISD::FMAD, VT)) 10185 return ISD::FMAD; 10186 10187 const TargetOptions &Options = DAG.getTarget().Options; 10188 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10189 (N0->getFlags().hasAllowContract() && 10190 N1->getFlags().hasAllowContract())) && 10191 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10192 return ISD::FMA; 10193 } 10194 10195 return 0; 10196 } 10197 10198 // For a reassociatable opcode perform: 10199 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10200 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10201 SelectionDAG &DAG) const { 10202 EVT VT = N->getValueType(0); 10203 if (VT != MVT::i32 && VT != MVT::i64) 10204 return SDValue(); 10205 10206 unsigned Opc = N->getOpcode(); 10207 SDValue Op0 = N->getOperand(0); 10208 SDValue Op1 = N->getOperand(1); 10209 10210 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10211 return SDValue(); 10212 10213 if (Op0->isDivergent()) 10214 std::swap(Op0, Op1); 10215 10216 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10217 return SDValue(); 10218 10219 SDValue Op2 = Op1.getOperand(1); 10220 Op1 = Op1.getOperand(0); 10221 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10222 return SDValue(); 10223 10224 if (Op1->isDivergent()) 10225 std::swap(Op1, Op2); 10226 10227 // If either operand is constant this will conflict with 10228 // DAGCombiner::ReassociateOps(). 10229 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10230 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10231 return SDValue(); 10232 10233 SDLoc SL(N); 10234 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10235 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10236 } 10237 10238 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10239 EVT VT, 10240 SDValue N0, SDValue N1, SDValue N2, 10241 bool Signed) { 10242 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10243 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10244 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10245 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10246 } 10247 10248 SDValue SITargetLowering::performAddCombine(SDNode *N, 10249 DAGCombinerInfo &DCI) const { 10250 SelectionDAG &DAG = DCI.DAG; 10251 EVT VT = N->getValueType(0); 10252 SDLoc SL(N); 10253 SDValue LHS = N->getOperand(0); 10254 SDValue RHS = N->getOperand(1); 10255 10256 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10257 && Subtarget->hasMad64_32() && 10258 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10259 VT.getScalarSizeInBits() <= 64) { 10260 if (LHS.getOpcode() != ISD::MUL) 10261 std::swap(LHS, RHS); 10262 10263 SDValue MulLHS = LHS.getOperand(0); 10264 SDValue MulRHS = LHS.getOperand(1); 10265 SDValue AddRHS = RHS; 10266 10267 // TODO: Maybe restrict if SGPR inputs. 10268 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10269 numBitsUnsigned(MulRHS, DAG) <= 32) { 10270 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10271 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10272 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10273 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10274 } 10275 10276 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10277 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10278 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10279 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10280 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10281 } 10282 10283 return SDValue(); 10284 } 10285 10286 if (SDValue V = reassociateScalarOps(N, DAG)) { 10287 return V; 10288 } 10289 10290 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10291 return SDValue(); 10292 10293 // add x, zext (setcc) => addcarry x, 0, setcc 10294 // add x, sext (setcc) => subcarry x, 0, setcc 10295 unsigned Opc = LHS.getOpcode(); 10296 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10297 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10298 std::swap(RHS, LHS); 10299 10300 Opc = RHS.getOpcode(); 10301 switch (Opc) { 10302 default: break; 10303 case ISD::ZERO_EXTEND: 10304 case ISD::SIGN_EXTEND: 10305 case ISD::ANY_EXTEND: { 10306 auto Cond = RHS.getOperand(0); 10307 // If this won't be a real VOPC output, we would still need to insert an 10308 // extra instruction anyway. 10309 if (!isBoolSGPR(Cond)) 10310 break; 10311 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10312 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10313 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10314 return DAG.getNode(Opc, SL, VTList, Args); 10315 } 10316 case ISD::ADDCARRY: { 10317 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10318 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10319 if (!C || C->getZExtValue() != 0) break; 10320 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10321 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10322 } 10323 } 10324 return SDValue(); 10325 } 10326 10327 SDValue SITargetLowering::performSubCombine(SDNode *N, 10328 DAGCombinerInfo &DCI) const { 10329 SelectionDAG &DAG = DCI.DAG; 10330 EVT VT = N->getValueType(0); 10331 10332 if (VT != MVT::i32) 10333 return SDValue(); 10334 10335 SDLoc SL(N); 10336 SDValue LHS = N->getOperand(0); 10337 SDValue RHS = N->getOperand(1); 10338 10339 // sub x, zext (setcc) => subcarry x, 0, setcc 10340 // sub x, sext (setcc) => addcarry x, 0, setcc 10341 unsigned Opc = RHS.getOpcode(); 10342 switch (Opc) { 10343 default: break; 10344 case ISD::ZERO_EXTEND: 10345 case ISD::SIGN_EXTEND: 10346 case ISD::ANY_EXTEND: { 10347 auto Cond = RHS.getOperand(0); 10348 // If this won't be a real VOPC output, we would still need to insert an 10349 // extra instruction anyway. 10350 if (!isBoolSGPR(Cond)) 10351 break; 10352 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10353 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10354 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10355 return DAG.getNode(Opc, SL, VTList, Args); 10356 } 10357 } 10358 10359 if (LHS.getOpcode() == ISD::SUBCARRY) { 10360 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10361 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10362 if (!C || !C->isNullValue()) 10363 return SDValue(); 10364 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10365 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10366 } 10367 return SDValue(); 10368 } 10369 10370 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10371 DAGCombinerInfo &DCI) const { 10372 10373 if (N->getValueType(0) != MVT::i32) 10374 return SDValue(); 10375 10376 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10377 if (!C || C->getZExtValue() != 0) 10378 return SDValue(); 10379 10380 SelectionDAG &DAG = DCI.DAG; 10381 SDValue LHS = N->getOperand(0); 10382 10383 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10384 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10385 unsigned LHSOpc = LHS.getOpcode(); 10386 unsigned Opc = N->getOpcode(); 10387 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10388 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10389 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10390 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10391 } 10392 return SDValue(); 10393 } 10394 10395 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10396 DAGCombinerInfo &DCI) const { 10397 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10398 return SDValue(); 10399 10400 SelectionDAG &DAG = DCI.DAG; 10401 EVT VT = N->getValueType(0); 10402 10403 SDLoc SL(N); 10404 SDValue LHS = N->getOperand(0); 10405 SDValue RHS = N->getOperand(1); 10406 10407 // These should really be instruction patterns, but writing patterns with 10408 // source modiifiers is a pain. 10409 10410 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10411 if (LHS.getOpcode() == ISD::FADD) { 10412 SDValue A = LHS.getOperand(0); 10413 if (A == LHS.getOperand(1)) { 10414 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10415 if (FusedOp != 0) { 10416 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10417 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10418 } 10419 } 10420 } 10421 10422 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10423 if (RHS.getOpcode() == ISD::FADD) { 10424 SDValue A = RHS.getOperand(0); 10425 if (A == RHS.getOperand(1)) { 10426 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10427 if (FusedOp != 0) { 10428 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10429 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10430 } 10431 } 10432 } 10433 10434 return SDValue(); 10435 } 10436 10437 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10438 DAGCombinerInfo &DCI) const { 10439 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10440 return SDValue(); 10441 10442 SelectionDAG &DAG = DCI.DAG; 10443 SDLoc SL(N); 10444 EVT VT = N->getValueType(0); 10445 assert(!VT.isVector()); 10446 10447 // Try to get the fneg to fold into the source modifier. This undoes generic 10448 // DAG combines and folds them into the mad. 10449 // 10450 // Only do this if we are not trying to support denormals. v_mad_f32 does 10451 // not support denormals ever. 10452 SDValue LHS = N->getOperand(0); 10453 SDValue RHS = N->getOperand(1); 10454 if (LHS.getOpcode() == ISD::FADD) { 10455 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10456 SDValue A = LHS.getOperand(0); 10457 if (A == LHS.getOperand(1)) { 10458 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10459 if (FusedOp != 0){ 10460 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10461 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10462 10463 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10464 } 10465 } 10466 } 10467 10468 if (RHS.getOpcode() == ISD::FADD) { 10469 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10470 10471 SDValue A = RHS.getOperand(0); 10472 if (A == RHS.getOperand(1)) { 10473 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10474 if (FusedOp != 0){ 10475 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10476 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10477 } 10478 } 10479 } 10480 10481 return SDValue(); 10482 } 10483 10484 SDValue SITargetLowering::performFMACombine(SDNode *N, 10485 DAGCombinerInfo &DCI) const { 10486 SelectionDAG &DAG = DCI.DAG; 10487 EVT VT = N->getValueType(0); 10488 SDLoc SL(N); 10489 10490 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10491 return SDValue(); 10492 10493 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10494 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10495 SDValue Op1 = N->getOperand(0); 10496 SDValue Op2 = N->getOperand(1); 10497 SDValue FMA = N->getOperand(2); 10498 10499 if (FMA.getOpcode() != ISD::FMA || 10500 Op1.getOpcode() != ISD::FP_EXTEND || 10501 Op2.getOpcode() != ISD::FP_EXTEND) 10502 return SDValue(); 10503 10504 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10505 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10506 // is sufficient to allow generaing fdot2. 10507 const TargetOptions &Options = DAG.getTarget().Options; 10508 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10509 (N->getFlags().hasAllowContract() && 10510 FMA->getFlags().hasAllowContract())) { 10511 Op1 = Op1.getOperand(0); 10512 Op2 = Op2.getOperand(0); 10513 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10514 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10515 return SDValue(); 10516 10517 SDValue Vec1 = Op1.getOperand(0); 10518 SDValue Idx1 = Op1.getOperand(1); 10519 SDValue Vec2 = Op2.getOperand(0); 10520 10521 SDValue FMAOp1 = FMA.getOperand(0); 10522 SDValue FMAOp2 = FMA.getOperand(1); 10523 SDValue FMAAcc = FMA.getOperand(2); 10524 10525 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10526 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10527 return SDValue(); 10528 10529 FMAOp1 = FMAOp1.getOperand(0); 10530 FMAOp2 = FMAOp2.getOperand(0); 10531 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10532 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10533 return SDValue(); 10534 10535 SDValue Vec3 = FMAOp1.getOperand(0); 10536 SDValue Vec4 = FMAOp2.getOperand(0); 10537 SDValue Idx2 = FMAOp1.getOperand(1); 10538 10539 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10540 // Idx1 and Idx2 cannot be the same. 10541 Idx1 == Idx2) 10542 return SDValue(); 10543 10544 if (Vec1 == Vec2 || Vec3 == Vec4) 10545 return SDValue(); 10546 10547 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10548 return SDValue(); 10549 10550 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10551 (Vec1 == Vec4 && Vec2 == Vec3)) { 10552 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10553 DAG.getTargetConstant(0, SL, MVT::i1)); 10554 } 10555 } 10556 return SDValue(); 10557 } 10558 10559 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10560 DAGCombinerInfo &DCI) const { 10561 SelectionDAG &DAG = DCI.DAG; 10562 SDLoc SL(N); 10563 10564 SDValue LHS = N->getOperand(0); 10565 SDValue RHS = N->getOperand(1); 10566 EVT VT = LHS.getValueType(); 10567 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10568 10569 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10570 if (!CRHS) { 10571 CRHS = dyn_cast<ConstantSDNode>(LHS); 10572 if (CRHS) { 10573 std::swap(LHS, RHS); 10574 CC = getSetCCSwappedOperands(CC); 10575 } 10576 } 10577 10578 if (CRHS) { 10579 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10580 isBoolSGPR(LHS.getOperand(0))) { 10581 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10582 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10583 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10584 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10585 if ((CRHS->isAllOnesValue() && 10586 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10587 (CRHS->isNullValue() && 10588 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10589 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10590 DAG.getConstant(-1, SL, MVT::i1)); 10591 if ((CRHS->isAllOnesValue() && 10592 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10593 (CRHS->isNullValue() && 10594 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10595 return LHS.getOperand(0); 10596 } 10597 10598 uint64_t CRHSVal = CRHS->getZExtValue(); 10599 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10600 LHS.getOpcode() == ISD::SELECT && 10601 isa<ConstantSDNode>(LHS.getOperand(1)) && 10602 isa<ConstantSDNode>(LHS.getOperand(2)) && 10603 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10604 isBoolSGPR(LHS.getOperand(0))) { 10605 // Given CT != FT: 10606 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10607 // setcc (select cc, CT, CF), CF, ne => cc 10608 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10609 // setcc (select cc, CT, CF), CT, eq => cc 10610 uint64_t CT = LHS.getConstantOperandVal(1); 10611 uint64_t CF = LHS.getConstantOperandVal(2); 10612 10613 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10614 (CT == CRHSVal && CC == ISD::SETNE)) 10615 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10616 DAG.getConstant(-1, SL, MVT::i1)); 10617 if ((CF == CRHSVal && CC == ISD::SETNE) || 10618 (CT == CRHSVal && CC == ISD::SETEQ)) 10619 return LHS.getOperand(0); 10620 } 10621 } 10622 10623 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10624 VT != MVT::f16)) 10625 return SDValue(); 10626 10627 // Match isinf/isfinite pattern 10628 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10629 // (fcmp one (fabs x), inf) -> (fp_class x, 10630 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10631 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10632 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10633 if (!CRHS) 10634 return SDValue(); 10635 10636 const APFloat &APF = CRHS->getValueAPF(); 10637 if (APF.isInfinity() && !APF.isNegative()) { 10638 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10639 SIInstrFlags::N_INFINITY; 10640 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10641 SIInstrFlags::P_ZERO | 10642 SIInstrFlags::N_NORMAL | 10643 SIInstrFlags::P_NORMAL | 10644 SIInstrFlags::N_SUBNORMAL | 10645 SIInstrFlags::P_SUBNORMAL; 10646 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10647 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10648 DAG.getConstant(Mask, SL, MVT::i32)); 10649 } 10650 } 10651 10652 return SDValue(); 10653 } 10654 10655 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10656 DAGCombinerInfo &DCI) const { 10657 SelectionDAG &DAG = DCI.DAG; 10658 SDLoc SL(N); 10659 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10660 10661 SDValue Src = N->getOperand(0); 10662 SDValue Shift = N->getOperand(0); 10663 10664 // TODO: Extend type shouldn't matter (assuming legal types). 10665 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10666 Shift = Shift.getOperand(0); 10667 10668 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10669 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10670 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10671 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10672 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10673 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10674 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10675 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10676 SDLoc(Shift.getOperand(0)), MVT::i32); 10677 10678 unsigned ShiftOffset = 8 * Offset; 10679 if (Shift.getOpcode() == ISD::SHL) 10680 ShiftOffset -= C->getZExtValue(); 10681 else 10682 ShiftOffset += C->getZExtValue(); 10683 10684 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10685 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10686 MVT::f32, Shift); 10687 } 10688 } 10689 } 10690 10691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10692 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10693 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10694 // We simplified Src. If this node is not dead, visit it again so it is 10695 // folded properly. 10696 if (N->getOpcode() != ISD::DELETED_NODE) 10697 DCI.AddToWorklist(N); 10698 return SDValue(N, 0); 10699 } 10700 10701 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10702 if (SDValue DemandedSrc = 10703 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10704 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10705 10706 return SDValue(); 10707 } 10708 10709 SDValue SITargetLowering::performClampCombine(SDNode *N, 10710 DAGCombinerInfo &DCI) const { 10711 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10712 if (!CSrc) 10713 return SDValue(); 10714 10715 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10716 const APFloat &F = CSrc->getValueAPF(); 10717 APFloat Zero = APFloat::getZero(F.getSemantics()); 10718 if (F < Zero || 10719 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10720 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10721 } 10722 10723 APFloat One(F.getSemantics(), "1.0"); 10724 if (F > One) 10725 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10726 10727 return SDValue(CSrc, 0); 10728 } 10729 10730 10731 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10732 DAGCombinerInfo &DCI) const { 10733 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10734 return SDValue(); 10735 switch (N->getOpcode()) { 10736 case ISD::ADD: 10737 return performAddCombine(N, DCI); 10738 case ISD::SUB: 10739 return performSubCombine(N, DCI); 10740 case ISD::ADDCARRY: 10741 case ISD::SUBCARRY: 10742 return performAddCarrySubCarryCombine(N, DCI); 10743 case ISD::FADD: 10744 return performFAddCombine(N, DCI); 10745 case ISD::FSUB: 10746 return performFSubCombine(N, DCI); 10747 case ISD::SETCC: 10748 return performSetCCCombine(N, DCI); 10749 case ISD::FMAXNUM: 10750 case ISD::FMINNUM: 10751 case ISD::FMAXNUM_IEEE: 10752 case ISD::FMINNUM_IEEE: 10753 case ISD::SMAX: 10754 case ISD::SMIN: 10755 case ISD::UMAX: 10756 case ISD::UMIN: 10757 case AMDGPUISD::FMIN_LEGACY: 10758 case AMDGPUISD::FMAX_LEGACY: 10759 return performMinMaxCombine(N, DCI); 10760 case ISD::FMA: 10761 return performFMACombine(N, DCI); 10762 case ISD::AND: 10763 return performAndCombine(N, DCI); 10764 case ISD::OR: 10765 return performOrCombine(N, DCI); 10766 case ISD::XOR: 10767 return performXorCombine(N, DCI); 10768 case ISD::ZERO_EXTEND: 10769 return performZeroExtendCombine(N, DCI); 10770 case ISD::SIGN_EXTEND_INREG: 10771 return performSignExtendInRegCombine(N , DCI); 10772 case AMDGPUISD::FP_CLASS: 10773 return performClassCombine(N, DCI); 10774 case ISD::FCANONICALIZE: 10775 return performFCanonicalizeCombine(N, DCI); 10776 case AMDGPUISD::RCP: 10777 return performRcpCombine(N, DCI); 10778 case AMDGPUISD::FRACT: 10779 case AMDGPUISD::RSQ: 10780 case AMDGPUISD::RCP_LEGACY: 10781 case AMDGPUISD::RCP_IFLAG: 10782 case AMDGPUISD::RSQ_CLAMP: 10783 case AMDGPUISD::LDEXP: { 10784 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10785 SDValue Src = N->getOperand(0); 10786 if (Src.isUndef()) 10787 return Src; 10788 break; 10789 } 10790 case ISD::SINT_TO_FP: 10791 case ISD::UINT_TO_FP: 10792 return performUCharToFloatCombine(N, DCI); 10793 case AMDGPUISD::CVT_F32_UBYTE0: 10794 case AMDGPUISD::CVT_F32_UBYTE1: 10795 case AMDGPUISD::CVT_F32_UBYTE2: 10796 case AMDGPUISD::CVT_F32_UBYTE3: 10797 return performCvtF32UByteNCombine(N, DCI); 10798 case AMDGPUISD::FMED3: 10799 return performFMed3Combine(N, DCI); 10800 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10801 return performCvtPkRTZCombine(N, DCI); 10802 case AMDGPUISD::CLAMP: 10803 return performClampCombine(N, DCI); 10804 case ISD::SCALAR_TO_VECTOR: { 10805 SelectionDAG &DAG = DCI.DAG; 10806 EVT VT = N->getValueType(0); 10807 10808 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10809 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10810 SDLoc SL(N); 10811 SDValue Src = N->getOperand(0); 10812 EVT EltVT = Src.getValueType(); 10813 if (EltVT == MVT::f16) 10814 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10815 10816 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10817 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10818 } 10819 10820 break; 10821 } 10822 case ISD::EXTRACT_VECTOR_ELT: 10823 return performExtractVectorEltCombine(N, DCI); 10824 case ISD::INSERT_VECTOR_ELT: 10825 return performInsertVectorEltCombine(N, DCI); 10826 case ISD::LOAD: { 10827 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10828 return Widended; 10829 LLVM_FALLTHROUGH; 10830 } 10831 default: { 10832 if (!DCI.isBeforeLegalize()) { 10833 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10834 return performMemSDNodeCombine(MemNode, DCI); 10835 } 10836 10837 break; 10838 } 10839 } 10840 10841 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10842 } 10843 10844 /// Helper function for adjustWritemask 10845 static unsigned SubIdx2Lane(unsigned Idx) { 10846 switch (Idx) { 10847 default: return 0; 10848 case AMDGPU::sub0: return 0; 10849 case AMDGPU::sub1: return 1; 10850 case AMDGPU::sub2: return 2; 10851 case AMDGPU::sub3: return 3; 10852 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10853 } 10854 } 10855 10856 /// Adjust the writemask of MIMG instructions 10857 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10858 SelectionDAG &DAG) const { 10859 unsigned Opcode = Node->getMachineOpcode(); 10860 10861 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10862 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10863 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10864 return Node; // not implemented for D16 10865 10866 SDNode *Users[5] = { nullptr }; 10867 unsigned Lane = 0; 10868 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10869 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10870 unsigned NewDmask = 0; 10871 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10872 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10873 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10874 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10875 unsigned TFCLane = 0; 10876 bool HasChain = Node->getNumValues() > 1; 10877 10878 if (OldDmask == 0) { 10879 // These are folded out, but on the chance it happens don't assert. 10880 return Node; 10881 } 10882 10883 unsigned OldBitsSet = countPopulation(OldDmask); 10884 // Work out which is the TFE/LWE lane if that is enabled. 10885 if (UsesTFC) { 10886 TFCLane = OldBitsSet; 10887 } 10888 10889 // Try to figure out the used register components 10890 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10891 I != E; ++I) { 10892 10893 // Don't look at users of the chain. 10894 if (I.getUse().getResNo() != 0) 10895 continue; 10896 10897 // Abort if we can't understand the usage 10898 if (!I->isMachineOpcode() || 10899 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10900 return Node; 10901 10902 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10903 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10904 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10905 // set, etc. 10906 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10907 10908 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10909 if (UsesTFC && Lane == TFCLane) { 10910 Users[Lane] = *I; 10911 } else { 10912 // Set which texture component corresponds to the lane. 10913 unsigned Comp; 10914 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10915 Comp = countTrailingZeros(Dmask); 10916 Dmask &= ~(1 << Comp); 10917 } 10918 10919 // Abort if we have more than one user per component. 10920 if (Users[Lane]) 10921 return Node; 10922 10923 Users[Lane] = *I; 10924 NewDmask |= 1 << Comp; 10925 } 10926 } 10927 10928 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10929 bool NoChannels = !NewDmask; 10930 if (NoChannels) { 10931 if (!UsesTFC) { 10932 // No uses of the result and not using TFC. Then do nothing. 10933 return Node; 10934 } 10935 // If the original dmask has one channel - then nothing to do 10936 if (OldBitsSet == 1) 10937 return Node; 10938 // Use an arbitrary dmask - required for the instruction to work 10939 NewDmask = 1; 10940 } 10941 // Abort if there's no change 10942 if (NewDmask == OldDmask) 10943 return Node; 10944 10945 unsigned BitsSet = countPopulation(NewDmask); 10946 10947 // Check for TFE or LWE - increase the number of channels by one to account 10948 // for the extra return value 10949 // This will need adjustment for D16 if this is also included in 10950 // adjustWriteMask (this function) but at present D16 are excluded. 10951 unsigned NewChannels = BitsSet + UsesTFC; 10952 10953 int NewOpcode = 10954 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10955 assert(NewOpcode != -1 && 10956 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10957 "failed to find equivalent MIMG op"); 10958 10959 // Adjust the writemask in the node 10960 SmallVector<SDValue, 12> Ops; 10961 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10962 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10963 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10964 10965 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10966 10967 MVT ResultVT = NewChannels == 1 ? 10968 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10969 NewChannels == 5 ? 8 : NewChannels); 10970 SDVTList NewVTList = HasChain ? 10971 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10972 10973 10974 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10975 NewVTList, Ops); 10976 10977 if (HasChain) { 10978 // Update chain. 10979 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10980 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10981 } 10982 10983 if (NewChannels == 1) { 10984 assert(Node->hasNUsesOfValue(1, 0)); 10985 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10986 SDLoc(Node), Users[Lane]->getValueType(0), 10987 SDValue(NewNode, 0)); 10988 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10989 return nullptr; 10990 } 10991 10992 // Update the users of the node with the new indices 10993 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10994 SDNode *User = Users[i]; 10995 if (!User) { 10996 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10997 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10998 if (i || !NoChannels) 10999 continue; 11000 } else { 11001 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11002 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11003 } 11004 11005 switch (Idx) { 11006 default: break; 11007 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11008 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11009 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11010 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11011 } 11012 } 11013 11014 DAG.RemoveDeadNode(Node); 11015 return nullptr; 11016 } 11017 11018 static bool isFrameIndexOp(SDValue Op) { 11019 if (Op.getOpcode() == ISD::AssertZext) 11020 Op = Op.getOperand(0); 11021 11022 return isa<FrameIndexSDNode>(Op); 11023 } 11024 11025 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11026 /// with frame index operands. 11027 /// LLVM assumes that inputs are to these instructions are registers. 11028 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11029 SelectionDAG &DAG) const { 11030 if (Node->getOpcode() == ISD::CopyToReg) { 11031 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11032 SDValue SrcVal = Node->getOperand(2); 11033 11034 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11035 // to try understanding copies to physical registers. 11036 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11037 SDLoc SL(Node); 11038 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11039 SDValue VReg = DAG.getRegister( 11040 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11041 11042 SDNode *Glued = Node->getGluedNode(); 11043 SDValue ToVReg 11044 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11045 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11046 SDValue ToResultReg 11047 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11048 VReg, ToVReg.getValue(1)); 11049 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11050 DAG.RemoveDeadNode(Node); 11051 return ToResultReg.getNode(); 11052 } 11053 } 11054 11055 SmallVector<SDValue, 8> Ops; 11056 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11057 if (!isFrameIndexOp(Node->getOperand(i))) { 11058 Ops.push_back(Node->getOperand(i)); 11059 continue; 11060 } 11061 11062 SDLoc DL(Node); 11063 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11064 Node->getOperand(i).getValueType(), 11065 Node->getOperand(i)), 0)); 11066 } 11067 11068 return DAG.UpdateNodeOperands(Node, Ops); 11069 } 11070 11071 /// Fold the instructions after selecting them. 11072 /// Returns null if users were already updated. 11073 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11074 SelectionDAG &DAG) const { 11075 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11076 unsigned Opcode = Node->getMachineOpcode(); 11077 11078 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11079 !TII->isGather4(Opcode) && 11080 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11081 return adjustWritemask(Node, DAG); 11082 } 11083 11084 if (Opcode == AMDGPU::INSERT_SUBREG || 11085 Opcode == AMDGPU::REG_SEQUENCE) { 11086 legalizeTargetIndependentNode(Node, DAG); 11087 return Node; 11088 } 11089 11090 switch (Opcode) { 11091 case AMDGPU::V_DIV_SCALE_F32: 11092 case AMDGPU::V_DIV_SCALE_F64: { 11093 // Satisfy the operand register constraint when one of the inputs is 11094 // undefined. Ordinarily each undef value will have its own implicit_def of 11095 // a vreg, so force these to use a single register. 11096 SDValue Src0 = Node->getOperand(1); 11097 SDValue Src1 = Node->getOperand(3); 11098 SDValue Src2 = Node->getOperand(5); 11099 11100 if ((Src0.isMachineOpcode() && 11101 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11102 (Src0 == Src1 || Src0 == Src2)) 11103 break; 11104 11105 MVT VT = Src0.getValueType().getSimpleVT(); 11106 const TargetRegisterClass *RC = 11107 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11108 11109 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11110 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11111 11112 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11113 UndefReg, Src0, SDValue()); 11114 11115 // src0 must be the same register as src1 or src2, even if the value is 11116 // undefined, so make sure we don't violate this constraint. 11117 if (Src0.isMachineOpcode() && 11118 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11119 if (Src1.isMachineOpcode() && 11120 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11121 Src0 = Src1; 11122 else if (Src2.isMachineOpcode() && 11123 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11124 Src0 = Src2; 11125 else { 11126 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11127 Src0 = UndefReg; 11128 Src1 = UndefReg; 11129 } 11130 } else 11131 break; 11132 11133 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11134 Ops[1] = Src0; 11135 Ops[3] = Src1; 11136 Ops[5] = Src2; 11137 Ops.push_back(ImpDef.getValue(1)); 11138 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11139 } 11140 default: 11141 break; 11142 } 11143 11144 return Node; 11145 } 11146 11147 /// Assign the register class depending on the number of 11148 /// bits set in the writemask 11149 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11150 SDNode *Node) const { 11151 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11152 11153 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11154 11155 if (TII->isVOP3(MI.getOpcode())) { 11156 // Make sure constant bus requirements are respected. 11157 TII->legalizeOperandsVOP3(MRI, MI); 11158 11159 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11160 // This saves a chain-copy of registers and better ballance register 11161 // use between vgpr and agpr as agpr tuples tend to be big. 11162 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11163 unsigned Opc = MI.getOpcode(); 11164 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11165 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11166 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11167 if (I == -1) 11168 break; 11169 MachineOperand &Op = MI.getOperand(I); 11170 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11171 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11172 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11173 continue; 11174 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11175 if (!Src || !Src->isCopy() || 11176 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11177 continue; 11178 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11179 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11180 // All uses of agpr64 and agpr32 can also accept vgpr except for 11181 // v_accvgpr_read, but we do not produce agpr reads during selection, 11182 // so no use checks are needed. 11183 MRI.setRegClass(Op.getReg(), NewRC); 11184 } 11185 } 11186 11187 return; 11188 } 11189 11190 // Replace unused atomics with the no return version. 11191 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11192 if (NoRetAtomicOp != -1) { 11193 if (!Node->hasAnyUseOfValue(0)) { 11194 int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11195 AMDGPU::OpName::glc1); 11196 if (Glc1Idx != -1) 11197 MI.RemoveOperand(Glc1Idx); 11198 MI.RemoveOperand(0); 11199 MI.setDesc(TII->get(NoRetAtomicOp)); 11200 return; 11201 } 11202 11203 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11204 // instruction, because the return type of these instructions is a vec2 of 11205 // the memory type, so it can be tied to the input operand. 11206 // This means these instructions always have a use, so we need to add a 11207 // special case to check if the atomic has only one extract_subreg use, 11208 // which itself has no uses. 11209 if ((Node->hasNUsesOfValue(1, 0) && 11210 Node->use_begin()->isMachineOpcode() && 11211 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11212 !Node->use_begin()->hasAnyUseOfValue(0))) { 11213 Register Def = MI.getOperand(0).getReg(); 11214 11215 // Change this into a noret atomic. 11216 MI.setDesc(TII->get(NoRetAtomicOp)); 11217 MI.RemoveOperand(0); 11218 11219 // If we only remove the def operand from the atomic instruction, the 11220 // extract_subreg will be left with a use of a vreg without a def. 11221 // So we need to insert an implicit_def to avoid machine verifier 11222 // errors. 11223 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11224 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11225 } 11226 return; 11227 } 11228 } 11229 11230 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11231 uint64_t Val) { 11232 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11233 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11234 } 11235 11236 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11237 const SDLoc &DL, 11238 SDValue Ptr) const { 11239 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11240 11241 // Build the half of the subregister with the constants before building the 11242 // full 128-bit register. If we are building multiple resource descriptors, 11243 // this will allow CSEing of the 2-component register. 11244 const SDValue Ops0[] = { 11245 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11246 buildSMovImm32(DAG, DL, 0), 11247 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11248 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11249 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11250 }; 11251 11252 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11253 MVT::v2i32, Ops0), 0); 11254 11255 // Combine the constants and the pointer. 11256 const SDValue Ops1[] = { 11257 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11258 Ptr, 11259 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11260 SubRegHi, 11261 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11262 }; 11263 11264 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11265 } 11266 11267 /// Return a resource descriptor with the 'Add TID' bit enabled 11268 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11269 /// of the resource descriptor) to create an offset, which is added to 11270 /// the resource pointer. 11271 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11272 SDValue Ptr, uint32_t RsrcDword1, 11273 uint64_t RsrcDword2And3) const { 11274 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11275 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11276 if (RsrcDword1) { 11277 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11278 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11279 0); 11280 } 11281 11282 SDValue DataLo = buildSMovImm32(DAG, DL, 11283 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11284 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11285 11286 const SDValue Ops[] = { 11287 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11288 PtrLo, 11289 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11290 PtrHi, 11291 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11292 DataLo, 11293 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11294 DataHi, 11295 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11296 }; 11297 11298 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11299 } 11300 11301 //===----------------------------------------------------------------------===// 11302 // SI Inline Assembly Support 11303 //===----------------------------------------------------------------------===// 11304 11305 std::pair<unsigned, const TargetRegisterClass *> 11306 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11307 StringRef Constraint, 11308 MVT VT) const { 11309 const TargetRegisterClass *RC = nullptr; 11310 if (Constraint.size() == 1) { 11311 const unsigned BitWidth = VT.getSizeInBits(); 11312 switch (Constraint[0]) { 11313 default: 11314 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11315 case 's': 11316 case 'r': 11317 switch (BitWidth) { 11318 case 16: 11319 RC = &AMDGPU::SReg_32RegClass; 11320 break; 11321 case 64: 11322 RC = &AMDGPU::SGPR_64RegClass; 11323 break; 11324 default: 11325 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11326 if (!RC) 11327 return std::make_pair(0U, nullptr); 11328 break; 11329 } 11330 break; 11331 case 'v': 11332 switch (BitWidth) { 11333 case 16: 11334 RC = &AMDGPU::VGPR_32RegClass; 11335 break; 11336 default: 11337 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11338 if (!RC) 11339 return std::make_pair(0U, nullptr); 11340 break; 11341 } 11342 break; 11343 case 'a': 11344 if (!Subtarget->hasMAIInsts()) 11345 break; 11346 switch (BitWidth) { 11347 case 16: 11348 RC = &AMDGPU::AGPR_32RegClass; 11349 break; 11350 default: 11351 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11352 if (!RC) 11353 return std::make_pair(0U, nullptr); 11354 break; 11355 } 11356 break; 11357 } 11358 // We actually support i128, i16 and f16 as inline parameters 11359 // even if they are not reported as legal 11360 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11361 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11362 return std::make_pair(0U, RC); 11363 } 11364 11365 if (Constraint.size() > 1) { 11366 if (Constraint[1] == 'v') { 11367 RC = &AMDGPU::VGPR_32RegClass; 11368 } else if (Constraint[1] == 's') { 11369 RC = &AMDGPU::SGPR_32RegClass; 11370 } else if (Constraint[1] == 'a') { 11371 RC = &AMDGPU::AGPR_32RegClass; 11372 } 11373 11374 if (RC) { 11375 uint32_t Idx; 11376 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11377 if (!Failed && Idx < RC->getNumRegs()) 11378 return std::make_pair(RC->getRegister(Idx), RC); 11379 } 11380 } 11381 11382 // FIXME: Returns VS_32 for physical SGPR constraints 11383 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11384 } 11385 11386 static bool isImmConstraint(StringRef Constraint) { 11387 if (Constraint.size() == 1) { 11388 switch (Constraint[0]) { 11389 default: break; 11390 case 'I': 11391 case 'J': 11392 case 'A': 11393 case 'B': 11394 case 'C': 11395 return true; 11396 } 11397 } else if (Constraint == "DA" || 11398 Constraint == "DB") { 11399 return true; 11400 } 11401 return false; 11402 } 11403 11404 SITargetLowering::ConstraintType 11405 SITargetLowering::getConstraintType(StringRef Constraint) const { 11406 if (Constraint.size() == 1) { 11407 switch (Constraint[0]) { 11408 default: break; 11409 case 's': 11410 case 'v': 11411 case 'a': 11412 return C_RegisterClass; 11413 } 11414 } 11415 if (isImmConstraint(Constraint)) { 11416 return C_Other; 11417 } 11418 return TargetLowering::getConstraintType(Constraint); 11419 } 11420 11421 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11422 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11423 Val = Val & maskTrailingOnes<uint64_t>(Size); 11424 } 11425 return Val; 11426 } 11427 11428 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11429 std::string &Constraint, 11430 std::vector<SDValue> &Ops, 11431 SelectionDAG &DAG) const { 11432 if (isImmConstraint(Constraint)) { 11433 uint64_t Val; 11434 if (getAsmOperandConstVal(Op, Val) && 11435 checkAsmConstraintVal(Op, Constraint, Val)) { 11436 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11437 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11438 } 11439 } else { 11440 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11441 } 11442 } 11443 11444 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11445 unsigned Size = Op.getScalarValueSizeInBits(); 11446 if (Size > 64) 11447 return false; 11448 11449 if (Size == 16 && !Subtarget->has16BitInsts()) 11450 return false; 11451 11452 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11453 Val = C->getSExtValue(); 11454 return true; 11455 } 11456 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11457 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11458 return true; 11459 } 11460 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11461 if (Size != 16 || Op.getNumOperands() != 2) 11462 return false; 11463 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11464 return false; 11465 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11466 Val = C->getSExtValue(); 11467 return true; 11468 } 11469 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11470 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11471 return true; 11472 } 11473 } 11474 11475 return false; 11476 } 11477 11478 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11479 const std::string &Constraint, 11480 uint64_t Val) const { 11481 if (Constraint.size() == 1) { 11482 switch (Constraint[0]) { 11483 case 'I': 11484 return AMDGPU::isInlinableIntLiteral(Val); 11485 case 'J': 11486 return isInt<16>(Val); 11487 case 'A': 11488 return checkAsmConstraintValA(Op, Val); 11489 case 'B': 11490 return isInt<32>(Val); 11491 case 'C': 11492 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11493 AMDGPU::isInlinableIntLiteral(Val); 11494 default: 11495 break; 11496 } 11497 } else if (Constraint.size() == 2) { 11498 if (Constraint == "DA") { 11499 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11500 int64_t LoBits = static_cast<int32_t>(Val); 11501 return checkAsmConstraintValA(Op, HiBits, 32) && 11502 checkAsmConstraintValA(Op, LoBits, 32); 11503 } 11504 if (Constraint == "DB") { 11505 return true; 11506 } 11507 } 11508 llvm_unreachable("Invalid asm constraint"); 11509 } 11510 11511 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11512 uint64_t Val, 11513 unsigned MaxSize) const { 11514 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11515 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11516 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11517 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11518 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11519 return true; 11520 } 11521 return false; 11522 } 11523 11524 // Figure out which registers should be reserved for stack access. Only after 11525 // the function is legalized do we know all of the non-spill stack objects or if 11526 // calls are present. 11527 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11528 MachineRegisterInfo &MRI = MF.getRegInfo(); 11529 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11530 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11531 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11532 11533 if (Info->isEntryFunction()) { 11534 // Callable functions have fixed registers used for stack access. 11535 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11536 } 11537 11538 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11539 Info->getStackPtrOffsetReg())); 11540 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11541 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11542 11543 // We need to worry about replacing the default register with itself in case 11544 // of MIR testcases missing the MFI. 11545 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11546 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11547 11548 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11549 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11550 11551 Info->limitOccupancy(MF); 11552 11553 if (ST.isWave32() && !MF.empty()) { 11554 // Add VCC_HI def because many instructions marked as imp-use VCC where 11555 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11556 // having a use of undef. 11557 11558 const SIInstrInfo *TII = ST.getInstrInfo(); 11559 DebugLoc DL; 11560 11561 MachineBasicBlock &MBB = MF.front(); 11562 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11563 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11564 11565 for (auto &MBB : MF) { 11566 for (auto &MI : MBB) { 11567 TII->fixImplicitOperands(MI); 11568 } 11569 } 11570 } 11571 11572 TargetLoweringBase::finalizeLowering(MF); 11573 11574 // Allocate a VGPR for future SGPR Spill if 11575 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11576 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11577 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11578 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11579 Info->reserveVGPRforSGPRSpills(MF); 11580 } 11581 11582 void SITargetLowering::computeKnownBitsForFrameIndex( 11583 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11584 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11585 11586 // Set the high bits to zero based on the maximum allowed scratch size per 11587 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11588 // calculation won't overflow, so assume the sign bit is never set. 11589 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11590 } 11591 11592 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11593 KnownBits &Known, unsigned Dim) { 11594 unsigned MaxValue = 11595 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11596 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11597 } 11598 11599 void SITargetLowering::computeKnownBitsForTargetInstr( 11600 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11601 const MachineRegisterInfo &MRI, unsigned Depth) const { 11602 const MachineInstr *MI = MRI.getVRegDef(R); 11603 switch (MI->getOpcode()) { 11604 case AMDGPU::G_INTRINSIC: { 11605 switch (MI->getIntrinsicID()) { 11606 case Intrinsic::amdgcn_workitem_id_x: 11607 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11608 break; 11609 case Intrinsic::amdgcn_workitem_id_y: 11610 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11611 break; 11612 case Intrinsic::amdgcn_workitem_id_z: 11613 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11614 break; 11615 case Intrinsic::amdgcn_mbcnt_lo: 11616 case Intrinsic::amdgcn_mbcnt_hi: { 11617 // These return at most the wavefront size - 1. 11618 unsigned Size = MRI.getType(R).getSizeInBits(); 11619 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11620 break; 11621 } 11622 case Intrinsic::amdgcn_groupstaticsize: { 11623 // We can report everything over the maximum size as 0. We can't report 11624 // based on the actual size because we don't know if it's accurate or not 11625 // at any given point. 11626 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11627 break; 11628 } 11629 } 11630 break; 11631 } 11632 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11633 Known.Zero.setHighBits(24); 11634 break; 11635 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11636 Known.Zero.setHighBits(16); 11637 break; 11638 } 11639 } 11640 11641 Align SITargetLowering::computeKnownAlignForTargetInstr( 11642 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11643 unsigned Depth) const { 11644 const MachineInstr *MI = MRI.getVRegDef(R); 11645 switch (MI->getOpcode()) { 11646 case AMDGPU::G_INTRINSIC: 11647 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11648 // FIXME: Can this move to generic code? What about the case where the call 11649 // site specifies a lower alignment? 11650 Intrinsic::ID IID = MI->getIntrinsicID(); 11651 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11652 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11653 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11654 return *RetAlign; 11655 return Align(1); 11656 } 11657 default: 11658 return Align(1); 11659 } 11660 } 11661 11662 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11663 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11664 const Align CacheLineAlign = Align(64); 11665 11666 // Pre-GFX10 target did not benefit from loop alignment 11667 if (!ML || DisableLoopAlignment || 11668 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11669 getSubtarget()->hasInstFwdPrefetchBug()) 11670 return PrefAlign; 11671 11672 // On GFX10 I$ is 4 x 64 bytes cache lines. 11673 // By default prefetcher keeps one cache line behind and reads two ahead. 11674 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11675 // behind and one ahead. 11676 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11677 // If loop fits 64 bytes it always spans no more than two cache lines and 11678 // does not need an alignment. 11679 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11680 // Else if loop is less or equal 192 bytes we need two lines behind. 11681 11682 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11683 const MachineBasicBlock *Header = ML->getHeader(); 11684 if (Header->getAlignment() != PrefAlign) 11685 return Header->getAlignment(); // Already processed. 11686 11687 unsigned LoopSize = 0; 11688 for (const MachineBasicBlock *MBB : ML->blocks()) { 11689 // If inner loop block is aligned assume in average half of the alignment 11690 // size to be added as nops. 11691 if (MBB != Header) 11692 LoopSize += MBB->getAlignment().value() / 2; 11693 11694 for (const MachineInstr &MI : *MBB) { 11695 LoopSize += TII->getInstSizeInBytes(MI); 11696 if (LoopSize > 192) 11697 return PrefAlign; 11698 } 11699 } 11700 11701 if (LoopSize <= 64) 11702 return PrefAlign; 11703 11704 if (LoopSize <= 128) 11705 return CacheLineAlign; 11706 11707 // If any of parent loops is surrounded by prefetch instructions do not 11708 // insert new for inner loop, which would reset parent's settings. 11709 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11710 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11711 auto I = Exit->getFirstNonDebugInstr(); 11712 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11713 return CacheLineAlign; 11714 } 11715 } 11716 11717 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11718 MachineBasicBlock *Exit = ML->getExitBlock(); 11719 11720 if (Pre && Exit) { 11721 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11722 TII->get(AMDGPU::S_INST_PREFETCH)) 11723 .addImm(1); // prefetch 2 lines behind PC 11724 11725 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11726 TII->get(AMDGPU::S_INST_PREFETCH)) 11727 .addImm(2); // prefetch 1 line behind PC 11728 } 11729 11730 return CacheLineAlign; 11731 } 11732 11733 LLVM_ATTRIBUTE_UNUSED 11734 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11735 assert(N->getOpcode() == ISD::CopyFromReg); 11736 do { 11737 // Follow the chain until we find an INLINEASM node. 11738 N = N->getOperand(0).getNode(); 11739 if (N->getOpcode() == ISD::INLINEASM || 11740 N->getOpcode() == ISD::INLINEASM_BR) 11741 return true; 11742 } while (N->getOpcode() == ISD::CopyFromReg); 11743 return false; 11744 } 11745 11746 bool SITargetLowering::isSDNodeSourceOfDivergence( 11747 const SDNode *N, FunctionLoweringInfo *FLI, 11748 LegacyDivergenceAnalysis *KDA) const { 11749 switch (N->getOpcode()) { 11750 case ISD::CopyFromReg: { 11751 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11752 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11753 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11754 Register Reg = R->getReg(); 11755 11756 // FIXME: Why does this need to consider isLiveIn? 11757 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11758 return !TRI->isSGPRReg(MRI, Reg); 11759 11760 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11761 return KDA->isDivergent(V); 11762 11763 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11764 return !TRI->isSGPRReg(MRI, Reg); 11765 } 11766 case ISD::LOAD: { 11767 const LoadSDNode *L = cast<LoadSDNode>(N); 11768 unsigned AS = L->getAddressSpace(); 11769 // A flat load may access private memory. 11770 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11771 } 11772 case ISD::CALLSEQ_END: 11773 return true; 11774 case ISD::INTRINSIC_WO_CHAIN: 11775 return AMDGPU::isIntrinsicSourceOfDivergence( 11776 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11777 case ISD::INTRINSIC_W_CHAIN: 11778 return AMDGPU::isIntrinsicSourceOfDivergence( 11779 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11780 } 11781 return false; 11782 } 11783 11784 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11785 EVT VT) const { 11786 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11787 case MVT::f32: 11788 return hasFP32Denormals(DAG.getMachineFunction()); 11789 case MVT::f64: 11790 case MVT::f16: 11791 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11792 default: 11793 return false; 11794 } 11795 } 11796 11797 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11798 const SelectionDAG &DAG, 11799 bool SNaN, 11800 unsigned Depth) const { 11801 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11802 const MachineFunction &MF = DAG.getMachineFunction(); 11803 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11804 11805 if (Info->getMode().DX10Clamp) 11806 return true; // Clamped to 0. 11807 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11808 } 11809 11810 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11811 SNaN, Depth); 11812 } 11813 11814 // Global FP atomic instructions have a hardcoded FP mode and do not support 11815 // FP32 denormals, and only support v2f16 denormals. 11816 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11817 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11818 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11819 if (&Flt == &APFloat::IEEEsingle()) 11820 return DenormMode == DenormalMode::getPreserveSign(); 11821 return DenormMode == DenormalMode::getIEEE(); 11822 } 11823 11824 TargetLowering::AtomicExpansionKind 11825 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11826 switch (RMW->getOperation()) { 11827 case AtomicRMWInst::FAdd: { 11828 Type *Ty = RMW->getType(); 11829 11830 // We don't have a way to support 16-bit atomics now, so just leave them 11831 // as-is. 11832 if (Ty->isHalfTy()) 11833 return AtomicExpansionKind::None; 11834 11835 if (!Ty->isFloatTy()) 11836 return AtomicExpansionKind::CmpXChg; 11837 11838 // TODO: Do have these for flat. Older targets also had them for buffers. 11839 unsigned AS = RMW->getPointerAddressSpace(); 11840 11841 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11842 if (!fpModeMatchesGlobalFPAtomicMode(RMW)) 11843 return AtomicExpansionKind::CmpXChg; 11844 11845 return RMW->use_empty() ? AtomicExpansionKind::None : 11846 AtomicExpansionKind::CmpXChg; 11847 } 11848 11849 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11850 // to round-to-nearest-even. 11851 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11852 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11853 } 11854 default: 11855 break; 11856 } 11857 11858 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11859 } 11860 11861 const TargetRegisterClass * 11862 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11863 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11864 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11865 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11866 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11867 : &AMDGPU::SReg_32RegClass; 11868 if (!TRI->isSGPRClass(RC) && !isDivergent) 11869 return TRI->getEquivalentSGPRClass(RC); 11870 else if (TRI->isSGPRClass(RC) && isDivergent) 11871 return TRI->getEquivalentVGPRClass(RC); 11872 11873 return RC; 11874 } 11875 11876 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11877 // uniform values (as produced by the mask results of control flow intrinsics) 11878 // used outside of divergent blocks. The phi users need to also be treated as 11879 // always uniform. 11880 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11881 unsigned WaveSize) { 11882 // FIXME: We asssume we never cast the mask results of a control flow 11883 // intrinsic. 11884 // Early exit if the type won't be consistent as a compile time hack. 11885 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11886 if (!IT || IT->getBitWidth() != WaveSize) 11887 return false; 11888 11889 if (!isa<Instruction>(V)) 11890 return false; 11891 if (!Visited.insert(V).second) 11892 return false; 11893 bool Result = false; 11894 for (auto U : V->users()) { 11895 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11896 if (V == U->getOperand(1)) { 11897 switch (Intrinsic->getIntrinsicID()) { 11898 default: 11899 Result = false; 11900 break; 11901 case Intrinsic::amdgcn_if_break: 11902 case Intrinsic::amdgcn_if: 11903 case Intrinsic::amdgcn_else: 11904 Result = true; 11905 break; 11906 } 11907 } 11908 if (V == U->getOperand(0)) { 11909 switch (Intrinsic->getIntrinsicID()) { 11910 default: 11911 Result = false; 11912 break; 11913 case Intrinsic::amdgcn_end_cf: 11914 case Intrinsic::amdgcn_loop: 11915 Result = true; 11916 break; 11917 } 11918 } 11919 } else { 11920 Result = hasCFUser(U, Visited, WaveSize); 11921 } 11922 if (Result) 11923 break; 11924 } 11925 return Result; 11926 } 11927 11928 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11929 const Value *V) const { 11930 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11931 if (CI->isInlineAsm()) { 11932 // FIXME: This cannot give a correct answer. This should only trigger in 11933 // the case where inline asm returns mixed SGPR and VGPR results, used 11934 // outside the defining block. We don't have a specific result to 11935 // consider, so this assumes if any value is SGPR, the overall register 11936 // also needs to be SGPR. 11937 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11938 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11939 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11940 for (auto &TC : TargetConstraints) { 11941 if (TC.Type == InlineAsm::isOutput) { 11942 ComputeConstraintToUse(TC, SDValue()); 11943 unsigned AssignedReg; 11944 const TargetRegisterClass *RC; 11945 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11946 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11947 if (RC) { 11948 MachineRegisterInfo &MRI = MF.getRegInfo(); 11949 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11950 return true; 11951 else if (SIRI->isSGPRClass(RC)) 11952 return true; 11953 } 11954 } 11955 } 11956 } 11957 } 11958 SmallPtrSet<const Value *, 16> Visited; 11959 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11960 } 11961 11962 std::pair<int, MVT> 11963 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11964 Type *Ty) const { 11965 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11966 auto Size = DL.getTypeSizeInBits(Ty); 11967 // Maximum load or store can handle 8 dwords for scalar and 4 for 11968 // vector ALU. Let's assume anything above 8 dwords is expensive 11969 // even if legal. 11970 if (Size <= 256) 11971 return Cost; 11972 11973 Cost.first = (Size + 255) / 256; 11974 return Cost; 11975 } 11976