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 (!isUInt<12>(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->hasUnalignedDSAccessEnabled() && 1437 !Subtarget->hasLDSMisalignedBug()) { 1438 if (IsFast) 1439 *IsFast = Alignment != Align(2); 1440 return true; 1441 } 1442 1443 if (Size == 64) { 1444 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1445 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1446 // with adjacent offsets. 1447 bool AlignedBy4 = Alignment >= Align(4); 1448 if (IsFast) 1449 *IsFast = AlignedBy4; 1450 1451 return AlignedBy4; 1452 } 1453 if (Size == 96) { 1454 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1455 bool Aligned = Alignment >= Align(16); 1456 if (IsFast) 1457 *IsFast = Aligned; 1458 1459 return Aligned; 1460 } 1461 if (Size == 128) { 1462 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1463 // can do a 8 byte aligned, 16 byte access in a single operation using 1464 // ds_read2/write2_b64. 1465 bool Aligned = Alignment >= Align(8); 1466 if (IsFast) 1467 *IsFast = Aligned; 1468 1469 return Aligned; 1470 } 1471 } 1472 1473 // FIXME: We have to be conservative here and assume that flat operations 1474 // will access scratch. If we had access to the IR function, then we 1475 // could determine if any private memory was used in the function. 1476 if (!Subtarget->hasUnalignedScratchAccess() && 1477 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1478 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1479 bool AlignedBy4 = Alignment >= Align(4); 1480 if (IsFast) 1481 *IsFast = AlignedBy4; 1482 1483 return AlignedBy4; 1484 } 1485 1486 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1487 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1488 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1489 // If we have an uniform constant load, it still requires using a slow 1490 // buffer instruction if unaligned. 1491 if (IsFast) { 1492 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1493 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1494 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1495 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1496 Alignment >= Align(4) : Alignment != Align(2); 1497 } 1498 1499 return true; 1500 } 1501 1502 // Smaller than dword value must be aligned. 1503 if (Size < 32) 1504 return false; 1505 1506 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1507 // byte-address are ignored, thus forcing Dword alignment. 1508 // This applies to private, global, and constant memory. 1509 if (IsFast) 1510 *IsFast = true; 1511 1512 return Size >= 32 && Alignment >= Align(4); 1513 } 1514 1515 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1516 EVT VT, unsigned AddrSpace, unsigned Alignment, 1517 MachineMemOperand::Flags Flags, bool *IsFast) const { 1518 if (IsFast) 1519 *IsFast = false; 1520 1521 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1522 // which isn't a simple VT. 1523 // Until MVT is extended to handle this, simply check for the size and 1524 // rely on the condition below: allow accesses if the size is a multiple of 4. 1525 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1526 VT.getStoreSize() > 16)) { 1527 return false; 1528 } 1529 1530 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1531 Align(Alignment), Flags, IsFast); 1532 } 1533 1534 EVT SITargetLowering::getOptimalMemOpType( 1535 const MemOp &Op, const AttributeList &FuncAttributes) const { 1536 // FIXME: Should account for address space here. 1537 1538 // The default fallback uses the private pointer size as a guess for a type to 1539 // use. Make sure we switch these to 64-bit accesses. 1540 1541 if (Op.size() >= 16 && 1542 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1543 return MVT::v4i32; 1544 1545 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1546 return MVT::v2i32; 1547 1548 // Use the default. 1549 return MVT::Other; 1550 } 1551 1552 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1553 const MemSDNode *MemNode = cast<MemSDNode>(N); 1554 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1555 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1556 return I && I->getMetadata("amdgpu.noclobber"); 1557 } 1558 1559 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1560 unsigned DestAS) const { 1561 // Flat -> private/local is a simple truncate. 1562 // Flat -> global is no-op 1563 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1564 return true; 1565 1566 const GCNTargetMachine &TM = 1567 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1568 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1569 } 1570 1571 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1572 const MemSDNode *MemNode = cast<MemSDNode>(N); 1573 1574 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1575 } 1576 1577 TargetLoweringBase::LegalizeTypeAction 1578 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1579 int NumElts = VT.getVectorNumElements(); 1580 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1581 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1582 return TargetLoweringBase::getPreferredVectorAction(VT); 1583 } 1584 1585 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1586 Type *Ty) const { 1587 // FIXME: Could be smarter if called for vector constants. 1588 return true; 1589 } 1590 1591 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1592 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1593 switch (Op) { 1594 case ISD::LOAD: 1595 case ISD::STORE: 1596 1597 // These operations are done with 32-bit instructions anyway. 1598 case ISD::AND: 1599 case ISD::OR: 1600 case ISD::XOR: 1601 case ISD::SELECT: 1602 // TODO: Extensions? 1603 return true; 1604 default: 1605 return false; 1606 } 1607 } 1608 1609 // SimplifySetCC uses this function to determine whether or not it should 1610 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1611 if (VT == MVT::i1 && Op == ISD::SETCC) 1612 return false; 1613 1614 return TargetLowering::isTypeDesirableForOp(Op, VT); 1615 } 1616 1617 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1618 const SDLoc &SL, 1619 SDValue Chain, 1620 uint64_t Offset) const { 1621 const DataLayout &DL = DAG.getDataLayout(); 1622 MachineFunction &MF = DAG.getMachineFunction(); 1623 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1624 1625 const ArgDescriptor *InputPtrReg; 1626 const TargetRegisterClass *RC; 1627 LLT ArgTy; 1628 1629 std::tie(InputPtrReg, RC, ArgTy) = 1630 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1631 1632 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1633 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1634 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1635 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1636 1637 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1638 } 1639 1640 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1641 const SDLoc &SL) const { 1642 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1643 FIRST_IMPLICIT); 1644 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1645 } 1646 1647 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1648 const SDLoc &SL, SDValue Val, 1649 bool Signed, 1650 const ISD::InputArg *Arg) const { 1651 // First, if it is a widened vector, narrow it. 1652 if (VT.isVector() && 1653 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1654 EVT NarrowedVT = 1655 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1656 VT.getVectorNumElements()); 1657 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1658 DAG.getConstant(0, SL, MVT::i32)); 1659 } 1660 1661 // Then convert the vector elements or scalar value. 1662 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1663 VT.bitsLT(MemVT)) { 1664 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1665 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1666 } 1667 1668 if (MemVT.isFloatingPoint()) 1669 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1670 else if (Signed) 1671 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1672 else 1673 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1674 1675 return Val; 1676 } 1677 1678 SDValue SITargetLowering::lowerKernargMemParameter( 1679 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1680 uint64_t Offset, Align Alignment, bool Signed, 1681 const ISD::InputArg *Arg) const { 1682 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1683 1684 // Try to avoid using an extload by loading earlier than the argument address, 1685 // and extracting the relevant bits. The load should hopefully be merged with 1686 // the previous argument. 1687 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1688 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1689 int64_t AlignDownOffset = alignDown(Offset, 4); 1690 int64_t OffsetDiff = Offset - AlignDownOffset; 1691 1692 EVT IntVT = MemVT.changeTypeToInteger(); 1693 1694 // TODO: If we passed in the base kernel offset we could have a better 1695 // alignment than 4, but we don't really need it. 1696 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1697 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1698 MachineMemOperand::MODereferenceable | 1699 MachineMemOperand::MOInvariant); 1700 1701 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1702 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1703 1704 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1705 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1706 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1707 1708 1709 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1710 } 1711 1712 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1713 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1714 MachineMemOperand::MODereferenceable | 1715 MachineMemOperand::MOInvariant); 1716 1717 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1718 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1719 } 1720 1721 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1722 const SDLoc &SL, SDValue Chain, 1723 const ISD::InputArg &Arg) const { 1724 MachineFunction &MF = DAG.getMachineFunction(); 1725 MachineFrameInfo &MFI = MF.getFrameInfo(); 1726 1727 if (Arg.Flags.isByVal()) { 1728 unsigned Size = Arg.Flags.getByValSize(); 1729 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1730 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1731 } 1732 1733 unsigned ArgOffset = VA.getLocMemOffset(); 1734 unsigned ArgSize = VA.getValVT().getStoreSize(); 1735 1736 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1737 1738 // Create load nodes to retrieve arguments from the stack. 1739 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1740 SDValue ArgValue; 1741 1742 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1743 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1744 MVT MemVT = VA.getValVT(); 1745 1746 switch (VA.getLocInfo()) { 1747 default: 1748 break; 1749 case CCValAssign::BCvt: 1750 MemVT = VA.getLocVT(); 1751 break; 1752 case CCValAssign::SExt: 1753 ExtType = ISD::SEXTLOAD; 1754 break; 1755 case CCValAssign::ZExt: 1756 ExtType = ISD::ZEXTLOAD; 1757 break; 1758 case CCValAssign::AExt: 1759 ExtType = ISD::EXTLOAD; 1760 break; 1761 } 1762 1763 ArgValue = DAG.getExtLoad( 1764 ExtType, SL, VA.getLocVT(), Chain, FIN, 1765 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1766 MemVT); 1767 return ArgValue; 1768 } 1769 1770 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1771 const SIMachineFunctionInfo &MFI, 1772 EVT VT, 1773 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1774 const ArgDescriptor *Reg; 1775 const TargetRegisterClass *RC; 1776 LLT Ty; 1777 1778 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1779 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1780 } 1781 1782 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1783 CallingConv::ID CallConv, 1784 ArrayRef<ISD::InputArg> Ins, 1785 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 (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2121 // If we have stack objects, we unquestionably need the private buffer 2122 // resource. For the Code Object V2 ABI, this will be the first 4 user 2123 // SGPR inputs. We can reserve those and use them directly. 2124 2125 Register PrivateSegmentBufferReg = 2126 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2127 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2128 } else { 2129 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2130 // We tentatively reserve the last registers (skipping the last registers 2131 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2132 // we'll replace these with the ones immediately after those which were 2133 // really allocated. In the prologue copies will be inserted from the 2134 // argument to these reserved registers. 2135 2136 // Without HSA, relocations are used for the scratch pointer and the 2137 // buffer resource setup is always inserted in the prologue. Scratch wave 2138 // offset is still in an input SGPR. 2139 Info.setScratchRSrcReg(ReservedBufferReg); 2140 } 2141 2142 MachineRegisterInfo &MRI = MF.getRegInfo(); 2143 2144 // For entry functions we have to set up the stack pointer if we use it, 2145 // whereas non-entry functions get this "for free". This means there is no 2146 // intrinsic advantage to using S32 over S34 in cases where we do not have 2147 // calls but do need a frame pointer (i.e. if we are requested to have one 2148 // because frame pointer elimination is disabled). To keep things simple we 2149 // only ever use S32 as the call ABI stack pointer, and so using it does not 2150 // imply we need a separate frame pointer. 2151 // 2152 // Try to use s32 as the SP, but move it if it would interfere with input 2153 // arguments. This won't work with calls though. 2154 // 2155 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2156 // registers. 2157 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2158 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2159 } else { 2160 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2161 2162 if (MFI.hasCalls()) 2163 report_fatal_error("call in graphics shader with too many input SGPRs"); 2164 2165 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2166 if (!MRI.isLiveIn(Reg)) { 2167 Info.setStackPtrOffsetReg(Reg); 2168 break; 2169 } 2170 } 2171 2172 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2173 report_fatal_error("failed to find register for SP"); 2174 } 2175 2176 // hasFP should be accurate for entry functions even before the frame is 2177 // finalized, because it does not rely on the known stack size, only 2178 // properties like whether variable sized objects are present. 2179 if (ST.getFrameLowering()->hasFP(MF)) { 2180 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2181 } 2182 } 2183 2184 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2185 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2186 return !Info->isEntryFunction(); 2187 } 2188 2189 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2190 2191 } 2192 2193 void SITargetLowering::insertCopiesSplitCSR( 2194 MachineBasicBlock *Entry, 2195 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2196 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2197 2198 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2199 if (!IStart) 2200 return; 2201 2202 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2203 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2204 MachineBasicBlock::iterator MBBI = Entry->begin(); 2205 for (const MCPhysReg *I = IStart; *I; ++I) { 2206 const TargetRegisterClass *RC = nullptr; 2207 if (AMDGPU::SReg_64RegClass.contains(*I)) 2208 RC = &AMDGPU::SGPR_64RegClass; 2209 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2210 RC = &AMDGPU::SGPR_32RegClass; 2211 else 2212 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2213 2214 Register NewVR = MRI->createVirtualRegister(RC); 2215 // Create copy from CSR to a virtual register. 2216 Entry->addLiveIn(*I); 2217 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2218 .addReg(*I); 2219 2220 // Insert the copy-back instructions right before the terminator. 2221 for (auto *Exit : Exits) 2222 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2223 TII->get(TargetOpcode::COPY), *I) 2224 .addReg(NewVR); 2225 } 2226 } 2227 2228 SDValue SITargetLowering::LowerFormalArguments( 2229 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2230 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2231 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2232 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2233 2234 MachineFunction &MF = DAG.getMachineFunction(); 2235 const Function &Fn = MF.getFunction(); 2236 FunctionType *FType = MF.getFunction().getFunctionType(); 2237 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2238 2239 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2240 DiagnosticInfoUnsupported NoGraphicsHSA( 2241 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2242 DAG.getContext()->diagnose(NoGraphicsHSA); 2243 return DAG.getEntryNode(); 2244 } 2245 2246 SmallVector<ISD::InputArg, 16> Splits; 2247 SmallVector<CCValAssign, 16> ArgLocs; 2248 BitVector Skipped(Ins.size()); 2249 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2250 *DAG.getContext()); 2251 2252 bool IsShader = AMDGPU::isShader(CallConv); 2253 bool IsKernel = AMDGPU::isKernel(CallConv); 2254 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2255 2256 if (IsShader) { 2257 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2258 2259 // At least one interpolation mode must be enabled or else the GPU will 2260 // hang. 2261 // 2262 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2263 // set PSInputAddr, the user wants to enable some bits after the compilation 2264 // based on run-time states. Since we can't know what the final PSInputEna 2265 // will look like, so we shouldn't do anything here and the user should take 2266 // responsibility for the correct programming. 2267 // 2268 // Otherwise, the following restrictions apply: 2269 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2270 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2271 // enabled too. 2272 if (CallConv == CallingConv::AMDGPU_PS) { 2273 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2274 ((Info->getPSInputAddr() & 0xF) == 0 && 2275 Info->isPSInputAllocated(11))) { 2276 CCInfo.AllocateReg(AMDGPU::VGPR0); 2277 CCInfo.AllocateReg(AMDGPU::VGPR1); 2278 Info->markPSInputAllocated(0); 2279 Info->markPSInputEnabled(0); 2280 } 2281 if (Subtarget->isAmdPalOS()) { 2282 // For isAmdPalOS, the user does not enable some bits after compilation 2283 // based on run-time states; the register values being generated here are 2284 // the final ones set in hardware. Therefore we need to apply the 2285 // workaround to PSInputAddr and PSInputEnable together. (The case where 2286 // a bit is set in PSInputAddr but not PSInputEnable is where the 2287 // frontend set up an input arg for a particular interpolation mode, but 2288 // nothing uses that input arg. Really we should have an earlier pass 2289 // that removes such an arg.) 2290 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2291 if ((PsInputBits & 0x7F) == 0 || 2292 ((PsInputBits & 0xF) == 0 && 2293 (PsInputBits >> 11 & 1))) 2294 Info->markPSInputEnabled( 2295 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2296 } 2297 } 2298 2299 assert(!Info->hasDispatchPtr() && 2300 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2301 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2302 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2303 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2304 !Info->hasWorkItemIDZ()); 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, IsShader); 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()) { 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(MF.getFunction().getCallingConv())) { 2945 // Note the issue is with the CC of the calling function, not of the call 2946 // itself. 2947 return lowerUnhandledCall(CLI, InVals, 2948 "unsupported call from graphics shader of function "); 2949 } 2950 2951 if (IsTailCall) { 2952 IsTailCall = isEligibleForTailCallOptimization( 2953 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2954 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2955 report_fatal_error("failed to perform tail call elimination on a call " 2956 "site marked musttail"); 2957 } 2958 2959 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2960 2961 // A sibling call is one where we're under the usual C ABI and not planning 2962 // to change that but can still do a tail call: 2963 if (!TailCallOpt && IsTailCall) 2964 IsSibCall = true; 2965 2966 if (IsTailCall) 2967 ++NumTailCalls; 2968 } 2969 2970 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2971 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2972 SmallVector<SDValue, 8> MemOpChains; 2973 2974 // Analyze operands of the call, assigning locations to each operand. 2975 SmallVector<CCValAssign, 16> ArgLocs; 2976 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2977 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2978 2979 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2980 // With a fixed ABI, allocate fixed registers before user arguments. 2981 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2982 } 2983 2984 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2985 2986 // Get a count of how many bytes are to be pushed on the stack. 2987 unsigned NumBytes = CCInfo.getNextStackOffset(); 2988 2989 if (IsSibCall) { 2990 // Since we're not changing the ABI to make this a tail call, the memory 2991 // operands are already available in the caller's incoming argument space. 2992 NumBytes = 0; 2993 } 2994 2995 // FPDiff is the byte offset of the call's argument area from the callee's. 2996 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2997 // by this amount for a tail call. In a sibling call it must be 0 because the 2998 // caller will deallocate the entire stack and the callee still expects its 2999 // arguments to begin at SP+0. Completely unused for non-tail calls. 3000 int32_t FPDiff = 0; 3001 MachineFrameInfo &MFI = MF.getFrameInfo(); 3002 3003 // Adjust the stack pointer for the new arguments... 3004 // These operations are automatically eliminated by the prolog/epilog pass 3005 if (!IsSibCall) { 3006 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3007 3008 SmallVector<SDValue, 4> CopyFromChains; 3009 3010 // In the HSA case, this should be an identity copy. 3011 SDValue ScratchRSrcReg 3012 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3013 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3014 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3015 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3016 } 3017 3018 MVT PtrVT = MVT::i32; 3019 3020 // Walk the register/memloc assignments, inserting copies/loads. 3021 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3022 CCValAssign &VA = ArgLocs[i]; 3023 SDValue Arg = OutVals[i]; 3024 3025 // Promote the value if needed. 3026 switch (VA.getLocInfo()) { 3027 case CCValAssign::Full: 3028 break; 3029 case CCValAssign::BCvt: 3030 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3031 break; 3032 case CCValAssign::ZExt: 3033 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3034 break; 3035 case CCValAssign::SExt: 3036 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3037 break; 3038 case CCValAssign::AExt: 3039 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3040 break; 3041 case CCValAssign::FPExt: 3042 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3043 break; 3044 default: 3045 llvm_unreachable("Unknown loc info!"); 3046 } 3047 3048 if (VA.isRegLoc()) { 3049 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3050 } else { 3051 assert(VA.isMemLoc()); 3052 3053 SDValue DstAddr; 3054 MachinePointerInfo DstInfo; 3055 3056 unsigned LocMemOffset = VA.getLocMemOffset(); 3057 int32_t Offset = LocMemOffset; 3058 3059 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3060 MaybeAlign Alignment; 3061 3062 if (IsTailCall) { 3063 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3064 unsigned OpSize = Flags.isByVal() ? 3065 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3066 3067 // FIXME: We can have better than the minimum byval required alignment. 3068 Alignment = 3069 Flags.isByVal() 3070 ? Flags.getNonZeroByValAlign() 3071 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3072 3073 Offset = Offset + FPDiff; 3074 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3075 3076 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3077 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3078 3079 // Make sure any stack arguments overlapping with where we're storing 3080 // are loaded before this eventual operation. Otherwise they'll be 3081 // clobbered. 3082 3083 // FIXME: Why is this really necessary? This seems to just result in a 3084 // lot of code to copy the stack and write them back to the same 3085 // locations, which are supposed to be immutable? 3086 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3087 } else { 3088 DstAddr = PtrOff; 3089 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3090 Alignment = 3091 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3092 } 3093 3094 if (Outs[i].Flags.isByVal()) { 3095 SDValue SizeNode = 3096 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3097 SDValue Cpy = 3098 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3099 Outs[i].Flags.getNonZeroByValAlign(), 3100 /*isVol = */ false, /*AlwaysInline = */ true, 3101 /*isTailCall = */ false, DstInfo, 3102 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3103 3104 MemOpChains.push_back(Cpy); 3105 } else { 3106 SDValue Store = 3107 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3108 MemOpChains.push_back(Store); 3109 } 3110 } 3111 } 3112 3113 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3114 // Copy special input registers after user input arguments. 3115 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3116 } 3117 3118 if (!MemOpChains.empty()) 3119 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3120 3121 // Build a sequence of copy-to-reg nodes chained together with token chain 3122 // and flag operands which copy the outgoing args into the appropriate regs. 3123 SDValue InFlag; 3124 for (auto &RegToPass : RegsToPass) { 3125 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3126 RegToPass.second, InFlag); 3127 InFlag = Chain.getValue(1); 3128 } 3129 3130 3131 SDValue PhysReturnAddrReg; 3132 if (IsTailCall) { 3133 // Since the return is being combined with the call, we need to pass on the 3134 // return address. 3135 3136 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3137 SDValue ReturnAddrReg = CreateLiveInRegister( 3138 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3139 3140 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3141 MVT::i64); 3142 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3143 InFlag = Chain.getValue(1); 3144 } 3145 3146 // We don't usually want to end the call-sequence here because we would tidy 3147 // the frame up *after* the call, however in the ABI-changing tail-call case 3148 // we've carefully laid out the parameters so that when sp is reset they'll be 3149 // in the correct location. 3150 if (IsTailCall && !IsSibCall) { 3151 Chain = DAG.getCALLSEQ_END(Chain, 3152 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3153 DAG.getTargetConstant(0, DL, MVT::i32), 3154 InFlag, DL); 3155 InFlag = Chain.getValue(1); 3156 } 3157 3158 std::vector<SDValue> Ops; 3159 Ops.push_back(Chain); 3160 Ops.push_back(Callee); 3161 // Add a redundant copy of the callee global which will not be legalized, as 3162 // we need direct access to the callee later. 3163 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3164 const GlobalValue *GV = GSD->getGlobal(); 3165 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3166 } else { 3167 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3168 } 3169 3170 if (IsTailCall) { 3171 // Each tail call may have to adjust the stack by a different amount, so 3172 // this information must travel along with the operation for eventual 3173 // consumption by emitEpilogue. 3174 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3175 3176 Ops.push_back(PhysReturnAddrReg); 3177 } 3178 3179 // Add argument registers to the end of the list so that they are known live 3180 // into the call. 3181 for (auto &RegToPass : RegsToPass) { 3182 Ops.push_back(DAG.getRegister(RegToPass.first, 3183 RegToPass.second.getValueType())); 3184 } 3185 3186 // Add a register mask operand representing the call-preserved registers. 3187 3188 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3189 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3190 assert(Mask && "Missing call preserved mask for calling convention"); 3191 Ops.push_back(DAG.getRegisterMask(Mask)); 3192 3193 if (InFlag.getNode()) 3194 Ops.push_back(InFlag); 3195 3196 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3197 3198 // If we're doing a tall call, use a TC_RETURN here rather than an 3199 // actual call instruction. 3200 if (IsTailCall) { 3201 MFI.setHasTailCall(); 3202 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3203 } 3204 3205 // Returns a chain and a flag for retval copy to use. 3206 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3207 Chain = Call.getValue(0); 3208 InFlag = Call.getValue(1); 3209 3210 uint64_t CalleePopBytes = NumBytes; 3211 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3212 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3213 InFlag, DL); 3214 if (!Ins.empty()) 3215 InFlag = Chain.getValue(1); 3216 3217 // Handle result values, copying them out of physregs into vregs that we 3218 // return. 3219 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3220 InVals, IsThisReturn, 3221 IsThisReturn ? OutVals[0] : SDValue()); 3222 } 3223 3224 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3225 // except for applying the wave size scale to the increment amount. 3226 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3227 SDValue Op, SelectionDAG &DAG) const { 3228 const MachineFunction &MF = DAG.getMachineFunction(); 3229 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3230 3231 SDLoc dl(Op); 3232 EVT VT = Op.getValueType(); 3233 SDValue Tmp1 = Op; 3234 SDValue Tmp2 = Op.getValue(1); 3235 SDValue Tmp3 = Op.getOperand(2); 3236 SDValue Chain = Tmp1.getOperand(0); 3237 3238 Register SPReg = Info->getStackPtrOffsetReg(); 3239 3240 // Chain the dynamic stack allocation so that it doesn't modify the stack 3241 // pointer when other instructions are using the stack. 3242 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3243 3244 SDValue Size = Tmp2.getOperand(1); 3245 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3246 Chain = SP.getValue(1); 3247 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3248 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3249 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3250 unsigned Opc = 3251 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3252 ISD::ADD : ISD::SUB; 3253 3254 SDValue ScaledSize = DAG.getNode( 3255 ISD::SHL, dl, VT, Size, 3256 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3257 3258 Align StackAlign = TFL->getStackAlign(); 3259 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3260 if (Alignment && *Alignment > StackAlign) { 3261 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3262 DAG.getConstant(-(uint64_t)Alignment->value() 3263 << ST.getWavefrontSizeLog2(), 3264 dl, VT)); 3265 } 3266 3267 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3268 Tmp2 = DAG.getCALLSEQ_END( 3269 Chain, DAG.getIntPtrConstant(0, dl, true), 3270 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3271 3272 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3273 } 3274 3275 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3276 SelectionDAG &DAG) const { 3277 // We only handle constant sizes here to allow non-entry block, static sized 3278 // allocas. A truly dynamic value is more difficult to support because we 3279 // don't know if the size value is uniform or not. If the size isn't uniform, 3280 // we would need to do a wave reduction to get the maximum size to know how 3281 // much to increment the uniform stack pointer. 3282 SDValue Size = Op.getOperand(1); 3283 if (isa<ConstantSDNode>(Size)) 3284 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3285 3286 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3287 } 3288 3289 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3290 const MachineFunction &MF) const { 3291 Register Reg = StringSwitch<Register>(RegName) 3292 .Case("m0", AMDGPU::M0) 3293 .Case("exec", AMDGPU::EXEC) 3294 .Case("exec_lo", AMDGPU::EXEC_LO) 3295 .Case("exec_hi", AMDGPU::EXEC_HI) 3296 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3297 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3298 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3299 .Default(Register()); 3300 3301 if (Reg == AMDGPU::NoRegister) { 3302 report_fatal_error(Twine("invalid register name \"" 3303 + StringRef(RegName) + "\".")); 3304 3305 } 3306 3307 if (!Subtarget->hasFlatScrRegister() && 3308 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3309 report_fatal_error(Twine("invalid register \"" 3310 + StringRef(RegName) + "\" for subtarget.")); 3311 } 3312 3313 switch (Reg) { 3314 case AMDGPU::M0: 3315 case AMDGPU::EXEC_LO: 3316 case AMDGPU::EXEC_HI: 3317 case AMDGPU::FLAT_SCR_LO: 3318 case AMDGPU::FLAT_SCR_HI: 3319 if (VT.getSizeInBits() == 32) 3320 return Reg; 3321 break; 3322 case AMDGPU::EXEC: 3323 case AMDGPU::FLAT_SCR: 3324 if (VT.getSizeInBits() == 64) 3325 return Reg; 3326 break; 3327 default: 3328 llvm_unreachable("missing register type checking"); 3329 } 3330 3331 report_fatal_error(Twine("invalid type for register \"" 3332 + StringRef(RegName) + "\".")); 3333 } 3334 3335 // If kill is not the last instruction, split the block so kill is always a 3336 // proper terminator. 3337 MachineBasicBlock * 3338 SITargetLowering::splitKillBlock(MachineInstr &MI, 3339 MachineBasicBlock *BB) const { 3340 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3341 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3342 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3343 return SplitBB; 3344 } 3345 3346 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3347 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3348 // be the first instruction in the remainder block. 3349 // 3350 /// \returns { LoopBody, Remainder } 3351 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3352 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3353 MachineFunction *MF = MBB.getParent(); 3354 MachineBasicBlock::iterator I(&MI); 3355 3356 // To insert the loop we need to split the block. Move everything after this 3357 // point to a new block, and insert a new empty block between the two. 3358 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3359 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3360 MachineFunction::iterator MBBI(MBB); 3361 ++MBBI; 3362 3363 MF->insert(MBBI, LoopBB); 3364 MF->insert(MBBI, RemainderBB); 3365 3366 LoopBB->addSuccessor(LoopBB); 3367 LoopBB->addSuccessor(RemainderBB); 3368 3369 // Move the rest of the block into a new block. 3370 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3371 3372 if (InstInLoop) { 3373 auto Next = std::next(I); 3374 3375 // Move instruction to loop body. 3376 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3377 3378 // Move the rest of the block. 3379 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3380 } else { 3381 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3382 } 3383 3384 MBB.addSuccessor(LoopBB); 3385 3386 return std::make_pair(LoopBB, RemainderBB); 3387 } 3388 3389 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3390 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3391 MachineBasicBlock *MBB = MI.getParent(); 3392 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3393 auto I = MI.getIterator(); 3394 auto E = std::next(I); 3395 3396 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3397 .addImm(0); 3398 3399 MIBundleBuilder Bundler(*MBB, I, E); 3400 finalizeBundle(*MBB, Bundler.begin()); 3401 } 3402 3403 MachineBasicBlock * 3404 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3405 MachineBasicBlock *BB) const { 3406 const DebugLoc &DL = MI.getDebugLoc(); 3407 3408 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3409 3410 MachineBasicBlock *LoopBB; 3411 MachineBasicBlock *RemainderBB; 3412 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3413 3414 // Apparently kill flags are only valid if the def is in the same block? 3415 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3416 Src->setIsKill(false); 3417 3418 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3419 3420 MachineBasicBlock::iterator I = LoopBB->end(); 3421 3422 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3423 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3424 3425 // Clear TRAP_STS.MEM_VIOL 3426 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3427 .addImm(0) 3428 .addImm(EncodedReg); 3429 3430 bundleInstWithWaitcnt(MI); 3431 3432 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3433 3434 // Load and check TRAP_STS.MEM_VIOL 3435 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3436 .addImm(EncodedReg); 3437 3438 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3439 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3440 .addReg(Reg, RegState::Kill) 3441 .addImm(0); 3442 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3443 .addMBB(LoopBB); 3444 3445 return RemainderBB; 3446 } 3447 3448 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3449 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3450 // will only do one iteration. In the worst case, this will loop 64 times. 3451 // 3452 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3453 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3454 const SIInstrInfo *TII, 3455 MachineRegisterInfo &MRI, 3456 MachineBasicBlock &OrigBB, 3457 MachineBasicBlock &LoopBB, 3458 const DebugLoc &DL, 3459 const MachineOperand &IdxReg, 3460 unsigned InitReg, 3461 unsigned ResultReg, 3462 unsigned PhiReg, 3463 unsigned InitSaveExecReg, 3464 int Offset, 3465 bool UseGPRIdxMode, 3466 bool IsIndirectSrc) { 3467 MachineFunction *MF = OrigBB.getParent(); 3468 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3469 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3470 MachineBasicBlock::iterator I = LoopBB.begin(); 3471 3472 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3473 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3474 Register NewExec = MRI.createVirtualRegister(BoolRC); 3475 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3476 Register CondReg = MRI.createVirtualRegister(BoolRC); 3477 3478 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3479 .addReg(InitReg) 3480 .addMBB(&OrigBB) 3481 .addReg(ResultReg) 3482 .addMBB(&LoopBB); 3483 3484 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3485 .addReg(InitSaveExecReg) 3486 .addMBB(&OrigBB) 3487 .addReg(NewExec) 3488 .addMBB(&LoopBB); 3489 3490 // Read the next variant <- also loop target. 3491 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3492 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3493 3494 // Compare the just read M0 value to all possible Idx values. 3495 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3496 .addReg(CurrentIdxReg) 3497 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3498 3499 // Update EXEC, save the original EXEC value to VCC. 3500 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3501 : AMDGPU::S_AND_SAVEEXEC_B64), 3502 NewExec) 3503 .addReg(CondReg, RegState::Kill); 3504 3505 MRI.setSimpleHint(NewExec, CondReg); 3506 3507 if (UseGPRIdxMode) { 3508 unsigned IdxReg; 3509 if (Offset == 0) { 3510 IdxReg = CurrentIdxReg; 3511 } else { 3512 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3513 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3514 .addReg(CurrentIdxReg, RegState::Kill) 3515 .addImm(Offset); 3516 } 3517 unsigned IdxMode = IsIndirectSrc ? 3518 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3519 MachineInstr *SetOn = 3520 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3521 .addReg(IdxReg, RegState::Kill) 3522 .addImm(IdxMode); 3523 SetOn->getOperand(3).setIsUndef(); 3524 } else { 3525 // Move index from VCC into M0 3526 if (Offset == 0) { 3527 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3528 .addReg(CurrentIdxReg, RegState::Kill); 3529 } else { 3530 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3531 .addReg(CurrentIdxReg, RegState::Kill) 3532 .addImm(Offset); 3533 } 3534 } 3535 3536 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3537 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3538 MachineInstr *InsertPt = 3539 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3540 : AMDGPU::S_XOR_B64_term), Exec) 3541 .addReg(Exec) 3542 .addReg(NewExec); 3543 3544 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3545 // s_cbranch_scc0? 3546 3547 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3548 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3549 .addMBB(&LoopBB); 3550 3551 return InsertPt->getIterator(); 3552 } 3553 3554 // This has slightly sub-optimal regalloc when the source vector is killed by 3555 // the read. The register allocator does not understand that the kill is 3556 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3557 // subregister from it, using 1 more VGPR than necessary. This was saved when 3558 // this was expanded after register allocation. 3559 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3560 MachineBasicBlock &MBB, 3561 MachineInstr &MI, 3562 unsigned InitResultReg, 3563 unsigned PhiReg, 3564 int Offset, 3565 bool UseGPRIdxMode, 3566 bool IsIndirectSrc) { 3567 MachineFunction *MF = MBB.getParent(); 3568 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3569 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3570 MachineRegisterInfo &MRI = MF->getRegInfo(); 3571 const DebugLoc &DL = MI.getDebugLoc(); 3572 MachineBasicBlock::iterator I(&MI); 3573 3574 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3575 Register DstReg = MI.getOperand(0).getReg(); 3576 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3577 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3578 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3579 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3580 3581 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3582 3583 // Save the EXEC mask 3584 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3585 .addReg(Exec); 3586 3587 MachineBasicBlock *LoopBB; 3588 MachineBasicBlock *RemainderBB; 3589 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3590 3591 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3592 3593 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3594 InitResultReg, DstReg, PhiReg, TmpExec, 3595 Offset, UseGPRIdxMode, IsIndirectSrc); 3596 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3597 MachineFunction::iterator MBBI(LoopBB); 3598 ++MBBI; 3599 MF->insert(MBBI, LandingPad); 3600 LoopBB->removeSuccessor(RemainderBB); 3601 LandingPad->addSuccessor(RemainderBB); 3602 LoopBB->addSuccessor(LandingPad); 3603 MachineBasicBlock::iterator First = LandingPad->begin(); 3604 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3605 .addReg(SaveExec); 3606 3607 return InsPt; 3608 } 3609 3610 // Returns subreg index, offset 3611 static std::pair<unsigned, int> 3612 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3613 const TargetRegisterClass *SuperRC, 3614 unsigned VecReg, 3615 int Offset) { 3616 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3617 3618 // Skip out of bounds offsets, or else we would end up using an undefined 3619 // register. 3620 if (Offset >= NumElts || Offset < 0) 3621 return std::make_pair(AMDGPU::sub0, Offset); 3622 3623 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3624 } 3625 3626 // Return true if the index is an SGPR and was set. 3627 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3628 MachineRegisterInfo &MRI, 3629 MachineInstr &MI, 3630 int Offset, 3631 bool UseGPRIdxMode, 3632 bool IsIndirectSrc) { 3633 MachineBasicBlock *MBB = MI.getParent(); 3634 const DebugLoc &DL = MI.getDebugLoc(); 3635 MachineBasicBlock::iterator I(&MI); 3636 3637 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3638 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3639 3640 assert(Idx->getReg() != AMDGPU::NoRegister); 3641 3642 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3643 return false; 3644 3645 if (UseGPRIdxMode) { 3646 unsigned IdxMode = IsIndirectSrc ? 3647 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3648 if (Offset == 0) { 3649 MachineInstr *SetOn = 3650 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3651 .add(*Idx) 3652 .addImm(IdxMode); 3653 3654 SetOn->getOperand(3).setIsUndef(); 3655 } else { 3656 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3657 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3658 .add(*Idx) 3659 .addImm(Offset); 3660 MachineInstr *SetOn = 3661 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3662 .addReg(Tmp, RegState::Kill) 3663 .addImm(IdxMode); 3664 3665 SetOn->getOperand(3).setIsUndef(); 3666 } 3667 3668 return true; 3669 } 3670 3671 if (Offset == 0) { 3672 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3673 .add(*Idx); 3674 } else { 3675 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3676 .add(*Idx) 3677 .addImm(Offset); 3678 } 3679 3680 return true; 3681 } 3682 3683 // Control flow needs to be inserted if indexing with a VGPR. 3684 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3685 MachineBasicBlock &MBB, 3686 const GCNSubtarget &ST) { 3687 const SIInstrInfo *TII = ST.getInstrInfo(); 3688 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3689 MachineFunction *MF = MBB.getParent(); 3690 MachineRegisterInfo &MRI = MF->getRegInfo(); 3691 3692 Register Dst = MI.getOperand(0).getReg(); 3693 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3694 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3695 3696 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3697 3698 unsigned SubReg; 3699 std::tie(SubReg, Offset) 3700 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3701 3702 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3703 3704 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3705 MachineBasicBlock::iterator I(&MI); 3706 const DebugLoc &DL = MI.getDebugLoc(); 3707 3708 if (UseGPRIdxMode) { 3709 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3710 // to avoid interfering with other uses, so probably requires a new 3711 // optimization pass. 3712 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3713 .addReg(SrcReg, 0, SubReg) 3714 .addReg(SrcReg, RegState::Implicit) 3715 .addReg(AMDGPU::M0, RegState::Implicit); 3716 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3717 } else { 3718 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3719 .addReg(SrcReg, 0, SubReg) 3720 .addReg(SrcReg, RegState::Implicit); 3721 } 3722 3723 MI.eraseFromParent(); 3724 3725 return &MBB; 3726 } 3727 3728 const DebugLoc &DL = MI.getDebugLoc(); 3729 MachineBasicBlock::iterator I(&MI); 3730 3731 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3732 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3733 3734 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3735 3736 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3737 Offset, UseGPRIdxMode, true); 3738 MachineBasicBlock *LoopBB = InsPt->getParent(); 3739 3740 if (UseGPRIdxMode) { 3741 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3742 .addReg(SrcReg, 0, SubReg) 3743 .addReg(SrcReg, RegState::Implicit) 3744 .addReg(AMDGPU::M0, RegState::Implicit); 3745 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3746 } else { 3747 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3748 .addReg(SrcReg, 0, SubReg) 3749 .addReg(SrcReg, RegState::Implicit); 3750 } 3751 3752 MI.eraseFromParent(); 3753 3754 return LoopBB; 3755 } 3756 3757 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3758 MachineBasicBlock &MBB, 3759 const GCNSubtarget &ST) { 3760 const SIInstrInfo *TII = ST.getInstrInfo(); 3761 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3762 MachineFunction *MF = MBB.getParent(); 3763 MachineRegisterInfo &MRI = MF->getRegInfo(); 3764 3765 Register Dst = MI.getOperand(0).getReg(); 3766 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3767 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3768 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3769 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3770 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3771 3772 // This can be an immediate, but will be folded later. 3773 assert(Val->getReg()); 3774 3775 unsigned SubReg; 3776 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3777 SrcVec->getReg(), 3778 Offset); 3779 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3780 3781 if (Idx->getReg() == AMDGPU::NoRegister) { 3782 MachineBasicBlock::iterator I(&MI); 3783 const DebugLoc &DL = MI.getDebugLoc(); 3784 3785 assert(Offset == 0); 3786 3787 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3788 .add(*SrcVec) 3789 .add(*Val) 3790 .addImm(SubReg); 3791 3792 MI.eraseFromParent(); 3793 return &MBB; 3794 } 3795 3796 const MCInstrDesc &MovRelDesc 3797 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3798 3799 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3800 MachineBasicBlock::iterator I(&MI); 3801 const DebugLoc &DL = MI.getDebugLoc(); 3802 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3803 .addReg(SrcVec->getReg()) 3804 .add(*Val) 3805 .addImm(SubReg); 3806 if (UseGPRIdxMode) 3807 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3808 3809 MI.eraseFromParent(); 3810 return &MBB; 3811 } 3812 3813 if (Val->isReg()) 3814 MRI.clearKillFlags(Val->getReg()); 3815 3816 const DebugLoc &DL = MI.getDebugLoc(); 3817 3818 Register PhiReg = MRI.createVirtualRegister(VecRC); 3819 3820 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3821 Offset, UseGPRIdxMode, false); 3822 MachineBasicBlock *LoopBB = InsPt->getParent(); 3823 3824 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3825 .addReg(PhiReg) 3826 .add(*Val) 3827 .addImm(AMDGPU::sub0); 3828 if (UseGPRIdxMode) 3829 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3830 3831 MI.eraseFromParent(); 3832 return LoopBB; 3833 } 3834 3835 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3836 MachineInstr &MI, MachineBasicBlock *BB) const { 3837 3838 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3839 MachineFunction *MF = BB->getParent(); 3840 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3841 3842 switch (MI.getOpcode()) { 3843 case AMDGPU::S_UADDO_PSEUDO: 3844 case AMDGPU::S_USUBO_PSEUDO: { 3845 const DebugLoc &DL = MI.getDebugLoc(); 3846 MachineOperand &Dest0 = MI.getOperand(0); 3847 MachineOperand &Dest1 = MI.getOperand(1); 3848 MachineOperand &Src0 = MI.getOperand(2); 3849 MachineOperand &Src1 = MI.getOperand(3); 3850 3851 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3852 ? AMDGPU::S_ADD_I32 3853 : AMDGPU::S_SUB_I32; 3854 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3855 3856 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3857 .addImm(1) 3858 .addImm(0); 3859 3860 MI.eraseFromParent(); 3861 return BB; 3862 } 3863 case AMDGPU::S_ADD_U64_PSEUDO: 3864 case AMDGPU::S_SUB_U64_PSEUDO: { 3865 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3866 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3867 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3868 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3869 const DebugLoc &DL = MI.getDebugLoc(); 3870 3871 MachineOperand &Dest = MI.getOperand(0); 3872 MachineOperand &Src0 = MI.getOperand(1); 3873 MachineOperand &Src1 = MI.getOperand(2); 3874 3875 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3876 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3877 3878 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3879 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3880 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3881 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3882 3883 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3884 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3885 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3886 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3887 3888 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3889 3890 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3891 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3892 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3893 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3894 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3895 .addReg(DestSub0) 3896 .addImm(AMDGPU::sub0) 3897 .addReg(DestSub1) 3898 .addImm(AMDGPU::sub1); 3899 MI.eraseFromParent(); 3900 return BB; 3901 } 3902 case AMDGPU::V_ADD_U64_PSEUDO: 3903 case AMDGPU::V_SUB_U64_PSEUDO: { 3904 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3905 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3906 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3907 const DebugLoc &DL = MI.getDebugLoc(); 3908 3909 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3910 3911 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3912 3913 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3914 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3915 3916 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3917 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3918 3919 MachineOperand &Dest = MI.getOperand(0); 3920 MachineOperand &Src0 = MI.getOperand(1); 3921 MachineOperand &Src1 = MI.getOperand(2); 3922 3923 const TargetRegisterClass *Src0RC = Src0.isReg() 3924 ? MRI.getRegClass(Src0.getReg()) 3925 : &AMDGPU::VReg_64RegClass; 3926 const TargetRegisterClass *Src1RC = Src1.isReg() 3927 ? MRI.getRegClass(Src1.getReg()) 3928 : &AMDGPU::VReg_64RegClass; 3929 3930 const TargetRegisterClass *Src0SubRC = 3931 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3932 const TargetRegisterClass *Src1SubRC = 3933 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3934 3935 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3936 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3937 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3938 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3939 3940 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3941 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3942 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3943 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3944 3945 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3946 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3947 .addReg(CarryReg, RegState::Define) 3948 .add(SrcReg0Sub0) 3949 .add(SrcReg1Sub0) 3950 .addImm(0); // clamp bit 3951 3952 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3953 MachineInstr *HiHalf = 3954 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3955 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3956 .add(SrcReg0Sub1) 3957 .add(SrcReg1Sub1) 3958 .addReg(CarryReg, RegState::Kill) 3959 .addImm(0); // clamp bit 3960 3961 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3962 .addReg(DestSub0) 3963 .addImm(AMDGPU::sub0) 3964 .addReg(DestSub1) 3965 .addImm(AMDGPU::sub1); 3966 TII->legalizeOperands(*LoHalf); 3967 TII->legalizeOperands(*HiHalf); 3968 MI.eraseFromParent(); 3969 return BB; 3970 } 3971 case AMDGPU::S_ADD_CO_PSEUDO: 3972 case AMDGPU::S_SUB_CO_PSEUDO: { 3973 // This pseudo has a chance to be selected 3974 // only from uniform add/subcarry node. All the VGPR operands 3975 // therefore assumed to be splat vectors. 3976 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3977 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3978 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3979 MachineBasicBlock::iterator MII = MI; 3980 const DebugLoc &DL = MI.getDebugLoc(); 3981 MachineOperand &Dest = MI.getOperand(0); 3982 MachineOperand &CarryDest = MI.getOperand(1); 3983 MachineOperand &Src0 = MI.getOperand(2); 3984 MachineOperand &Src1 = MI.getOperand(3); 3985 MachineOperand &Src2 = MI.getOperand(4); 3986 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3987 ? AMDGPU::S_ADDC_U32 3988 : AMDGPU::S_SUBB_U32; 3989 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3990 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3991 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3992 .addReg(Src0.getReg()); 3993 Src0.setReg(RegOp0); 3994 } 3995 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3996 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3997 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3998 .addReg(Src1.getReg()); 3999 Src1.setReg(RegOp1); 4000 } 4001 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4002 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4003 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4004 .addReg(Src2.getReg()); 4005 Src2.setReg(RegOp2); 4006 } 4007 4008 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 4009 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4010 .addReg(Src2.getReg()) 4011 .addImm(0); 4012 } else { 4013 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4014 .addReg(Src2.getReg()) 4015 .addImm(0); 4016 } 4017 4018 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4019 4020 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4021 .addReg(AMDGPU::SCC); 4022 MI.eraseFromParent(); 4023 return BB; 4024 } 4025 case AMDGPU::SI_INIT_M0: { 4026 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4027 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4028 .add(MI.getOperand(0)); 4029 MI.eraseFromParent(); 4030 return BB; 4031 } 4032 case AMDGPU::SI_INIT_EXEC: 4033 // This should be before all vector instructions. 4034 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4035 AMDGPU::EXEC) 4036 .addImm(MI.getOperand(0).getImm()); 4037 MI.eraseFromParent(); 4038 return BB; 4039 4040 case AMDGPU::SI_INIT_EXEC_LO: 4041 // This should be before all vector instructions. 4042 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4043 AMDGPU::EXEC_LO) 4044 .addImm(MI.getOperand(0).getImm()); 4045 MI.eraseFromParent(); 4046 return BB; 4047 4048 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4049 // Extract the thread count from an SGPR input and set EXEC accordingly. 4050 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4051 // 4052 // S_BFE_U32 count, input, {shift, 7} 4053 // S_BFM_B64 exec, count, 0 4054 // S_CMP_EQ_U32 count, 64 4055 // S_CMOV_B64 exec, -1 4056 MachineInstr *FirstMI = &*BB->begin(); 4057 MachineRegisterInfo &MRI = MF->getRegInfo(); 4058 Register InputReg = MI.getOperand(0).getReg(); 4059 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4060 bool Found = false; 4061 4062 // Move the COPY of the input reg to the beginning, so that we can use it. 4063 for (auto I = BB->begin(); I != &MI; I++) { 4064 if (I->getOpcode() != TargetOpcode::COPY || 4065 I->getOperand(0).getReg() != InputReg) 4066 continue; 4067 4068 if (I == FirstMI) { 4069 FirstMI = &*++BB->begin(); 4070 } else { 4071 I->removeFromParent(); 4072 BB->insert(FirstMI, &*I); 4073 } 4074 Found = true; 4075 break; 4076 } 4077 assert(Found); 4078 (void)Found; 4079 4080 // This should be before all vector instructions. 4081 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4082 bool isWave32 = getSubtarget()->isWave32(); 4083 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4084 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4085 .addReg(InputReg) 4086 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4087 BuildMI(*BB, FirstMI, DebugLoc(), 4088 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4089 Exec) 4090 .addReg(CountReg) 4091 .addImm(0); 4092 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4093 .addReg(CountReg, RegState::Kill) 4094 .addImm(getSubtarget()->getWavefrontSize()); 4095 BuildMI(*BB, FirstMI, DebugLoc(), 4096 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4097 Exec) 4098 .addImm(-1); 4099 MI.eraseFromParent(); 4100 return BB; 4101 } 4102 4103 case AMDGPU::GET_GROUPSTATICSIZE: { 4104 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4105 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4106 DebugLoc DL = MI.getDebugLoc(); 4107 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4108 .add(MI.getOperand(0)) 4109 .addImm(MFI->getLDSSize()); 4110 MI.eraseFromParent(); 4111 return BB; 4112 } 4113 case AMDGPU::SI_INDIRECT_SRC_V1: 4114 case AMDGPU::SI_INDIRECT_SRC_V2: 4115 case AMDGPU::SI_INDIRECT_SRC_V4: 4116 case AMDGPU::SI_INDIRECT_SRC_V8: 4117 case AMDGPU::SI_INDIRECT_SRC_V16: 4118 case AMDGPU::SI_INDIRECT_SRC_V32: 4119 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4120 case AMDGPU::SI_INDIRECT_DST_V1: 4121 case AMDGPU::SI_INDIRECT_DST_V2: 4122 case AMDGPU::SI_INDIRECT_DST_V4: 4123 case AMDGPU::SI_INDIRECT_DST_V8: 4124 case AMDGPU::SI_INDIRECT_DST_V16: 4125 case AMDGPU::SI_INDIRECT_DST_V32: 4126 return emitIndirectDst(MI, *BB, *getSubtarget()); 4127 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4128 case AMDGPU::SI_KILL_I1_PSEUDO: 4129 return splitKillBlock(MI, BB); 4130 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4131 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4132 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4133 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4134 4135 Register Dst = MI.getOperand(0).getReg(); 4136 Register Src0 = MI.getOperand(1).getReg(); 4137 Register Src1 = MI.getOperand(2).getReg(); 4138 const DebugLoc &DL = MI.getDebugLoc(); 4139 Register SrcCond = MI.getOperand(3).getReg(); 4140 4141 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4142 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4143 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4144 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4145 4146 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4147 .addReg(SrcCond); 4148 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4149 .addImm(0) 4150 .addReg(Src0, 0, AMDGPU::sub0) 4151 .addImm(0) 4152 .addReg(Src1, 0, AMDGPU::sub0) 4153 .addReg(SrcCondCopy); 4154 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4155 .addImm(0) 4156 .addReg(Src0, 0, AMDGPU::sub1) 4157 .addImm(0) 4158 .addReg(Src1, 0, AMDGPU::sub1) 4159 .addReg(SrcCondCopy); 4160 4161 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4162 .addReg(DstLo) 4163 .addImm(AMDGPU::sub0) 4164 .addReg(DstHi) 4165 .addImm(AMDGPU::sub1); 4166 MI.eraseFromParent(); 4167 return BB; 4168 } 4169 case AMDGPU::SI_BR_UNDEF: { 4170 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4171 const DebugLoc &DL = MI.getDebugLoc(); 4172 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4173 .add(MI.getOperand(0)); 4174 Br->getOperand(1).setIsUndef(true); // read undef SCC 4175 MI.eraseFromParent(); 4176 return BB; 4177 } 4178 case AMDGPU::ADJCALLSTACKUP: 4179 case AMDGPU::ADJCALLSTACKDOWN: { 4180 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4181 MachineInstrBuilder MIB(*MF, &MI); 4182 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4183 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4184 return BB; 4185 } 4186 case AMDGPU::SI_CALL_ISEL: { 4187 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4188 const DebugLoc &DL = MI.getDebugLoc(); 4189 4190 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4191 4192 MachineInstrBuilder MIB; 4193 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4194 4195 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4196 MIB.add(MI.getOperand(I)); 4197 4198 MIB.cloneMemRefs(MI); 4199 MI.eraseFromParent(); 4200 return BB; 4201 } 4202 case AMDGPU::V_ADD_CO_U32_e32: 4203 case AMDGPU::V_SUB_CO_U32_e32: 4204 case AMDGPU::V_SUBREV_CO_U32_e32: { 4205 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4206 const DebugLoc &DL = MI.getDebugLoc(); 4207 unsigned Opc = MI.getOpcode(); 4208 4209 bool NeedClampOperand = false; 4210 if (TII->pseudoToMCOpcode(Opc) == -1) { 4211 Opc = AMDGPU::getVOPe64(Opc); 4212 NeedClampOperand = true; 4213 } 4214 4215 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4216 if (TII->isVOP3(*I)) { 4217 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4218 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4219 I.addReg(TRI->getVCC(), RegState::Define); 4220 } 4221 I.add(MI.getOperand(1)) 4222 .add(MI.getOperand(2)); 4223 if (NeedClampOperand) 4224 I.addImm(0); // clamp bit for e64 encoding 4225 4226 TII->legalizeOperands(*I); 4227 4228 MI.eraseFromParent(); 4229 return BB; 4230 } 4231 case AMDGPU::DS_GWS_INIT: 4232 case AMDGPU::DS_GWS_SEMA_V: 4233 case AMDGPU::DS_GWS_SEMA_BR: 4234 case AMDGPU::DS_GWS_SEMA_P: 4235 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4236 case AMDGPU::DS_GWS_BARRIER: 4237 // A s_waitcnt 0 is required to be the instruction immediately following. 4238 if (getSubtarget()->hasGWSAutoReplay()) { 4239 bundleInstWithWaitcnt(MI); 4240 return BB; 4241 } 4242 4243 return emitGWSMemViolTestLoop(MI, BB); 4244 case AMDGPU::S_SETREG_B32: { 4245 // Try to optimize cases that only set the denormal mode or rounding mode. 4246 // 4247 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4248 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4249 // instead. 4250 // 4251 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4252 // allow you to have a no side effect instruction in the output of a 4253 // sideeffecting pattern. 4254 unsigned ID, Offset, Width; 4255 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4256 if (ID != AMDGPU::Hwreg::ID_MODE) 4257 return BB; 4258 4259 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4260 const unsigned SetMask = WidthMask << Offset; 4261 4262 if (getSubtarget()->hasDenormModeInst()) { 4263 unsigned SetDenormOp = 0; 4264 unsigned SetRoundOp = 0; 4265 4266 // The dedicated instructions can only set the whole denorm or round mode 4267 // at once, not a subset of bits in either. 4268 if (SetMask == 4269 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4270 // If this fully sets both the round and denorm mode, emit the two 4271 // dedicated instructions for these. 4272 SetRoundOp = AMDGPU::S_ROUND_MODE; 4273 SetDenormOp = AMDGPU::S_DENORM_MODE; 4274 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4275 SetRoundOp = AMDGPU::S_ROUND_MODE; 4276 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4277 SetDenormOp = AMDGPU::S_DENORM_MODE; 4278 } 4279 4280 if (SetRoundOp || SetDenormOp) { 4281 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4282 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4283 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4284 unsigned ImmVal = Def->getOperand(1).getImm(); 4285 if (SetRoundOp) { 4286 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4287 .addImm(ImmVal & 0xf); 4288 4289 // If we also have the denorm mode, get just the denorm mode bits. 4290 ImmVal >>= 4; 4291 } 4292 4293 if (SetDenormOp) { 4294 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4295 .addImm(ImmVal & 0xf); 4296 } 4297 4298 MI.eraseFromParent(); 4299 return BB; 4300 } 4301 } 4302 } 4303 4304 // If only FP bits are touched, used the no side effects pseudo. 4305 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4306 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4307 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4308 4309 return BB; 4310 } 4311 default: 4312 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4313 } 4314 } 4315 4316 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4317 return isTypeLegal(VT.getScalarType()); 4318 } 4319 4320 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4321 // This currently forces unfolding various combinations of fsub into fma with 4322 // free fneg'd operands. As long as we have fast FMA (controlled by 4323 // isFMAFasterThanFMulAndFAdd), we should perform these. 4324 4325 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4326 // most of these combines appear to be cycle neutral but save on instruction 4327 // count / code size. 4328 return true; 4329 } 4330 4331 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4332 EVT VT) const { 4333 if (!VT.isVector()) { 4334 return MVT::i1; 4335 } 4336 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4337 } 4338 4339 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4340 // TODO: Should i16 be used always if legal? For now it would force VALU 4341 // shifts. 4342 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4343 } 4344 4345 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4346 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4347 ? Ty.changeElementSize(16) 4348 : Ty.changeElementSize(32); 4349 } 4350 4351 // Answering this is somewhat tricky and depends on the specific device which 4352 // have different rates for fma or all f64 operations. 4353 // 4354 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4355 // regardless of which device (although the number of cycles differs between 4356 // devices), so it is always profitable for f64. 4357 // 4358 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4359 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4360 // which we can always do even without fused FP ops since it returns the same 4361 // result as the separate operations and since it is always full 4362 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4363 // however does not support denormals, so we do report fma as faster if we have 4364 // a fast fma device and require denormals. 4365 // 4366 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4367 EVT VT) const { 4368 VT = VT.getScalarType(); 4369 4370 switch (VT.getSimpleVT().SimpleTy) { 4371 case MVT::f32: { 4372 // If mad is not available this depends only on if f32 fma is full rate. 4373 if (!Subtarget->hasMadMacF32Insts()) 4374 return Subtarget->hasFastFMAF32(); 4375 4376 // Otherwise f32 mad is always full rate and returns the same result as 4377 // the separate operations so should be preferred over fma. 4378 // However does not support denomals. 4379 if (hasFP32Denormals(MF)) 4380 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4381 4382 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4383 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4384 } 4385 case MVT::f64: 4386 return true; 4387 case MVT::f16: 4388 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4389 default: 4390 break; 4391 } 4392 4393 return false; 4394 } 4395 4396 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4397 const SDNode *N) const { 4398 // TODO: Check future ftz flag 4399 // v_mad_f32/v_mac_f32 do not support denormals. 4400 EVT VT = N->getValueType(0); 4401 if (VT == MVT::f32) 4402 return Subtarget->hasMadMacF32Insts() && 4403 !hasFP32Denormals(DAG.getMachineFunction()); 4404 if (VT == MVT::f16) { 4405 return Subtarget->hasMadF16() && 4406 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4407 } 4408 4409 return false; 4410 } 4411 4412 //===----------------------------------------------------------------------===// 4413 // Custom DAG Lowering Operations 4414 //===----------------------------------------------------------------------===// 4415 4416 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4417 // wider vector type is legal. 4418 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4419 SelectionDAG &DAG) const { 4420 unsigned Opc = Op.getOpcode(); 4421 EVT VT = Op.getValueType(); 4422 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4423 4424 SDValue Lo, Hi; 4425 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4426 4427 SDLoc SL(Op); 4428 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4429 Op->getFlags()); 4430 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4431 Op->getFlags()); 4432 4433 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4434 } 4435 4436 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4437 // wider vector type is legal. 4438 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4439 SelectionDAG &DAG) const { 4440 unsigned Opc = Op.getOpcode(); 4441 EVT VT = Op.getValueType(); 4442 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4443 4444 SDValue Lo0, Hi0; 4445 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4446 SDValue Lo1, Hi1; 4447 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4448 4449 SDLoc SL(Op); 4450 4451 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4452 Op->getFlags()); 4453 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4454 Op->getFlags()); 4455 4456 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4457 } 4458 4459 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4460 SelectionDAG &DAG) const { 4461 unsigned Opc = Op.getOpcode(); 4462 EVT VT = Op.getValueType(); 4463 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4464 4465 SDValue Lo0, Hi0; 4466 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4467 SDValue Lo1, Hi1; 4468 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4469 SDValue Lo2, Hi2; 4470 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4471 4472 SDLoc SL(Op); 4473 4474 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4475 Op->getFlags()); 4476 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4477 Op->getFlags()); 4478 4479 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4480 } 4481 4482 4483 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4484 switch (Op.getOpcode()) { 4485 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4486 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4487 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4488 case ISD::LOAD: { 4489 SDValue Result = LowerLOAD(Op, DAG); 4490 assert((!Result.getNode() || 4491 Result.getNode()->getNumValues() == 2) && 4492 "Load should return a value and a chain"); 4493 return Result; 4494 } 4495 4496 case ISD::FSIN: 4497 case ISD::FCOS: 4498 return LowerTrig(Op, DAG); 4499 case ISD::SELECT: return LowerSELECT(Op, DAG); 4500 case ISD::FDIV: return LowerFDIV(Op, DAG); 4501 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4502 case ISD::STORE: return LowerSTORE(Op, DAG); 4503 case ISD::GlobalAddress: { 4504 MachineFunction &MF = DAG.getMachineFunction(); 4505 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4506 return LowerGlobalAddress(MFI, Op, DAG); 4507 } 4508 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4509 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4510 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4511 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4512 case ISD::INSERT_SUBVECTOR: 4513 return lowerINSERT_SUBVECTOR(Op, DAG); 4514 case ISD::INSERT_VECTOR_ELT: 4515 return lowerINSERT_VECTOR_ELT(Op, DAG); 4516 case ISD::EXTRACT_VECTOR_ELT: 4517 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4518 case ISD::VECTOR_SHUFFLE: 4519 return lowerVECTOR_SHUFFLE(Op, DAG); 4520 case ISD::BUILD_VECTOR: 4521 return lowerBUILD_VECTOR(Op, DAG); 4522 case ISD::FP_ROUND: 4523 return lowerFP_ROUND(Op, DAG); 4524 case ISD::TRAP: 4525 return lowerTRAP(Op, DAG); 4526 case ISD::DEBUGTRAP: 4527 return lowerDEBUGTRAP(Op, DAG); 4528 case ISD::FABS: 4529 case ISD::FNEG: 4530 case ISD::FCANONICALIZE: 4531 case ISD::BSWAP: 4532 return splitUnaryVectorOp(Op, DAG); 4533 case ISD::FMINNUM: 4534 case ISD::FMAXNUM: 4535 return lowerFMINNUM_FMAXNUM(Op, DAG); 4536 case ISD::FMA: 4537 return splitTernaryVectorOp(Op, DAG); 4538 case ISD::SHL: 4539 case ISD::SRA: 4540 case ISD::SRL: 4541 case ISD::ADD: 4542 case ISD::SUB: 4543 case ISD::MUL: 4544 case ISD::SMIN: 4545 case ISD::SMAX: 4546 case ISD::UMIN: 4547 case ISD::UMAX: 4548 case ISD::FADD: 4549 case ISD::FMUL: 4550 case ISD::FMINNUM_IEEE: 4551 case ISD::FMAXNUM_IEEE: 4552 case ISD::UADDSAT: 4553 case ISD::USUBSAT: 4554 case ISD::SADDSAT: 4555 case ISD::SSUBSAT: 4556 return splitBinaryVectorOp(Op, DAG); 4557 case ISD::SMULO: 4558 case ISD::UMULO: 4559 return lowerXMULO(Op, DAG); 4560 case ISD::DYNAMIC_STACKALLOC: 4561 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4562 } 4563 return SDValue(); 4564 } 4565 4566 // Used for D16: Casts the result of an instruction into the right vector, 4567 // packs values if loads return unpacked values. 4568 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4569 const SDLoc &DL, 4570 SelectionDAG &DAG, bool Unpacked) { 4571 if (!LoadVT.isVector()) 4572 return Result; 4573 4574 // Cast back to the original packed type or to a larger type that is a 4575 // multiple of 32 bit for D16. Widening the return type is a required for 4576 // legalization. 4577 EVT FittingLoadVT = LoadVT; 4578 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4579 FittingLoadVT = 4580 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4581 LoadVT.getVectorNumElements() + 1); 4582 } 4583 4584 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4585 // Truncate to v2i16/v4i16. 4586 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4587 4588 // Workaround legalizer not scalarizing truncate after vector op 4589 // legalization but not creating intermediate vector trunc. 4590 SmallVector<SDValue, 4> Elts; 4591 DAG.ExtractVectorElements(Result, Elts); 4592 for (SDValue &Elt : Elts) 4593 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4594 4595 // Pad illegal v1i16/v3fi6 to v4i16 4596 if ((LoadVT.getVectorNumElements() % 2) == 1) 4597 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4598 4599 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4600 4601 // Bitcast to original type (v2f16/v4f16). 4602 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4603 } 4604 4605 // Cast back to the original packed type. 4606 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4607 } 4608 4609 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4610 MemSDNode *M, 4611 SelectionDAG &DAG, 4612 ArrayRef<SDValue> Ops, 4613 bool IsIntrinsic) const { 4614 SDLoc DL(M); 4615 4616 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4617 EVT LoadVT = M->getValueType(0); 4618 4619 EVT EquivLoadVT = LoadVT; 4620 if (LoadVT.isVector()) { 4621 if (Unpacked) { 4622 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4623 LoadVT.getVectorNumElements()); 4624 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4625 // Widen v3f16 to legal type 4626 EquivLoadVT = 4627 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4628 LoadVT.getVectorNumElements() + 1); 4629 } 4630 } 4631 4632 // Change from v4f16/v2f16 to EquivLoadVT. 4633 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4634 4635 SDValue Load 4636 = DAG.getMemIntrinsicNode( 4637 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4638 VTList, Ops, M->getMemoryVT(), 4639 M->getMemOperand()); 4640 4641 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4642 4643 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4644 } 4645 4646 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4647 SelectionDAG &DAG, 4648 ArrayRef<SDValue> Ops) const { 4649 SDLoc DL(M); 4650 EVT LoadVT = M->getValueType(0); 4651 EVT EltType = LoadVT.getScalarType(); 4652 EVT IntVT = LoadVT.changeTypeToInteger(); 4653 4654 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4655 4656 unsigned Opc = 4657 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4658 4659 if (IsD16) { 4660 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4661 } 4662 4663 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4664 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4665 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4666 4667 if (isTypeLegal(LoadVT)) { 4668 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4669 M->getMemOperand(), DAG); 4670 } 4671 4672 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4673 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4674 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4675 M->getMemOperand(), DAG); 4676 return DAG.getMergeValues( 4677 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4678 DL); 4679 } 4680 4681 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4682 SDNode *N, SelectionDAG &DAG) { 4683 EVT VT = N->getValueType(0); 4684 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4685 unsigned CondCode = CD->getZExtValue(); 4686 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4687 return DAG.getUNDEF(VT); 4688 4689 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4690 4691 SDValue LHS = N->getOperand(1); 4692 SDValue RHS = N->getOperand(2); 4693 4694 SDLoc DL(N); 4695 4696 EVT CmpVT = LHS.getValueType(); 4697 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4698 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4699 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4700 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4701 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4702 } 4703 4704 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4705 4706 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4707 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4708 4709 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4710 DAG.getCondCode(CCOpcode)); 4711 if (VT.bitsEq(CCVT)) 4712 return SetCC; 4713 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4714 } 4715 4716 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4717 SDNode *N, SelectionDAG &DAG) { 4718 EVT VT = N->getValueType(0); 4719 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4720 4721 unsigned CondCode = CD->getZExtValue(); 4722 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4723 return DAG.getUNDEF(VT); 4724 4725 SDValue Src0 = N->getOperand(1); 4726 SDValue Src1 = N->getOperand(2); 4727 EVT CmpVT = Src0.getValueType(); 4728 SDLoc SL(N); 4729 4730 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4731 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4732 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4733 } 4734 4735 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4736 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4737 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4738 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4739 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4740 Src1, DAG.getCondCode(CCOpcode)); 4741 if (VT.bitsEq(CCVT)) 4742 return SetCC; 4743 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4744 } 4745 4746 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4747 SelectionDAG &DAG) { 4748 EVT VT = N->getValueType(0); 4749 SDValue Src = N->getOperand(1); 4750 SDLoc SL(N); 4751 4752 if (Src.getOpcode() == ISD::SETCC) { 4753 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4754 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4755 Src.getOperand(1), Src.getOperand(2)); 4756 } 4757 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4758 // (ballot 0) -> 0 4759 if (Arg->isNullValue()) 4760 return DAG.getConstant(0, SL, VT); 4761 4762 // (ballot 1) -> EXEC/EXEC_LO 4763 if (Arg->isOne()) { 4764 Register Exec; 4765 if (VT.getScalarSizeInBits() == 32) 4766 Exec = AMDGPU::EXEC_LO; 4767 else if (VT.getScalarSizeInBits() == 64) 4768 Exec = AMDGPU::EXEC; 4769 else 4770 return SDValue(); 4771 4772 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4773 } 4774 } 4775 4776 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4777 // ISD::SETNE) 4778 return DAG.getNode( 4779 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4780 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4781 } 4782 4783 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4784 SmallVectorImpl<SDValue> &Results, 4785 SelectionDAG &DAG) const { 4786 switch (N->getOpcode()) { 4787 case ISD::INSERT_VECTOR_ELT: { 4788 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4789 Results.push_back(Res); 4790 return; 4791 } 4792 case ISD::EXTRACT_VECTOR_ELT: { 4793 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4794 Results.push_back(Res); 4795 return; 4796 } 4797 case ISD::INTRINSIC_WO_CHAIN: { 4798 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4799 switch (IID) { 4800 case Intrinsic::amdgcn_cvt_pkrtz: { 4801 SDValue Src0 = N->getOperand(1); 4802 SDValue Src1 = N->getOperand(2); 4803 SDLoc SL(N); 4804 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4805 Src0, Src1); 4806 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4807 return; 4808 } 4809 case Intrinsic::amdgcn_cvt_pknorm_i16: 4810 case Intrinsic::amdgcn_cvt_pknorm_u16: 4811 case Intrinsic::amdgcn_cvt_pk_i16: 4812 case Intrinsic::amdgcn_cvt_pk_u16: { 4813 SDValue Src0 = N->getOperand(1); 4814 SDValue Src1 = N->getOperand(2); 4815 SDLoc SL(N); 4816 unsigned Opcode; 4817 4818 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4819 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4820 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4821 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4822 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4823 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4824 else 4825 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4826 4827 EVT VT = N->getValueType(0); 4828 if (isTypeLegal(VT)) 4829 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4830 else { 4831 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4832 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4833 } 4834 return; 4835 } 4836 } 4837 break; 4838 } 4839 case ISD::INTRINSIC_W_CHAIN: { 4840 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4841 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4842 // FIXME: Hacky 4843 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4844 Results.push_back(Res.getOperand(I)); 4845 } 4846 } else { 4847 Results.push_back(Res); 4848 Results.push_back(Res.getValue(1)); 4849 } 4850 return; 4851 } 4852 4853 break; 4854 } 4855 case ISD::SELECT: { 4856 SDLoc SL(N); 4857 EVT VT = N->getValueType(0); 4858 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4859 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4860 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4861 4862 EVT SelectVT = NewVT; 4863 if (NewVT.bitsLT(MVT::i32)) { 4864 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4865 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4866 SelectVT = MVT::i32; 4867 } 4868 4869 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4870 N->getOperand(0), LHS, RHS); 4871 4872 if (NewVT != SelectVT) 4873 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4874 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4875 return; 4876 } 4877 case ISD::FNEG: { 4878 if (N->getValueType(0) != MVT::v2f16) 4879 break; 4880 4881 SDLoc SL(N); 4882 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4883 4884 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4885 BC, 4886 DAG.getConstant(0x80008000, SL, MVT::i32)); 4887 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4888 return; 4889 } 4890 case ISD::FABS: { 4891 if (N->getValueType(0) != MVT::v2f16) 4892 break; 4893 4894 SDLoc SL(N); 4895 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4896 4897 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4898 BC, 4899 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4900 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4901 return; 4902 } 4903 default: 4904 break; 4905 } 4906 } 4907 4908 /// Helper function for LowerBRCOND 4909 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4910 4911 SDNode *Parent = Value.getNode(); 4912 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4913 I != E; ++I) { 4914 4915 if (I.getUse().get() != Value) 4916 continue; 4917 4918 if (I->getOpcode() == Opcode) 4919 return *I; 4920 } 4921 return nullptr; 4922 } 4923 4924 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4925 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4926 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4927 case Intrinsic::amdgcn_if: 4928 return AMDGPUISD::IF; 4929 case Intrinsic::amdgcn_else: 4930 return AMDGPUISD::ELSE; 4931 case Intrinsic::amdgcn_loop: 4932 return AMDGPUISD::LOOP; 4933 case Intrinsic::amdgcn_end_cf: 4934 llvm_unreachable("should not occur"); 4935 default: 4936 return 0; 4937 } 4938 } 4939 4940 // break, if_break, else_break are all only used as inputs to loop, not 4941 // directly as branch conditions. 4942 return 0; 4943 } 4944 4945 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4946 const Triple &TT = getTargetMachine().getTargetTriple(); 4947 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4948 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4949 AMDGPU::shouldEmitConstantsToTextSection(TT); 4950 } 4951 4952 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4953 // FIXME: Either avoid relying on address space here or change the default 4954 // address space for functions to avoid the explicit check. 4955 return (GV->getValueType()->isFunctionTy() || 4956 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4957 !shouldEmitFixup(GV) && 4958 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4959 } 4960 4961 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4962 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4963 } 4964 4965 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4966 if (!GV->hasExternalLinkage()) 4967 return true; 4968 4969 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4970 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4971 } 4972 4973 /// This transforms the control flow intrinsics to get the branch destination as 4974 /// last parameter, also switches branch target with BR if the need arise 4975 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4976 SelectionDAG &DAG) const { 4977 SDLoc DL(BRCOND); 4978 4979 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4980 SDValue Target = BRCOND.getOperand(2); 4981 SDNode *BR = nullptr; 4982 SDNode *SetCC = nullptr; 4983 4984 if (Intr->getOpcode() == ISD::SETCC) { 4985 // As long as we negate the condition everything is fine 4986 SetCC = Intr; 4987 Intr = SetCC->getOperand(0).getNode(); 4988 4989 } else { 4990 // Get the target from BR if we don't negate the condition 4991 BR = findUser(BRCOND, ISD::BR); 4992 assert(BR && "brcond missing unconditional branch user"); 4993 Target = BR->getOperand(1); 4994 } 4995 4996 unsigned CFNode = isCFIntrinsic(Intr); 4997 if (CFNode == 0) { 4998 // This is a uniform branch so we don't need to legalize. 4999 return BRCOND; 5000 } 5001 5002 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5003 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5004 5005 assert(!SetCC || 5006 (SetCC->getConstantOperandVal(1) == 1 && 5007 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5008 ISD::SETNE)); 5009 5010 // operands of the new intrinsic call 5011 SmallVector<SDValue, 4> Ops; 5012 if (HaveChain) 5013 Ops.push_back(BRCOND.getOperand(0)); 5014 5015 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5016 Ops.push_back(Target); 5017 5018 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5019 5020 // build the new intrinsic call 5021 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5022 5023 if (!HaveChain) { 5024 SDValue Ops[] = { 5025 SDValue(Result, 0), 5026 BRCOND.getOperand(0) 5027 }; 5028 5029 Result = DAG.getMergeValues(Ops, DL).getNode(); 5030 } 5031 5032 if (BR) { 5033 // Give the branch instruction our target 5034 SDValue Ops[] = { 5035 BR->getOperand(0), 5036 BRCOND.getOperand(2) 5037 }; 5038 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5039 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5040 } 5041 5042 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5043 5044 // Copy the intrinsic results to registers 5045 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5046 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5047 if (!CopyToReg) 5048 continue; 5049 5050 Chain = DAG.getCopyToReg( 5051 Chain, DL, 5052 CopyToReg->getOperand(1), 5053 SDValue(Result, i - 1), 5054 SDValue()); 5055 5056 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5057 } 5058 5059 // Remove the old intrinsic from the chain 5060 DAG.ReplaceAllUsesOfValueWith( 5061 SDValue(Intr, Intr->getNumValues() - 1), 5062 Intr->getOperand(0)); 5063 5064 return Chain; 5065 } 5066 5067 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5068 SelectionDAG &DAG) const { 5069 MVT VT = Op.getSimpleValueType(); 5070 SDLoc DL(Op); 5071 // Checking the depth 5072 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5073 return DAG.getConstant(0, DL, VT); 5074 5075 MachineFunction &MF = DAG.getMachineFunction(); 5076 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5077 // Check for kernel and shader functions 5078 if (Info->isEntryFunction()) 5079 return DAG.getConstant(0, DL, VT); 5080 5081 MachineFrameInfo &MFI = MF.getFrameInfo(); 5082 // There is a call to @llvm.returnaddress in this function 5083 MFI.setReturnAddressIsTaken(true); 5084 5085 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5086 // Get the return address reg and mark it as an implicit live-in 5087 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5088 5089 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5090 } 5091 5092 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5093 SDValue Op, 5094 const SDLoc &DL, 5095 EVT VT) const { 5096 return Op.getValueType().bitsLE(VT) ? 5097 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5098 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5099 DAG.getTargetConstant(0, DL, MVT::i32)); 5100 } 5101 5102 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5103 assert(Op.getValueType() == MVT::f16 && 5104 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5105 5106 SDValue Src = Op.getOperand(0); 5107 EVT SrcVT = Src.getValueType(); 5108 if (SrcVT != MVT::f64) 5109 return Op; 5110 5111 SDLoc DL(Op); 5112 5113 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5114 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5115 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5116 } 5117 5118 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5119 SelectionDAG &DAG) const { 5120 EVT VT = Op.getValueType(); 5121 const MachineFunction &MF = DAG.getMachineFunction(); 5122 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5123 bool IsIEEEMode = Info->getMode().IEEE; 5124 5125 // FIXME: Assert during selection that this is only selected for 5126 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5127 // mode functions, but this happens to be OK since it's only done in cases 5128 // where there is known no sNaN. 5129 if (IsIEEEMode) 5130 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5131 5132 if (VT == MVT::v4f16) 5133 return splitBinaryVectorOp(Op, DAG); 5134 return Op; 5135 } 5136 5137 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5138 EVT VT = Op.getValueType(); 5139 SDLoc SL(Op); 5140 SDValue LHS = Op.getOperand(0); 5141 SDValue RHS = Op.getOperand(1); 5142 bool isSigned = Op.getOpcode() == ISD::SMULO; 5143 5144 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5145 const APInt &C = RHSC->getAPIntValue(); 5146 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5147 if (C.isPowerOf2()) { 5148 // smulo(x, signed_min) is same as umulo(x, signed_min). 5149 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5150 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5151 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5152 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5153 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5154 SL, VT, Result, ShiftAmt), 5155 LHS, ISD::SETNE); 5156 return DAG.getMergeValues({ Result, Overflow }, SL); 5157 } 5158 } 5159 5160 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5161 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5162 SL, VT, LHS, RHS); 5163 5164 SDValue Sign = isSigned 5165 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5166 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5167 : DAG.getConstant(0, SL, VT); 5168 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5169 5170 return DAG.getMergeValues({ Result, Overflow }, SL); 5171 } 5172 5173 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5174 SDLoc SL(Op); 5175 SDValue Chain = Op.getOperand(0); 5176 5177 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5178 !Subtarget->isTrapHandlerEnabled()) 5179 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5180 5181 MachineFunction &MF = DAG.getMachineFunction(); 5182 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5183 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5184 assert(UserSGPR != AMDGPU::NoRegister); 5185 SDValue QueuePtr = CreateLiveInRegister( 5186 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5187 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5188 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5189 QueuePtr, SDValue()); 5190 SDValue Ops[] = { 5191 ToReg, 5192 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5193 SGPR01, 5194 ToReg.getValue(1) 5195 }; 5196 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5197 } 5198 5199 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5200 SDLoc SL(Op); 5201 SDValue Chain = Op.getOperand(0); 5202 MachineFunction &MF = DAG.getMachineFunction(); 5203 5204 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5205 !Subtarget->isTrapHandlerEnabled()) { 5206 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5207 "debugtrap handler not supported", 5208 Op.getDebugLoc(), 5209 DS_Warning); 5210 LLVMContext &Ctx = MF.getFunction().getContext(); 5211 Ctx.diagnose(NoTrap); 5212 return Chain; 5213 } 5214 5215 SDValue Ops[] = { 5216 Chain, 5217 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5218 }; 5219 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5220 } 5221 5222 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5223 SelectionDAG &DAG) const { 5224 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5225 if (Subtarget->hasApertureRegs()) { 5226 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5227 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5228 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5229 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5230 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5231 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5232 unsigned Encoding = 5233 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5234 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5235 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5236 5237 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5238 SDValue ApertureReg = SDValue( 5239 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5240 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5241 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5242 } 5243 5244 MachineFunction &MF = DAG.getMachineFunction(); 5245 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5246 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5247 assert(UserSGPR != AMDGPU::NoRegister); 5248 5249 SDValue QueuePtr = CreateLiveInRegister( 5250 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5251 5252 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5253 // private_segment_aperture_base_hi. 5254 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5255 5256 SDValue Ptr = 5257 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5258 5259 // TODO: Use custom target PseudoSourceValue. 5260 // TODO: We should use the value from the IR intrinsic call, but it might not 5261 // be available and how do we get it? 5262 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5263 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5264 commonAlignment(Align(64), StructOffset), 5265 MachineMemOperand::MODereferenceable | 5266 MachineMemOperand::MOInvariant); 5267 } 5268 5269 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5270 SelectionDAG &DAG) const { 5271 SDLoc SL(Op); 5272 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5273 5274 SDValue Src = ASC->getOperand(0); 5275 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5276 5277 const AMDGPUTargetMachine &TM = 5278 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5279 5280 // flat -> local/private 5281 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5282 unsigned DestAS = ASC->getDestAddressSpace(); 5283 5284 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5285 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5286 unsigned NullVal = TM.getNullPointerValue(DestAS); 5287 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5288 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5289 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5290 5291 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5292 NonNull, Ptr, SegmentNullPtr); 5293 } 5294 } 5295 5296 // local/private -> flat 5297 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5298 unsigned SrcAS = ASC->getSrcAddressSpace(); 5299 5300 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5301 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5302 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5303 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5304 5305 SDValue NonNull 5306 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5307 5308 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5309 SDValue CvtPtr 5310 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5311 5312 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5313 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5314 FlatNullPtr); 5315 } 5316 } 5317 5318 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5319 Src.getValueType() == MVT::i64) 5320 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5321 5322 // global <-> flat are no-ops and never emitted. 5323 5324 const MachineFunction &MF = DAG.getMachineFunction(); 5325 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5326 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5327 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5328 5329 return DAG.getUNDEF(ASC->getValueType(0)); 5330 } 5331 5332 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5333 // the small vector and inserting them into the big vector. That is better than 5334 // the default expansion of doing it via a stack slot. Even though the use of 5335 // the stack slot would be optimized away afterwards, the stack slot itself 5336 // remains. 5337 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5338 SelectionDAG &DAG) const { 5339 SDValue Vec = Op.getOperand(0); 5340 SDValue Ins = Op.getOperand(1); 5341 SDValue Idx = Op.getOperand(2); 5342 EVT VecVT = Vec.getValueType(); 5343 EVT InsVT = Ins.getValueType(); 5344 EVT EltVT = VecVT.getVectorElementType(); 5345 unsigned InsNumElts = InsVT.getVectorNumElements(); 5346 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5347 SDLoc SL(Op); 5348 5349 for (unsigned I = 0; I != InsNumElts; ++I) { 5350 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5351 DAG.getConstant(I, SL, MVT::i32)); 5352 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5353 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5354 } 5355 return Vec; 5356 } 5357 5358 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5359 SelectionDAG &DAG) const { 5360 SDValue Vec = Op.getOperand(0); 5361 SDValue InsVal = Op.getOperand(1); 5362 SDValue Idx = Op.getOperand(2); 5363 EVT VecVT = Vec.getValueType(); 5364 EVT EltVT = VecVT.getVectorElementType(); 5365 unsigned VecSize = VecVT.getSizeInBits(); 5366 unsigned EltSize = EltVT.getSizeInBits(); 5367 5368 5369 assert(VecSize <= 64); 5370 5371 unsigned NumElts = VecVT.getVectorNumElements(); 5372 SDLoc SL(Op); 5373 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5374 5375 if (NumElts == 4 && EltSize == 16 && KIdx) { 5376 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5377 5378 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5379 DAG.getConstant(0, SL, MVT::i32)); 5380 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5381 DAG.getConstant(1, SL, MVT::i32)); 5382 5383 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5384 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5385 5386 unsigned Idx = KIdx->getZExtValue(); 5387 bool InsertLo = Idx < 2; 5388 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5389 InsertLo ? LoVec : HiVec, 5390 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5391 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5392 5393 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5394 5395 SDValue Concat = InsertLo ? 5396 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5397 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5398 5399 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5400 } 5401 5402 if (isa<ConstantSDNode>(Idx)) 5403 return SDValue(); 5404 5405 MVT IntVT = MVT::getIntegerVT(VecSize); 5406 5407 // Avoid stack access for dynamic indexing. 5408 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5409 5410 // Create a congruent vector with the target value in each element so that 5411 // the required element can be masked and ORed into the target vector. 5412 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5413 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5414 5415 assert(isPowerOf2_32(EltSize)); 5416 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5417 5418 // Convert vector index to bit-index. 5419 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5420 5421 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5422 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5423 DAG.getConstant(0xffff, SL, IntVT), 5424 ScaledIdx); 5425 5426 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5427 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5428 DAG.getNOT(SL, BFM, IntVT), BCVec); 5429 5430 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5431 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5432 } 5433 5434 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5435 SelectionDAG &DAG) const { 5436 SDLoc SL(Op); 5437 5438 EVT ResultVT = Op.getValueType(); 5439 SDValue Vec = Op.getOperand(0); 5440 SDValue Idx = Op.getOperand(1); 5441 EVT VecVT = Vec.getValueType(); 5442 unsigned VecSize = VecVT.getSizeInBits(); 5443 EVT EltVT = VecVT.getVectorElementType(); 5444 assert(VecSize <= 64); 5445 5446 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5447 5448 // Make sure we do any optimizations that will make it easier to fold 5449 // source modifiers before obscuring it with bit operations. 5450 5451 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5452 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5453 return Combined; 5454 5455 unsigned EltSize = EltVT.getSizeInBits(); 5456 assert(isPowerOf2_32(EltSize)); 5457 5458 MVT IntVT = MVT::getIntegerVT(VecSize); 5459 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5460 5461 // Convert vector index to bit-index (* EltSize) 5462 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5463 5464 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5465 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5466 5467 if (ResultVT == MVT::f16) { 5468 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5469 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5470 } 5471 5472 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5473 } 5474 5475 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5476 assert(Elt % 2 == 0); 5477 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5478 } 5479 5480 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5481 SelectionDAG &DAG) const { 5482 SDLoc SL(Op); 5483 EVT ResultVT = Op.getValueType(); 5484 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5485 5486 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5487 EVT EltVT = PackVT.getVectorElementType(); 5488 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5489 5490 // vector_shuffle <0,1,6,7> lhs, rhs 5491 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5492 // 5493 // vector_shuffle <6,7,2,3> lhs, rhs 5494 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5495 // 5496 // vector_shuffle <6,7,0,1> lhs, rhs 5497 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5498 5499 // Avoid scalarizing when both halves are reading from consecutive elements. 5500 SmallVector<SDValue, 4> Pieces; 5501 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5502 if (elementPairIsContiguous(SVN->getMask(), I)) { 5503 const int Idx = SVN->getMaskElt(I); 5504 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5505 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5506 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5507 PackVT, SVN->getOperand(VecIdx), 5508 DAG.getConstant(EltIdx, SL, MVT::i32)); 5509 Pieces.push_back(SubVec); 5510 } else { 5511 const int Idx0 = SVN->getMaskElt(I); 5512 const int Idx1 = SVN->getMaskElt(I + 1); 5513 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5514 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5515 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5516 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5517 5518 SDValue Vec0 = SVN->getOperand(VecIdx0); 5519 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5520 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5521 5522 SDValue Vec1 = SVN->getOperand(VecIdx1); 5523 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5524 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5525 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5526 } 5527 } 5528 5529 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5530 } 5531 5532 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5533 SelectionDAG &DAG) const { 5534 SDLoc SL(Op); 5535 EVT VT = Op.getValueType(); 5536 5537 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5538 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5539 5540 // Turn into pair of packed build_vectors. 5541 // TODO: Special case for constants that can be materialized with s_mov_b64. 5542 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5543 { Op.getOperand(0), Op.getOperand(1) }); 5544 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5545 { Op.getOperand(2), Op.getOperand(3) }); 5546 5547 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5548 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5549 5550 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5551 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5552 } 5553 5554 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5555 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5556 5557 SDValue Lo = Op.getOperand(0); 5558 SDValue Hi = Op.getOperand(1); 5559 5560 // Avoid adding defined bits with the zero_extend. 5561 if (Hi.isUndef()) { 5562 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5563 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5564 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5565 } 5566 5567 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5568 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5569 5570 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5571 DAG.getConstant(16, SL, MVT::i32)); 5572 if (Lo.isUndef()) 5573 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5574 5575 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5576 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5577 5578 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5579 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5580 } 5581 5582 bool 5583 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5584 // We can fold offsets for anything that doesn't require a GOT relocation. 5585 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5586 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5587 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5588 !shouldEmitGOTReloc(GA->getGlobal()); 5589 } 5590 5591 static SDValue 5592 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5593 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5594 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5595 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5596 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5597 // lowered to the following code sequence: 5598 // 5599 // For constant address space: 5600 // s_getpc_b64 s[0:1] 5601 // s_add_u32 s0, s0, $symbol 5602 // s_addc_u32 s1, s1, 0 5603 // 5604 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5605 // a fixup or relocation is emitted to replace $symbol with a literal 5606 // constant, which is a pc-relative offset from the encoding of the $symbol 5607 // operand to the global variable. 5608 // 5609 // For global address space: 5610 // s_getpc_b64 s[0:1] 5611 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5612 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5613 // 5614 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5615 // fixups or relocations are emitted to replace $symbol@*@lo and 5616 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5617 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5618 // operand to the global variable. 5619 // 5620 // What we want here is an offset from the value returned by s_getpc 5621 // (which is the address of the s_add_u32 instruction) to the global 5622 // variable, but since the encoding of $symbol starts 4 bytes after the start 5623 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5624 // small. This requires us to add 4 to the global variable offset in order to 5625 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5626 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5627 // instruction. 5628 SDValue PtrLo = 5629 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5630 SDValue PtrHi; 5631 if (GAFlags == SIInstrInfo::MO_NONE) { 5632 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5633 } else { 5634 PtrHi = 5635 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5636 } 5637 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5638 } 5639 5640 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5641 SDValue Op, 5642 SelectionDAG &DAG) const { 5643 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5644 SDLoc DL(GSD); 5645 EVT PtrVT = Op.getValueType(); 5646 5647 const GlobalValue *GV = GSD->getGlobal(); 5648 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5649 shouldUseLDSConstAddress(GV)) || 5650 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5651 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5652 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5653 GV->hasExternalLinkage()) { 5654 Type *Ty = GV->getValueType(); 5655 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5656 // zero-sized type in other languages to declare the dynamic shared 5657 // memory which size is not known at the compile time. They will be 5658 // allocated by the runtime and placed directly after the static 5659 // allocated ones. They all share the same offset. 5660 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5661 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5662 // Adjust alignment for that dynamic shared memory array. 5663 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5664 return SDValue( 5665 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5666 } 5667 } 5668 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5669 } 5670 5671 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5672 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5673 SIInstrInfo::MO_ABS32_LO); 5674 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5675 } 5676 5677 if (shouldEmitFixup(GV)) 5678 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5679 else if (shouldEmitPCReloc(GV)) 5680 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5681 SIInstrInfo::MO_REL32); 5682 5683 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5684 SIInstrInfo::MO_GOTPCREL32); 5685 5686 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5687 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5688 const DataLayout &DataLayout = DAG.getDataLayout(); 5689 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5690 MachinePointerInfo PtrInfo 5691 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5692 5693 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5694 MachineMemOperand::MODereferenceable | 5695 MachineMemOperand::MOInvariant); 5696 } 5697 5698 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5699 const SDLoc &DL, SDValue V) const { 5700 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5701 // the destination register. 5702 // 5703 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5704 // so we will end up with redundant moves to m0. 5705 // 5706 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5707 5708 // A Null SDValue creates a glue result. 5709 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5710 V, Chain); 5711 return SDValue(M0, 0); 5712 } 5713 5714 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5715 SDValue Op, 5716 MVT VT, 5717 unsigned Offset) const { 5718 SDLoc SL(Op); 5719 SDValue Param = lowerKernargMemParameter( 5720 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5721 // The local size values will have the hi 16-bits as zero. 5722 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5723 DAG.getValueType(VT)); 5724 } 5725 5726 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5727 EVT VT) { 5728 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5729 "non-hsa intrinsic with hsa target", 5730 DL.getDebugLoc()); 5731 DAG.getContext()->diagnose(BadIntrin); 5732 return DAG.getUNDEF(VT); 5733 } 5734 5735 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5736 EVT VT) { 5737 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5738 "intrinsic not supported on subtarget", 5739 DL.getDebugLoc()); 5740 DAG.getContext()->diagnose(BadIntrin); 5741 return DAG.getUNDEF(VT); 5742 } 5743 5744 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5745 ArrayRef<SDValue> Elts) { 5746 assert(!Elts.empty()); 5747 MVT Type; 5748 unsigned NumElts; 5749 5750 if (Elts.size() == 1) { 5751 Type = MVT::f32; 5752 NumElts = 1; 5753 } else if (Elts.size() == 2) { 5754 Type = MVT::v2f32; 5755 NumElts = 2; 5756 } else if (Elts.size() == 3) { 5757 Type = MVT::v3f32; 5758 NumElts = 3; 5759 } else if (Elts.size() <= 4) { 5760 Type = MVT::v4f32; 5761 NumElts = 4; 5762 } else if (Elts.size() <= 8) { 5763 Type = MVT::v8f32; 5764 NumElts = 8; 5765 } else { 5766 assert(Elts.size() <= 16); 5767 Type = MVT::v16f32; 5768 NumElts = 16; 5769 } 5770 5771 SmallVector<SDValue, 16> VecElts(NumElts); 5772 for (unsigned i = 0; i < Elts.size(); ++i) { 5773 SDValue Elt = Elts[i]; 5774 if (Elt.getValueType() != MVT::f32) 5775 Elt = DAG.getBitcast(MVT::f32, Elt); 5776 VecElts[i] = Elt; 5777 } 5778 for (unsigned i = Elts.size(); i < NumElts; ++i) 5779 VecElts[i] = DAG.getUNDEF(MVT::f32); 5780 5781 if (NumElts == 1) 5782 return VecElts[0]; 5783 return DAG.getBuildVector(Type, DL, VecElts); 5784 } 5785 5786 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5787 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5788 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5789 5790 uint64_t Value = CachePolicyConst->getZExtValue(); 5791 SDLoc DL(CachePolicy); 5792 if (GLC) { 5793 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5794 Value &= ~(uint64_t)0x1; 5795 } 5796 if (SLC) { 5797 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5798 Value &= ~(uint64_t)0x2; 5799 } 5800 if (DLC) { 5801 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5802 Value &= ~(uint64_t)0x4; 5803 } 5804 5805 return Value == 0; 5806 } 5807 5808 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5809 SDValue Src, int ExtraElts) { 5810 EVT SrcVT = Src.getValueType(); 5811 5812 SmallVector<SDValue, 8> Elts; 5813 5814 if (SrcVT.isVector()) 5815 DAG.ExtractVectorElements(Src, Elts); 5816 else 5817 Elts.push_back(Src); 5818 5819 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5820 while (ExtraElts--) 5821 Elts.push_back(Undef); 5822 5823 return DAG.getBuildVector(CastVT, DL, Elts); 5824 } 5825 5826 // Re-construct the required return value for a image load intrinsic. 5827 // This is more complicated due to the optional use TexFailCtrl which means the required 5828 // return type is an aggregate 5829 static SDValue constructRetValue(SelectionDAG &DAG, 5830 MachineSDNode *Result, 5831 ArrayRef<EVT> ResultTypes, 5832 bool IsTexFail, bool Unpacked, bool IsD16, 5833 int DMaskPop, int NumVDataDwords, 5834 const SDLoc &DL, LLVMContext &Context) { 5835 // Determine the required return type. This is the same regardless of IsTexFail flag 5836 EVT ReqRetVT = ResultTypes[0]; 5837 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5838 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5839 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5840 5841 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5842 DMaskPop : (DMaskPop + 1) / 2; 5843 5844 MVT DataDwordVT = NumDataDwords == 1 ? 5845 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5846 5847 MVT MaskPopVT = MaskPopDwords == 1 ? 5848 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5849 5850 SDValue Data(Result, 0); 5851 SDValue TexFail; 5852 5853 if (IsTexFail) { 5854 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5855 if (MaskPopVT.isVector()) { 5856 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5857 SDValue(Result, 0), ZeroIdx); 5858 } else { 5859 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5860 SDValue(Result, 0), ZeroIdx); 5861 } 5862 5863 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5864 SDValue(Result, 0), 5865 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5866 } 5867 5868 if (DataDwordVT.isVector()) 5869 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5870 NumDataDwords - MaskPopDwords); 5871 5872 if (IsD16) 5873 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5874 5875 EVT LegalReqRetVT = ReqRetVT; 5876 if (!ReqRetVT.isVector()) { 5877 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5878 } else { 5879 // We need to widen the return vector to a legal type 5880 if ((ReqRetVT.getVectorNumElements() % 2) == 1) { 5881 LegalReqRetVT = 5882 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5883 ReqRetVT.getVectorNumElements() + 1); 5884 } 5885 } 5886 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5887 5888 if (TexFail) 5889 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5890 5891 if (Result->getNumValues() == 1) 5892 return Data; 5893 5894 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5895 } 5896 5897 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5898 SDValue *LWE, bool &IsTexFail) { 5899 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5900 5901 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5902 if (Value) { 5903 IsTexFail = true; 5904 } 5905 5906 SDLoc DL(TexFailCtrlConst); 5907 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5908 Value &= ~(uint64_t)0x1; 5909 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5910 Value &= ~(uint64_t)0x2; 5911 5912 return Value == 0; 5913 } 5914 5915 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5916 MVT PackVectorVT, 5917 SmallVectorImpl<SDValue> &PackedAddrs, 5918 unsigned DimIdx, unsigned EndIdx, 5919 unsigned NumGradients) { 5920 SDLoc DL(Op); 5921 for (unsigned I = DimIdx; I < EndIdx; I++) { 5922 SDValue Addr = Op.getOperand(I); 5923 5924 // Gradients are packed with undef for each coordinate. 5925 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5926 // 1D: undef,dx/dh; undef,dx/dv 5927 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5928 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5929 if (((I + 1) >= EndIdx) || 5930 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5931 I == DimIdx + NumGradients - 1))) { 5932 if (Addr.getValueType() != MVT::i16) 5933 Addr = DAG.getBitcast(MVT::i16, Addr); 5934 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5935 } else { 5936 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5937 I++; 5938 } 5939 Addr = DAG.getBitcast(MVT::f32, Addr); 5940 PackedAddrs.push_back(Addr); 5941 } 5942 } 5943 5944 SDValue SITargetLowering::lowerImage(SDValue Op, 5945 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5946 SelectionDAG &DAG) const { 5947 SDLoc DL(Op); 5948 MachineFunction &MF = DAG.getMachineFunction(); 5949 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5950 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5951 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5952 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5953 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5954 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5955 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5956 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5957 unsigned IntrOpcode = Intr->BaseOpcode; 5958 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5959 5960 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5961 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5962 bool IsD16 = false; 5963 bool IsG16 = false; 5964 bool IsA16 = false; 5965 SDValue VData; 5966 int NumVDataDwords; 5967 bool AdjustRetType = false; 5968 5969 unsigned AddrIdx; // Index of first address argument 5970 unsigned DMask; 5971 unsigned DMaskLanes = 0; 5972 5973 if (BaseOpcode->Atomic) { 5974 VData = Op.getOperand(2); 5975 5976 bool Is64Bit = VData.getValueType() == MVT::i64; 5977 if (BaseOpcode->AtomicX2) { 5978 SDValue VData2 = Op.getOperand(3); 5979 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5980 {VData, VData2}); 5981 if (Is64Bit) 5982 VData = DAG.getBitcast(MVT::v4i32, VData); 5983 5984 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5985 DMask = Is64Bit ? 0xf : 0x3; 5986 NumVDataDwords = Is64Bit ? 4 : 2; 5987 AddrIdx = 4; 5988 } else { 5989 DMask = Is64Bit ? 0x3 : 0x1; 5990 NumVDataDwords = Is64Bit ? 2 : 1; 5991 AddrIdx = 3; 5992 } 5993 } else { 5994 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5995 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5996 DMask = DMaskConst->getZExtValue(); 5997 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5998 5999 if (BaseOpcode->Store) { 6000 VData = Op.getOperand(2); 6001 6002 MVT StoreVT = VData.getSimpleValueType(); 6003 if (StoreVT.getScalarType() == MVT::f16) { 6004 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6005 return Op; // D16 is unsupported for this instruction 6006 6007 IsD16 = true; 6008 VData = handleD16VData(VData, DAG); 6009 } 6010 6011 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6012 } else { 6013 // Work out the num dwords based on the dmask popcount and underlying type 6014 // and whether packing is supported. 6015 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6016 if (LoadVT.getScalarType() == MVT::f16) { 6017 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6018 return Op; // D16 is unsupported for this instruction 6019 6020 IsD16 = true; 6021 } 6022 6023 // Confirm that the return type is large enough for the dmask specified 6024 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6025 (!LoadVT.isVector() && DMaskLanes > 1)) 6026 return Op; 6027 6028 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 6029 NumVDataDwords = (DMaskLanes + 1) / 2; 6030 else 6031 NumVDataDwords = DMaskLanes; 6032 6033 AdjustRetType = true; 6034 } 6035 6036 AddrIdx = DMaskIdx + 1; 6037 } 6038 6039 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 6040 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 6041 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 6042 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 6043 NumCoords + NumLCM; 6044 unsigned NumMIVAddrs = NumVAddrs; 6045 6046 SmallVector<SDValue, 4> VAddrs; 6047 6048 // Optimize _L to _LZ when _L is zero 6049 if (LZMappingInfo) { 6050 if (auto ConstantLod = 6051 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 6052 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6053 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6054 NumMIVAddrs--; // remove 'lod' 6055 } 6056 } 6057 } 6058 6059 // Optimize _mip away, when 'lod' is zero 6060 if (MIPMappingInfo) { 6061 if (auto ConstantLod = 6062 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 6063 if (ConstantLod->isNullValue()) { 6064 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6065 NumMIVAddrs--; // remove 'lod' 6066 } 6067 } 6068 } 6069 6070 // Push back extra arguments. 6071 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 6072 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 6073 6074 // Check for 16 bit addresses or derivatives and pack if true. 6075 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 6076 unsigned CoordIdx = DimIdx + NumGradients; 6077 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 6078 6079 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 6080 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6081 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6082 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6083 6084 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 6085 VAddrScalarVT = VAddrVT.getScalarType(); 6086 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6087 if (IsA16 || IsG16) { 6088 if (IsA16) { 6089 if (!ST->hasA16()) { 6090 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6091 "support 16 bit addresses\n"); 6092 return Op; 6093 } 6094 if (!IsG16) { 6095 LLVM_DEBUG( 6096 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6097 "need 16 bit derivatives but got 32 bit derivatives\n"); 6098 return Op; 6099 } 6100 } else if (!ST->hasG16()) { 6101 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6102 "support 16 bit derivatives\n"); 6103 return Op; 6104 } 6105 6106 if (BaseOpcode->Gradients && !IsA16) { 6107 if (!ST->hasG16()) { 6108 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6109 "support 16 bit derivatives\n"); 6110 return Op; 6111 } 6112 // Activate g16 6113 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6114 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6115 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6116 } 6117 6118 // Don't compress addresses for G16 6119 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 6120 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 6121 PackEndIdx, NumGradients); 6122 6123 if (!IsA16) { 6124 // Add uncompressed address 6125 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 6126 VAddrs.push_back(Op.getOperand(I)); 6127 } 6128 } else { 6129 for (unsigned I = DimIdx; I < CoordsEnd; I++) 6130 VAddrs.push_back(Op.getOperand(I)); 6131 } 6132 6133 // If the register allocator cannot place the address registers contiguously 6134 // without introducing moves, then using the non-sequential address encoding 6135 // is always preferable, since it saves VALU instructions and is usually a 6136 // wash in terms of code size or even better. 6137 // 6138 // However, we currently have no way of hinting to the register allocator that 6139 // MIMG addresses should be placed contiguously when it is possible to do so, 6140 // so force non-NSA for the common 2-address case as a heuristic. 6141 // 6142 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6143 // allocation when possible. 6144 bool UseNSA = 6145 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6146 SDValue VAddr; 6147 if (!UseNSA) 6148 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6149 6150 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6151 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6152 unsigned CtrlIdx; // Index of texfailctrl argument 6153 SDValue Unorm; 6154 if (!BaseOpcode->Sampler) { 6155 Unorm = True; 6156 CtrlIdx = AddrIdx + NumVAddrs + 1; 6157 } else { 6158 auto UnormConst = 6159 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6160 6161 Unorm = UnormConst->getZExtValue() ? True : False; 6162 CtrlIdx = AddrIdx + NumVAddrs + 3; 6163 } 6164 6165 SDValue TFE; 6166 SDValue LWE; 6167 SDValue TexFail = Op.getOperand(CtrlIdx); 6168 bool IsTexFail = false; 6169 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6170 return Op; 6171 6172 if (IsTexFail) { 6173 if (!DMaskLanes) { 6174 // Expecting to get an error flag since TFC is on - and dmask is 0 6175 // Force dmask to be at least 1 otherwise the instruction will fail 6176 DMask = 0x1; 6177 DMaskLanes = 1; 6178 NumVDataDwords = 1; 6179 } 6180 NumVDataDwords += 1; 6181 AdjustRetType = true; 6182 } 6183 6184 // Has something earlier tagged that the return type needs adjusting 6185 // This happens if the instruction is a load or has set TexFailCtrl flags 6186 if (AdjustRetType) { 6187 // NumVDataDwords reflects the true number of dwords required in the return type 6188 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6189 // This is a no-op load. This can be eliminated 6190 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6191 if (isa<MemSDNode>(Op)) 6192 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6193 return Undef; 6194 } 6195 6196 EVT NewVT = NumVDataDwords > 1 ? 6197 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6198 : MVT::i32; 6199 6200 ResultTypes[0] = NewVT; 6201 if (ResultTypes.size() == 3) { 6202 // Original result was aggregate type used for TexFailCtrl results 6203 // The actual instruction returns as a vector type which has now been 6204 // created. Remove the aggregate result. 6205 ResultTypes.erase(&ResultTypes[1]); 6206 } 6207 } 6208 6209 SDValue GLC; 6210 SDValue SLC; 6211 SDValue DLC; 6212 if (BaseOpcode->Atomic) { 6213 GLC = True; // TODO no-return optimization 6214 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6215 IsGFX10 ? &DLC : nullptr)) 6216 return Op; 6217 } else { 6218 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6219 IsGFX10 ? &DLC : nullptr)) 6220 return Op; 6221 } 6222 6223 SmallVector<SDValue, 26> Ops; 6224 if (BaseOpcode->Store || BaseOpcode->Atomic) 6225 Ops.push_back(VData); // vdata 6226 if (UseNSA) { 6227 for (const SDValue &Addr : VAddrs) 6228 Ops.push_back(Addr); 6229 } else { 6230 Ops.push_back(VAddr); 6231 } 6232 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6233 if (BaseOpcode->Sampler) 6234 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6235 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6236 if (IsGFX10) 6237 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6238 Ops.push_back(Unorm); 6239 if (IsGFX10) 6240 Ops.push_back(DLC); 6241 Ops.push_back(GLC); 6242 Ops.push_back(SLC); 6243 Ops.push_back(IsA16 && // r128, a16 for gfx9 6244 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6245 if (IsGFX10) 6246 Ops.push_back(IsA16 ? True : False); 6247 Ops.push_back(TFE); 6248 Ops.push_back(LWE); 6249 if (!IsGFX10) 6250 Ops.push_back(DimInfo->DA ? True : False); 6251 if (BaseOpcode->HasD16) 6252 Ops.push_back(IsD16 ? True : False); 6253 if (isa<MemSDNode>(Op)) 6254 Ops.push_back(Op.getOperand(0)); // chain 6255 6256 int NumVAddrDwords = 6257 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6258 int Opcode = -1; 6259 6260 if (IsGFX10) { 6261 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6262 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6263 : AMDGPU::MIMGEncGfx10Default, 6264 NumVDataDwords, NumVAddrDwords); 6265 } else { 6266 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6267 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6268 NumVDataDwords, NumVAddrDwords); 6269 if (Opcode == -1) 6270 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6271 NumVDataDwords, NumVAddrDwords); 6272 } 6273 assert(Opcode != -1); 6274 6275 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6276 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6277 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6278 DAG.setNodeMemRefs(NewNode, {MemRef}); 6279 } 6280 6281 if (BaseOpcode->AtomicX2) { 6282 SmallVector<SDValue, 1> Elt; 6283 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6284 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6285 } else if (!BaseOpcode->Store) { 6286 return constructRetValue(DAG, NewNode, 6287 OrigResultTypes, IsTexFail, 6288 Subtarget->hasUnpackedD16VMem(), IsD16, 6289 DMaskLanes, NumVDataDwords, DL, 6290 *DAG.getContext()); 6291 } 6292 6293 return SDValue(NewNode, 0); 6294 } 6295 6296 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6297 SDValue Offset, SDValue CachePolicy, 6298 SelectionDAG &DAG) const { 6299 MachineFunction &MF = DAG.getMachineFunction(); 6300 6301 const DataLayout &DataLayout = DAG.getDataLayout(); 6302 Align Alignment = 6303 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6304 6305 MachineMemOperand *MMO = MF.getMachineMemOperand( 6306 MachinePointerInfo(), 6307 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6308 MachineMemOperand::MOInvariant, 6309 VT.getStoreSize(), Alignment); 6310 6311 if (!Offset->isDivergent()) { 6312 SDValue Ops[] = { 6313 Rsrc, 6314 Offset, // Offset 6315 CachePolicy 6316 }; 6317 6318 // Widen vec3 load to vec4. 6319 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6320 EVT WidenedVT = 6321 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6322 auto WidenedOp = DAG.getMemIntrinsicNode( 6323 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6324 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6325 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6326 DAG.getVectorIdxConstant(0, DL)); 6327 return Subvector; 6328 } 6329 6330 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6331 DAG.getVTList(VT), Ops, VT, MMO); 6332 } 6333 6334 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6335 // assume that the buffer is unswizzled. 6336 SmallVector<SDValue, 4> Loads; 6337 unsigned NumLoads = 1; 6338 MVT LoadVT = VT.getSimpleVT(); 6339 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6340 assert((LoadVT.getScalarType() == MVT::i32 || 6341 LoadVT.getScalarType() == MVT::f32)); 6342 6343 if (NumElts == 8 || NumElts == 16) { 6344 NumLoads = NumElts / 4; 6345 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6346 } 6347 6348 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6349 SDValue Ops[] = { 6350 DAG.getEntryNode(), // Chain 6351 Rsrc, // rsrc 6352 DAG.getConstant(0, DL, MVT::i32), // vindex 6353 {}, // voffset 6354 {}, // soffset 6355 {}, // offset 6356 CachePolicy, // cachepolicy 6357 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6358 }; 6359 6360 // Use the alignment to ensure that the required offsets will fit into the 6361 // immediate offsets. 6362 setBufferOffsets(Offset, DAG, &Ops[3], 6363 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6364 6365 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6366 for (unsigned i = 0; i < NumLoads; ++i) { 6367 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6368 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6369 LoadVT, MMO, DAG)); 6370 } 6371 6372 if (NumElts == 8 || NumElts == 16) 6373 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6374 6375 return Loads[0]; 6376 } 6377 6378 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6379 SelectionDAG &DAG) const { 6380 MachineFunction &MF = DAG.getMachineFunction(); 6381 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6382 6383 EVT VT = Op.getValueType(); 6384 SDLoc DL(Op); 6385 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6386 6387 // TODO: Should this propagate fast-math-flags? 6388 6389 switch (IntrinsicID) { 6390 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6391 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6392 return emitNonHSAIntrinsicError(DAG, DL, VT); 6393 return getPreloadedValue(DAG, *MFI, VT, 6394 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6395 } 6396 case Intrinsic::amdgcn_dispatch_ptr: 6397 case Intrinsic::amdgcn_queue_ptr: { 6398 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6399 DiagnosticInfoUnsupported BadIntrin( 6400 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6401 DL.getDebugLoc()); 6402 DAG.getContext()->diagnose(BadIntrin); 6403 return DAG.getUNDEF(VT); 6404 } 6405 6406 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6407 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6408 return getPreloadedValue(DAG, *MFI, VT, RegID); 6409 } 6410 case Intrinsic::amdgcn_implicitarg_ptr: { 6411 if (MFI->isEntryFunction()) 6412 return getImplicitArgPtr(DAG, DL); 6413 return getPreloadedValue(DAG, *MFI, VT, 6414 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6415 } 6416 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6417 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6418 // This only makes sense to call in a kernel, so just lower to null. 6419 return DAG.getConstant(0, DL, VT); 6420 } 6421 6422 return getPreloadedValue(DAG, *MFI, VT, 6423 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6424 } 6425 case Intrinsic::amdgcn_dispatch_id: { 6426 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6427 } 6428 case Intrinsic::amdgcn_rcp: 6429 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6430 case Intrinsic::amdgcn_rsq: 6431 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6432 case Intrinsic::amdgcn_rsq_legacy: 6433 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6434 return emitRemovedIntrinsicError(DAG, DL, VT); 6435 return SDValue(); 6436 case Intrinsic::amdgcn_rcp_legacy: 6437 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6438 return emitRemovedIntrinsicError(DAG, DL, VT); 6439 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6440 case Intrinsic::amdgcn_rsq_clamp: { 6441 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6442 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6443 6444 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6445 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6446 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6447 6448 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6449 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6450 DAG.getConstantFP(Max, DL, VT)); 6451 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6452 DAG.getConstantFP(Min, DL, VT)); 6453 } 6454 case Intrinsic::r600_read_ngroups_x: 6455 if (Subtarget->isAmdHsaOS()) 6456 return emitNonHSAIntrinsicError(DAG, DL, VT); 6457 6458 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6459 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6460 false); 6461 case Intrinsic::r600_read_ngroups_y: 6462 if (Subtarget->isAmdHsaOS()) 6463 return emitNonHSAIntrinsicError(DAG, DL, VT); 6464 6465 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6466 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6467 false); 6468 case Intrinsic::r600_read_ngroups_z: 6469 if (Subtarget->isAmdHsaOS()) 6470 return emitNonHSAIntrinsicError(DAG, DL, VT); 6471 6472 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6473 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6474 false); 6475 case Intrinsic::r600_read_global_size_x: 6476 if (Subtarget->isAmdHsaOS()) 6477 return emitNonHSAIntrinsicError(DAG, DL, VT); 6478 6479 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6480 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6481 Align(4), false); 6482 case Intrinsic::r600_read_global_size_y: 6483 if (Subtarget->isAmdHsaOS()) 6484 return emitNonHSAIntrinsicError(DAG, DL, VT); 6485 6486 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6487 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6488 Align(4), false); 6489 case Intrinsic::r600_read_global_size_z: 6490 if (Subtarget->isAmdHsaOS()) 6491 return emitNonHSAIntrinsicError(DAG, DL, VT); 6492 6493 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6494 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6495 Align(4), false); 6496 case Intrinsic::r600_read_local_size_x: 6497 if (Subtarget->isAmdHsaOS()) 6498 return emitNonHSAIntrinsicError(DAG, DL, VT); 6499 6500 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6501 SI::KernelInputOffsets::LOCAL_SIZE_X); 6502 case Intrinsic::r600_read_local_size_y: 6503 if (Subtarget->isAmdHsaOS()) 6504 return emitNonHSAIntrinsicError(DAG, DL, VT); 6505 6506 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6507 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6508 case Intrinsic::r600_read_local_size_z: 6509 if (Subtarget->isAmdHsaOS()) 6510 return emitNonHSAIntrinsicError(DAG, DL, VT); 6511 6512 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6513 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6514 case Intrinsic::amdgcn_workgroup_id_x: 6515 return getPreloadedValue(DAG, *MFI, VT, 6516 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6517 case Intrinsic::amdgcn_workgroup_id_y: 6518 return getPreloadedValue(DAG, *MFI, VT, 6519 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6520 case Intrinsic::amdgcn_workgroup_id_z: 6521 return getPreloadedValue(DAG, *MFI, VT, 6522 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6523 case Intrinsic::amdgcn_workitem_id_x: 6524 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6525 SDLoc(DAG.getEntryNode()), 6526 MFI->getArgInfo().WorkItemIDX); 6527 case Intrinsic::amdgcn_workitem_id_y: 6528 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6529 SDLoc(DAG.getEntryNode()), 6530 MFI->getArgInfo().WorkItemIDY); 6531 case Intrinsic::amdgcn_workitem_id_z: 6532 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6533 SDLoc(DAG.getEntryNode()), 6534 MFI->getArgInfo().WorkItemIDZ); 6535 case Intrinsic::amdgcn_wavefrontsize: 6536 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6537 SDLoc(Op), MVT::i32); 6538 case Intrinsic::amdgcn_s_buffer_load: { 6539 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6540 SDValue GLC; 6541 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6542 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6543 IsGFX10 ? &DLC : nullptr)) 6544 return Op; 6545 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6546 DAG); 6547 } 6548 case Intrinsic::amdgcn_fdiv_fast: 6549 return lowerFDIV_FAST(Op, DAG); 6550 case Intrinsic::amdgcn_sin: 6551 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6552 6553 case Intrinsic::amdgcn_cos: 6554 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6555 6556 case Intrinsic::amdgcn_mul_u24: 6557 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6558 case Intrinsic::amdgcn_mul_i24: 6559 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6560 6561 case Intrinsic::amdgcn_log_clamp: { 6562 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6563 return SDValue(); 6564 6565 DiagnosticInfoUnsupported BadIntrin( 6566 MF.getFunction(), "intrinsic not supported on subtarget", 6567 DL.getDebugLoc()); 6568 DAG.getContext()->diagnose(BadIntrin); 6569 return DAG.getUNDEF(VT); 6570 } 6571 case Intrinsic::amdgcn_ldexp: 6572 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6573 Op.getOperand(1), Op.getOperand(2)); 6574 6575 case Intrinsic::amdgcn_fract: 6576 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6577 6578 case Intrinsic::amdgcn_class: 6579 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6580 Op.getOperand(1), Op.getOperand(2)); 6581 case Intrinsic::amdgcn_div_fmas: 6582 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6583 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6584 Op.getOperand(4)); 6585 6586 case Intrinsic::amdgcn_div_fixup: 6587 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6588 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6589 6590 case Intrinsic::amdgcn_div_scale: { 6591 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6592 6593 // Translate to the operands expected by the machine instruction. The 6594 // first parameter must be the same as the first instruction. 6595 SDValue Numerator = Op.getOperand(1); 6596 SDValue Denominator = Op.getOperand(2); 6597 6598 // Note this order is opposite of the machine instruction's operations, 6599 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6600 // intrinsic has the numerator as the first operand to match a normal 6601 // division operation. 6602 6603 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6604 6605 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6606 Denominator, Numerator); 6607 } 6608 case Intrinsic::amdgcn_icmp: { 6609 // There is a Pat that handles this variant, so return it as-is. 6610 if (Op.getOperand(1).getValueType() == MVT::i1 && 6611 Op.getConstantOperandVal(2) == 0 && 6612 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6613 return Op; 6614 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6615 } 6616 case Intrinsic::amdgcn_fcmp: { 6617 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6618 } 6619 case Intrinsic::amdgcn_ballot: 6620 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6621 case Intrinsic::amdgcn_fmed3: 6622 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6623 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6624 case Intrinsic::amdgcn_fdot2: 6625 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6626 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6627 Op.getOperand(4)); 6628 case Intrinsic::amdgcn_fmul_legacy: 6629 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6630 Op.getOperand(1), Op.getOperand(2)); 6631 case Intrinsic::amdgcn_sffbh: 6632 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6633 case Intrinsic::amdgcn_sbfe: 6634 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6635 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6636 case Intrinsic::amdgcn_ubfe: 6637 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6638 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6639 case Intrinsic::amdgcn_cvt_pkrtz: 6640 case Intrinsic::amdgcn_cvt_pknorm_i16: 6641 case Intrinsic::amdgcn_cvt_pknorm_u16: 6642 case Intrinsic::amdgcn_cvt_pk_i16: 6643 case Intrinsic::amdgcn_cvt_pk_u16: { 6644 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6645 EVT VT = Op.getValueType(); 6646 unsigned Opcode; 6647 6648 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6649 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6650 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6651 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6652 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6653 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6654 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6655 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6656 else 6657 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6658 6659 if (isTypeLegal(VT)) 6660 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6661 6662 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6663 Op.getOperand(1), Op.getOperand(2)); 6664 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6665 } 6666 case Intrinsic::amdgcn_fmad_ftz: 6667 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6668 Op.getOperand(2), Op.getOperand(3)); 6669 6670 case Intrinsic::amdgcn_if_break: 6671 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6672 Op->getOperand(1), Op->getOperand(2)), 0); 6673 6674 case Intrinsic::amdgcn_groupstaticsize: { 6675 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6676 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6677 return Op; 6678 6679 const Module *M = MF.getFunction().getParent(); 6680 const GlobalValue *GV = 6681 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6682 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6683 SIInstrInfo::MO_ABS32_LO); 6684 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6685 } 6686 case Intrinsic::amdgcn_is_shared: 6687 case Intrinsic::amdgcn_is_private: { 6688 SDLoc SL(Op); 6689 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6690 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6691 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6692 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6693 Op.getOperand(1)); 6694 6695 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6696 DAG.getConstant(1, SL, MVT::i32)); 6697 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6698 } 6699 case Intrinsic::amdgcn_alignbit: 6700 return DAG.getNode(ISD::FSHR, DL, VT, 6701 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6702 case Intrinsic::amdgcn_reloc_constant: { 6703 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6704 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6705 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6706 auto RelocSymbol = cast<GlobalVariable>( 6707 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6708 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6709 SIInstrInfo::MO_ABS32_LO); 6710 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6711 } 6712 default: 6713 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6714 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6715 return lowerImage(Op, ImageDimIntr, DAG); 6716 6717 return Op; 6718 } 6719 } 6720 6721 // This function computes an appropriate offset to pass to 6722 // MachineMemOperand::setOffset() based on the offset inputs to 6723 // an intrinsic. If any of the offsets are non-contstant or 6724 // if VIndex is non-zero then this function returns 0. Otherwise, 6725 // it returns the sum of VOffset, SOffset, and Offset. 6726 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6727 SDValue SOffset, 6728 SDValue Offset, 6729 SDValue VIndex = SDValue()) { 6730 6731 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6732 !isa<ConstantSDNode>(Offset)) 6733 return 0; 6734 6735 if (VIndex) { 6736 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6737 return 0; 6738 } 6739 6740 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6741 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6742 cast<ConstantSDNode>(Offset)->getSExtValue(); 6743 } 6744 6745 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6746 SelectionDAG &DAG, 6747 unsigned NewOpcode) const { 6748 SDLoc DL(Op); 6749 6750 SDValue VData = Op.getOperand(2); 6751 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6752 SDValue Ops[] = { 6753 Op.getOperand(0), // Chain 6754 VData, // vdata 6755 Op.getOperand(3), // rsrc 6756 DAG.getConstant(0, DL, MVT::i32), // vindex 6757 Offsets.first, // voffset 6758 Op.getOperand(5), // soffset 6759 Offsets.second, // offset 6760 Op.getOperand(6), // cachepolicy 6761 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6762 }; 6763 6764 auto *M = cast<MemSDNode>(Op); 6765 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6766 6767 EVT MemVT = VData.getValueType(); 6768 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6769 M->getMemOperand()); 6770 } 6771 6772 SDValue 6773 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6774 unsigned NewOpcode) const { 6775 SDLoc DL(Op); 6776 6777 SDValue VData = Op.getOperand(2); 6778 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6779 SDValue Ops[] = { 6780 Op.getOperand(0), // Chain 6781 VData, // vdata 6782 Op.getOperand(3), // rsrc 6783 Op.getOperand(4), // vindex 6784 Offsets.first, // voffset 6785 Op.getOperand(6), // soffset 6786 Offsets.second, // offset 6787 Op.getOperand(7), // cachepolicy 6788 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6789 }; 6790 6791 auto *M = cast<MemSDNode>(Op); 6792 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6793 Ops[3])); 6794 6795 EVT MemVT = VData.getValueType(); 6796 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6797 M->getMemOperand()); 6798 } 6799 6800 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6801 SelectionDAG &DAG) const { 6802 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6803 SDLoc DL(Op); 6804 6805 switch (IntrID) { 6806 case Intrinsic::amdgcn_ds_ordered_add: 6807 case Intrinsic::amdgcn_ds_ordered_swap: { 6808 MemSDNode *M = cast<MemSDNode>(Op); 6809 SDValue Chain = M->getOperand(0); 6810 SDValue M0 = M->getOperand(2); 6811 SDValue Value = M->getOperand(3); 6812 unsigned IndexOperand = M->getConstantOperandVal(7); 6813 unsigned WaveRelease = M->getConstantOperandVal(8); 6814 unsigned WaveDone = M->getConstantOperandVal(9); 6815 6816 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6817 IndexOperand &= ~0x3f; 6818 unsigned CountDw = 0; 6819 6820 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6821 CountDw = (IndexOperand >> 24) & 0xf; 6822 IndexOperand &= ~(0xf << 24); 6823 6824 if (CountDw < 1 || CountDw > 4) { 6825 report_fatal_error( 6826 "ds_ordered_count: dword count must be between 1 and 4"); 6827 } 6828 } 6829 6830 if (IndexOperand) 6831 report_fatal_error("ds_ordered_count: bad index operand"); 6832 6833 if (WaveDone && !WaveRelease) 6834 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6835 6836 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6837 unsigned ShaderType = 6838 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6839 unsigned Offset0 = OrderedCountIndex << 2; 6840 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6841 (Instruction << 4); 6842 6843 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6844 Offset1 |= (CountDw - 1) << 6; 6845 6846 unsigned Offset = Offset0 | (Offset1 << 8); 6847 6848 SDValue Ops[] = { 6849 Chain, 6850 Value, 6851 DAG.getTargetConstant(Offset, DL, MVT::i16), 6852 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6853 }; 6854 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6855 M->getVTList(), Ops, M->getMemoryVT(), 6856 M->getMemOperand()); 6857 } 6858 case Intrinsic::amdgcn_ds_fadd: { 6859 MemSDNode *M = cast<MemSDNode>(Op); 6860 unsigned Opc; 6861 switch (IntrID) { 6862 case Intrinsic::amdgcn_ds_fadd: 6863 Opc = ISD::ATOMIC_LOAD_FADD; 6864 break; 6865 } 6866 6867 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6868 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6869 M->getMemOperand()); 6870 } 6871 case Intrinsic::amdgcn_atomic_inc: 6872 case Intrinsic::amdgcn_atomic_dec: 6873 case Intrinsic::amdgcn_ds_fmin: 6874 case Intrinsic::amdgcn_ds_fmax: { 6875 MemSDNode *M = cast<MemSDNode>(Op); 6876 unsigned Opc; 6877 switch (IntrID) { 6878 case Intrinsic::amdgcn_atomic_inc: 6879 Opc = AMDGPUISD::ATOMIC_INC; 6880 break; 6881 case Intrinsic::amdgcn_atomic_dec: 6882 Opc = AMDGPUISD::ATOMIC_DEC; 6883 break; 6884 case Intrinsic::amdgcn_ds_fmin: 6885 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6886 break; 6887 case Intrinsic::amdgcn_ds_fmax: 6888 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6889 break; 6890 default: 6891 llvm_unreachable("Unknown intrinsic!"); 6892 } 6893 SDValue Ops[] = { 6894 M->getOperand(0), // Chain 6895 M->getOperand(2), // Ptr 6896 M->getOperand(3) // Value 6897 }; 6898 6899 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6900 M->getMemoryVT(), M->getMemOperand()); 6901 } 6902 case Intrinsic::amdgcn_buffer_load: 6903 case Intrinsic::amdgcn_buffer_load_format: { 6904 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6905 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6906 unsigned IdxEn = 1; 6907 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6908 IdxEn = Idx->getZExtValue() != 0; 6909 SDValue Ops[] = { 6910 Op.getOperand(0), // Chain 6911 Op.getOperand(2), // rsrc 6912 Op.getOperand(3), // vindex 6913 SDValue(), // voffset -- will be set by setBufferOffsets 6914 SDValue(), // soffset -- will be set by setBufferOffsets 6915 SDValue(), // offset -- will be set by setBufferOffsets 6916 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6917 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6918 }; 6919 6920 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6921 // We don't know the offset if vindex is non-zero, so clear it. 6922 if (IdxEn) 6923 Offset = 0; 6924 6925 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6926 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6927 6928 EVT VT = Op.getValueType(); 6929 EVT IntVT = VT.changeTypeToInteger(); 6930 auto *M = cast<MemSDNode>(Op); 6931 M->getMemOperand()->setOffset(Offset); 6932 EVT LoadVT = Op.getValueType(); 6933 6934 if (LoadVT.getScalarType() == MVT::f16) 6935 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6936 M, DAG, Ops); 6937 6938 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6939 if (LoadVT.getScalarType() == MVT::i8 || 6940 LoadVT.getScalarType() == MVT::i16) 6941 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6942 6943 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6944 M->getMemOperand(), DAG); 6945 } 6946 case Intrinsic::amdgcn_raw_buffer_load: 6947 case Intrinsic::amdgcn_raw_buffer_load_format: { 6948 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6949 6950 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6951 SDValue Ops[] = { 6952 Op.getOperand(0), // Chain 6953 Op.getOperand(2), // rsrc 6954 DAG.getConstant(0, DL, MVT::i32), // vindex 6955 Offsets.first, // voffset 6956 Op.getOperand(4), // soffset 6957 Offsets.second, // offset 6958 Op.getOperand(5), // cachepolicy, swizzled buffer 6959 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6960 }; 6961 6962 auto *M = cast<MemSDNode>(Op); 6963 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6964 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6965 } 6966 case Intrinsic::amdgcn_struct_buffer_load: 6967 case Intrinsic::amdgcn_struct_buffer_load_format: { 6968 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6969 6970 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6971 SDValue Ops[] = { 6972 Op.getOperand(0), // Chain 6973 Op.getOperand(2), // rsrc 6974 Op.getOperand(3), // vindex 6975 Offsets.first, // voffset 6976 Op.getOperand(5), // soffset 6977 Offsets.second, // offset 6978 Op.getOperand(6), // cachepolicy, swizzled buffer 6979 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6980 }; 6981 6982 auto *M = cast<MemSDNode>(Op); 6983 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6984 Ops[2])); 6985 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6986 } 6987 case Intrinsic::amdgcn_tbuffer_load: { 6988 MemSDNode *M = cast<MemSDNode>(Op); 6989 EVT LoadVT = Op.getValueType(); 6990 6991 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6992 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6993 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6994 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6995 unsigned IdxEn = 1; 6996 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6997 IdxEn = Idx->getZExtValue() != 0; 6998 SDValue Ops[] = { 6999 Op.getOperand(0), // Chain 7000 Op.getOperand(2), // rsrc 7001 Op.getOperand(3), // vindex 7002 Op.getOperand(4), // voffset 7003 Op.getOperand(5), // soffset 7004 Op.getOperand(6), // offset 7005 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7006 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7007 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7008 }; 7009 7010 if (LoadVT.getScalarType() == MVT::f16) 7011 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7012 M, DAG, Ops); 7013 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7014 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7015 DAG); 7016 } 7017 case Intrinsic::amdgcn_raw_tbuffer_load: { 7018 MemSDNode *M = cast<MemSDNode>(Op); 7019 EVT LoadVT = Op.getValueType(); 7020 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7021 7022 SDValue Ops[] = { 7023 Op.getOperand(0), // Chain 7024 Op.getOperand(2), // rsrc 7025 DAG.getConstant(0, DL, MVT::i32), // vindex 7026 Offsets.first, // voffset 7027 Op.getOperand(4), // soffset 7028 Offsets.second, // offset 7029 Op.getOperand(5), // format 7030 Op.getOperand(6), // cachepolicy, swizzled buffer 7031 DAG.getTargetConstant(0, 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_struct_tbuffer_load: { 7042 MemSDNode *M = cast<MemSDNode>(Op); 7043 EVT LoadVT = Op.getValueType(); 7044 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7045 7046 SDValue Ops[] = { 7047 Op.getOperand(0), // Chain 7048 Op.getOperand(2), // rsrc 7049 Op.getOperand(3), // vindex 7050 Offsets.first, // voffset 7051 Op.getOperand(5), // soffset 7052 Offsets.second, // offset 7053 Op.getOperand(6), // format 7054 Op.getOperand(7), // cachepolicy, swizzled buffer 7055 DAG.getTargetConstant(1, 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_buffer_atomic_swap: 7066 case Intrinsic::amdgcn_buffer_atomic_add: 7067 case Intrinsic::amdgcn_buffer_atomic_sub: 7068 case Intrinsic::amdgcn_buffer_atomic_csub: 7069 case Intrinsic::amdgcn_buffer_atomic_smin: 7070 case Intrinsic::amdgcn_buffer_atomic_umin: 7071 case Intrinsic::amdgcn_buffer_atomic_smax: 7072 case Intrinsic::amdgcn_buffer_atomic_umax: 7073 case Intrinsic::amdgcn_buffer_atomic_and: 7074 case Intrinsic::amdgcn_buffer_atomic_or: 7075 case Intrinsic::amdgcn_buffer_atomic_xor: 7076 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7077 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7078 unsigned IdxEn = 1; 7079 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7080 IdxEn = Idx->getZExtValue() != 0; 7081 SDValue Ops[] = { 7082 Op.getOperand(0), // Chain 7083 Op.getOperand(2), // vdata 7084 Op.getOperand(3), // rsrc 7085 Op.getOperand(4), // vindex 7086 SDValue(), // voffset -- will be set by setBufferOffsets 7087 SDValue(), // soffset -- will be set by setBufferOffsets 7088 SDValue(), // offset -- will be set by setBufferOffsets 7089 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7090 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7091 }; 7092 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7093 // We don't know the offset if vindex is non-zero, so clear it. 7094 if (IdxEn) 7095 Offset = 0; 7096 EVT VT = Op.getValueType(); 7097 7098 auto *M = cast<MemSDNode>(Op); 7099 M->getMemOperand()->setOffset(Offset); 7100 unsigned Opcode = 0; 7101 7102 switch (IntrID) { 7103 case Intrinsic::amdgcn_buffer_atomic_swap: 7104 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7105 break; 7106 case Intrinsic::amdgcn_buffer_atomic_add: 7107 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7108 break; 7109 case Intrinsic::amdgcn_buffer_atomic_sub: 7110 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7111 break; 7112 case Intrinsic::amdgcn_buffer_atomic_csub: 7113 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7114 break; 7115 case Intrinsic::amdgcn_buffer_atomic_smin: 7116 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7117 break; 7118 case Intrinsic::amdgcn_buffer_atomic_umin: 7119 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7120 break; 7121 case Intrinsic::amdgcn_buffer_atomic_smax: 7122 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7123 break; 7124 case Intrinsic::amdgcn_buffer_atomic_umax: 7125 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7126 break; 7127 case Intrinsic::amdgcn_buffer_atomic_and: 7128 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7129 break; 7130 case Intrinsic::amdgcn_buffer_atomic_or: 7131 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7132 break; 7133 case Intrinsic::amdgcn_buffer_atomic_xor: 7134 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7135 break; 7136 case Intrinsic::amdgcn_buffer_atomic_fadd: 7137 if (!Op.getValue(0).use_empty()) { 7138 DiagnosticInfoUnsupported 7139 NoFpRet(DAG.getMachineFunction().getFunction(), 7140 "return versions of fp atomics not supported", 7141 DL.getDebugLoc(), DS_Error); 7142 DAG.getContext()->diagnose(NoFpRet); 7143 return SDValue(); 7144 } 7145 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7146 break; 7147 default: 7148 llvm_unreachable("unhandled atomic opcode"); 7149 } 7150 7151 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7152 M->getMemOperand()); 7153 } 7154 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7155 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7156 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7157 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7158 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7159 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7160 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7161 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7162 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7163 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7164 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7165 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7166 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7167 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7168 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7169 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7170 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7171 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7172 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7173 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7174 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7175 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7176 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7177 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7178 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7179 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7180 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7181 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7182 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7183 return lowerStructBufferAtomicIntrin(Op, DAG, 7184 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7185 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7186 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7187 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7188 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7189 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7190 return lowerStructBufferAtomicIntrin(Op, DAG, 7191 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7192 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7193 return lowerStructBufferAtomicIntrin(Op, DAG, 7194 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7195 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7196 return lowerStructBufferAtomicIntrin(Op, DAG, 7197 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7198 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7199 return lowerStructBufferAtomicIntrin(Op, DAG, 7200 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7201 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7202 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7203 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7204 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7205 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7206 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7207 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7208 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7209 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7210 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7211 7212 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7213 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7214 unsigned IdxEn = 1; 7215 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7216 IdxEn = Idx->getZExtValue() != 0; 7217 SDValue Ops[] = { 7218 Op.getOperand(0), // Chain 7219 Op.getOperand(2), // src 7220 Op.getOperand(3), // cmp 7221 Op.getOperand(4), // rsrc 7222 Op.getOperand(5), // vindex 7223 SDValue(), // voffset -- will be set by setBufferOffsets 7224 SDValue(), // soffset -- will be set by setBufferOffsets 7225 SDValue(), // offset -- will be set by setBufferOffsets 7226 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7227 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7228 }; 7229 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7230 // We don't know the offset if vindex is non-zero, so clear it. 7231 if (IdxEn) 7232 Offset = 0; 7233 EVT VT = Op.getValueType(); 7234 auto *M = cast<MemSDNode>(Op); 7235 M->getMemOperand()->setOffset(Offset); 7236 7237 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7238 Op->getVTList(), Ops, VT, M->getMemOperand()); 7239 } 7240 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7241 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7242 SDValue Ops[] = { 7243 Op.getOperand(0), // Chain 7244 Op.getOperand(2), // src 7245 Op.getOperand(3), // cmp 7246 Op.getOperand(4), // rsrc 7247 DAG.getConstant(0, DL, MVT::i32), // vindex 7248 Offsets.first, // voffset 7249 Op.getOperand(6), // soffset 7250 Offsets.second, // offset 7251 Op.getOperand(7), // cachepolicy 7252 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7253 }; 7254 EVT VT = Op.getValueType(); 7255 auto *M = cast<MemSDNode>(Op); 7256 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7257 7258 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7259 Op->getVTList(), Ops, VT, M->getMemOperand()); 7260 } 7261 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7262 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7263 SDValue Ops[] = { 7264 Op.getOperand(0), // Chain 7265 Op.getOperand(2), // src 7266 Op.getOperand(3), // cmp 7267 Op.getOperand(4), // rsrc 7268 Op.getOperand(5), // vindex 7269 Offsets.first, // voffset 7270 Op.getOperand(7), // soffset 7271 Offsets.second, // offset 7272 Op.getOperand(8), // cachepolicy 7273 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7274 }; 7275 EVT VT = Op.getValueType(); 7276 auto *M = cast<MemSDNode>(Op); 7277 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7278 Ops[4])); 7279 7280 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7281 Op->getVTList(), Ops, VT, M->getMemOperand()); 7282 } 7283 case Intrinsic::amdgcn_global_atomic_fadd: { 7284 if (!Op.getValue(0).use_empty()) { 7285 DiagnosticInfoUnsupported 7286 NoFpRet(DAG.getMachineFunction().getFunction(), 7287 "return versions of fp atomics not supported", 7288 DL.getDebugLoc(), DS_Error); 7289 DAG.getContext()->diagnose(NoFpRet); 7290 return SDValue(); 7291 } 7292 MemSDNode *M = cast<MemSDNode>(Op); 7293 SDValue Ops[] = { 7294 M->getOperand(0), // Chain 7295 M->getOperand(2), // Ptr 7296 M->getOperand(3) // Value 7297 }; 7298 7299 EVT VT = Op.getOperand(3).getValueType(); 7300 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7301 DAG.getVTList(VT, MVT::Other), Ops, 7302 M->getMemOperand()); 7303 } 7304 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7305 SDLoc DL(Op); 7306 MemSDNode *M = cast<MemSDNode>(Op); 7307 SDValue NodePtr = M->getOperand(2); 7308 SDValue RayExtent = M->getOperand(3); 7309 SDValue RayOrigin = M->getOperand(4); 7310 SDValue RayDir = M->getOperand(5); 7311 SDValue RayInvDir = M->getOperand(6); 7312 SDValue TDescr = M->getOperand(7); 7313 7314 assert(NodePtr.getValueType() == MVT::i32 || 7315 NodePtr.getValueType() == MVT::i64); 7316 assert(RayDir.getValueType() == MVT::v4f16 || 7317 RayDir.getValueType() == MVT::v4f32); 7318 7319 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7320 bool Is64 = NodePtr.getValueType() == MVT::i64; 7321 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7322 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7323 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7324 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7325 7326 SmallVector<SDValue, 16> Ops; 7327 7328 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7329 SmallVector<SDValue, 3> Lanes; 7330 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7331 if (Lanes[0].getValueSizeInBits() == 32) { 7332 for (unsigned I = 0; I < 3; ++I) 7333 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7334 } else { 7335 if (IsAligned) { 7336 Ops.push_back( 7337 DAG.getBitcast(MVT::i32, 7338 DAG.getBuildVector(MVT::v2f16, DL, 7339 { Lanes[0], Lanes[1] }))); 7340 Ops.push_back(Lanes[2]); 7341 } else { 7342 SDValue Elt0 = Ops.pop_back_val(); 7343 Ops.push_back( 7344 DAG.getBitcast(MVT::i32, 7345 DAG.getBuildVector(MVT::v2f16, DL, 7346 { Elt0, Lanes[0] }))); 7347 Ops.push_back( 7348 DAG.getBitcast(MVT::i32, 7349 DAG.getBuildVector(MVT::v2f16, DL, 7350 { Lanes[1], Lanes[2] }))); 7351 } 7352 } 7353 }; 7354 7355 if (Is64) 7356 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7357 else 7358 Ops.push_back(NodePtr); 7359 7360 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7361 packLanes(RayOrigin, true); 7362 packLanes(RayDir, true); 7363 packLanes(RayInvDir, false); 7364 Ops.push_back(TDescr); 7365 if (IsA16) 7366 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7367 Ops.push_back(M->getChain()); 7368 7369 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7370 MachineMemOperand *MemRef = M->getMemOperand(); 7371 DAG.setNodeMemRefs(NewNode, {MemRef}); 7372 return SDValue(NewNode, 0); 7373 } 7374 default: 7375 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7376 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7377 return lowerImage(Op, ImageDimIntr, DAG); 7378 7379 return SDValue(); 7380 } 7381 } 7382 7383 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7384 // dwordx4 if on SI. 7385 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7386 SDVTList VTList, 7387 ArrayRef<SDValue> Ops, EVT MemVT, 7388 MachineMemOperand *MMO, 7389 SelectionDAG &DAG) const { 7390 EVT VT = VTList.VTs[0]; 7391 EVT WidenedVT = VT; 7392 EVT WidenedMemVT = MemVT; 7393 if (!Subtarget->hasDwordx3LoadStores() && 7394 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7395 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7396 WidenedVT.getVectorElementType(), 4); 7397 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7398 WidenedMemVT.getVectorElementType(), 4); 7399 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7400 } 7401 7402 assert(VTList.NumVTs == 2); 7403 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7404 7405 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7406 WidenedMemVT, MMO); 7407 if (WidenedVT != VT) { 7408 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7409 DAG.getVectorIdxConstant(0, DL)); 7410 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7411 } 7412 return NewOp; 7413 } 7414 7415 SDValue SITargetLowering::handleD16VData(SDValue VData, 7416 SelectionDAG &DAG) const { 7417 EVT StoreVT = VData.getValueType(); 7418 7419 // No change for f16 and legal vector D16 types. 7420 if (!StoreVT.isVector()) 7421 return VData; 7422 7423 SDLoc DL(VData); 7424 unsigned NumElements = StoreVT.getVectorNumElements(); 7425 7426 if (Subtarget->hasUnpackedD16VMem()) { 7427 // We need to unpack the packed data to store. 7428 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7429 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7430 7431 EVT EquivStoreVT = 7432 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7433 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7434 return DAG.UnrollVectorOp(ZExt.getNode()); 7435 } else if (NumElements == 3) { 7436 EVT IntStoreVT = 7437 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7438 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7439 7440 EVT WidenedStoreVT = EVT::getVectorVT( 7441 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7442 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7443 WidenedStoreVT.getStoreSizeInBits()); 7444 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7445 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7446 } 7447 7448 assert(isTypeLegal(StoreVT)); 7449 return VData; 7450 } 7451 7452 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7453 SelectionDAG &DAG) const { 7454 SDLoc DL(Op); 7455 SDValue Chain = Op.getOperand(0); 7456 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7457 MachineFunction &MF = DAG.getMachineFunction(); 7458 7459 switch (IntrinsicID) { 7460 case Intrinsic::amdgcn_exp_compr: { 7461 SDValue Src0 = Op.getOperand(4); 7462 SDValue Src1 = Op.getOperand(5); 7463 // Hack around illegal type on SI by directly selecting it. 7464 if (isTypeLegal(Src0.getValueType())) 7465 return SDValue(); 7466 7467 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7468 SDValue Undef = DAG.getUNDEF(MVT::f32); 7469 const SDValue Ops[] = { 7470 Op.getOperand(2), // tgt 7471 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7472 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7473 Undef, // src2 7474 Undef, // src3 7475 Op.getOperand(7), // vm 7476 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7477 Op.getOperand(3), // en 7478 Op.getOperand(0) // Chain 7479 }; 7480 7481 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7482 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7483 } 7484 case Intrinsic::amdgcn_s_barrier: { 7485 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7486 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7487 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7488 if (WGSize <= ST.getWavefrontSize()) 7489 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7490 Op.getOperand(0)), 0); 7491 } 7492 return SDValue(); 7493 }; 7494 case Intrinsic::amdgcn_tbuffer_store: { 7495 SDValue VData = Op.getOperand(2); 7496 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7497 if (IsD16) 7498 VData = handleD16VData(VData, DAG); 7499 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7500 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7501 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7502 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7503 unsigned IdxEn = 1; 7504 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7505 IdxEn = Idx->getZExtValue() != 0; 7506 SDValue Ops[] = { 7507 Chain, 7508 VData, // vdata 7509 Op.getOperand(3), // rsrc 7510 Op.getOperand(4), // vindex 7511 Op.getOperand(5), // voffset 7512 Op.getOperand(6), // soffset 7513 Op.getOperand(7), // offset 7514 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7515 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7516 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7517 }; 7518 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7519 AMDGPUISD::TBUFFER_STORE_FORMAT; 7520 MemSDNode *M = cast<MemSDNode>(Op); 7521 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7522 M->getMemoryVT(), M->getMemOperand()); 7523 } 7524 7525 case Intrinsic::amdgcn_struct_tbuffer_store: { 7526 SDValue VData = Op.getOperand(2); 7527 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7528 if (IsD16) 7529 VData = handleD16VData(VData, DAG); 7530 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7531 SDValue Ops[] = { 7532 Chain, 7533 VData, // vdata 7534 Op.getOperand(3), // rsrc 7535 Op.getOperand(4), // vindex 7536 Offsets.first, // voffset 7537 Op.getOperand(6), // soffset 7538 Offsets.second, // offset 7539 Op.getOperand(7), // format 7540 Op.getOperand(8), // cachepolicy, swizzled buffer 7541 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7542 }; 7543 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7544 AMDGPUISD::TBUFFER_STORE_FORMAT; 7545 MemSDNode *M = cast<MemSDNode>(Op); 7546 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7547 M->getMemoryVT(), M->getMemOperand()); 7548 } 7549 7550 case Intrinsic::amdgcn_raw_tbuffer_store: { 7551 SDValue VData = Op.getOperand(2); 7552 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7553 if (IsD16) 7554 VData = handleD16VData(VData, DAG); 7555 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7556 SDValue Ops[] = { 7557 Chain, 7558 VData, // vdata 7559 Op.getOperand(3), // rsrc 7560 DAG.getConstant(0, DL, MVT::i32), // vindex 7561 Offsets.first, // voffset 7562 Op.getOperand(5), // soffset 7563 Offsets.second, // offset 7564 Op.getOperand(6), // format 7565 Op.getOperand(7), // cachepolicy, swizzled buffer 7566 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7567 }; 7568 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7569 AMDGPUISD::TBUFFER_STORE_FORMAT; 7570 MemSDNode *M = cast<MemSDNode>(Op); 7571 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7572 M->getMemoryVT(), M->getMemOperand()); 7573 } 7574 7575 case Intrinsic::amdgcn_buffer_store: 7576 case Intrinsic::amdgcn_buffer_store_format: { 7577 SDValue VData = Op.getOperand(2); 7578 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7579 if (IsD16) 7580 VData = handleD16VData(VData, DAG); 7581 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7582 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7583 unsigned IdxEn = 1; 7584 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7585 IdxEn = Idx->getZExtValue() != 0; 7586 SDValue Ops[] = { 7587 Chain, 7588 VData, 7589 Op.getOperand(3), // rsrc 7590 Op.getOperand(4), // vindex 7591 SDValue(), // voffset -- will be set by setBufferOffsets 7592 SDValue(), // soffset -- will be set by setBufferOffsets 7593 SDValue(), // offset -- will be set by setBufferOffsets 7594 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7595 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7596 }; 7597 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7598 // We don't know the offset if vindex is non-zero, so clear it. 7599 if (IdxEn) 7600 Offset = 0; 7601 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7602 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7603 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7604 MemSDNode *M = cast<MemSDNode>(Op); 7605 M->getMemOperand()->setOffset(Offset); 7606 7607 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7608 EVT VDataType = VData.getValueType().getScalarType(); 7609 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7610 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7611 7612 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7613 M->getMemoryVT(), M->getMemOperand()); 7614 } 7615 7616 case Intrinsic::amdgcn_raw_buffer_store: 7617 case Intrinsic::amdgcn_raw_buffer_store_format: { 7618 const bool IsFormat = 7619 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7620 7621 SDValue VData = Op.getOperand(2); 7622 EVT VDataVT = VData.getValueType(); 7623 EVT EltType = VDataVT.getScalarType(); 7624 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7625 if (IsD16) { 7626 VData = handleD16VData(VData, DAG); 7627 VDataVT = VData.getValueType(); 7628 } 7629 7630 if (!isTypeLegal(VDataVT)) { 7631 VData = 7632 DAG.getNode(ISD::BITCAST, DL, 7633 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7634 } 7635 7636 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7637 SDValue Ops[] = { 7638 Chain, 7639 VData, 7640 Op.getOperand(3), // rsrc 7641 DAG.getConstant(0, DL, MVT::i32), // vindex 7642 Offsets.first, // voffset 7643 Op.getOperand(5), // soffset 7644 Offsets.second, // offset 7645 Op.getOperand(6), // cachepolicy, swizzled buffer 7646 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7647 }; 7648 unsigned Opc = 7649 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7650 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7651 MemSDNode *M = cast<MemSDNode>(Op); 7652 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7653 7654 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7655 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7656 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7657 7658 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7659 M->getMemoryVT(), M->getMemOperand()); 7660 } 7661 7662 case Intrinsic::amdgcn_struct_buffer_store: 7663 case Intrinsic::amdgcn_struct_buffer_store_format: { 7664 const bool IsFormat = 7665 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7666 7667 SDValue VData = Op.getOperand(2); 7668 EVT VDataVT = VData.getValueType(); 7669 EVT EltType = VDataVT.getScalarType(); 7670 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7671 7672 if (IsD16) { 7673 VData = handleD16VData(VData, DAG); 7674 VDataVT = VData.getValueType(); 7675 } 7676 7677 if (!isTypeLegal(VDataVT)) { 7678 VData = 7679 DAG.getNode(ISD::BITCAST, DL, 7680 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7681 } 7682 7683 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7684 SDValue Ops[] = { 7685 Chain, 7686 VData, 7687 Op.getOperand(3), // rsrc 7688 Op.getOperand(4), // vindex 7689 Offsets.first, // voffset 7690 Op.getOperand(6), // soffset 7691 Offsets.second, // offset 7692 Op.getOperand(7), // cachepolicy, swizzled buffer 7693 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7694 }; 7695 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7696 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7697 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7698 MemSDNode *M = cast<MemSDNode>(Op); 7699 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7700 Ops[3])); 7701 7702 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7703 EVT VDataType = VData.getValueType().getScalarType(); 7704 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7705 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7706 7707 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7708 M->getMemoryVT(), M->getMemOperand()); 7709 } 7710 case Intrinsic::amdgcn_end_cf: 7711 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7712 Op->getOperand(2), Chain), 0); 7713 7714 default: { 7715 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7716 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7717 return lowerImage(Op, ImageDimIntr, DAG); 7718 7719 return Op; 7720 } 7721 } 7722 } 7723 7724 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7725 // offset (the offset that is included in bounds checking and swizzling, to be 7726 // split between the instruction's voffset and immoffset fields) and soffset 7727 // (the offset that is excluded from bounds checking and swizzling, to go in 7728 // the instruction's soffset field). This function takes the first kind of 7729 // offset and figures out how to split it between voffset and immoffset. 7730 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7731 SDValue Offset, SelectionDAG &DAG) const { 7732 SDLoc DL(Offset); 7733 const unsigned MaxImm = 4095; 7734 SDValue N0 = Offset; 7735 ConstantSDNode *C1 = nullptr; 7736 7737 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7738 N0 = SDValue(); 7739 else if (DAG.isBaseWithConstantOffset(N0)) { 7740 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7741 N0 = N0.getOperand(0); 7742 } 7743 7744 if (C1) { 7745 unsigned ImmOffset = C1->getZExtValue(); 7746 // If the immediate value is too big for the immoffset field, put the value 7747 // and -4096 into the immoffset field so that the value that is copied/added 7748 // for the voffset field is a multiple of 4096, and it stands more chance 7749 // of being CSEd with the copy/add for another similar load/store. 7750 // However, do not do that rounding down to a multiple of 4096 if that is a 7751 // negative number, as it appears to be illegal to have a negative offset 7752 // in the vgpr, even if adding the immediate offset makes it positive. 7753 unsigned Overflow = ImmOffset & ~MaxImm; 7754 ImmOffset -= Overflow; 7755 if ((int32_t)Overflow < 0) { 7756 Overflow += ImmOffset; 7757 ImmOffset = 0; 7758 } 7759 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7760 if (Overflow) { 7761 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7762 if (!N0) 7763 N0 = OverflowVal; 7764 else { 7765 SDValue Ops[] = { N0, OverflowVal }; 7766 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7767 } 7768 } 7769 } 7770 if (!N0) 7771 N0 = DAG.getConstant(0, DL, MVT::i32); 7772 if (!C1) 7773 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7774 return {N0, SDValue(C1, 0)}; 7775 } 7776 7777 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7778 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7779 // pointed to by Offsets. 7780 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7781 SelectionDAG &DAG, SDValue *Offsets, 7782 Align Alignment) const { 7783 SDLoc DL(CombinedOffset); 7784 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7785 uint32_t Imm = C->getZExtValue(); 7786 uint32_t SOffset, ImmOffset; 7787 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7788 Alignment)) { 7789 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7790 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7791 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7792 return SOffset + ImmOffset; 7793 } 7794 } 7795 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7796 SDValue N0 = CombinedOffset.getOperand(0); 7797 SDValue N1 = CombinedOffset.getOperand(1); 7798 uint32_t SOffset, ImmOffset; 7799 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7800 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7801 Subtarget, Alignment)) { 7802 Offsets[0] = N0; 7803 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7804 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7805 return 0; 7806 } 7807 } 7808 Offsets[0] = CombinedOffset; 7809 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7810 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7811 return 0; 7812 } 7813 7814 // Handle 8 bit and 16 bit buffer loads 7815 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7816 EVT LoadVT, SDLoc DL, 7817 ArrayRef<SDValue> Ops, 7818 MemSDNode *M) const { 7819 EVT IntVT = LoadVT.changeTypeToInteger(); 7820 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7821 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7822 7823 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7824 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7825 Ops, IntVT, 7826 M->getMemOperand()); 7827 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7828 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7829 7830 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7831 } 7832 7833 // Handle 8 bit and 16 bit buffer stores 7834 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7835 EVT VDataType, SDLoc DL, 7836 SDValue Ops[], 7837 MemSDNode *M) const { 7838 if (VDataType == MVT::f16) 7839 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7840 7841 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7842 Ops[1] = BufferStoreExt; 7843 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7844 AMDGPUISD::BUFFER_STORE_SHORT; 7845 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7846 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7847 M->getMemOperand()); 7848 } 7849 7850 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7851 ISD::LoadExtType ExtType, SDValue Op, 7852 const SDLoc &SL, EVT VT) { 7853 if (VT.bitsLT(Op.getValueType())) 7854 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7855 7856 switch (ExtType) { 7857 case ISD::SEXTLOAD: 7858 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7859 case ISD::ZEXTLOAD: 7860 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7861 case ISD::EXTLOAD: 7862 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7863 case ISD::NON_EXTLOAD: 7864 return Op; 7865 } 7866 7867 llvm_unreachable("invalid ext type"); 7868 } 7869 7870 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7871 SelectionDAG &DAG = DCI.DAG; 7872 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7873 return SDValue(); 7874 7875 // FIXME: Constant loads should all be marked invariant. 7876 unsigned AS = Ld->getAddressSpace(); 7877 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7878 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7879 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7880 return SDValue(); 7881 7882 // Don't do this early, since it may interfere with adjacent load merging for 7883 // illegal types. We can avoid losing alignment information for exotic types 7884 // pre-legalize. 7885 EVT MemVT = Ld->getMemoryVT(); 7886 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7887 MemVT.getSizeInBits() >= 32) 7888 return SDValue(); 7889 7890 SDLoc SL(Ld); 7891 7892 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7893 "unexpected vector extload"); 7894 7895 // TODO: Drop only high part of range. 7896 SDValue Ptr = Ld->getBasePtr(); 7897 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7898 MVT::i32, SL, Ld->getChain(), Ptr, 7899 Ld->getOffset(), 7900 Ld->getPointerInfo(), MVT::i32, 7901 Ld->getAlignment(), 7902 Ld->getMemOperand()->getFlags(), 7903 Ld->getAAInfo(), 7904 nullptr); // Drop ranges 7905 7906 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7907 if (MemVT.isFloatingPoint()) { 7908 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7909 "unexpected fp extload"); 7910 TruncVT = MemVT.changeTypeToInteger(); 7911 } 7912 7913 SDValue Cvt = NewLoad; 7914 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7915 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7916 DAG.getValueType(TruncVT)); 7917 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7918 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7919 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7920 } else { 7921 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7922 } 7923 7924 EVT VT = Ld->getValueType(0); 7925 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7926 7927 DCI.AddToWorklist(Cvt.getNode()); 7928 7929 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7930 // the appropriate extension from the 32-bit load. 7931 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7932 DCI.AddToWorklist(Cvt.getNode()); 7933 7934 // Handle conversion back to floating point if necessary. 7935 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7936 7937 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7938 } 7939 7940 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7941 SDLoc DL(Op); 7942 LoadSDNode *Load = cast<LoadSDNode>(Op); 7943 ISD::LoadExtType ExtType = Load->getExtensionType(); 7944 EVT MemVT = Load->getMemoryVT(); 7945 7946 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7947 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7948 return SDValue(); 7949 7950 // FIXME: Copied from PPC 7951 // First, load into 32 bits, then truncate to 1 bit. 7952 7953 SDValue Chain = Load->getChain(); 7954 SDValue BasePtr = Load->getBasePtr(); 7955 MachineMemOperand *MMO = Load->getMemOperand(); 7956 7957 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7958 7959 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7960 BasePtr, RealMemVT, MMO); 7961 7962 if (!MemVT.isVector()) { 7963 SDValue Ops[] = { 7964 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7965 NewLD.getValue(1) 7966 }; 7967 7968 return DAG.getMergeValues(Ops, DL); 7969 } 7970 7971 SmallVector<SDValue, 3> Elts; 7972 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7973 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7974 DAG.getConstant(I, DL, MVT::i32)); 7975 7976 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7977 } 7978 7979 SDValue Ops[] = { 7980 DAG.getBuildVector(MemVT, DL, Elts), 7981 NewLD.getValue(1) 7982 }; 7983 7984 return DAG.getMergeValues(Ops, DL); 7985 } 7986 7987 if (!MemVT.isVector()) 7988 return SDValue(); 7989 7990 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7991 "Custom lowering for non-i32 vectors hasn't been implemented."); 7992 7993 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7994 MemVT, *Load->getMemOperand())) { 7995 SDValue Ops[2]; 7996 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7997 return DAG.getMergeValues(Ops, DL); 7998 } 7999 8000 unsigned Alignment = Load->getAlignment(); 8001 unsigned AS = Load->getAddressSpace(); 8002 if (Subtarget->hasLDSMisalignedBug() && 8003 AS == AMDGPUAS::FLAT_ADDRESS && 8004 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8005 return SplitVectorLoad(Op, DAG); 8006 } 8007 8008 MachineFunction &MF = DAG.getMachineFunction(); 8009 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8010 // If there is a possibilty that flat instruction access scratch memory 8011 // then we need to use the same legalization rules we use for private. 8012 if (AS == AMDGPUAS::FLAT_ADDRESS && 8013 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8014 AS = MFI->hasFlatScratchInit() ? 8015 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8016 8017 unsigned NumElements = MemVT.getVectorNumElements(); 8018 8019 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8020 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8021 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8022 if (MemVT.isPow2VectorType()) 8023 return SDValue(); 8024 if (NumElements == 3) 8025 return WidenVectorLoad(Op, DAG); 8026 return SplitVectorLoad(Op, DAG); 8027 } 8028 // Non-uniform loads will be selected to MUBUF instructions, so they 8029 // have the same legalization requirements as global and private 8030 // loads. 8031 // 8032 } 8033 8034 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8035 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8036 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8037 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8038 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8039 Alignment >= 4 && NumElements < 32) { 8040 if (MemVT.isPow2VectorType()) 8041 return SDValue(); 8042 if (NumElements == 3) 8043 return WidenVectorLoad(Op, DAG); 8044 return SplitVectorLoad(Op, DAG); 8045 } 8046 // Non-uniform loads will be selected to MUBUF instructions, so they 8047 // have the same legalization requirements as global and private 8048 // loads. 8049 // 8050 } 8051 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8052 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8053 AS == AMDGPUAS::GLOBAL_ADDRESS || 8054 AS == AMDGPUAS::FLAT_ADDRESS) { 8055 if (NumElements > 4) 8056 return SplitVectorLoad(Op, DAG); 8057 // v3 loads not supported on SI. 8058 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8059 return WidenVectorLoad(Op, DAG); 8060 // v3 and v4 loads are supported for private and global memory. 8061 return SDValue(); 8062 } 8063 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8064 // Depending on the setting of the private_element_size field in the 8065 // resource descriptor, we can only make private accesses up to a certain 8066 // size. 8067 switch (Subtarget->getMaxPrivateElementSize()) { 8068 case 4: { 8069 SDValue Ops[2]; 8070 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8071 return DAG.getMergeValues(Ops, DL); 8072 } 8073 case 8: 8074 if (NumElements > 2) 8075 return SplitVectorLoad(Op, DAG); 8076 return SDValue(); 8077 case 16: 8078 // Same as global/flat 8079 if (NumElements > 4) 8080 return SplitVectorLoad(Op, DAG); 8081 // v3 loads not supported on SI. 8082 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8083 return WidenVectorLoad(Op, DAG); 8084 return SDValue(); 8085 default: 8086 llvm_unreachable("unsupported private_element_size"); 8087 } 8088 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8089 // Use ds_read_b128 or ds_read_b96 when possible. 8090 if (Subtarget->hasDS96AndDS128() && 8091 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8092 MemVT.getStoreSize() == 12) && 8093 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8094 Load->getAlign())) 8095 return SDValue(); 8096 8097 if (NumElements > 2) 8098 return SplitVectorLoad(Op, DAG); 8099 8100 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8101 // address is negative, then the instruction is incorrectly treated as 8102 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8103 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8104 // load later in the SILoadStoreOptimizer. 8105 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8106 NumElements == 2 && MemVT.getStoreSize() == 8 && 8107 Load->getAlignment() < 8) { 8108 return SplitVectorLoad(Op, DAG); 8109 } 8110 } 8111 return SDValue(); 8112 } 8113 8114 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8115 EVT VT = Op.getValueType(); 8116 assert(VT.getSizeInBits() == 64); 8117 8118 SDLoc DL(Op); 8119 SDValue Cond = Op.getOperand(0); 8120 8121 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8122 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8123 8124 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8125 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8126 8127 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8128 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8129 8130 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8131 8132 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8133 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8134 8135 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8136 8137 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8138 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8139 } 8140 8141 // Catch division cases where we can use shortcuts with rcp and rsq 8142 // instructions. 8143 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8144 SelectionDAG &DAG) const { 8145 SDLoc SL(Op); 8146 SDValue LHS = Op.getOperand(0); 8147 SDValue RHS = Op.getOperand(1); 8148 EVT VT = Op.getValueType(); 8149 const SDNodeFlags Flags = Op->getFlags(); 8150 8151 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8152 Flags.hasApproximateFuncs(); 8153 8154 // Without !fpmath accuracy information, we can't do more because we don't 8155 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8156 if (!AllowInaccurateRcp) 8157 return SDValue(); 8158 8159 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8160 if (CLHS->isExactlyValue(1.0)) { 8161 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8162 // the CI documentation has a worst case error of 1 ulp. 8163 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8164 // use it as long as we aren't trying to use denormals. 8165 // 8166 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8167 8168 // 1.0 / sqrt(x) -> rsq(x) 8169 8170 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8171 // error seems really high at 2^29 ULP. 8172 if (RHS.getOpcode() == ISD::FSQRT) 8173 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8174 8175 // 1.0 / x -> rcp(x) 8176 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8177 } 8178 8179 // Same as for 1.0, but expand the sign out of the constant. 8180 if (CLHS->isExactlyValue(-1.0)) { 8181 // -1.0 / x -> rcp (fneg x) 8182 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8183 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8184 } 8185 } 8186 8187 // Turn into multiply by the reciprocal. 8188 // x / y -> x * (1.0 / y) 8189 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8190 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8191 } 8192 8193 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8194 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8195 SDNodeFlags Flags) { 8196 if (GlueChain->getNumValues() <= 1) { 8197 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8198 } 8199 8200 assert(GlueChain->getNumValues() == 3); 8201 8202 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8203 switch (Opcode) { 8204 default: llvm_unreachable("no chain equivalent for opcode"); 8205 case ISD::FMUL: 8206 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8207 break; 8208 } 8209 8210 return DAG.getNode(Opcode, SL, VTList, 8211 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8212 Flags); 8213 } 8214 8215 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8216 EVT VT, SDValue A, SDValue B, SDValue C, 8217 SDValue GlueChain, SDNodeFlags Flags) { 8218 if (GlueChain->getNumValues() <= 1) { 8219 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8220 } 8221 8222 assert(GlueChain->getNumValues() == 3); 8223 8224 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8225 switch (Opcode) { 8226 default: llvm_unreachable("no chain equivalent for opcode"); 8227 case ISD::FMA: 8228 Opcode = AMDGPUISD::FMA_W_CHAIN; 8229 break; 8230 } 8231 8232 return DAG.getNode(Opcode, SL, VTList, 8233 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8234 Flags); 8235 } 8236 8237 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8238 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8239 return FastLowered; 8240 8241 SDLoc SL(Op); 8242 SDValue Src0 = Op.getOperand(0); 8243 SDValue Src1 = Op.getOperand(1); 8244 8245 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8246 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8247 8248 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8249 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8250 8251 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8252 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8253 8254 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8255 } 8256 8257 // Faster 2.5 ULP division that does not support denormals. 8258 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8259 SDLoc SL(Op); 8260 SDValue LHS = Op.getOperand(1); 8261 SDValue RHS = Op.getOperand(2); 8262 8263 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8264 8265 const APFloat K0Val(BitsToFloat(0x6f800000)); 8266 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8267 8268 const APFloat K1Val(BitsToFloat(0x2f800000)); 8269 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8270 8271 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8272 8273 EVT SetCCVT = 8274 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8275 8276 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8277 8278 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8279 8280 // TODO: Should this propagate fast-math-flags? 8281 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8282 8283 // rcp does not support denormals. 8284 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8285 8286 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8287 8288 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8289 } 8290 8291 // Returns immediate value for setting the F32 denorm mode when using the 8292 // S_DENORM_MODE instruction. 8293 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8294 const SDLoc &SL, const GCNSubtarget *ST) { 8295 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8296 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8297 ? FP_DENORM_FLUSH_NONE 8298 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8299 8300 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8301 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8302 } 8303 8304 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8305 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8306 return FastLowered; 8307 8308 // The selection matcher assumes anything with a chain selecting to a 8309 // mayRaiseFPException machine instruction. Since we're introducing a chain 8310 // here, we need to explicitly report nofpexcept for the regular fdiv 8311 // lowering. 8312 SDNodeFlags Flags = Op->getFlags(); 8313 Flags.setNoFPExcept(true); 8314 8315 SDLoc SL(Op); 8316 SDValue LHS = Op.getOperand(0); 8317 SDValue RHS = Op.getOperand(1); 8318 8319 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8320 8321 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8322 8323 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8324 {RHS, RHS, LHS}, Flags); 8325 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8326 {LHS, RHS, LHS}, Flags); 8327 8328 // Denominator is scaled to not be denormal, so using rcp is ok. 8329 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8330 DenominatorScaled, Flags); 8331 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8332 DenominatorScaled, Flags); 8333 8334 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8335 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8336 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8337 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8338 8339 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8340 8341 if (!HasFP32Denormals) { 8342 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8343 // lowering. The chain dependence is insufficient, and we need glue. We do 8344 // not need the glue variants in a strictfp function. 8345 8346 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8347 8348 SDNode *EnableDenorm; 8349 if (Subtarget->hasDenormModeInst()) { 8350 const SDValue EnableDenormValue = 8351 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8352 8353 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8354 DAG.getEntryNode(), EnableDenormValue).getNode(); 8355 } else { 8356 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8357 SL, MVT::i32); 8358 EnableDenorm = 8359 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8360 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8361 } 8362 8363 SDValue Ops[3] = { 8364 NegDivScale0, 8365 SDValue(EnableDenorm, 0), 8366 SDValue(EnableDenorm, 1) 8367 }; 8368 8369 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8370 } 8371 8372 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8373 ApproxRcp, One, NegDivScale0, Flags); 8374 8375 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8376 ApproxRcp, Fma0, Flags); 8377 8378 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8379 Fma1, Fma1, Flags); 8380 8381 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8382 NumeratorScaled, Mul, Flags); 8383 8384 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8385 Fma2, Fma1, Mul, Fma2, Flags); 8386 8387 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8388 NumeratorScaled, Fma3, Flags); 8389 8390 if (!HasFP32Denormals) { 8391 SDNode *DisableDenorm; 8392 if (Subtarget->hasDenormModeInst()) { 8393 const SDValue DisableDenormValue = 8394 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8395 8396 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8397 Fma4.getValue(1), DisableDenormValue, 8398 Fma4.getValue(2)).getNode(); 8399 } else { 8400 const SDValue DisableDenormValue = 8401 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8402 8403 DisableDenorm = DAG.getMachineNode( 8404 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8405 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8406 } 8407 8408 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8409 SDValue(DisableDenorm, 0), DAG.getRoot()); 8410 DAG.setRoot(OutputChain); 8411 } 8412 8413 SDValue Scale = NumeratorScaled.getValue(1); 8414 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8415 {Fma4, Fma1, Fma3, Scale}, Flags); 8416 8417 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8418 } 8419 8420 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8421 if (DAG.getTarget().Options.UnsafeFPMath) 8422 return lowerFastUnsafeFDIV(Op, DAG); 8423 8424 SDLoc SL(Op); 8425 SDValue X = Op.getOperand(0); 8426 SDValue Y = Op.getOperand(1); 8427 8428 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8429 8430 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8431 8432 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8433 8434 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8435 8436 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8437 8438 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8439 8440 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8441 8442 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8443 8444 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8445 8446 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8447 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8448 8449 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8450 NegDivScale0, Mul, DivScale1); 8451 8452 SDValue Scale; 8453 8454 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8455 // Workaround a hardware bug on SI where the condition output from div_scale 8456 // is not usable. 8457 8458 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8459 8460 // Figure out if the scale to use for div_fmas. 8461 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8462 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8463 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8464 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8465 8466 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8467 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8468 8469 SDValue Scale0Hi 8470 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8471 SDValue Scale1Hi 8472 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8473 8474 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8475 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8476 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8477 } else { 8478 Scale = DivScale1.getValue(1); 8479 } 8480 8481 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8482 Fma4, Fma3, Mul, Scale); 8483 8484 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8485 } 8486 8487 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8488 EVT VT = Op.getValueType(); 8489 8490 if (VT == MVT::f32) 8491 return LowerFDIV32(Op, DAG); 8492 8493 if (VT == MVT::f64) 8494 return LowerFDIV64(Op, DAG); 8495 8496 if (VT == MVT::f16) 8497 return LowerFDIV16(Op, DAG); 8498 8499 llvm_unreachable("Unexpected type for fdiv"); 8500 } 8501 8502 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8503 SDLoc DL(Op); 8504 StoreSDNode *Store = cast<StoreSDNode>(Op); 8505 EVT VT = Store->getMemoryVT(); 8506 8507 if (VT == MVT::i1) { 8508 return DAG.getTruncStore(Store->getChain(), DL, 8509 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8510 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8511 } 8512 8513 assert(VT.isVector() && 8514 Store->getValue().getValueType().getScalarType() == MVT::i32); 8515 8516 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8517 VT, *Store->getMemOperand())) { 8518 return expandUnalignedStore(Store, DAG); 8519 } 8520 8521 unsigned AS = Store->getAddressSpace(); 8522 if (Subtarget->hasLDSMisalignedBug() && 8523 AS == AMDGPUAS::FLAT_ADDRESS && 8524 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8525 return SplitVectorStore(Op, DAG); 8526 } 8527 8528 MachineFunction &MF = DAG.getMachineFunction(); 8529 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8530 // If there is a possibilty that flat instruction access scratch memory 8531 // then we need to use the same legalization rules we use for private. 8532 if (AS == AMDGPUAS::FLAT_ADDRESS && 8533 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8534 AS = MFI->hasFlatScratchInit() ? 8535 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8536 8537 unsigned NumElements = VT.getVectorNumElements(); 8538 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8539 AS == AMDGPUAS::FLAT_ADDRESS) { 8540 if (NumElements > 4) 8541 return SplitVectorStore(Op, DAG); 8542 // v3 stores not supported on SI. 8543 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8544 return SplitVectorStore(Op, DAG); 8545 return SDValue(); 8546 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8547 switch (Subtarget->getMaxPrivateElementSize()) { 8548 case 4: 8549 return scalarizeVectorStore(Store, DAG); 8550 case 8: 8551 if (NumElements > 2) 8552 return SplitVectorStore(Op, DAG); 8553 return SDValue(); 8554 case 16: 8555 if (NumElements > 4 || NumElements == 3) 8556 return SplitVectorStore(Op, DAG); 8557 return SDValue(); 8558 default: 8559 llvm_unreachable("unsupported private_element_size"); 8560 } 8561 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8562 // Use ds_write_b128 or ds_write_b96 when possible. 8563 if (Subtarget->hasDS96AndDS128() && 8564 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8565 (VT.getStoreSize() == 12)) && 8566 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8567 Store->getAlign())) 8568 return SDValue(); 8569 8570 if (NumElements > 2) 8571 return SplitVectorStore(Op, DAG); 8572 8573 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8574 // address is negative, then the instruction is incorrectly treated as 8575 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8576 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8577 // store later in the SILoadStoreOptimizer. 8578 if (!Subtarget->hasUsableDSOffset() && 8579 NumElements == 2 && VT.getStoreSize() == 8 && 8580 Store->getAlignment() < 8) { 8581 return SplitVectorStore(Op, DAG); 8582 } 8583 8584 return SDValue(); 8585 } else { 8586 llvm_unreachable("unhandled address space"); 8587 } 8588 } 8589 8590 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8591 SDLoc DL(Op); 8592 EVT VT = Op.getValueType(); 8593 SDValue Arg = Op.getOperand(0); 8594 SDValue TrigVal; 8595 8596 // Propagate fast-math flags so that the multiply we introduce can be folded 8597 // if Arg is already the result of a multiply by constant. 8598 auto Flags = Op->getFlags(); 8599 8600 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8601 8602 if (Subtarget->hasTrigReducedRange()) { 8603 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8604 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8605 } else { 8606 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8607 } 8608 8609 switch (Op.getOpcode()) { 8610 case ISD::FCOS: 8611 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8612 case ISD::FSIN: 8613 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8614 default: 8615 llvm_unreachable("Wrong trig opcode"); 8616 } 8617 } 8618 8619 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8620 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8621 assert(AtomicNode->isCompareAndSwap()); 8622 unsigned AS = AtomicNode->getAddressSpace(); 8623 8624 // No custom lowering required for local address space 8625 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8626 return Op; 8627 8628 // Non-local address space requires custom lowering for atomic compare 8629 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8630 SDLoc DL(Op); 8631 SDValue ChainIn = Op.getOperand(0); 8632 SDValue Addr = Op.getOperand(1); 8633 SDValue Old = Op.getOperand(2); 8634 SDValue New = Op.getOperand(3); 8635 EVT VT = Op.getValueType(); 8636 MVT SimpleVT = VT.getSimpleVT(); 8637 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8638 8639 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8640 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8641 8642 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8643 Ops, VT, AtomicNode->getMemOperand()); 8644 } 8645 8646 //===----------------------------------------------------------------------===// 8647 // Custom DAG optimizations 8648 //===----------------------------------------------------------------------===// 8649 8650 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8651 DAGCombinerInfo &DCI) const { 8652 EVT VT = N->getValueType(0); 8653 EVT ScalarVT = VT.getScalarType(); 8654 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8655 return SDValue(); 8656 8657 SelectionDAG &DAG = DCI.DAG; 8658 SDLoc DL(N); 8659 8660 SDValue Src = N->getOperand(0); 8661 EVT SrcVT = Src.getValueType(); 8662 8663 // TODO: We could try to match extracting the higher bytes, which would be 8664 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8665 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8666 // about in practice. 8667 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8668 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8669 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8670 DCI.AddToWorklist(Cvt.getNode()); 8671 8672 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8673 if (ScalarVT != MVT::f32) { 8674 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8675 DAG.getTargetConstant(0, DL, MVT::i32)); 8676 } 8677 return Cvt; 8678 } 8679 } 8680 8681 return SDValue(); 8682 } 8683 8684 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8685 8686 // This is a variant of 8687 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8688 // 8689 // The normal DAG combiner will do this, but only if the add has one use since 8690 // that would increase the number of instructions. 8691 // 8692 // This prevents us from seeing a constant offset that can be folded into a 8693 // memory instruction's addressing mode. If we know the resulting add offset of 8694 // a pointer can be folded into an addressing offset, we can replace the pointer 8695 // operand with the add of new constant offset. This eliminates one of the uses, 8696 // and may allow the remaining use to also be simplified. 8697 // 8698 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8699 unsigned AddrSpace, 8700 EVT MemVT, 8701 DAGCombinerInfo &DCI) const { 8702 SDValue N0 = N->getOperand(0); 8703 SDValue N1 = N->getOperand(1); 8704 8705 // We only do this to handle cases where it's profitable when there are 8706 // multiple uses of the add, so defer to the standard combine. 8707 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8708 N0->hasOneUse()) 8709 return SDValue(); 8710 8711 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8712 if (!CN1) 8713 return SDValue(); 8714 8715 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8716 if (!CAdd) 8717 return SDValue(); 8718 8719 // If the resulting offset is too large, we can't fold it into the addressing 8720 // mode offset. 8721 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8722 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8723 8724 AddrMode AM; 8725 AM.HasBaseReg = true; 8726 AM.BaseOffs = Offset.getSExtValue(); 8727 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8728 return SDValue(); 8729 8730 SelectionDAG &DAG = DCI.DAG; 8731 SDLoc SL(N); 8732 EVT VT = N->getValueType(0); 8733 8734 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8735 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8736 8737 SDNodeFlags Flags; 8738 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8739 (N0.getOpcode() == ISD::OR || 8740 N0->getFlags().hasNoUnsignedWrap())); 8741 8742 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8743 } 8744 8745 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8746 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8747 /// specific intrinsic, but they all place the pointer operand first. 8748 static unsigned getBasePtrIndex(const MemSDNode *N) { 8749 switch (N->getOpcode()) { 8750 case ISD::STORE: 8751 case ISD::INTRINSIC_W_CHAIN: 8752 case ISD::INTRINSIC_VOID: 8753 return 2; 8754 default: 8755 return 1; 8756 } 8757 } 8758 8759 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8760 DAGCombinerInfo &DCI) const { 8761 SelectionDAG &DAG = DCI.DAG; 8762 SDLoc SL(N); 8763 8764 unsigned PtrIdx = getBasePtrIndex(N); 8765 SDValue Ptr = N->getOperand(PtrIdx); 8766 8767 // TODO: We could also do this for multiplies. 8768 if (Ptr.getOpcode() == ISD::SHL) { 8769 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8770 N->getMemoryVT(), DCI); 8771 if (NewPtr) { 8772 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8773 8774 NewOps[PtrIdx] = NewPtr; 8775 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8776 } 8777 } 8778 8779 return SDValue(); 8780 } 8781 8782 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8783 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8784 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8785 (Opc == ISD::XOR && Val == 0); 8786 } 8787 8788 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8789 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8790 // integer combine opportunities since most 64-bit operations are decomposed 8791 // this way. TODO: We won't want this for SALU especially if it is an inline 8792 // immediate. 8793 SDValue SITargetLowering::splitBinaryBitConstantOp( 8794 DAGCombinerInfo &DCI, 8795 const SDLoc &SL, 8796 unsigned Opc, SDValue LHS, 8797 const ConstantSDNode *CRHS) const { 8798 uint64_t Val = CRHS->getZExtValue(); 8799 uint32_t ValLo = Lo_32(Val); 8800 uint32_t ValHi = Hi_32(Val); 8801 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8802 8803 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8804 bitOpWithConstantIsReducible(Opc, ValHi)) || 8805 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8806 // If we need to materialize a 64-bit immediate, it will be split up later 8807 // anyway. Avoid creating the harder to understand 64-bit immediate 8808 // materialization. 8809 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8810 } 8811 8812 return SDValue(); 8813 } 8814 8815 // Returns true if argument is a boolean value which is not serialized into 8816 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8817 static bool isBoolSGPR(SDValue V) { 8818 if (V.getValueType() != MVT::i1) 8819 return false; 8820 switch (V.getOpcode()) { 8821 default: break; 8822 case ISD::SETCC: 8823 case ISD::AND: 8824 case ISD::OR: 8825 case ISD::XOR: 8826 case AMDGPUISD::FP_CLASS: 8827 return true; 8828 } 8829 return false; 8830 } 8831 8832 // If a constant has all zeroes or all ones within each byte return it. 8833 // Otherwise return 0. 8834 static uint32_t getConstantPermuteMask(uint32_t C) { 8835 // 0xff for any zero byte in the mask 8836 uint32_t ZeroByteMask = 0; 8837 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8838 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8839 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8840 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8841 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8842 if ((NonZeroByteMask & C) != NonZeroByteMask) 8843 return 0; // Partial bytes selected. 8844 return C; 8845 } 8846 8847 // Check if a node selects whole bytes from its operand 0 starting at a byte 8848 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8849 // or -1 if not succeeded. 8850 // Note byte select encoding: 8851 // value 0-3 selects corresponding source byte; 8852 // value 0xc selects zero; 8853 // value 0xff selects 0xff. 8854 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8855 assert(V.getValueSizeInBits() == 32); 8856 8857 if (V.getNumOperands() != 2) 8858 return ~0; 8859 8860 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8861 if (!N1) 8862 return ~0; 8863 8864 uint32_t C = N1->getZExtValue(); 8865 8866 switch (V.getOpcode()) { 8867 default: 8868 break; 8869 case ISD::AND: 8870 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8871 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8872 } 8873 break; 8874 8875 case ISD::OR: 8876 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8877 return (0x03020100 & ~ConstMask) | ConstMask; 8878 } 8879 break; 8880 8881 case ISD::SHL: 8882 if (C % 8) 8883 return ~0; 8884 8885 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8886 8887 case ISD::SRL: 8888 if (C % 8) 8889 return ~0; 8890 8891 return uint32_t(0x0c0c0c0c03020100ull >> C); 8892 } 8893 8894 return ~0; 8895 } 8896 8897 SDValue SITargetLowering::performAndCombine(SDNode *N, 8898 DAGCombinerInfo &DCI) const { 8899 if (DCI.isBeforeLegalize()) 8900 return SDValue(); 8901 8902 SelectionDAG &DAG = DCI.DAG; 8903 EVT VT = N->getValueType(0); 8904 SDValue LHS = N->getOperand(0); 8905 SDValue RHS = N->getOperand(1); 8906 8907 8908 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8909 if (VT == MVT::i64 && CRHS) { 8910 if (SDValue Split 8911 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8912 return Split; 8913 } 8914 8915 if (CRHS && VT == MVT::i32) { 8916 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8917 // nb = number of trailing zeroes in mask 8918 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8919 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8920 uint64_t Mask = CRHS->getZExtValue(); 8921 unsigned Bits = countPopulation(Mask); 8922 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8923 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8924 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8925 unsigned Shift = CShift->getZExtValue(); 8926 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8927 unsigned Offset = NB + Shift; 8928 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8929 SDLoc SL(N); 8930 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8931 LHS->getOperand(0), 8932 DAG.getConstant(Offset, SL, MVT::i32), 8933 DAG.getConstant(Bits, SL, MVT::i32)); 8934 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8935 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8936 DAG.getValueType(NarrowVT)); 8937 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8938 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8939 return Shl; 8940 } 8941 } 8942 } 8943 8944 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8945 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8946 isa<ConstantSDNode>(LHS.getOperand(2))) { 8947 uint32_t Sel = getConstantPermuteMask(Mask); 8948 if (!Sel) 8949 return SDValue(); 8950 8951 // Select 0xc for all zero bytes 8952 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8953 SDLoc DL(N); 8954 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8955 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8956 } 8957 } 8958 8959 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8960 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8961 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8962 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8963 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8964 8965 SDValue X = LHS.getOperand(0); 8966 SDValue Y = RHS.getOperand(0); 8967 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8968 return SDValue(); 8969 8970 if (LCC == ISD::SETO) { 8971 if (X != LHS.getOperand(1)) 8972 return SDValue(); 8973 8974 if (RCC == ISD::SETUNE) { 8975 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8976 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8977 return SDValue(); 8978 8979 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8980 SIInstrFlags::N_SUBNORMAL | 8981 SIInstrFlags::N_ZERO | 8982 SIInstrFlags::P_ZERO | 8983 SIInstrFlags::P_SUBNORMAL | 8984 SIInstrFlags::P_NORMAL; 8985 8986 static_assert(((~(SIInstrFlags::S_NAN | 8987 SIInstrFlags::Q_NAN | 8988 SIInstrFlags::N_INFINITY | 8989 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8990 "mask not equal"); 8991 8992 SDLoc DL(N); 8993 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8994 X, DAG.getConstant(Mask, DL, MVT::i32)); 8995 } 8996 } 8997 } 8998 8999 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9000 std::swap(LHS, RHS); 9001 9002 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9003 RHS.hasOneUse()) { 9004 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9005 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9006 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9007 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9008 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9009 (RHS.getOperand(0) == LHS.getOperand(0) && 9010 LHS.getOperand(0) == LHS.getOperand(1))) { 9011 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9012 unsigned NewMask = LCC == ISD::SETO ? 9013 Mask->getZExtValue() & ~OrdMask : 9014 Mask->getZExtValue() & OrdMask; 9015 9016 SDLoc DL(N); 9017 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9018 DAG.getConstant(NewMask, DL, MVT::i32)); 9019 } 9020 } 9021 9022 if (VT == MVT::i32 && 9023 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9024 // and x, (sext cc from i1) => select cc, x, 0 9025 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9026 std::swap(LHS, RHS); 9027 if (isBoolSGPR(RHS.getOperand(0))) 9028 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9029 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9030 } 9031 9032 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9033 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9034 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9035 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9036 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9037 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9038 if (LHSMask != ~0u && RHSMask != ~0u) { 9039 // Canonicalize the expression in an attempt to have fewer unique masks 9040 // and therefore fewer registers used to hold the masks. 9041 if (LHSMask > RHSMask) { 9042 std::swap(LHSMask, RHSMask); 9043 std::swap(LHS, RHS); 9044 } 9045 9046 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9047 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9048 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9049 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9050 9051 // Check of we need to combine values from two sources within a byte. 9052 if (!(LHSUsedLanes & RHSUsedLanes) && 9053 // If we select high and lower word keep it for SDWA. 9054 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9055 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9056 // Each byte in each mask is either selector mask 0-3, or has higher 9057 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9058 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9059 // mask which is not 0xff wins. By anding both masks we have a correct 9060 // result except that 0x0c shall be corrected to give 0x0c only. 9061 uint32_t Mask = LHSMask & RHSMask; 9062 for (unsigned I = 0; I < 32; I += 8) { 9063 uint32_t ByteSel = 0xff << I; 9064 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9065 Mask &= (0x0c << I) & 0xffffffff; 9066 } 9067 9068 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9069 // or 0x0c. 9070 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9071 SDLoc DL(N); 9072 9073 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9074 LHS.getOperand(0), RHS.getOperand(0), 9075 DAG.getConstant(Sel, DL, MVT::i32)); 9076 } 9077 } 9078 } 9079 9080 return SDValue(); 9081 } 9082 9083 SDValue SITargetLowering::performOrCombine(SDNode *N, 9084 DAGCombinerInfo &DCI) const { 9085 SelectionDAG &DAG = DCI.DAG; 9086 SDValue LHS = N->getOperand(0); 9087 SDValue RHS = N->getOperand(1); 9088 9089 EVT VT = N->getValueType(0); 9090 if (VT == MVT::i1) { 9091 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9092 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9093 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9094 SDValue Src = LHS.getOperand(0); 9095 if (Src != RHS.getOperand(0)) 9096 return SDValue(); 9097 9098 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9099 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9100 if (!CLHS || !CRHS) 9101 return SDValue(); 9102 9103 // Only 10 bits are used. 9104 static const uint32_t MaxMask = 0x3ff; 9105 9106 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9107 SDLoc DL(N); 9108 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9109 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9110 } 9111 9112 return SDValue(); 9113 } 9114 9115 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9116 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9117 LHS.getOpcode() == AMDGPUISD::PERM && 9118 isa<ConstantSDNode>(LHS.getOperand(2))) { 9119 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9120 if (!Sel) 9121 return SDValue(); 9122 9123 Sel |= LHS.getConstantOperandVal(2); 9124 SDLoc DL(N); 9125 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9126 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9127 } 9128 9129 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9130 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9131 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9132 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9133 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9134 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9135 if (LHSMask != ~0u && RHSMask != ~0u) { 9136 // Canonicalize the expression in an attempt to have fewer unique masks 9137 // and therefore fewer registers used to hold the masks. 9138 if (LHSMask > RHSMask) { 9139 std::swap(LHSMask, RHSMask); 9140 std::swap(LHS, RHS); 9141 } 9142 9143 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9144 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9145 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9146 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9147 9148 // Check of we need to combine values from two sources within a byte. 9149 if (!(LHSUsedLanes & RHSUsedLanes) && 9150 // If we select high and lower word keep it for SDWA. 9151 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9152 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9153 // Kill zero bytes selected by other mask. Zero value is 0xc. 9154 LHSMask &= ~RHSUsedLanes; 9155 RHSMask &= ~LHSUsedLanes; 9156 // Add 4 to each active LHS lane 9157 LHSMask |= LHSUsedLanes & 0x04040404; 9158 // Combine masks 9159 uint32_t Sel = LHSMask | RHSMask; 9160 SDLoc DL(N); 9161 9162 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9163 LHS.getOperand(0), RHS.getOperand(0), 9164 DAG.getConstant(Sel, DL, MVT::i32)); 9165 } 9166 } 9167 } 9168 9169 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9170 return SDValue(); 9171 9172 // TODO: This could be a generic combine with a predicate for extracting the 9173 // high half of an integer being free. 9174 9175 // (or i64:x, (zero_extend i32:y)) -> 9176 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9177 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9178 RHS.getOpcode() != ISD::ZERO_EXTEND) 9179 std::swap(LHS, RHS); 9180 9181 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9182 SDValue ExtSrc = RHS.getOperand(0); 9183 EVT SrcVT = ExtSrc.getValueType(); 9184 if (SrcVT == MVT::i32) { 9185 SDLoc SL(N); 9186 SDValue LowLHS, HiBits; 9187 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9188 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9189 9190 DCI.AddToWorklist(LowOr.getNode()); 9191 DCI.AddToWorklist(HiBits.getNode()); 9192 9193 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9194 LowOr, HiBits); 9195 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9196 } 9197 } 9198 9199 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9200 if (CRHS) { 9201 if (SDValue Split 9202 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9203 return Split; 9204 } 9205 9206 return SDValue(); 9207 } 9208 9209 SDValue SITargetLowering::performXorCombine(SDNode *N, 9210 DAGCombinerInfo &DCI) const { 9211 EVT VT = N->getValueType(0); 9212 if (VT != MVT::i64) 9213 return SDValue(); 9214 9215 SDValue LHS = N->getOperand(0); 9216 SDValue RHS = N->getOperand(1); 9217 9218 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9219 if (CRHS) { 9220 if (SDValue Split 9221 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9222 return Split; 9223 } 9224 9225 return SDValue(); 9226 } 9227 9228 // Instructions that will be lowered with a final instruction that zeros the 9229 // high result bits. 9230 // XXX - probably only need to list legal operations. 9231 static bool fp16SrcZerosHighBits(unsigned Opc) { 9232 switch (Opc) { 9233 case ISD::FADD: 9234 case ISD::FSUB: 9235 case ISD::FMUL: 9236 case ISD::FDIV: 9237 case ISD::FREM: 9238 case ISD::FMA: 9239 case ISD::FMAD: 9240 case ISD::FCANONICALIZE: 9241 case ISD::FP_ROUND: 9242 case ISD::UINT_TO_FP: 9243 case ISD::SINT_TO_FP: 9244 case ISD::FABS: 9245 // Fabs is lowered to a bit operation, but it's an and which will clear the 9246 // high bits anyway. 9247 case ISD::FSQRT: 9248 case ISD::FSIN: 9249 case ISD::FCOS: 9250 case ISD::FPOWI: 9251 case ISD::FPOW: 9252 case ISD::FLOG: 9253 case ISD::FLOG2: 9254 case ISD::FLOG10: 9255 case ISD::FEXP: 9256 case ISD::FEXP2: 9257 case ISD::FCEIL: 9258 case ISD::FTRUNC: 9259 case ISD::FRINT: 9260 case ISD::FNEARBYINT: 9261 case ISD::FROUND: 9262 case ISD::FFLOOR: 9263 case ISD::FMINNUM: 9264 case ISD::FMAXNUM: 9265 case AMDGPUISD::FRACT: 9266 case AMDGPUISD::CLAMP: 9267 case AMDGPUISD::COS_HW: 9268 case AMDGPUISD::SIN_HW: 9269 case AMDGPUISD::FMIN3: 9270 case AMDGPUISD::FMAX3: 9271 case AMDGPUISD::FMED3: 9272 case AMDGPUISD::FMAD_FTZ: 9273 case AMDGPUISD::RCP: 9274 case AMDGPUISD::RSQ: 9275 case AMDGPUISD::RCP_IFLAG: 9276 case AMDGPUISD::LDEXP: 9277 return true; 9278 default: 9279 // fcopysign, select and others may be lowered to 32-bit bit operations 9280 // which don't zero the high bits. 9281 return false; 9282 } 9283 } 9284 9285 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9286 DAGCombinerInfo &DCI) const { 9287 if (!Subtarget->has16BitInsts() || 9288 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9289 return SDValue(); 9290 9291 EVT VT = N->getValueType(0); 9292 if (VT != MVT::i32) 9293 return SDValue(); 9294 9295 SDValue Src = N->getOperand(0); 9296 if (Src.getValueType() != MVT::i16) 9297 return SDValue(); 9298 9299 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9300 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9301 if (Src.getOpcode() == ISD::BITCAST) { 9302 SDValue BCSrc = Src.getOperand(0); 9303 if (BCSrc.getValueType() == MVT::f16 && 9304 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9305 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9306 } 9307 9308 return SDValue(); 9309 } 9310 9311 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9312 DAGCombinerInfo &DCI) 9313 const { 9314 SDValue Src = N->getOperand(0); 9315 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9316 9317 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9318 VTSign->getVT() == MVT::i8) || 9319 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9320 VTSign->getVT() == MVT::i16)) && 9321 Src.hasOneUse()) { 9322 auto *M = cast<MemSDNode>(Src); 9323 SDValue Ops[] = { 9324 Src.getOperand(0), // Chain 9325 Src.getOperand(1), // rsrc 9326 Src.getOperand(2), // vindex 9327 Src.getOperand(3), // voffset 9328 Src.getOperand(4), // soffset 9329 Src.getOperand(5), // offset 9330 Src.getOperand(6), 9331 Src.getOperand(7) 9332 }; 9333 // replace with BUFFER_LOAD_BYTE/SHORT 9334 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9335 Src.getOperand(0).getValueType()); 9336 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9337 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9338 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9339 ResList, 9340 Ops, M->getMemoryVT(), 9341 M->getMemOperand()); 9342 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9343 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9344 } 9345 return SDValue(); 9346 } 9347 9348 SDValue SITargetLowering::performClassCombine(SDNode *N, 9349 DAGCombinerInfo &DCI) const { 9350 SelectionDAG &DAG = DCI.DAG; 9351 SDValue Mask = N->getOperand(1); 9352 9353 // fp_class x, 0 -> false 9354 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9355 if (CMask->isNullValue()) 9356 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9357 } 9358 9359 if (N->getOperand(0).isUndef()) 9360 return DAG.getUNDEF(MVT::i1); 9361 9362 return SDValue(); 9363 } 9364 9365 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9366 DAGCombinerInfo &DCI) const { 9367 EVT VT = N->getValueType(0); 9368 SDValue N0 = N->getOperand(0); 9369 9370 if (N0.isUndef()) 9371 return N0; 9372 9373 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9374 N0.getOpcode() == ISD::SINT_TO_FP)) { 9375 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9376 N->getFlags()); 9377 } 9378 9379 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9380 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9381 N0.getOperand(0), N->getFlags()); 9382 } 9383 9384 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9385 } 9386 9387 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9388 unsigned MaxDepth) const { 9389 unsigned Opcode = Op.getOpcode(); 9390 if (Opcode == ISD::FCANONICALIZE) 9391 return true; 9392 9393 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9394 auto F = CFP->getValueAPF(); 9395 if (F.isNaN() && F.isSignaling()) 9396 return false; 9397 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9398 } 9399 9400 // If source is a result of another standard FP operation it is already in 9401 // canonical form. 9402 if (MaxDepth == 0) 9403 return false; 9404 9405 switch (Opcode) { 9406 // These will flush denorms if required. 9407 case ISD::FADD: 9408 case ISD::FSUB: 9409 case ISD::FMUL: 9410 case ISD::FCEIL: 9411 case ISD::FFLOOR: 9412 case ISD::FMA: 9413 case ISD::FMAD: 9414 case ISD::FSQRT: 9415 case ISD::FDIV: 9416 case ISD::FREM: 9417 case ISD::FP_ROUND: 9418 case ISD::FP_EXTEND: 9419 case AMDGPUISD::FMUL_LEGACY: 9420 case AMDGPUISD::FMAD_FTZ: 9421 case AMDGPUISD::RCP: 9422 case AMDGPUISD::RSQ: 9423 case AMDGPUISD::RSQ_CLAMP: 9424 case AMDGPUISD::RCP_LEGACY: 9425 case AMDGPUISD::RCP_IFLAG: 9426 case AMDGPUISD::DIV_SCALE: 9427 case AMDGPUISD::DIV_FMAS: 9428 case AMDGPUISD::DIV_FIXUP: 9429 case AMDGPUISD::FRACT: 9430 case AMDGPUISD::LDEXP: 9431 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9432 case AMDGPUISD::CVT_F32_UBYTE0: 9433 case AMDGPUISD::CVT_F32_UBYTE1: 9434 case AMDGPUISD::CVT_F32_UBYTE2: 9435 case AMDGPUISD::CVT_F32_UBYTE3: 9436 return true; 9437 9438 // It can/will be lowered or combined as a bit operation. 9439 // Need to check their input recursively to handle. 9440 case ISD::FNEG: 9441 case ISD::FABS: 9442 case ISD::FCOPYSIGN: 9443 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9444 9445 case ISD::FSIN: 9446 case ISD::FCOS: 9447 case ISD::FSINCOS: 9448 return Op.getValueType().getScalarType() != MVT::f16; 9449 9450 case ISD::FMINNUM: 9451 case ISD::FMAXNUM: 9452 case ISD::FMINNUM_IEEE: 9453 case ISD::FMAXNUM_IEEE: 9454 case AMDGPUISD::CLAMP: 9455 case AMDGPUISD::FMED3: 9456 case AMDGPUISD::FMAX3: 9457 case AMDGPUISD::FMIN3: { 9458 // FIXME: Shouldn't treat the generic operations different based these. 9459 // However, we aren't really required to flush the result from 9460 // minnum/maxnum.. 9461 9462 // snans will be quieted, so we only need to worry about denormals. 9463 if (Subtarget->supportsMinMaxDenormModes() || 9464 denormalsEnabledForType(DAG, Op.getValueType())) 9465 return true; 9466 9467 // Flushing may be required. 9468 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9469 // targets need to check their input recursively. 9470 9471 // FIXME: Does this apply with clamp? It's implemented with max. 9472 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9473 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9474 return false; 9475 } 9476 9477 return true; 9478 } 9479 case ISD::SELECT: { 9480 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9481 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9482 } 9483 case ISD::BUILD_VECTOR: { 9484 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9485 SDValue SrcOp = Op.getOperand(i); 9486 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9487 return false; 9488 } 9489 9490 return true; 9491 } 9492 case ISD::EXTRACT_VECTOR_ELT: 9493 case ISD::EXTRACT_SUBVECTOR: { 9494 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9495 } 9496 case ISD::INSERT_VECTOR_ELT: { 9497 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9498 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9499 } 9500 case ISD::UNDEF: 9501 // Could be anything. 9502 return false; 9503 9504 case ISD::BITCAST: { 9505 // Hack round the mess we make when legalizing extract_vector_elt 9506 SDValue Src = Op.getOperand(0); 9507 if (Src.getValueType() == MVT::i16 && 9508 Src.getOpcode() == ISD::TRUNCATE) { 9509 SDValue TruncSrc = Src.getOperand(0); 9510 if (TruncSrc.getValueType() == MVT::i32 && 9511 TruncSrc.getOpcode() == ISD::BITCAST && 9512 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9513 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9514 } 9515 } 9516 9517 return false; 9518 } 9519 case ISD::INTRINSIC_WO_CHAIN: { 9520 unsigned IntrinsicID 9521 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9522 // TODO: Handle more intrinsics 9523 switch (IntrinsicID) { 9524 case Intrinsic::amdgcn_cvt_pkrtz: 9525 case Intrinsic::amdgcn_cubeid: 9526 case Intrinsic::amdgcn_frexp_mant: 9527 case Intrinsic::amdgcn_fdot2: 9528 case Intrinsic::amdgcn_rcp: 9529 case Intrinsic::amdgcn_rsq: 9530 case Intrinsic::amdgcn_rsq_clamp: 9531 case Intrinsic::amdgcn_rcp_legacy: 9532 case Intrinsic::amdgcn_rsq_legacy: 9533 case Intrinsic::amdgcn_trig_preop: 9534 return true; 9535 default: 9536 break; 9537 } 9538 9539 LLVM_FALLTHROUGH; 9540 } 9541 default: 9542 return denormalsEnabledForType(DAG, Op.getValueType()) && 9543 DAG.isKnownNeverSNaN(Op); 9544 } 9545 9546 llvm_unreachable("invalid operation"); 9547 } 9548 9549 // Constant fold canonicalize. 9550 SDValue SITargetLowering::getCanonicalConstantFP( 9551 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9552 // Flush denormals to 0 if not enabled. 9553 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9554 return DAG.getConstantFP(0.0, SL, VT); 9555 9556 if (C.isNaN()) { 9557 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9558 if (C.isSignaling()) { 9559 // Quiet a signaling NaN. 9560 // FIXME: Is this supposed to preserve payload bits? 9561 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9562 } 9563 9564 // Make sure it is the canonical NaN bitpattern. 9565 // 9566 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9567 // immediate? 9568 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9569 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9570 } 9571 9572 // Already canonical. 9573 return DAG.getConstantFP(C, SL, VT); 9574 } 9575 9576 static bool vectorEltWillFoldAway(SDValue Op) { 9577 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9578 } 9579 9580 SDValue SITargetLowering::performFCanonicalizeCombine( 9581 SDNode *N, 9582 DAGCombinerInfo &DCI) const { 9583 SelectionDAG &DAG = DCI.DAG; 9584 SDValue N0 = N->getOperand(0); 9585 EVT VT = N->getValueType(0); 9586 9587 // fcanonicalize undef -> qnan 9588 if (N0.isUndef()) { 9589 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9590 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9591 } 9592 9593 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9594 EVT VT = N->getValueType(0); 9595 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9596 } 9597 9598 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9599 // (fcanonicalize k) 9600 // 9601 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9602 9603 // TODO: This could be better with wider vectors that will be split to v2f16, 9604 // and to consider uses since there aren't that many packed operations. 9605 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9606 isTypeLegal(MVT::v2f16)) { 9607 SDLoc SL(N); 9608 SDValue NewElts[2]; 9609 SDValue Lo = N0.getOperand(0); 9610 SDValue Hi = N0.getOperand(1); 9611 EVT EltVT = Lo.getValueType(); 9612 9613 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9614 for (unsigned I = 0; I != 2; ++I) { 9615 SDValue Op = N0.getOperand(I); 9616 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9617 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9618 CFP->getValueAPF()); 9619 } else if (Op.isUndef()) { 9620 // Handled below based on what the other operand is. 9621 NewElts[I] = Op; 9622 } else { 9623 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9624 } 9625 } 9626 9627 // If one half is undef, and one is constant, perfer a splat vector rather 9628 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9629 // cheaper to use and may be free with a packed operation. 9630 if (NewElts[0].isUndef()) { 9631 if (isa<ConstantFPSDNode>(NewElts[1])) 9632 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9633 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9634 } 9635 9636 if (NewElts[1].isUndef()) { 9637 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9638 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9639 } 9640 9641 return DAG.getBuildVector(VT, SL, NewElts); 9642 } 9643 } 9644 9645 unsigned SrcOpc = N0.getOpcode(); 9646 9647 // If it's free to do so, push canonicalizes further up the source, which may 9648 // find a canonical source. 9649 // 9650 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9651 // sNaNs. 9652 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9653 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9654 if (CRHS && N0.hasOneUse()) { 9655 SDLoc SL(N); 9656 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9657 N0.getOperand(0)); 9658 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9659 DCI.AddToWorklist(Canon0.getNode()); 9660 9661 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9662 } 9663 } 9664 9665 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9666 } 9667 9668 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9669 switch (Opc) { 9670 case ISD::FMAXNUM: 9671 case ISD::FMAXNUM_IEEE: 9672 return AMDGPUISD::FMAX3; 9673 case ISD::SMAX: 9674 return AMDGPUISD::SMAX3; 9675 case ISD::UMAX: 9676 return AMDGPUISD::UMAX3; 9677 case ISD::FMINNUM: 9678 case ISD::FMINNUM_IEEE: 9679 return AMDGPUISD::FMIN3; 9680 case ISD::SMIN: 9681 return AMDGPUISD::SMIN3; 9682 case ISD::UMIN: 9683 return AMDGPUISD::UMIN3; 9684 default: 9685 llvm_unreachable("Not a min/max opcode"); 9686 } 9687 } 9688 9689 SDValue SITargetLowering::performIntMed3ImmCombine( 9690 SelectionDAG &DAG, const SDLoc &SL, 9691 SDValue Op0, SDValue Op1, bool Signed) const { 9692 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9693 if (!K1) 9694 return SDValue(); 9695 9696 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9697 if (!K0) 9698 return SDValue(); 9699 9700 if (Signed) { 9701 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9702 return SDValue(); 9703 } else { 9704 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9705 return SDValue(); 9706 } 9707 9708 EVT VT = K0->getValueType(0); 9709 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9710 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9711 return DAG.getNode(Med3Opc, SL, VT, 9712 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9713 } 9714 9715 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9716 MVT NVT = MVT::i32; 9717 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9718 9719 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9720 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9721 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9722 9723 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9724 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9725 } 9726 9727 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9728 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9729 return C; 9730 9731 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9732 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9733 return C; 9734 } 9735 9736 return nullptr; 9737 } 9738 9739 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9740 const SDLoc &SL, 9741 SDValue Op0, 9742 SDValue Op1) const { 9743 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9744 if (!K1) 9745 return SDValue(); 9746 9747 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9748 if (!K0) 9749 return SDValue(); 9750 9751 // Ordered >= (although NaN inputs should have folded away by now). 9752 if (K0->getValueAPF() > K1->getValueAPF()) 9753 return SDValue(); 9754 9755 const MachineFunction &MF = DAG.getMachineFunction(); 9756 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9757 9758 // TODO: Check IEEE bit enabled? 9759 EVT VT = Op0.getValueType(); 9760 if (Info->getMode().DX10Clamp) { 9761 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9762 // hardware fmed3 behavior converting to a min. 9763 // FIXME: Should this be allowing -0.0? 9764 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9765 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9766 } 9767 9768 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9769 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9770 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9771 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9772 // then give the other result, which is different from med3 with a NaN 9773 // input. 9774 SDValue Var = Op0.getOperand(0); 9775 if (!DAG.isKnownNeverSNaN(Var)) 9776 return SDValue(); 9777 9778 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9779 9780 if ((!K0->hasOneUse() || 9781 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9782 (!K1->hasOneUse() || 9783 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9784 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9785 Var, SDValue(K0, 0), SDValue(K1, 0)); 9786 } 9787 } 9788 9789 return SDValue(); 9790 } 9791 9792 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9793 DAGCombinerInfo &DCI) const { 9794 SelectionDAG &DAG = DCI.DAG; 9795 9796 EVT VT = N->getValueType(0); 9797 unsigned Opc = N->getOpcode(); 9798 SDValue Op0 = N->getOperand(0); 9799 SDValue Op1 = N->getOperand(1); 9800 9801 // Only do this if the inner op has one use since this will just increases 9802 // register pressure for no benefit. 9803 9804 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9805 !VT.isVector() && 9806 (VT == MVT::i32 || VT == MVT::f32 || 9807 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9808 // max(max(a, b), c) -> max3(a, b, c) 9809 // min(min(a, b), c) -> min3(a, b, c) 9810 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9811 SDLoc DL(N); 9812 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9813 DL, 9814 N->getValueType(0), 9815 Op0.getOperand(0), 9816 Op0.getOperand(1), 9817 Op1); 9818 } 9819 9820 // Try commuted. 9821 // max(a, max(b, c)) -> max3(a, b, c) 9822 // min(a, min(b, c)) -> min3(a, b, c) 9823 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9824 SDLoc DL(N); 9825 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9826 DL, 9827 N->getValueType(0), 9828 Op0, 9829 Op1.getOperand(0), 9830 Op1.getOperand(1)); 9831 } 9832 } 9833 9834 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9835 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9836 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9837 return Med3; 9838 } 9839 9840 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9841 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9842 return Med3; 9843 } 9844 9845 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9846 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9847 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9848 (Opc == AMDGPUISD::FMIN_LEGACY && 9849 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9850 (VT == MVT::f32 || VT == MVT::f64 || 9851 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9852 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9853 Op0.hasOneUse()) { 9854 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9855 return Res; 9856 } 9857 9858 return SDValue(); 9859 } 9860 9861 static bool isClampZeroToOne(SDValue A, SDValue B) { 9862 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9863 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9864 // FIXME: Should this be allowing -0.0? 9865 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9866 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9867 } 9868 } 9869 9870 return false; 9871 } 9872 9873 // FIXME: Should only worry about snans for version with chain. 9874 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9875 DAGCombinerInfo &DCI) const { 9876 EVT VT = N->getValueType(0); 9877 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9878 // NaNs. With a NaN input, the order of the operands may change the result. 9879 9880 SelectionDAG &DAG = DCI.DAG; 9881 SDLoc SL(N); 9882 9883 SDValue Src0 = N->getOperand(0); 9884 SDValue Src1 = N->getOperand(1); 9885 SDValue Src2 = N->getOperand(2); 9886 9887 if (isClampZeroToOne(Src0, Src1)) { 9888 // const_a, const_b, x -> clamp is safe in all cases including signaling 9889 // nans. 9890 // FIXME: Should this be allowing -0.0? 9891 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9892 } 9893 9894 const MachineFunction &MF = DAG.getMachineFunction(); 9895 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9896 9897 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9898 // handling no dx10-clamp? 9899 if (Info->getMode().DX10Clamp) { 9900 // If NaNs is clamped to 0, we are free to reorder the inputs. 9901 9902 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9903 std::swap(Src0, Src1); 9904 9905 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9906 std::swap(Src1, Src2); 9907 9908 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9909 std::swap(Src0, Src1); 9910 9911 if (isClampZeroToOne(Src1, Src2)) 9912 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9913 } 9914 9915 return SDValue(); 9916 } 9917 9918 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9919 DAGCombinerInfo &DCI) const { 9920 SDValue Src0 = N->getOperand(0); 9921 SDValue Src1 = N->getOperand(1); 9922 if (Src0.isUndef() && Src1.isUndef()) 9923 return DCI.DAG.getUNDEF(N->getValueType(0)); 9924 return SDValue(); 9925 } 9926 9927 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9928 // expanded into a set of cmp/select instructions. 9929 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9930 unsigned NumElem, 9931 bool IsDivergentIdx) { 9932 if (UseDivergentRegisterIndexing) 9933 return false; 9934 9935 unsigned VecSize = EltSize * NumElem; 9936 9937 // Sub-dword vectors of size 2 dword or less have better implementation. 9938 if (VecSize <= 64 && EltSize < 32) 9939 return false; 9940 9941 // Always expand the rest of sub-dword instructions, otherwise it will be 9942 // lowered via memory. 9943 if (EltSize < 32) 9944 return true; 9945 9946 // Always do this if var-idx is divergent, otherwise it will become a loop. 9947 if (IsDivergentIdx) 9948 return true; 9949 9950 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9951 unsigned NumInsts = NumElem /* Number of compares */ + 9952 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9953 return NumInsts <= 16; 9954 } 9955 9956 static bool shouldExpandVectorDynExt(SDNode *N) { 9957 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9958 if (isa<ConstantSDNode>(Idx)) 9959 return false; 9960 9961 SDValue Vec = N->getOperand(0); 9962 EVT VecVT = Vec.getValueType(); 9963 EVT EltVT = VecVT.getVectorElementType(); 9964 unsigned EltSize = EltVT.getSizeInBits(); 9965 unsigned NumElem = VecVT.getVectorNumElements(); 9966 9967 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9968 Idx->isDivergent()); 9969 } 9970 9971 SDValue SITargetLowering::performExtractVectorEltCombine( 9972 SDNode *N, DAGCombinerInfo &DCI) const { 9973 SDValue Vec = N->getOperand(0); 9974 SelectionDAG &DAG = DCI.DAG; 9975 9976 EVT VecVT = Vec.getValueType(); 9977 EVT EltVT = VecVT.getVectorElementType(); 9978 9979 if ((Vec.getOpcode() == ISD::FNEG || 9980 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9981 SDLoc SL(N); 9982 EVT EltVT = N->getValueType(0); 9983 SDValue Idx = N->getOperand(1); 9984 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9985 Vec.getOperand(0), Idx); 9986 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9987 } 9988 9989 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9990 // => 9991 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9992 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9993 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9994 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9995 SDLoc SL(N); 9996 EVT EltVT = N->getValueType(0); 9997 SDValue Idx = N->getOperand(1); 9998 unsigned Opc = Vec.getOpcode(); 9999 10000 switch(Opc) { 10001 default: 10002 break; 10003 // TODO: Support other binary operations. 10004 case ISD::FADD: 10005 case ISD::FSUB: 10006 case ISD::FMUL: 10007 case ISD::ADD: 10008 case ISD::UMIN: 10009 case ISD::UMAX: 10010 case ISD::SMIN: 10011 case ISD::SMAX: 10012 case ISD::FMAXNUM: 10013 case ISD::FMINNUM: 10014 case ISD::FMAXNUM_IEEE: 10015 case ISD::FMINNUM_IEEE: { 10016 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10017 Vec.getOperand(0), Idx); 10018 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10019 Vec.getOperand(1), Idx); 10020 10021 DCI.AddToWorklist(Elt0.getNode()); 10022 DCI.AddToWorklist(Elt1.getNode()); 10023 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10024 } 10025 } 10026 } 10027 10028 unsigned VecSize = VecVT.getSizeInBits(); 10029 unsigned EltSize = EltVT.getSizeInBits(); 10030 10031 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10032 if (::shouldExpandVectorDynExt(N)) { 10033 SDLoc SL(N); 10034 SDValue Idx = N->getOperand(1); 10035 SDValue V; 10036 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10037 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10038 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10039 if (I == 0) 10040 V = Elt; 10041 else 10042 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10043 } 10044 return V; 10045 } 10046 10047 if (!DCI.isBeforeLegalize()) 10048 return SDValue(); 10049 10050 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10051 // elements. This exposes more load reduction opportunities by replacing 10052 // multiple small extract_vector_elements with a single 32-bit extract. 10053 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10054 if (isa<MemSDNode>(Vec) && 10055 EltSize <= 16 && 10056 EltVT.isByteSized() && 10057 VecSize > 32 && 10058 VecSize % 32 == 0 && 10059 Idx) { 10060 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10061 10062 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10063 unsigned EltIdx = BitIndex / 32; 10064 unsigned LeftoverBitIdx = BitIndex % 32; 10065 SDLoc SL(N); 10066 10067 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10068 DCI.AddToWorklist(Cast.getNode()); 10069 10070 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10071 DAG.getConstant(EltIdx, SL, MVT::i32)); 10072 DCI.AddToWorklist(Elt.getNode()); 10073 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10074 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10075 DCI.AddToWorklist(Srl.getNode()); 10076 10077 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10078 DCI.AddToWorklist(Trunc.getNode()); 10079 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10080 } 10081 10082 return SDValue(); 10083 } 10084 10085 SDValue 10086 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10087 DAGCombinerInfo &DCI) const { 10088 SDValue Vec = N->getOperand(0); 10089 SDValue Idx = N->getOperand(2); 10090 EVT VecVT = Vec.getValueType(); 10091 EVT EltVT = VecVT.getVectorElementType(); 10092 10093 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10094 // => BUILD_VECTOR n x select (e, const-idx) 10095 if (!::shouldExpandVectorDynExt(N)) 10096 return SDValue(); 10097 10098 SelectionDAG &DAG = DCI.DAG; 10099 SDLoc SL(N); 10100 SDValue Ins = N->getOperand(1); 10101 EVT IdxVT = Idx.getValueType(); 10102 10103 SmallVector<SDValue, 16> Ops; 10104 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10105 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10106 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10107 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10108 Ops.push_back(V); 10109 } 10110 10111 return DAG.getBuildVector(VecVT, SL, Ops); 10112 } 10113 10114 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10115 const SDNode *N0, 10116 const SDNode *N1) const { 10117 EVT VT = N0->getValueType(0); 10118 10119 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10120 // support denormals ever. 10121 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10122 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10123 getSubtarget()->hasMadF16())) && 10124 isOperationLegal(ISD::FMAD, VT)) 10125 return ISD::FMAD; 10126 10127 const TargetOptions &Options = DAG.getTarget().Options; 10128 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10129 (N0->getFlags().hasAllowContract() && 10130 N1->getFlags().hasAllowContract())) && 10131 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10132 return ISD::FMA; 10133 } 10134 10135 return 0; 10136 } 10137 10138 // For a reassociatable opcode perform: 10139 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10140 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10141 SelectionDAG &DAG) const { 10142 EVT VT = N->getValueType(0); 10143 if (VT != MVT::i32 && VT != MVT::i64) 10144 return SDValue(); 10145 10146 unsigned Opc = N->getOpcode(); 10147 SDValue Op0 = N->getOperand(0); 10148 SDValue Op1 = N->getOperand(1); 10149 10150 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10151 return SDValue(); 10152 10153 if (Op0->isDivergent()) 10154 std::swap(Op0, Op1); 10155 10156 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10157 return SDValue(); 10158 10159 SDValue Op2 = Op1.getOperand(1); 10160 Op1 = Op1.getOperand(0); 10161 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10162 return SDValue(); 10163 10164 if (Op1->isDivergent()) 10165 std::swap(Op1, Op2); 10166 10167 // If either operand is constant this will conflict with 10168 // DAGCombiner::ReassociateOps(). 10169 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10170 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10171 return SDValue(); 10172 10173 SDLoc SL(N); 10174 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10175 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10176 } 10177 10178 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10179 EVT VT, 10180 SDValue N0, SDValue N1, SDValue N2, 10181 bool Signed) { 10182 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10183 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10184 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10185 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10186 } 10187 10188 SDValue SITargetLowering::performAddCombine(SDNode *N, 10189 DAGCombinerInfo &DCI) const { 10190 SelectionDAG &DAG = DCI.DAG; 10191 EVT VT = N->getValueType(0); 10192 SDLoc SL(N); 10193 SDValue LHS = N->getOperand(0); 10194 SDValue RHS = N->getOperand(1); 10195 10196 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10197 && Subtarget->hasMad64_32() && 10198 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10199 VT.getScalarSizeInBits() <= 64) { 10200 if (LHS.getOpcode() != ISD::MUL) 10201 std::swap(LHS, RHS); 10202 10203 SDValue MulLHS = LHS.getOperand(0); 10204 SDValue MulRHS = LHS.getOperand(1); 10205 SDValue AddRHS = RHS; 10206 10207 // TODO: Maybe restrict if SGPR inputs. 10208 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10209 numBitsUnsigned(MulRHS, DAG) <= 32) { 10210 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10211 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10212 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10213 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10214 } 10215 10216 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10217 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10218 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10219 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10220 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10221 } 10222 10223 return SDValue(); 10224 } 10225 10226 if (SDValue V = reassociateScalarOps(N, DAG)) { 10227 return V; 10228 } 10229 10230 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10231 return SDValue(); 10232 10233 // add x, zext (setcc) => addcarry x, 0, setcc 10234 // add x, sext (setcc) => subcarry x, 0, setcc 10235 unsigned Opc = LHS.getOpcode(); 10236 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10237 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10238 std::swap(RHS, LHS); 10239 10240 Opc = RHS.getOpcode(); 10241 switch (Opc) { 10242 default: break; 10243 case ISD::ZERO_EXTEND: 10244 case ISD::SIGN_EXTEND: 10245 case ISD::ANY_EXTEND: { 10246 auto Cond = RHS.getOperand(0); 10247 // If this won't be a real VOPC output, we would still need to insert an 10248 // extra instruction anyway. 10249 if (!isBoolSGPR(Cond)) 10250 break; 10251 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10252 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10253 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10254 return DAG.getNode(Opc, SL, VTList, Args); 10255 } 10256 case ISD::ADDCARRY: { 10257 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10258 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10259 if (!C || C->getZExtValue() != 0) break; 10260 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10261 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10262 } 10263 } 10264 return SDValue(); 10265 } 10266 10267 SDValue SITargetLowering::performSubCombine(SDNode *N, 10268 DAGCombinerInfo &DCI) const { 10269 SelectionDAG &DAG = DCI.DAG; 10270 EVT VT = N->getValueType(0); 10271 10272 if (VT != MVT::i32) 10273 return SDValue(); 10274 10275 SDLoc SL(N); 10276 SDValue LHS = N->getOperand(0); 10277 SDValue RHS = N->getOperand(1); 10278 10279 // sub x, zext (setcc) => subcarry x, 0, setcc 10280 // sub x, sext (setcc) => addcarry x, 0, setcc 10281 unsigned Opc = RHS.getOpcode(); 10282 switch (Opc) { 10283 default: break; 10284 case ISD::ZERO_EXTEND: 10285 case ISD::SIGN_EXTEND: 10286 case ISD::ANY_EXTEND: { 10287 auto Cond = RHS.getOperand(0); 10288 // If this won't be a real VOPC output, we would still need to insert an 10289 // extra instruction anyway. 10290 if (!isBoolSGPR(Cond)) 10291 break; 10292 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10293 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10294 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10295 return DAG.getNode(Opc, SL, VTList, Args); 10296 } 10297 } 10298 10299 if (LHS.getOpcode() == ISD::SUBCARRY) { 10300 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10301 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10302 if (!C || !C->isNullValue()) 10303 return SDValue(); 10304 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10305 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10306 } 10307 return SDValue(); 10308 } 10309 10310 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10311 DAGCombinerInfo &DCI) const { 10312 10313 if (N->getValueType(0) != MVT::i32) 10314 return SDValue(); 10315 10316 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10317 if (!C || C->getZExtValue() != 0) 10318 return SDValue(); 10319 10320 SelectionDAG &DAG = DCI.DAG; 10321 SDValue LHS = N->getOperand(0); 10322 10323 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10324 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10325 unsigned LHSOpc = LHS.getOpcode(); 10326 unsigned Opc = N->getOpcode(); 10327 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10328 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10329 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10330 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10331 } 10332 return SDValue(); 10333 } 10334 10335 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10336 DAGCombinerInfo &DCI) const { 10337 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10338 return SDValue(); 10339 10340 SelectionDAG &DAG = DCI.DAG; 10341 EVT VT = N->getValueType(0); 10342 10343 SDLoc SL(N); 10344 SDValue LHS = N->getOperand(0); 10345 SDValue RHS = N->getOperand(1); 10346 10347 // These should really be instruction patterns, but writing patterns with 10348 // source modiifiers is a pain. 10349 10350 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10351 if (LHS.getOpcode() == ISD::FADD) { 10352 SDValue A = LHS.getOperand(0); 10353 if (A == LHS.getOperand(1)) { 10354 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10355 if (FusedOp != 0) { 10356 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10357 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10358 } 10359 } 10360 } 10361 10362 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10363 if (RHS.getOpcode() == ISD::FADD) { 10364 SDValue A = RHS.getOperand(0); 10365 if (A == RHS.getOperand(1)) { 10366 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10367 if (FusedOp != 0) { 10368 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10369 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10370 } 10371 } 10372 } 10373 10374 return SDValue(); 10375 } 10376 10377 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10378 DAGCombinerInfo &DCI) const { 10379 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10380 return SDValue(); 10381 10382 SelectionDAG &DAG = DCI.DAG; 10383 SDLoc SL(N); 10384 EVT VT = N->getValueType(0); 10385 assert(!VT.isVector()); 10386 10387 // Try to get the fneg to fold into the source modifier. This undoes generic 10388 // DAG combines and folds them into the mad. 10389 // 10390 // Only do this if we are not trying to support denormals. v_mad_f32 does 10391 // not support denormals ever. 10392 SDValue LHS = N->getOperand(0); 10393 SDValue RHS = N->getOperand(1); 10394 if (LHS.getOpcode() == ISD::FADD) { 10395 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10396 SDValue A = LHS.getOperand(0); 10397 if (A == LHS.getOperand(1)) { 10398 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10399 if (FusedOp != 0){ 10400 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10401 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10402 10403 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10404 } 10405 } 10406 } 10407 10408 if (RHS.getOpcode() == ISD::FADD) { 10409 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10410 10411 SDValue A = RHS.getOperand(0); 10412 if (A == RHS.getOperand(1)) { 10413 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10414 if (FusedOp != 0){ 10415 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10416 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10417 } 10418 } 10419 } 10420 10421 return SDValue(); 10422 } 10423 10424 SDValue SITargetLowering::performFMACombine(SDNode *N, 10425 DAGCombinerInfo &DCI) const { 10426 SelectionDAG &DAG = DCI.DAG; 10427 EVT VT = N->getValueType(0); 10428 SDLoc SL(N); 10429 10430 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10431 return SDValue(); 10432 10433 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10434 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10435 SDValue Op1 = N->getOperand(0); 10436 SDValue Op2 = N->getOperand(1); 10437 SDValue FMA = N->getOperand(2); 10438 10439 if (FMA.getOpcode() != ISD::FMA || 10440 Op1.getOpcode() != ISD::FP_EXTEND || 10441 Op2.getOpcode() != ISD::FP_EXTEND) 10442 return SDValue(); 10443 10444 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10445 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10446 // is sufficient to allow generaing fdot2. 10447 const TargetOptions &Options = DAG.getTarget().Options; 10448 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10449 (N->getFlags().hasAllowContract() && 10450 FMA->getFlags().hasAllowContract())) { 10451 Op1 = Op1.getOperand(0); 10452 Op2 = Op2.getOperand(0); 10453 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10454 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10455 return SDValue(); 10456 10457 SDValue Vec1 = Op1.getOperand(0); 10458 SDValue Idx1 = Op1.getOperand(1); 10459 SDValue Vec2 = Op2.getOperand(0); 10460 10461 SDValue FMAOp1 = FMA.getOperand(0); 10462 SDValue FMAOp2 = FMA.getOperand(1); 10463 SDValue FMAAcc = FMA.getOperand(2); 10464 10465 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10466 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10467 return SDValue(); 10468 10469 FMAOp1 = FMAOp1.getOperand(0); 10470 FMAOp2 = FMAOp2.getOperand(0); 10471 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10472 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10473 return SDValue(); 10474 10475 SDValue Vec3 = FMAOp1.getOperand(0); 10476 SDValue Vec4 = FMAOp2.getOperand(0); 10477 SDValue Idx2 = FMAOp1.getOperand(1); 10478 10479 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10480 // Idx1 and Idx2 cannot be the same. 10481 Idx1 == Idx2) 10482 return SDValue(); 10483 10484 if (Vec1 == Vec2 || Vec3 == Vec4) 10485 return SDValue(); 10486 10487 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10488 return SDValue(); 10489 10490 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10491 (Vec1 == Vec4 && Vec2 == Vec3)) { 10492 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10493 DAG.getTargetConstant(0, SL, MVT::i1)); 10494 } 10495 } 10496 return SDValue(); 10497 } 10498 10499 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10500 DAGCombinerInfo &DCI) const { 10501 SelectionDAG &DAG = DCI.DAG; 10502 SDLoc SL(N); 10503 10504 SDValue LHS = N->getOperand(0); 10505 SDValue RHS = N->getOperand(1); 10506 EVT VT = LHS.getValueType(); 10507 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10508 10509 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10510 if (!CRHS) { 10511 CRHS = dyn_cast<ConstantSDNode>(LHS); 10512 if (CRHS) { 10513 std::swap(LHS, RHS); 10514 CC = getSetCCSwappedOperands(CC); 10515 } 10516 } 10517 10518 if (CRHS) { 10519 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10520 isBoolSGPR(LHS.getOperand(0))) { 10521 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10522 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10523 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10524 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10525 if ((CRHS->isAllOnesValue() && 10526 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10527 (CRHS->isNullValue() && 10528 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10529 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10530 DAG.getConstant(-1, SL, MVT::i1)); 10531 if ((CRHS->isAllOnesValue() && 10532 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10533 (CRHS->isNullValue() && 10534 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10535 return LHS.getOperand(0); 10536 } 10537 10538 uint64_t CRHSVal = CRHS->getZExtValue(); 10539 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10540 LHS.getOpcode() == ISD::SELECT && 10541 isa<ConstantSDNode>(LHS.getOperand(1)) && 10542 isa<ConstantSDNode>(LHS.getOperand(2)) && 10543 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10544 isBoolSGPR(LHS.getOperand(0))) { 10545 // Given CT != FT: 10546 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10547 // setcc (select cc, CT, CF), CF, ne => cc 10548 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10549 // setcc (select cc, CT, CF), CT, eq => cc 10550 uint64_t CT = LHS.getConstantOperandVal(1); 10551 uint64_t CF = LHS.getConstantOperandVal(2); 10552 10553 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10554 (CT == CRHSVal && CC == ISD::SETNE)) 10555 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10556 DAG.getConstant(-1, SL, MVT::i1)); 10557 if ((CF == CRHSVal && CC == ISD::SETNE) || 10558 (CT == CRHSVal && CC == ISD::SETEQ)) 10559 return LHS.getOperand(0); 10560 } 10561 } 10562 10563 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10564 VT != MVT::f16)) 10565 return SDValue(); 10566 10567 // Match isinf/isfinite pattern 10568 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10569 // (fcmp one (fabs x), inf) -> (fp_class x, 10570 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10571 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10572 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10573 if (!CRHS) 10574 return SDValue(); 10575 10576 const APFloat &APF = CRHS->getValueAPF(); 10577 if (APF.isInfinity() && !APF.isNegative()) { 10578 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10579 SIInstrFlags::N_INFINITY; 10580 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10581 SIInstrFlags::P_ZERO | 10582 SIInstrFlags::N_NORMAL | 10583 SIInstrFlags::P_NORMAL | 10584 SIInstrFlags::N_SUBNORMAL | 10585 SIInstrFlags::P_SUBNORMAL; 10586 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10587 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10588 DAG.getConstant(Mask, SL, MVT::i32)); 10589 } 10590 } 10591 10592 return SDValue(); 10593 } 10594 10595 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10596 DAGCombinerInfo &DCI) const { 10597 SelectionDAG &DAG = DCI.DAG; 10598 SDLoc SL(N); 10599 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10600 10601 SDValue Src = N->getOperand(0); 10602 SDValue Shift = N->getOperand(0); 10603 10604 // TODO: Extend type shouldn't matter (assuming legal types). 10605 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10606 Shift = Shift.getOperand(0); 10607 10608 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10609 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10610 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10611 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10612 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10613 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10614 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10615 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10616 SDLoc(Shift.getOperand(0)), MVT::i32); 10617 10618 unsigned ShiftOffset = 8 * Offset; 10619 if (Shift.getOpcode() == ISD::SHL) 10620 ShiftOffset -= C->getZExtValue(); 10621 else 10622 ShiftOffset += C->getZExtValue(); 10623 10624 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10625 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10626 MVT::f32, Shift); 10627 } 10628 } 10629 } 10630 10631 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10632 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10633 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10634 // We simplified Src. If this node is not dead, visit it again so it is 10635 // folded properly. 10636 if (N->getOpcode() != ISD::DELETED_NODE) 10637 DCI.AddToWorklist(N); 10638 return SDValue(N, 0); 10639 } 10640 10641 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10642 if (SDValue DemandedSrc = 10643 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10644 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10645 10646 return SDValue(); 10647 } 10648 10649 SDValue SITargetLowering::performClampCombine(SDNode *N, 10650 DAGCombinerInfo &DCI) const { 10651 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10652 if (!CSrc) 10653 return SDValue(); 10654 10655 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10656 const APFloat &F = CSrc->getValueAPF(); 10657 APFloat Zero = APFloat::getZero(F.getSemantics()); 10658 if (F < Zero || 10659 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10660 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10661 } 10662 10663 APFloat One(F.getSemantics(), "1.0"); 10664 if (F > One) 10665 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10666 10667 return SDValue(CSrc, 0); 10668 } 10669 10670 10671 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10672 DAGCombinerInfo &DCI) const { 10673 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10674 return SDValue(); 10675 switch (N->getOpcode()) { 10676 case ISD::ADD: 10677 return performAddCombine(N, DCI); 10678 case ISD::SUB: 10679 return performSubCombine(N, DCI); 10680 case ISD::ADDCARRY: 10681 case ISD::SUBCARRY: 10682 return performAddCarrySubCarryCombine(N, DCI); 10683 case ISD::FADD: 10684 return performFAddCombine(N, DCI); 10685 case ISD::FSUB: 10686 return performFSubCombine(N, DCI); 10687 case ISD::SETCC: 10688 return performSetCCCombine(N, DCI); 10689 case ISD::FMAXNUM: 10690 case ISD::FMINNUM: 10691 case ISD::FMAXNUM_IEEE: 10692 case ISD::FMINNUM_IEEE: 10693 case ISD::SMAX: 10694 case ISD::SMIN: 10695 case ISD::UMAX: 10696 case ISD::UMIN: 10697 case AMDGPUISD::FMIN_LEGACY: 10698 case AMDGPUISD::FMAX_LEGACY: 10699 return performMinMaxCombine(N, DCI); 10700 case ISD::FMA: 10701 return performFMACombine(N, DCI); 10702 case ISD::AND: 10703 return performAndCombine(N, DCI); 10704 case ISD::OR: 10705 return performOrCombine(N, DCI); 10706 case ISD::XOR: 10707 return performXorCombine(N, DCI); 10708 case ISD::ZERO_EXTEND: 10709 return performZeroExtendCombine(N, DCI); 10710 case ISD::SIGN_EXTEND_INREG: 10711 return performSignExtendInRegCombine(N , DCI); 10712 case AMDGPUISD::FP_CLASS: 10713 return performClassCombine(N, DCI); 10714 case ISD::FCANONICALIZE: 10715 return performFCanonicalizeCombine(N, DCI); 10716 case AMDGPUISD::RCP: 10717 return performRcpCombine(N, DCI); 10718 case AMDGPUISD::FRACT: 10719 case AMDGPUISD::RSQ: 10720 case AMDGPUISD::RCP_LEGACY: 10721 case AMDGPUISD::RCP_IFLAG: 10722 case AMDGPUISD::RSQ_CLAMP: 10723 case AMDGPUISD::LDEXP: { 10724 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10725 SDValue Src = N->getOperand(0); 10726 if (Src.isUndef()) 10727 return Src; 10728 break; 10729 } 10730 case ISD::SINT_TO_FP: 10731 case ISD::UINT_TO_FP: 10732 return performUCharToFloatCombine(N, DCI); 10733 case AMDGPUISD::CVT_F32_UBYTE0: 10734 case AMDGPUISD::CVT_F32_UBYTE1: 10735 case AMDGPUISD::CVT_F32_UBYTE2: 10736 case AMDGPUISD::CVT_F32_UBYTE3: 10737 return performCvtF32UByteNCombine(N, DCI); 10738 case AMDGPUISD::FMED3: 10739 return performFMed3Combine(N, DCI); 10740 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10741 return performCvtPkRTZCombine(N, DCI); 10742 case AMDGPUISD::CLAMP: 10743 return performClampCombine(N, DCI); 10744 case ISD::SCALAR_TO_VECTOR: { 10745 SelectionDAG &DAG = DCI.DAG; 10746 EVT VT = N->getValueType(0); 10747 10748 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10749 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10750 SDLoc SL(N); 10751 SDValue Src = N->getOperand(0); 10752 EVT EltVT = Src.getValueType(); 10753 if (EltVT == MVT::f16) 10754 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10755 10756 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10757 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10758 } 10759 10760 break; 10761 } 10762 case ISD::EXTRACT_VECTOR_ELT: 10763 return performExtractVectorEltCombine(N, DCI); 10764 case ISD::INSERT_VECTOR_ELT: 10765 return performInsertVectorEltCombine(N, DCI); 10766 case ISD::LOAD: { 10767 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10768 return Widended; 10769 LLVM_FALLTHROUGH; 10770 } 10771 default: { 10772 if (!DCI.isBeforeLegalize()) { 10773 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10774 return performMemSDNodeCombine(MemNode, DCI); 10775 } 10776 10777 break; 10778 } 10779 } 10780 10781 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10782 } 10783 10784 /// Helper function for adjustWritemask 10785 static unsigned SubIdx2Lane(unsigned Idx) { 10786 switch (Idx) { 10787 default: return 0; 10788 case AMDGPU::sub0: return 0; 10789 case AMDGPU::sub1: return 1; 10790 case AMDGPU::sub2: return 2; 10791 case AMDGPU::sub3: return 3; 10792 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10793 } 10794 } 10795 10796 /// Adjust the writemask of MIMG instructions 10797 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10798 SelectionDAG &DAG) const { 10799 unsigned Opcode = Node->getMachineOpcode(); 10800 10801 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10802 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10803 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10804 return Node; // not implemented for D16 10805 10806 SDNode *Users[5] = { nullptr }; 10807 unsigned Lane = 0; 10808 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10809 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10810 unsigned NewDmask = 0; 10811 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10812 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10813 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10814 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10815 unsigned TFCLane = 0; 10816 bool HasChain = Node->getNumValues() > 1; 10817 10818 if (OldDmask == 0) { 10819 // These are folded out, but on the chance it happens don't assert. 10820 return Node; 10821 } 10822 10823 unsigned OldBitsSet = countPopulation(OldDmask); 10824 // Work out which is the TFE/LWE lane if that is enabled. 10825 if (UsesTFC) { 10826 TFCLane = OldBitsSet; 10827 } 10828 10829 // Try to figure out the used register components 10830 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10831 I != E; ++I) { 10832 10833 // Don't look at users of the chain. 10834 if (I.getUse().getResNo() != 0) 10835 continue; 10836 10837 // Abort if we can't understand the usage 10838 if (!I->isMachineOpcode() || 10839 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10840 return Node; 10841 10842 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10843 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10844 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10845 // set, etc. 10846 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10847 10848 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10849 if (UsesTFC && Lane == TFCLane) { 10850 Users[Lane] = *I; 10851 } else { 10852 // Set which texture component corresponds to the lane. 10853 unsigned Comp; 10854 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10855 Comp = countTrailingZeros(Dmask); 10856 Dmask &= ~(1 << Comp); 10857 } 10858 10859 // Abort if we have more than one user per component. 10860 if (Users[Lane]) 10861 return Node; 10862 10863 Users[Lane] = *I; 10864 NewDmask |= 1 << Comp; 10865 } 10866 } 10867 10868 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10869 bool NoChannels = !NewDmask; 10870 if (NoChannels) { 10871 if (!UsesTFC) { 10872 // No uses of the result and not using TFC. Then do nothing. 10873 return Node; 10874 } 10875 // If the original dmask has one channel - then nothing to do 10876 if (OldBitsSet == 1) 10877 return Node; 10878 // Use an arbitrary dmask - required for the instruction to work 10879 NewDmask = 1; 10880 } 10881 // Abort if there's no change 10882 if (NewDmask == OldDmask) 10883 return Node; 10884 10885 unsigned BitsSet = countPopulation(NewDmask); 10886 10887 // Check for TFE or LWE - increase the number of channels by one to account 10888 // for the extra return value 10889 // This will need adjustment for D16 if this is also included in 10890 // adjustWriteMask (this function) but at present D16 are excluded. 10891 unsigned NewChannels = BitsSet + UsesTFC; 10892 10893 int NewOpcode = 10894 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10895 assert(NewOpcode != -1 && 10896 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10897 "failed to find equivalent MIMG op"); 10898 10899 // Adjust the writemask in the node 10900 SmallVector<SDValue, 12> Ops; 10901 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10902 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10903 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10904 10905 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10906 10907 MVT ResultVT = NewChannels == 1 ? 10908 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10909 NewChannels == 5 ? 8 : NewChannels); 10910 SDVTList NewVTList = HasChain ? 10911 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10912 10913 10914 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10915 NewVTList, Ops); 10916 10917 if (HasChain) { 10918 // Update chain. 10919 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10920 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10921 } 10922 10923 if (NewChannels == 1) { 10924 assert(Node->hasNUsesOfValue(1, 0)); 10925 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10926 SDLoc(Node), Users[Lane]->getValueType(0), 10927 SDValue(NewNode, 0)); 10928 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10929 return nullptr; 10930 } 10931 10932 // Update the users of the node with the new indices 10933 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10934 SDNode *User = Users[i]; 10935 if (!User) { 10936 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10937 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10938 if (i || !NoChannels) 10939 continue; 10940 } else { 10941 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10942 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10943 } 10944 10945 switch (Idx) { 10946 default: break; 10947 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10948 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10949 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10950 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10951 } 10952 } 10953 10954 DAG.RemoveDeadNode(Node); 10955 return nullptr; 10956 } 10957 10958 static bool isFrameIndexOp(SDValue Op) { 10959 if (Op.getOpcode() == ISD::AssertZext) 10960 Op = Op.getOperand(0); 10961 10962 return isa<FrameIndexSDNode>(Op); 10963 } 10964 10965 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10966 /// with frame index operands. 10967 /// LLVM assumes that inputs are to these instructions are registers. 10968 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10969 SelectionDAG &DAG) const { 10970 if (Node->getOpcode() == ISD::CopyToReg) { 10971 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10972 SDValue SrcVal = Node->getOperand(2); 10973 10974 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10975 // to try understanding copies to physical registers. 10976 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 10977 SDLoc SL(Node); 10978 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10979 SDValue VReg = DAG.getRegister( 10980 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10981 10982 SDNode *Glued = Node->getGluedNode(); 10983 SDValue ToVReg 10984 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10985 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10986 SDValue ToResultReg 10987 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10988 VReg, ToVReg.getValue(1)); 10989 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10990 DAG.RemoveDeadNode(Node); 10991 return ToResultReg.getNode(); 10992 } 10993 } 10994 10995 SmallVector<SDValue, 8> Ops; 10996 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10997 if (!isFrameIndexOp(Node->getOperand(i))) { 10998 Ops.push_back(Node->getOperand(i)); 10999 continue; 11000 } 11001 11002 SDLoc DL(Node); 11003 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11004 Node->getOperand(i).getValueType(), 11005 Node->getOperand(i)), 0)); 11006 } 11007 11008 return DAG.UpdateNodeOperands(Node, Ops); 11009 } 11010 11011 /// Fold the instructions after selecting them. 11012 /// Returns null if users were already updated. 11013 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11014 SelectionDAG &DAG) const { 11015 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11016 unsigned Opcode = Node->getMachineOpcode(); 11017 11018 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11019 !TII->isGather4(Opcode) && 11020 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11021 return adjustWritemask(Node, DAG); 11022 } 11023 11024 if (Opcode == AMDGPU::INSERT_SUBREG || 11025 Opcode == AMDGPU::REG_SEQUENCE) { 11026 legalizeTargetIndependentNode(Node, DAG); 11027 return Node; 11028 } 11029 11030 switch (Opcode) { 11031 case AMDGPU::V_DIV_SCALE_F32: 11032 case AMDGPU::V_DIV_SCALE_F64: { 11033 // Satisfy the operand register constraint when one of the inputs is 11034 // undefined. Ordinarily each undef value will have its own implicit_def of 11035 // a vreg, so force these to use a single register. 11036 SDValue Src0 = Node->getOperand(0); 11037 SDValue Src1 = Node->getOperand(1); 11038 SDValue Src2 = Node->getOperand(2); 11039 11040 if ((Src0.isMachineOpcode() && 11041 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11042 (Src0 == Src1 || Src0 == Src2)) 11043 break; 11044 11045 MVT VT = Src0.getValueType().getSimpleVT(); 11046 const TargetRegisterClass *RC = 11047 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11048 11049 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11050 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11051 11052 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11053 UndefReg, Src0, SDValue()); 11054 11055 // src0 must be the same register as src1 or src2, even if the value is 11056 // undefined, so make sure we don't violate this constraint. 11057 if (Src0.isMachineOpcode() && 11058 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11059 if (Src1.isMachineOpcode() && 11060 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11061 Src0 = Src1; 11062 else if (Src2.isMachineOpcode() && 11063 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11064 Src0 = Src2; 11065 else { 11066 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11067 Src0 = UndefReg; 11068 Src1 = UndefReg; 11069 } 11070 } else 11071 break; 11072 11073 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 11074 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 11075 Ops.push_back(Node->getOperand(I)); 11076 11077 Ops.push_back(ImpDef.getValue(1)); 11078 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11079 } 11080 default: 11081 break; 11082 } 11083 11084 return Node; 11085 } 11086 11087 /// Assign the register class depending on the number of 11088 /// bits set in the writemask 11089 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11090 SDNode *Node) const { 11091 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11092 11093 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11094 11095 if (TII->isVOP3(MI.getOpcode())) { 11096 // Make sure constant bus requirements are respected. 11097 TII->legalizeOperandsVOP3(MRI, MI); 11098 11099 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11100 // This saves a chain-copy of registers and better ballance register 11101 // use between vgpr and agpr as agpr tuples tend to be big. 11102 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11103 unsigned Opc = MI.getOpcode(); 11104 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11105 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11106 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11107 if (I == -1) 11108 break; 11109 MachineOperand &Op = MI.getOperand(I); 11110 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11111 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11112 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11113 continue; 11114 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11115 if (!Src || !Src->isCopy() || 11116 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11117 continue; 11118 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11119 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11120 // All uses of agpr64 and agpr32 can also accept vgpr except for 11121 // v_accvgpr_read, but we do not produce agpr reads during selection, 11122 // so no use checks are needed. 11123 MRI.setRegClass(Op.getReg(), NewRC); 11124 } 11125 } 11126 11127 return; 11128 } 11129 11130 // Replace unused atomics with the no return version. 11131 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11132 if (NoRetAtomicOp != -1) { 11133 if (!Node->hasAnyUseOfValue(0)) { 11134 MI.setDesc(TII->get(NoRetAtomicOp)); 11135 MI.RemoveOperand(0); 11136 return; 11137 } 11138 11139 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11140 // instruction, because the return type of these instructions is a vec2 of 11141 // the memory type, so it can be tied to the input operand. 11142 // This means these instructions always have a use, so we need to add a 11143 // special case to check if the atomic has only one extract_subreg use, 11144 // which itself has no uses. 11145 if ((Node->hasNUsesOfValue(1, 0) && 11146 Node->use_begin()->isMachineOpcode() && 11147 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11148 !Node->use_begin()->hasAnyUseOfValue(0))) { 11149 Register Def = MI.getOperand(0).getReg(); 11150 11151 // Change this into a noret atomic. 11152 MI.setDesc(TII->get(NoRetAtomicOp)); 11153 MI.RemoveOperand(0); 11154 11155 // If we only remove the def operand from the atomic instruction, the 11156 // extract_subreg will be left with a use of a vreg without a def. 11157 // So we need to insert an implicit_def to avoid machine verifier 11158 // errors. 11159 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11160 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11161 } 11162 return; 11163 } 11164 } 11165 11166 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11167 uint64_t Val) { 11168 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11169 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11170 } 11171 11172 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11173 const SDLoc &DL, 11174 SDValue Ptr) const { 11175 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11176 11177 // Build the half of the subregister with the constants before building the 11178 // full 128-bit register. If we are building multiple resource descriptors, 11179 // this will allow CSEing of the 2-component register. 11180 const SDValue Ops0[] = { 11181 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11182 buildSMovImm32(DAG, DL, 0), 11183 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11184 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11185 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11186 }; 11187 11188 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11189 MVT::v2i32, Ops0), 0); 11190 11191 // Combine the constants and the pointer. 11192 const SDValue Ops1[] = { 11193 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11194 Ptr, 11195 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11196 SubRegHi, 11197 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11198 }; 11199 11200 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11201 } 11202 11203 /// Return a resource descriptor with the 'Add TID' bit enabled 11204 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11205 /// of the resource descriptor) to create an offset, which is added to 11206 /// the resource pointer. 11207 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11208 SDValue Ptr, uint32_t RsrcDword1, 11209 uint64_t RsrcDword2And3) const { 11210 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11211 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11212 if (RsrcDword1) { 11213 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11214 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11215 0); 11216 } 11217 11218 SDValue DataLo = buildSMovImm32(DAG, DL, 11219 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11220 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11221 11222 const SDValue Ops[] = { 11223 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11224 PtrLo, 11225 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11226 PtrHi, 11227 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11228 DataLo, 11229 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11230 DataHi, 11231 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11232 }; 11233 11234 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11235 } 11236 11237 //===----------------------------------------------------------------------===// 11238 // SI Inline Assembly Support 11239 //===----------------------------------------------------------------------===// 11240 11241 std::pair<unsigned, const TargetRegisterClass *> 11242 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11243 StringRef Constraint, 11244 MVT VT) const { 11245 const TargetRegisterClass *RC = nullptr; 11246 if (Constraint.size() == 1) { 11247 const unsigned BitWidth = VT.getSizeInBits(); 11248 switch (Constraint[0]) { 11249 default: 11250 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11251 case 's': 11252 case 'r': 11253 switch (BitWidth) { 11254 case 16: 11255 RC = &AMDGPU::SReg_32RegClass; 11256 break; 11257 case 64: 11258 RC = &AMDGPU::SGPR_64RegClass; 11259 break; 11260 default: 11261 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11262 if (!RC) 11263 return std::make_pair(0U, nullptr); 11264 break; 11265 } 11266 break; 11267 case 'v': 11268 switch (BitWidth) { 11269 case 16: 11270 RC = &AMDGPU::VGPR_32RegClass; 11271 break; 11272 default: 11273 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11274 if (!RC) 11275 return std::make_pair(0U, nullptr); 11276 break; 11277 } 11278 break; 11279 case 'a': 11280 if (!Subtarget->hasMAIInsts()) 11281 break; 11282 switch (BitWidth) { 11283 case 16: 11284 RC = &AMDGPU::AGPR_32RegClass; 11285 break; 11286 default: 11287 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11288 if (!RC) 11289 return std::make_pair(0U, nullptr); 11290 break; 11291 } 11292 break; 11293 } 11294 // We actually support i128, i16 and f16 as inline parameters 11295 // even if they are not reported as legal 11296 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11297 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11298 return std::make_pair(0U, RC); 11299 } 11300 11301 if (Constraint.size() > 1) { 11302 if (Constraint[1] == 'v') { 11303 RC = &AMDGPU::VGPR_32RegClass; 11304 } else if (Constraint[1] == 's') { 11305 RC = &AMDGPU::SGPR_32RegClass; 11306 } else if (Constraint[1] == 'a') { 11307 RC = &AMDGPU::AGPR_32RegClass; 11308 } 11309 11310 if (RC) { 11311 uint32_t Idx; 11312 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11313 if (!Failed && Idx < RC->getNumRegs()) 11314 return std::make_pair(RC->getRegister(Idx), RC); 11315 } 11316 } 11317 11318 // FIXME: Returns VS_32 for physical SGPR constraints 11319 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11320 } 11321 11322 static bool isImmConstraint(StringRef Constraint) { 11323 if (Constraint.size() == 1) { 11324 switch (Constraint[0]) { 11325 default: break; 11326 case 'I': 11327 case 'J': 11328 case 'A': 11329 case 'B': 11330 case 'C': 11331 return true; 11332 } 11333 } else if (Constraint == "DA" || 11334 Constraint == "DB") { 11335 return true; 11336 } 11337 return false; 11338 } 11339 11340 SITargetLowering::ConstraintType 11341 SITargetLowering::getConstraintType(StringRef Constraint) const { 11342 if (Constraint.size() == 1) { 11343 switch (Constraint[0]) { 11344 default: break; 11345 case 's': 11346 case 'v': 11347 case 'a': 11348 return C_RegisterClass; 11349 } 11350 } 11351 if (isImmConstraint(Constraint)) { 11352 return C_Other; 11353 } 11354 return TargetLowering::getConstraintType(Constraint); 11355 } 11356 11357 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11358 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11359 Val = Val & maskTrailingOnes<uint64_t>(Size); 11360 } 11361 return Val; 11362 } 11363 11364 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11365 std::string &Constraint, 11366 std::vector<SDValue> &Ops, 11367 SelectionDAG &DAG) const { 11368 if (isImmConstraint(Constraint)) { 11369 uint64_t Val; 11370 if (getAsmOperandConstVal(Op, Val) && 11371 checkAsmConstraintVal(Op, Constraint, Val)) { 11372 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11373 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11374 } 11375 } else { 11376 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11377 } 11378 } 11379 11380 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11381 unsigned Size = Op.getScalarValueSizeInBits(); 11382 if (Size > 64) 11383 return false; 11384 11385 if (Size == 16 && !Subtarget->has16BitInsts()) 11386 return false; 11387 11388 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11389 Val = C->getSExtValue(); 11390 return true; 11391 } 11392 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11393 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11394 return true; 11395 } 11396 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11397 if (Size != 16 || Op.getNumOperands() != 2) 11398 return false; 11399 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11400 return false; 11401 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11402 Val = C->getSExtValue(); 11403 return true; 11404 } 11405 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11406 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11407 return true; 11408 } 11409 } 11410 11411 return false; 11412 } 11413 11414 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11415 const std::string &Constraint, 11416 uint64_t Val) const { 11417 if (Constraint.size() == 1) { 11418 switch (Constraint[0]) { 11419 case 'I': 11420 return AMDGPU::isInlinableIntLiteral(Val); 11421 case 'J': 11422 return isInt<16>(Val); 11423 case 'A': 11424 return checkAsmConstraintValA(Op, Val); 11425 case 'B': 11426 return isInt<32>(Val); 11427 case 'C': 11428 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11429 AMDGPU::isInlinableIntLiteral(Val); 11430 default: 11431 break; 11432 } 11433 } else if (Constraint.size() == 2) { 11434 if (Constraint == "DA") { 11435 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11436 int64_t LoBits = static_cast<int32_t>(Val); 11437 return checkAsmConstraintValA(Op, HiBits, 32) && 11438 checkAsmConstraintValA(Op, LoBits, 32); 11439 } 11440 if (Constraint == "DB") { 11441 return true; 11442 } 11443 } 11444 llvm_unreachable("Invalid asm constraint"); 11445 } 11446 11447 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11448 uint64_t Val, 11449 unsigned MaxSize) const { 11450 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11451 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11452 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11453 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11454 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11455 return true; 11456 } 11457 return false; 11458 } 11459 11460 // Figure out which registers should be reserved for stack access. Only after 11461 // the function is legalized do we know all of the non-spill stack objects or if 11462 // calls are present. 11463 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11464 MachineRegisterInfo &MRI = MF.getRegInfo(); 11465 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11466 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11467 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11468 11469 if (Info->isEntryFunction()) { 11470 // Callable functions have fixed registers used for stack access. 11471 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11472 } 11473 11474 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11475 Info->getStackPtrOffsetReg())); 11476 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11477 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11478 11479 // We need to worry about replacing the default register with itself in case 11480 // of MIR testcases missing the MFI. 11481 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11482 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11483 11484 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11485 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11486 11487 Info->limitOccupancy(MF); 11488 11489 if (ST.isWave32() && !MF.empty()) { 11490 // Add VCC_HI def because many instructions marked as imp-use VCC where 11491 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11492 // having a use of undef. 11493 11494 const SIInstrInfo *TII = ST.getInstrInfo(); 11495 DebugLoc DL; 11496 11497 MachineBasicBlock &MBB = MF.front(); 11498 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11499 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11500 11501 for (auto &MBB : MF) { 11502 for (auto &MI : MBB) { 11503 TII->fixImplicitOperands(MI); 11504 } 11505 } 11506 } 11507 11508 TargetLoweringBase::finalizeLowering(MF); 11509 11510 // Allocate a VGPR for future SGPR Spill if 11511 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11512 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11513 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11514 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11515 Info->reserveVGPRforSGPRSpills(MF); 11516 } 11517 11518 void SITargetLowering::computeKnownBitsForFrameIndex( 11519 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11520 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11521 11522 // Set the high bits to zero based on the maximum allowed scratch size per 11523 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11524 // calculation won't overflow, so assume the sign bit is never set. 11525 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11526 } 11527 11528 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11529 KnownBits &Known, unsigned Dim) { 11530 unsigned MaxValue = 11531 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11532 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11533 } 11534 11535 void SITargetLowering::computeKnownBitsForTargetInstr( 11536 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11537 const MachineRegisterInfo &MRI, unsigned Depth) const { 11538 const MachineInstr *MI = MRI.getVRegDef(R); 11539 switch (MI->getOpcode()) { 11540 case AMDGPU::G_INTRINSIC: { 11541 switch (MI->getIntrinsicID()) { 11542 case Intrinsic::amdgcn_workitem_id_x: 11543 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11544 break; 11545 case Intrinsic::amdgcn_workitem_id_y: 11546 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11547 break; 11548 case Intrinsic::amdgcn_workitem_id_z: 11549 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11550 break; 11551 case Intrinsic::amdgcn_mbcnt_lo: 11552 case Intrinsic::amdgcn_mbcnt_hi: { 11553 // These return at most the wavefront size - 1. 11554 unsigned Size = MRI.getType(R).getSizeInBits(); 11555 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11556 break; 11557 } 11558 case Intrinsic::amdgcn_groupstaticsize: { 11559 // We can report everything over the maximum size as 0. We can't report 11560 // based on the actual size because we don't know if it's accurate or not 11561 // at any given point. 11562 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11563 break; 11564 } 11565 default: 11566 break; 11567 } 11568 } 11569 } 11570 } 11571 11572 Align SITargetLowering::computeKnownAlignForTargetInstr( 11573 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11574 unsigned Depth) const { 11575 const MachineInstr *MI = MRI.getVRegDef(R); 11576 switch (MI->getOpcode()) { 11577 case AMDGPU::G_INTRINSIC: 11578 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11579 // FIXME: Can this move to generic code? What about the case where the call 11580 // site specifies a lower alignment? 11581 Intrinsic::ID IID = MI->getIntrinsicID(); 11582 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11583 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11584 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11585 return *RetAlign; 11586 return Align(1); 11587 } 11588 default: 11589 return Align(1); 11590 } 11591 } 11592 11593 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11594 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11595 const Align CacheLineAlign = Align(64); 11596 11597 // Pre-GFX10 target did not benefit from loop alignment 11598 if (!ML || DisableLoopAlignment || 11599 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11600 getSubtarget()->hasInstFwdPrefetchBug()) 11601 return PrefAlign; 11602 11603 // On GFX10 I$ is 4 x 64 bytes cache lines. 11604 // By default prefetcher keeps one cache line behind and reads two ahead. 11605 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11606 // behind and one ahead. 11607 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11608 // If loop fits 64 bytes it always spans no more than two cache lines and 11609 // does not need an alignment. 11610 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11611 // Else if loop is less or equal 192 bytes we need two lines behind. 11612 11613 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11614 const MachineBasicBlock *Header = ML->getHeader(); 11615 if (Header->getAlignment() != PrefAlign) 11616 return Header->getAlignment(); // Already processed. 11617 11618 unsigned LoopSize = 0; 11619 for (const MachineBasicBlock *MBB : ML->blocks()) { 11620 // If inner loop block is aligned assume in average half of the alignment 11621 // size to be added as nops. 11622 if (MBB != Header) 11623 LoopSize += MBB->getAlignment().value() / 2; 11624 11625 for (const MachineInstr &MI : *MBB) { 11626 LoopSize += TII->getInstSizeInBytes(MI); 11627 if (LoopSize > 192) 11628 return PrefAlign; 11629 } 11630 } 11631 11632 if (LoopSize <= 64) 11633 return PrefAlign; 11634 11635 if (LoopSize <= 128) 11636 return CacheLineAlign; 11637 11638 // If any of parent loops is surrounded by prefetch instructions do not 11639 // insert new for inner loop, which would reset parent's settings. 11640 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11641 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11642 auto I = Exit->getFirstNonDebugInstr(); 11643 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11644 return CacheLineAlign; 11645 } 11646 } 11647 11648 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11649 MachineBasicBlock *Exit = ML->getExitBlock(); 11650 11651 if (Pre && Exit) { 11652 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11653 TII->get(AMDGPU::S_INST_PREFETCH)) 11654 .addImm(1); // prefetch 2 lines behind PC 11655 11656 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11657 TII->get(AMDGPU::S_INST_PREFETCH)) 11658 .addImm(2); // prefetch 1 line behind PC 11659 } 11660 11661 return CacheLineAlign; 11662 } 11663 11664 LLVM_ATTRIBUTE_UNUSED 11665 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11666 assert(N->getOpcode() == ISD::CopyFromReg); 11667 do { 11668 // Follow the chain until we find an INLINEASM node. 11669 N = N->getOperand(0).getNode(); 11670 if (N->getOpcode() == ISD::INLINEASM || 11671 N->getOpcode() == ISD::INLINEASM_BR) 11672 return true; 11673 } while (N->getOpcode() == ISD::CopyFromReg); 11674 return false; 11675 } 11676 11677 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11678 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11679 { 11680 switch (N->getOpcode()) { 11681 case ISD::CopyFromReg: 11682 { 11683 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11684 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11685 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11686 Register Reg = R->getReg(); 11687 11688 // FIXME: Why does this need to consider isLiveIn? 11689 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11690 return !TRI->isSGPRReg(MRI, Reg); 11691 11692 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11693 return KDA->isDivergent(V); 11694 11695 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11696 return !TRI->isSGPRReg(MRI, Reg); 11697 } 11698 break; 11699 case ISD::LOAD: { 11700 const LoadSDNode *L = cast<LoadSDNode>(N); 11701 unsigned AS = L->getAddressSpace(); 11702 // A flat load may access private memory. 11703 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11704 } break; 11705 case ISD::CALLSEQ_END: 11706 return true; 11707 break; 11708 case ISD::INTRINSIC_WO_CHAIN: 11709 { 11710 11711 } 11712 return AMDGPU::isIntrinsicSourceOfDivergence( 11713 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11714 case ISD::INTRINSIC_W_CHAIN: 11715 return AMDGPU::isIntrinsicSourceOfDivergence( 11716 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11717 } 11718 return false; 11719 } 11720 11721 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11722 EVT VT) const { 11723 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11724 case MVT::f32: 11725 return hasFP32Denormals(DAG.getMachineFunction()); 11726 case MVT::f64: 11727 case MVT::f16: 11728 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11729 default: 11730 return false; 11731 } 11732 } 11733 11734 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11735 const SelectionDAG &DAG, 11736 bool SNaN, 11737 unsigned Depth) const { 11738 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11739 const MachineFunction &MF = DAG.getMachineFunction(); 11740 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11741 11742 if (Info->getMode().DX10Clamp) 11743 return true; // Clamped to 0. 11744 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11745 } 11746 11747 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11748 SNaN, Depth); 11749 } 11750 11751 TargetLowering::AtomicExpansionKind 11752 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11753 switch (RMW->getOperation()) { 11754 case AtomicRMWInst::FAdd: { 11755 Type *Ty = RMW->getType(); 11756 11757 // We don't have a way to support 16-bit atomics now, so just leave them 11758 // as-is. 11759 if (Ty->isHalfTy()) 11760 return AtomicExpansionKind::None; 11761 11762 if (!Ty->isFloatTy()) 11763 return AtomicExpansionKind::CmpXChg; 11764 11765 // TODO: Do have these for flat. Older targets also had them for buffers. 11766 unsigned AS = RMW->getPointerAddressSpace(); 11767 11768 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11769 return RMW->use_empty() ? AtomicExpansionKind::None : 11770 AtomicExpansionKind::CmpXChg; 11771 } 11772 11773 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11774 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11775 } 11776 default: 11777 break; 11778 } 11779 11780 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11781 } 11782 11783 const TargetRegisterClass * 11784 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11785 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11786 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11787 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11788 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11789 : &AMDGPU::SReg_32RegClass; 11790 if (!TRI->isSGPRClass(RC) && !isDivergent) 11791 return TRI->getEquivalentSGPRClass(RC); 11792 else if (TRI->isSGPRClass(RC) && isDivergent) 11793 return TRI->getEquivalentVGPRClass(RC); 11794 11795 return RC; 11796 } 11797 11798 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11799 // uniform values (as produced by the mask results of control flow intrinsics) 11800 // used outside of divergent blocks. The phi users need to also be treated as 11801 // always uniform. 11802 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11803 unsigned WaveSize) { 11804 // FIXME: We asssume we never cast the mask results of a control flow 11805 // intrinsic. 11806 // Early exit if the type won't be consistent as a compile time hack. 11807 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11808 if (!IT || IT->getBitWidth() != WaveSize) 11809 return false; 11810 11811 if (!isa<Instruction>(V)) 11812 return false; 11813 if (!Visited.insert(V).second) 11814 return false; 11815 bool Result = false; 11816 for (auto U : V->users()) { 11817 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11818 if (V == U->getOperand(1)) { 11819 switch (Intrinsic->getIntrinsicID()) { 11820 default: 11821 Result = false; 11822 break; 11823 case Intrinsic::amdgcn_if_break: 11824 case Intrinsic::amdgcn_if: 11825 case Intrinsic::amdgcn_else: 11826 Result = true; 11827 break; 11828 } 11829 } 11830 if (V == U->getOperand(0)) { 11831 switch (Intrinsic->getIntrinsicID()) { 11832 default: 11833 Result = false; 11834 break; 11835 case Intrinsic::amdgcn_end_cf: 11836 case Intrinsic::amdgcn_loop: 11837 Result = true; 11838 break; 11839 } 11840 } 11841 } else { 11842 Result = hasCFUser(U, Visited, WaveSize); 11843 } 11844 if (Result) 11845 break; 11846 } 11847 return Result; 11848 } 11849 11850 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11851 const Value *V) const { 11852 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11853 if (CI->isInlineAsm()) { 11854 // FIXME: This cannot give a correct answer. This should only trigger in 11855 // the case where inline asm returns mixed SGPR and VGPR results, used 11856 // outside the defining block. We don't have a specific result to 11857 // consider, so this assumes if any value is SGPR, the overall register 11858 // also needs to be SGPR. 11859 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11860 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11861 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11862 for (auto &TC : TargetConstraints) { 11863 if (TC.Type == InlineAsm::isOutput) { 11864 ComputeConstraintToUse(TC, SDValue()); 11865 unsigned AssignedReg; 11866 const TargetRegisterClass *RC; 11867 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11868 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11869 if (RC) { 11870 MachineRegisterInfo &MRI = MF.getRegInfo(); 11871 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11872 return true; 11873 else if (SIRI->isSGPRClass(RC)) 11874 return true; 11875 } 11876 } 11877 } 11878 } 11879 } 11880 SmallPtrSet<const Value *, 16> Visited; 11881 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11882 } 11883 11884 std::pair<int, MVT> 11885 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11886 Type *Ty) const { 11887 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11888 auto Size = DL.getTypeSizeInBits(Ty); 11889 // Maximum load or store can handle 8 dwords for scalar and 4 for 11890 // vector ALU. Let's assume anything above 8 dwords is expensive 11891 // even if legal. 11892 if (Size <= 256) 11893 return Cost; 11894 11895 Cost.first = (Size + 255) / 256; 11896 return Cost; 11897 } 11898