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->hasUnalignedDSAccess() && 1437 Subtarget->hasUnalignedAccessMode() && 1438 !Subtarget->hasLDSMisalignedBug()) { 1439 if (IsFast) 1440 *IsFast = Alignment != Align(2); 1441 return true; 1442 } 1443 1444 if (Size == 64) { 1445 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1446 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1447 // with adjacent offsets. 1448 bool AlignedBy4 = Alignment >= Align(4); 1449 if (IsFast) 1450 *IsFast = AlignedBy4; 1451 1452 return AlignedBy4; 1453 } 1454 if (Size == 96) { 1455 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1456 bool Aligned = Alignment >= Align(16); 1457 if (IsFast) 1458 *IsFast = Aligned; 1459 1460 return Aligned; 1461 } 1462 if (Size == 128) { 1463 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1464 // can do a 8 byte aligned, 16 byte access in a single operation using 1465 // ds_read2/write2_b64. 1466 bool Aligned = Alignment >= Align(8); 1467 if (IsFast) 1468 *IsFast = Aligned; 1469 1470 return Aligned; 1471 } 1472 } 1473 1474 // FIXME: We have to be conservative here and assume that flat operations 1475 // will access scratch. If we had access to the IR function, then we 1476 // could determine if any private memory was used in the function. 1477 if (!Subtarget->hasUnalignedScratchAccess() && 1478 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1479 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1480 bool AlignedBy4 = Alignment >= Align(4); 1481 if (IsFast) 1482 *IsFast = AlignedBy4; 1483 1484 return AlignedBy4; 1485 } 1486 1487 if (Subtarget->hasUnalignedBufferAccess() && 1488 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1489 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1490 // If we have an uniform constant load, it still requires using a slow 1491 // buffer instruction if unaligned. 1492 if (IsFast) { 1493 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1494 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1495 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1496 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1497 Alignment >= Align(4) : Alignment != Align(2); 1498 } 1499 1500 return true; 1501 } 1502 1503 // Smaller than dword value must be aligned. 1504 if (Size < 32) 1505 return false; 1506 1507 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1508 // byte-address are ignored, thus forcing Dword alignment. 1509 // This applies to private, global, and constant memory. 1510 if (IsFast) 1511 *IsFast = true; 1512 1513 return Size >= 32 && Alignment >= Align(4); 1514 } 1515 1516 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1517 EVT VT, unsigned AddrSpace, unsigned Alignment, 1518 MachineMemOperand::Flags Flags, bool *IsFast) const { 1519 if (IsFast) 1520 *IsFast = false; 1521 1522 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1523 // which isn't a simple VT. 1524 // Until MVT is extended to handle this, simply check for the size and 1525 // rely on the condition below: allow accesses if the size is a multiple of 4. 1526 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1527 VT.getStoreSize() > 16)) { 1528 return false; 1529 } 1530 1531 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1532 Align(Alignment), Flags, IsFast); 1533 } 1534 1535 EVT SITargetLowering::getOptimalMemOpType( 1536 const MemOp &Op, const AttributeList &FuncAttributes) const { 1537 // FIXME: Should account for address space here. 1538 1539 // The default fallback uses the private pointer size as a guess for a type to 1540 // use. Make sure we switch these to 64-bit accesses. 1541 1542 if (Op.size() >= 16 && 1543 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1544 return MVT::v4i32; 1545 1546 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1547 return MVT::v2i32; 1548 1549 // Use the default. 1550 return MVT::Other; 1551 } 1552 1553 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1554 const MemSDNode *MemNode = cast<MemSDNode>(N); 1555 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1556 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1557 return I && I->getMetadata("amdgpu.noclobber"); 1558 } 1559 1560 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1561 unsigned DestAS) const { 1562 // Flat -> private/local is a simple truncate. 1563 // Flat -> global is no-op 1564 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1565 return true; 1566 1567 const GCNTargetMachine &TM = 1568 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1569 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1570 } 1571 1572 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1573 const MemSDNode *MemNode = cast<MemSDNode>(N); 1574 1575 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1576 } 1577 1578 TargetLoweringBase::LegalizeTypeAction 1579 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1580 int NumElts = VT.getVectorNumElements(); 1581 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1582 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1583 return TargetLoweringBase::getPreferredVectorAction(VT); 1584 } 1585 1586 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1587 Type *Ty) const { 1588 // FIXME: Could be smarter if called for vector constants. 1589 return true; 1590 } 1591 1592 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1593 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1594 switch (Op) { 1595 case ISD::LOAD: 1596 case ISD::STORE: 1597 1598 // These operations are done with 32-bit instructions anyway. 1599 case ISD::AND: 1600 case ISD::OR: 1601 case ISD::XOR: 1602 case ISD::SELECT: 1603 // TODO: Extensions? 1604 return true; 1605 default: 1606 return false; 1607 } 1608 } 1609 1610 // SimplifySetCC uses this function to determine whether or not it should 1611 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1612 if (VT == MVT::i1 && Op == ISD::SETCC) 1613 return false; 1614 1615 return TargetLowering::isTypeDesirableForOp(Op, VT); 1616 } 1617 1618 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1619 const SDLoc &SL, 1620 SDValue Chain, 1621 uint64_t Offset) const { 1622 const DataLayout &DL = DAG.getDataLayout(); 1623 MachineFunction &MF = DAG.getMachineFunction(); 1624 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1625 1626 const ArgDescriptor *InputPtrReg; 1627 const TargetRegisterClass *RC; 1628 LLT ArgTy; 1629 1630 std::tie(InputPtrReg, RC, ArgTy) = 1631 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1632 1633 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1634 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1635 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1636 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1637 1638 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1639 } 1640 1641 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1642 const SDLoc &SL) const { 1643 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1644 FIRST_IMPLICIT); 1645 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1646 } 1647 1648 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1649 const SDLoc &SL, SDValue Val, 1650 bool Signed, 1651 const ISD::InputArg *Arg) const { 1652 // First, if it is a widened vector, narrow it. 1653 if (VT.isVector() && 1654 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1655 EVT NarrowedVT = 1656 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1657 VT.getVectorNumElements()); 1658 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1659 DAG.getConstant(0, SL, MVT::i32)); 1660 } 1661 1662 // Then convert the vector elements or scalar value. 1663 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1664 VT.bitsLT(MemVT)) { 1665 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1666 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1667 } 1668 1669 if (MemVT.isFloatingPoint()) 1670 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1671 else if (Signed) 1672 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1673 else 1674 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1675 1676 return Val; 1677 } 1678 1679 SDValue SITargetLowering::lowerKernargMemParameter( 1680 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1681 uint64_t Offset, Align Alignment, bool Signed, 1682 const ISD::InputArg *Arg) const { 1683 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1684 1685 // Try to avoid using an extload by loading earlier than the argument address, 1686 // and extracting the relevant bits. The load should hopefully be merged with 1687 // the previous argument. 1688 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1689 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1690 int64_t AlignDownOffset = alignDown(Offset, 4); 1691 int64_t OffsetDiff = Offset - AlignDownOffset; 1692 1693 EVT IntVT = MemVT.changeTypeToInteger(); 1694 1695 // TODO: If we passed in the base kernel offset we could have a better 1696 // alignment than 4, but we don't really need it. 1697 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1698 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1699 MachineMemOperand::MODereferenceable | 1700 MachineMemOperand::MOInvariant); 1701 1702 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1703 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1704 1705 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1706 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1707 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1708 1709 1710 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1711 } 1712 1713 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1714 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1715 MachineMemOperand::MODereferenceable | 1716 MachineMemOperand::MOInvariant); 1717 1718 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1719 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1720 } 1721 1722 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1723 const SDLoc &SL, SDValue Chain, 1724 const ISD::InputArg &Arg) const { 1725 MachineFunction &MF = DAG.getMachineFunction(); 1726 MachineFrameInfo &MFI = MF.getFrameInfo(); 1727 1728 if (Arg.Flags.isByVal()) { 1729 unsigned Size = Arg.Flags.getByValSize(); 1730 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1731 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1732 } 1733 1734 unsigned ArgOffset = VA.getLocMemOffset(); 1735 unsigned ArgSize = VA.getValVT().getStoreSize(); 1736 1737 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1738 1739 // Create load nodes to retrieve arguments from the stack. 1740 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1741 SDValue ArgValue; 1742 1743 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1744 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1745 MVT MemVT = VA.getValVT(); 1746 1747 switch (VA.getLocInfo()) { 1748 default: 1749 break; 1750 case CCValAssign::BCvt: 1751 MemVT = VA.getLocVT(); 1752 break; 1753 case CCValAssign::SExt: 1754 ExtType = ISD::SEXTLOAD; 1755 break; 1756 case CCValAssign::ZExt: 1757 ExtType = ISD::ZEXTLOAD; 1758 break; 1759 case CCValAssign::AExt: 1760 ExtType = ISD::EXTLOAD; 1761 break; 1762 } 1763 1764 ArgValue = DAG.getExtLoad( 1765 ExtType, SL, VA.getLocVT(), Chain, FIN, 1766 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1767 MemVT); 1768 return ArgValue; 1769 } 1770 1771 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1772 const SIMachineFunctionInfo &MFI, 1773 EVT VT, 1774 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1775 const ArgDescriptor *Reg; 1776 const TargetRegisterClass *RC; 1777 LLT Ty; 1778 1779 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1780 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1781 } 1782 1783 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1784 CallingConv::ID CallConv, 1785 ArrayRef<ISD::InputArg> Ins, 1786 BitVector &Skipped, 1787 FunctionType *FType, 1788 SIMachineFunctionInfo *Info) { 1789 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1790 const ISD::InputArg *Arg = &Ins[I]; 1791 1792 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1793 "vector type argument should have been split"); 1794 1795 // First check if it's a PS input addr. 1796 if (CallConv == CallingConv::AMDGPU_PS && 1797 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1798 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1799 1800 // Inconveniently only the first part of the split is marked as isSplit, 1801 // so skip to the end. We only want to increment PSInputNum once for the 1802 // entire split argument. 1803 if (Arg->Flags.isSplit()) { 1804 while (!Arg->Flags.isSplitEnd()) { 1805 assert((!Arg->VT.isVector() || 1806 Arg->VT.getScalarSizeInBits() == 16) && 1807 "unexpected vector split in ps argument type"); 1808 if (!SkipArg) 1809 Splits.push_back(*Arg); 1810 Arg = &Ins[++I]; 1811 } 1812 } 1813 1814 if (SkipArg) { 1815 // We can safely skip PS inputs. 1816 Skipped.set(Arg->getOrigArgIndex()); 1817 ++PSInputNum; 1818 continue; 1819 } 1820 1821 Info->markPSInputAllocated(PSInputNum); 1822 if (Arg->Used) 1823 Info->markPSInputEnabled(PSInputNum); 1824 1825 ++PSInputNum; 1826 } 1827 1828 Splits.push_back(*Arg); 1829 } 1830 } 1831 1832 // Allocate special inputs passed in VGPRs. 1833 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1834 MachineFunction &MF, 1835 const SIRegisterInfo &TRI, 1836 SIMachineFunctionInfo &Info) const { 1837 const LLT S32 = LLT::scalar(32); 1838 MachineRegisterInfo &MRI = MF.getRegInfo(); 1839 1840 if (Info.hasWorkItemIDX()) { 1841 Register Reg = AMDGPU::VGPR0; 1842 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1843 1844 CCInfo.AllocateReg(Reg); 1845 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1846 } 1847 1848 if (Info.hasWorkItemIDY()) { 1849 Register Reg = AMDGPU::VGPR1; 1850 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1851 1852 CCInfo.AllocateReg(Reg); 1853 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1854 } 1855 1856 if (Info.hasWorkItemIDZ()) { 1857 Register Reg = AMDGPU::VGPR2; 1858 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1859 1860 CCInfo.AllocateReg(Reg); 1861 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1862 } 1863 } 1864 1865 // Try to allocate a VGPR at the end of the argument list, or if no argument 1866 // VGPRs are left allocating a stack slot. 1867 // If \p Mask is is given it indicates bitfield position in the register. 1868 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1869 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1870 ArgDescriptor Arg = ArgDescriptor()) { 1871 if (Arg.isSet()) 1872 return ArgDescriptor::createArg(Arg, Mask); 1873 1874 ArrayRef<MCPhysReg> ArgVGPRs 1875 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1876 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1877 if (RegIdx == ArgVGPRs.size()) { 1878 // Spill to stack required. 1879 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1880 1881 return ArgDescriptor::createStack(Offset, Mask); 1882 } 1883 1884 unsigned Reg = ArgVGPRs[RegIdx]; 1885 Reg = CCInfo.AllocateReg(Reg); 1886 assert(Reg != AMDGPU::NoRegister); 1887 1888 MachineFunction &MF = CCInfo.getMachineFunction(); 1889 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1890 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1891 return ArgDescriptor::createRegister(Reg, Mask); 1892 } 1893 1894 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1895 const TargetRegisterClass *RC, 1896 unsigned NumArgRegs) { 1897 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1898 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1899 if (RegIdx == ArgSGPRs.size()) 1900 report_fatal_error("ran out of SGPRs for arguments"); 1901 1902 unsigned Reg = ArgSGPRs[RegIdx]; 1903 Reg = CCInfo.AllocateReg(Reg); 1904 assert(Reg != AMDGPU::NoRegister); 1905 1906 MachineFunction &MF = CCInfo.getMachineFunction(); 1907 MF.addLiveIn(Reg, RC); 1908 return ArgDescriptor::createRegister(Reg); 1909 } 1910 1911 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1912 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1913 } 1914 1915 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1916 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1917 } 1918 1919 /// Allocate implicit function VGPR arguments at the end of allocated user 1920 /// arguments. 1921 void SITargetLowering::allocateSpecialInputVGPRs( 1922 CCState &CCInfo, MachineFunction &MF, 1923 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1924 const unsigned Mask = 0x3ff; 1925 ArgDescriptor Arg; 1926 1927 if (Info.hasWorkItemIDX()) { 1928 Arg = allocateVGPR32Input(CCInfo, Mask); 1929 Info.setWorkItemIDX(Arg); 1930 } 1931 1932 if (Info.hasWorkItemIDY()) { 1933 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1934 Info.setWorkItemIDY(Arg); 1935 } 1936 1937 if (Info.hasWorkItemIDZ()) 1938 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1939 } 1940 1941 /// Allocate implicit function VGPR arguments in fixed registers. 1942 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1943 CCState &CCInfo, MachineFunction &MF, 1944 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1945 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1946 if (!Reg) 1947 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1948 1949 const unsigned Mask = 0x3ff; 1950 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1951 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1952 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1953 } 1954 1955 void SITargetLowering::allocateSpecialInputSGPRs( 1956 CCState &CCInfo, 1957 MachineFunction &MF, 1958 const SIRegisterInfo &TRI, 1959 SIMachineFunctionInfo &Info) const { 1960 auto &ArgInfo = Info.getArgInfo(); 1961 1962 // TODO: Unify handling with private memory pointers. 1963 1964 if (Info.hasDispatchPtr()) 1965 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1966 1967 if (Info.hasQueuePtr()) 1968 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1969 1970 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1971 // constant offset from the kernarg segment. 1972 if (Info.hasImplicitArgPtr()) 1973 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1974 1975 if (Info.hasDispatchID()) 1976 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1977 1978 // flat_scratch_init is not applicable for non-kernel functions. 1979 1980 if (Info.hasWorkGroupIDX()) 1981 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1982 1983 if (Info.hasWorkGroupIDY()) 1984 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1985 1986 if (Info.hasWorkGroupIDZ()) 1987 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1988 } 1989 1990 // Allocate special inputs passed in user SGPRs. 1991 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1992 MachineFunction &MF, 1993 const SIRegisterInfo &TRI, 1994 SIMachineFunctionInfo &Info) const { 1995 if (Info.hasImplicitBufferPtr()) { 1996 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1997 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1998 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1999 } 2000 2001 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2002 if (Info.hasPrivateSegmentBuffer()) { 2003 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2004 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2005 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2006 } 2007 2008 if (Info.hasDispatchPtr()) { 2009 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2010 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2011 CCInfo.AllocateReg(DispatchPtrReg); 2012 } 2013 2014 if (Info.hasQueuePtr()) { 2015 Register QueuePtrReg = Info.addQueuePtr(TRI); 2016 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2017 CCInfo.AllocateReg(QueuePtrReg); 2018 } 2019 2020 if (Info.hasKernargSegmentPtr()) { 2021 MachineRegisterInfo &MRI = MF.getRegInfo(); 2022 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2023 CCInfo.AllocateReg(InputPtrReg); 2024 2025 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2026 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2027 } 2028 2029 if (Info.hasDispatchID()) { 2030 Register DispatchIDReg = Info.addDispatchID(TRI); 2031 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2032 CCInfo.AllocateReg(DispatchIDReg); 2033 } 2034 2035 if (Info.hasFlatScratchInit()) { 2036 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2037 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2038 CCInfo.AllocateReg(FlatScratchInitReg); 2039 } 2040 2041 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2042 // these from the dispatch pointer. 2043 } 2044 2045 // Allocate special input registers that are initialized per-wave. 2046 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2047 MachineFunction &MF, 2048 SIMachineFunctionInfo &Info, 2049 CallingConv::ID CallConv, 2050 bool IsShader) const { 2051 if (Info.hasWorkGroupIDX()) { 2052 Register Reg = Info.addWorkGroupIDX(); 2053 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2054 CCInfo.AllocateReg(Reg); 2055 } 2056 2057 if (Info.hasWorkGroupIDY()) { 2058 Register Reg = Info.addWorkGroupIDY(); 2059 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2060 CCInfo.AllocateReg(Reg); 2061 } 2062 2063 if (Info.hasWorkGroupIDZ()) { 2064 Register Reg = Info.addWorkGroupIDZ(); 2065 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2066 CCInfo.AllocateReg(Reg); 2067 } 2068 2069 if (Info.hasWorkGroupInfo()) { 2070 Register Reg = Info.addWorkGroupInfo(); 2071 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2072 CCInfo.AllocateReg(Reg); 2073 } 2074 2075 if (Info.hasPrivateSegmentWaveByteOffset()) { 2076 // Scratch wave offset passed in system SGPR. 2077 unsigned PrivateSegmentWaveByteOffsetReg; 2078 2079 if (IsShader) { 2080 PrivateSegmentWaveByteOffsetReg = 2081 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2082 2083 // This is true if the scratch wave byte offset doesn't have a fixed 2084 // location. 2085 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2086 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2087 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2088 } 2089 } else 2090 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2091 2092 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2093 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2094 } 2095 } 2096 2097 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2098 MachineFunction &MF, 2099 const SIRegisterInfo &TRI, 2100 SIMachineFunctionInfo &Info) { 2101 // Now that we've figured out where the scratch register inputs are, see if 2102 // should reserve the arguments and use them directly. 2103 MachineFrameInfo &MFI = MF.getFrameInfo(); 2104 bool HasStackObjects = MFI.hasStackObjects(); 2105 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2106 2107 // Record that we know we have non-spill stack objects so we don't need to 2108 // check all stack objects later. 2109 if (HasStackObjects) 2110 Info.setHasNonSpillStackObjects(true); 2111 2112 // Everything live out of a block is spilled with fast regalloc, so it's 2113 // almost certain that spilling will be required. 2114 if (TM.getOptLevel() == CodeGenOpt::None) 2115 HasStackObjects = true; 2116 2117 // For now assume stack access is needed in any callee functions, so we need 2118 // the scratch registers to pass in. 2119 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2120 2121 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2122 // If we have stack objects, we unquestionably need the private buffer 2123 // resource. For the Code Object V2 ABI, this will be the first 4 user 2124 // SGPR inputs. We can reserve those and use them directly. 2125 2126 Register PrivateSegmentBufferReg = 2127 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2128 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2129 } else { 2130 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2131 // We tentatively reserve the last registers (skipping the last registers 2132 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2133 // we'll replace these with the ones immediately after those which were 2134 // really allocated. In the prologue copies will be inserted from the 2135 // argument to these reserved registers. 2136 2137 // Without HSA, relocations are used for the scratch pointer and the 2138 // buffer resource setup is always inserted in the prologue. Scratch wave 2139 // offset is still in an input SGPR. 2140 Info.setScratchRSrcReg(ReservedBufferReg); 2141 } 2142 2143 MachineRegisterInfo &MRI = MF.getRegInfo(); 2144 2145 // For entry functions we have to set up the stack pointer if we use it, 2146 // whereas non-entry functions get this "for free". This means there is no 2147 // intrinsic advantage to using S32 over S34 in cases where we do not have 2148 // calls but do need a frame pointer (i.e. if we are requested to have one 2149 // because frame pointer elimination is disabled). To keep things simple we 2150 // only ever use S32 as the call ABI stack pointer, and so using it does not 2151 // imply we need a separate frame pointer. 2152 // 2153 // Try to use s32 as the SP, but move it if it would interfere with input 2154 // arguments. This won't work with calls though. 2155 // 2156 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2157 // registers. 2158 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2159 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2160 } else { 2161 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2162 2163 if (MFI.hasCalls()) 2164 report_fatal_error("call in graphics shader with too many input SGPRs"); 2165 2166 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2167 if (!MRI.isLiveIn(Reg)) { 2168 Info.setStackPtrOffsetReg(Reg); 2169 break; 2170 } 2171 } 2172 2173 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2174 report_fatal_error("failed to find register for SP"); 2175 } 2176 2177 // hasFP should be accurate for entry functions even before the frame is 2178 // finalized, because it does not rely on the known stack size, only 2179 // properties like whether variable sized objects are present. 2180 if (ST.getFrameLowering()->hasFP(MF)) { 2181 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2182 } 2183 } 2184 2185 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2186 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2187 return !Info->isEntryFunction(); 2188 } 2189 2190 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2191 2192 } 2193 2194 void SITargetLowering::insertCopiesSplitCSR( 2195 MachineBasicBlock *Entry, 2196 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2197 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2198 2199 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2200 if (!IStart) 2201 return; 2202 2203 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2204 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2205 MachineBasicBlock::iterator MBBI = Entry->begin(); 2206 for (const MCPhysReg *I = IStart; *I; ++I) { 2207 const TargetRegisterClass *RC = nullptr; 2208 if (AMDGPU::SReg_64RegClass.contains(*I)) 2209 RC = &AMDGPU::SGPR_64RegClass; 2210 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2211 RC = &AMDGPU::SGPR_32RegClass; 2212 else 2213 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2214 2215 Register NewVR = MRI->createVirtualRegister(RC); 2216 // Create copy from CSR to a virtual register. 2217 Entry->addLiveIn(*I); 2218 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2219 .addReg(*I); 2220 2221 // Insert the copy-back instructions right before the terminator. 2222 for (auto *Exit : Exits) 2223 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2224 TII->get(TargetOpcode::COPY), *I) 2225 .addReg(NewVR); 2226 } 2227 } 2228 2229 SDValue SITargetLowering::LowerFormalArguments( 2230 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2231 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2232 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2233 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2234 2235 MachineFunction &MF = DAG.getMachineFunction(); 2236 const Function &Fn = MF.getFunction(); 2237 FunctionType *FType = MF.getFunction().getFunctionType(); 2238 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2239 2240 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2241 DiagnosticInfoUnsupported NoGraphicsHSA( 2242 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2243 DAG.getContext()->diagnose(NoGraphicsHSA); 2244 return DAG.getEntryNode(); 2245 } 2246 2247 SmallVector<ISD::InputArg, 16> Splits; 2248 SmallVector<CCValAssign, 16> ArgLocs; 2249 BitVector Skipped(Ins.size()); 2250 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2251 *DAG.getContext()); 2252 2253 bool IsShader = AMDGPU::isShader(CallConv); 2254 bool IsKernel = AMDGPU::isKernel(CallConv); 2255 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2256 2257 if (IsShader) { 2258 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2259 2260 // At least one interpolation mode must be enabled or else the GPU will 2261 // hang. 2262 // 2263 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2264 // set PSInputAddr, the user wants to enable some bits after the compilation 2265 // based on run-time states. Since we can't know what the final PSInputEna 2266 // will look like, so we shouldn't do anything here and the user should take 2267 // responsibility for the correct programming. 2268 // 2269 // Otherwise, the following restrictions apply: 2270 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2271 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2272 // enabled too. 2273 if (CallConv == CallingConv::AMDGPU_PS) { 2274 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2275 ((Info->getPSInputAddr() & 0xF) == 0 && 2276 Info->isPSInputAllocated(11))) { 2277 CCInfo.AllocateReg(AMDGPU::VGPR0); 2278 CCInfo.AllocateReg(AMDGPU::VGPR1); 2279 Info->markPSInputAllocated(0); 2280 Info->markPSInputEnabled(0); 2281 } 2282 if (Subtarget->isAmdPalOS()) { 2283 // For isAmdPalOS, the user does not enable some bits after compilation 2284 // based on run-time states; the register values being generated here are 2285 // the final ones set in hardware. Therefore we need to apply the 2286 // workaround to PSInputAddr and PSInputEnable together. (The case where 2287 // a bit is set in PSInputAddr but not PSInputEnable is where the 2288 // frontend set up an input arg for a particular interpolation mode, but 2289 // nothing uses that input arg. Really we should have an earlier pass 2290 // that removes such an arg.) 2291 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2292 if ((PsInputBits & 0x7F) == 0 || 2293 ((PsInputBits & 0xF) == 0 && 2294 (PsInputBits >> 11 & 1))) 2295 Info->markPSInputEnabled( 2296 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2297 } 2298 } 2299 2300 assert(!Info->hasDispatchPtr() && 2301 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2302 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2303 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2304 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2305 !Info->hasWorkItemIDZ()); 2306 } else if (IsKernel) { 2307 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2308 } else { 2309 Splits.append(Ins.begin(), Ins.end()); 2310 } 2311 2312 if (IsEntryFunc) { 2313 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2314 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2315 } else { 2316 // For the fixed ABI, pass workitem IDs in the last argument register. 2317 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2318 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2319 } 2320 2321 if (IsKernel) { 2322 analyzeFormalArgumentsCompute(CCInfo, Ins); 2323 } else { 2324 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2325 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2326 } 2327 2328 SmallVector<SDValue, 16> Chains; 2329 2330 // FIXME: This is the minimum kernel argument alignment. We should improve 2331 // this to the maximum alignment of the arguments. 2332 // 2333 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2334 // kern arg offset. 2335 const Align KernelArgBaseAlign = Align(16); 2336 2337 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2338 const ISD::InputArg &Arg = Ins[i]; 2339 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2340 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2341 continue; 2342 } 2343 2344 CCValAssign &VA = ArgLocs[ArgIdx++]; 2345 MVT VT = VA.getLocVT(); 2346 2347 if (IsEntryFunc && VA.isMemLoc()) { 2348 VT = Ins[i].VT; 2349 EVT MemVT = VA.getLocVT(); 2350 2351 const uint64_t Offset = VA.getLocMemOffset(); 2352 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2353 2354 if (Arg.Flags.isByRef()) { 2355 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2356 2357 const GCNTargetMachine &TM = 2358 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2359 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2360 Arg.Flags.getPointerAddrSpace())) { 2361 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2362 Arg.Flags.getPointerAddrSpace()); 2363 } 2364 2365 InVals.push_back(Ptr); 2366 continue; 2367 } 2368 2369 SDValue Arg = lowerKernargMemParameter( 2370 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2371 Chains.push_back(Arg.getValue(1)); 2372 2373 auto *ParamTy = 2374 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2375 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2376 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2377 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2378 // On SI local pointers are just offsets into LDS, so they are always 2379 // less than 16-bits. On CI and newer they could potentially be 2380 // real pointers, so we can't guarantee their size. 2381 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2382 DAG.getValueType(MVT::i16)); 2383 } 2384 2385 InVals.push_back(Arg); 2386 continue; 2387 } else if (!IsEntryFunc && VA.isMemLoc()) { 2388 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2389 InVals.push_back(Val); 2390 if (!Arg.Flags.isByVal()) 2391 Chains.push_back(Val.getValue(1)); 2392 continue; 2393 } 2394 2395 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2396 2397 Register Reg = VA.getLocReg(); 2398 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2399 EVT ValVT = VA.getValVT(); 2400 2401 Reg = MF.addLiveIn(Reg, RC); 2402 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2403 2404 if (Arg.Flags.isSRet()) { 2405 // The return object should be reasonably addressable. 2406 2407 // FIXME: This helps when the return is a real sret. If it is a 2408 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2409 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2410 unsigned NumBits 2411 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2412 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2413 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2414 } 2415 2416 // If this is an 8 or 16-bit value, it is really passed promoted 2417 // to 32 bits. Insert an assert[sz]ext to capture this, then 2418 // truncate to the right size. 2419 switch (VA.getLocInfo()) { 2420 case CCValAssign::Full: 2421 break; 2422 case CCValAssign::BCvt: 2423 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2424 break; 2425 case CCValAssign::SExt: 2426 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2427 DAG.getValueType(ValVT)); 2428 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2429 break; 2430 case CCValAssign::ZExt: 2431 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2432 DAG.getValueType(ValVT)); 2433 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2434 break; 2435 case CCValAssign::AExt: 2436 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2437 break; 2438 default: 2439 llvm_unreachable("Unknown loc info!"); 2440 } 2441 2442 InVals.push_back(Val); 2443 } 2444 2445 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2446 // Special inputs come after user arguments. 2447 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2448 } 2449 2450 // Start adding system SGPRs. 2451 if (IsEntryFunc) { 2452 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2453 } else { 2454 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2455 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2456 } 2457 2458 auto &ArgUsageInfo = 2459 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2460 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2461 2462 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2463 Info->setBytesInStackArgArea(StackArgSize); 2464 2465 return Chains.empty() ? Chain : 2466 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2467 } 2468 2469 // TODO: If return values can't fit in registers, we should return as many as 2470 // possible in registers before passing on stack. 2471 bool SITargetLowering::CanLowerReturn( 2472 CallingConv::ID CallConv, 2473 MachineFunction &MF, bool IsVarArg, 2474 const SmallVectorImpl<ISD::OutputArg> &Outs, 2475 LLVMContext &Context) const { 2476 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2477 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2478 // for shaders. Vector types should be explicitly handled by CC. 2479 if (AMDGPU::isEntryFunctionCC(CallConv)) 2480 return true; 2481 2482 SmallVector<CCValAssign, 16> RVLocs; 2483 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2484 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2485 } 2486 2487 SDValue 2488 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2489 bool isVarArg, 2490 const SmallVectorImpl<ISD::OutputArg> &Outs, 2491 const SmallVectorImpl<SDValue> &OutVals, 2492 const SDLoc &DL, SelectionDAG &DAG) const { 2493 MachineFunction &MF = DAG.getMachineFunction(); 2494 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2495 2496 if (AMDGPU::isKernel(CallConv)) { 2497 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2498 OutVals, DL, DAG); 2499 } 2500 2501 bool IsShader = AMDGPU::isShader(CallConv); 2502 2503 Info->setIfReturnsVoid(Outs.empty()); 2504 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2505 2506 // CCValAssign - represent the assignment of the return value to a location. 2507 SmallVector<CCValAssign, 48> RVLocs; 2508 SmallVector<ISD::OutputArg, 48> Splits; 2509 2510 // CCState - Info about the registers and stack slots. 2511 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2512 *DAG.getContext()); 2513 2514 // Analyze outgoing return values. 2515 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2516 2517 SDValue Flag; 2518 SmallVector<SDValue, 48> RetOps; 2519 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2520 2521 // Add return address for callable functions. 2522 if (!Info->isEntryFunction()) { 2523 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2524 SDValue ReturnAddrReg = CreateLiveInRegister( 2525 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2526 2527 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2528 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2529 MVT::i64); 2530 Chain = 2531 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2532 Flag = Chain.getValue(1); 2533 RetOps.push_back(ReturnAddrVirtualReg); 2534 } 2535 2536 // Copy the result values into the output registers. 2537 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2538 ++I, ++RealRVLocIdx) { 2539 CCValAssign &VA = RVLocs[I]; 2540 assert(VA.isRegLoc() && "Can only return in registers!"); 2541 // TODO: Partially return in registers if return values don't fit. 2542 SDValue Arg = OutVals[RealRVLocIdx]; 2543 2544 // Copied from other backends. 2545 switch (VA.getLocInfo()) { 2546 case CCValAssign::Full: 2547 break; 2548 case CCValAssign::BCvt: 2549 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2550 break; 2551 case CCValAssign::SExt: 2552 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2553 break; 2554 case CCValAssign::ZExt: 2555 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2556 break; 2557 case CCValAssign::AExt: 2558 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2559 break; 2560 default: 2561 llvm_unreachable("Unknown loc info!"); 2562 } 2563 2564 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2565 Flag = Chain.getValue(1); 2566 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2567 } 2568 2569 // FIXME: Does sret work properly? 2570 if (!Info->isEntryFunction()) { 2571 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2572 const MCPhysReg *I = 2573 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2574 if (I) { 2575 for (; *I; ++I) { 2576 if (AMDGPU::SReg_64RegClass.contains(*I)) 2577 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2578 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2579 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2580 else 2581 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2582 } 2583 } 2584 } 2585 2586 // Update chain and glue. 2587 RetOps[0] = Chain; 2588 if (Flag.getNode()) 2589 RetOps.push_back(Flag); 2590 2591 unsigned Opc = AMDGPUISD::ENDPGM; 2592 if (!IsWaveEnd) 2593 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2594 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2595 } 2596 2597 SDValue SITargetLowering::LowerCallResult( 2598 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2599 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2600 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2601 SDValue ThisVal) const { 2602 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2603 2604 // Assign locations to each value returned by this call. 2605 SmallVector<CCValAssign, 16> RVLocs; 2606 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2607 *DAG.getContext()); 2608 CCInfo.AnalyzeCallResult(Ins, RetCC); 2609 2610 // Copy all of the result registers out of their specified physreg. 2611 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2612 CCValAssign VA = RVLocs[i]; 2613 SDValue Val; 2614 2615 if (VA.isRegLoc()) { 2616 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2617 Chain = Val.getValue(1); 2618 InFlag = Val.getValue(2); 2619 } else if (VA.isMemLoc()) { 2620 report_fatal_error("TODO: return values in memory"); 2621 } else 2622 llvm_unreachable("unknown argument location type"); 2623 2624 switch (VA.getLocInfo()) { 2625 case CCValAssign::Full: 2626 break; 2627 case CCValAssign::BCvt: 2628 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2629 break; 2630 case CCValAssign::ZExt: 2631 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2632 DAG.getValueType(VA.getValVT())); 2633 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2634 break; 2635 case CCValAssign::SExt: 2636 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2637 DAG.getValueType(VA.getValVT())); 2638 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2639 break; 2640 case CCValAssign::AExt: 2641 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2642 break; 2643 default: 2644 llvm_unreachable("Unknown loc info!"); 2645 } 2646 2647 InVals.push_back(Val); 2648 } 2649 2650 return Chain; 2651 } 2652 2653 // Add code to pass special inputs required depending on used features separate 2654 // from the explicit user arguments present in the IR. 2655 void SITargetLowering::passSpecialInputs( 2656 CallLoweringInfo &CLI, 2657 CCState &CCInfo, 2658 const SIMachineFunctionInfo &Info, 2659 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2660 SmallVectorImpl<SDValue> &MemOpChains, 2661 SDValue Chain) const { 2662 // If we don't have a call site, this was a call inserted by 2663 // legalization. These can never use special inputs. 2664 if (!CLI.CB) 2665 return; 2666 2667 SelectionDAG &DAG = CLI.DAG; 2668 const SDLoc &DL = CLI.DL; 2669 2670 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2671 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2672 2673 const AMDGPUFunctionArgInfo *CalleeArgInfo 2674 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2675 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2676 auto &ArgUsageInfo = 2677 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2678 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2679 } 2680 2681 // TODO: Unify with private memory register handling. This is complicated by 2682 // the fact that at least in kernels, the input argument is not necessarily 2683 // in the same location as the input. 2684 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2685 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2686 AMDGPUFunctionArgInfo::QUEUE_PTR, 2687 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2688 AMDGPUFunctionArgInfo::DISPATCH_ID, 2689 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2690 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2691 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2692 }; 2693 2694 for (auto InputID : InputRegs) { 2695 const ArgDescriptor *OutgoingArg; 2696 const TargetRegisterClass *ArgRC; 2697 LLT ArgTy; 2698 2699 std::tie(OutgoingArg, ArgRC, ArgTy) = 2700 CalleeArgInfo->getPreloadedValue(InputID); 2701 if (!OutgoingArg) 2702 continue; 2703 2704 const ArgDescriptor *IncomingArg; 2705 const TargetRegisterClass *IncomingArgRC; 2706 LLT Ty; 2707 std::tie(IncomingArg, IncomingArgRC, Ty) = 2708 CallerArgInfo.getPreloadedValue(InputID); 2709 assert(IncomingArgRC == ArgRC); 2710 2711 // All special arguments are ints for now. 2712 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2713 SDValue InputReg; 2714 2715 if (IncomingArg) { 2716 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2717 } else { 2718 // The implicit arg ptr is special because it doesn't have a corresponding 2719 // input for kernels, and is computed from the kernarg segment pointer. 2720 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2721 InputReg = getImplicitArgPtr(DAG, DL); 2722 } 2723 2724 if (OutgoingArg->isRegister()) { 2725 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2726 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2727 report_fatal_error("failed to allocate implicit input argument"); 2728 } else { 2729 unsigned SpecialArgOffset = 2730 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2731 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2732 SpecialArgOffset); 2733 MemOpChains.push_back(ArgStore); 2734 } 2735 } 2736 2737 // Pack workitem IDs into a single register or pass it as is if already 2738 // packed. 2739 const ArgDescriptor *OutgoingArg; 2740 const TargetRegisterClass *ArgRC; 2741 LLT Ty; 2742 2743 std::tie(OutgoingArg, ArgRC, Ty) = 2744 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2745 if (!OutgoingArg) 2746 std::tie(OutgoingArg, ArgRC, Ty) = 2747 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2748 if (!OutgoingArg) 2749 std::tie(OutgoingArg, ArgRC, Ty) = 2750 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2751 if (!OutgoingArg) 2752 return; 2753 2754 const ArgDescriptor *IncomingArgX = std::get<0>( 2755 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2756 const ArgDescriptor *IncomingArgY = std::get<0>( 2757 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2758 const ArgDescriptor *IncomingArgZ = std::get<0>( 2759 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2760 2761 SDValue InputReg; 2762 SDLoc SL; 2763 2764 // If incoming ids are not packed we need to pack them. 2765 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2766 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2767 2768 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2769 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2770 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2771 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2772 InputReg = InputReg.getNode() ? 2773 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2774 } 2775 2776 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2777 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2778 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2779 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2780 InputReg = InputReg.getNode() ? 2781 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2782 } 2783 2784 if (!InputReg.getNode()) { 2785 // Workitem ids are already packed, any of present incoming arguments 2786 // will carry all required fields. 2787 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2788 IncomingArgX ? *IncomingArgX : 2789 IncomingArgY ? *IncomingArgY : 2790 *IncomingArgZ, ~0u); 2791 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2792 } 2793 2794 if (OutgoingArg->isRegister()) { 2795 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2796 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2797 } else { 2798 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2799 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2800 SpecialArgOffset); 2801 MemOpChains.push_back(ArgStore); 2802 } 2803 } 2804 2805 static bool canGuaranteeTCO(CallingConv::ID CC) { 2806 return CC == CallingConv::Fast; 2807 } 2808 2809 /// Return true if we might ever do TCO for calls with this calling convention. 2810 static bool mayTailCallThisCC(CallingConv::ID CC) { 2811 switch (CC) { 2812 case CallingConv::C: 2813 return true; 2814 default: 2815 return canGuaranteeTCO(CC); 2816 } 2817 } 2818 2819 bool SITargetLowering::isEligibleForTailCallOptimization( 2820 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2821 const SmallVectorImpl<ISD::OutputArg> &Outs, 2822 const SmallVectorImpl<SDValue> &OutVals, 2823 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2824 if (!mayTailCallThisCC(CalleeCC)) 2825 return false; 2826 2827 MachineFunction &MF = DAG.getMachineFunction(); 2828 const Function &CallerF = MF.getFunction(); 2829 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2830 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2831 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2832 2833 // Kernels aren't callable, and don't have a live in return address so it 2834 // doesn't make sense to do a tail call with entry functions. 2835 if (!CallerPreserved) 2836 return false; 2837 2838 bool CCMatch = CallerCC == CalleeCC; 2839 2840 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2841 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2842 return true; 2843 return false; 2844 } 2845 2846 // TODO: Can we handle var args? 2847 if (IsVarArg) 2848 return false; 2849 2850 for (const Argument &Arg : CallerF.args()) { 2851 if (Arg.hasByValAttr()) 2852 return false; 2853 } 2854 2855 LLVMContext &Ctx = *DAG.getContext(); 2856 2857 // Check that the call results are passed in the same way. 2858 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2859 CCAssignFnForCall(CalleeCC, IsVarArg), 2860 CCAssignFnForCall(CallerCC, IsVarArg))) 2861 return false; 2862 2863 // The callee has to preserve all registers the caller needs to preserve. 2864 if (!CCMatch) { 2865 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2866 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2867 return false; 2868 } 2869 2870 // Nothing more to check if the callee is taking no arguments. 2871 if (Outs.empty()) 2872 return true; 2873 2874 SmallVector<CCValAssign, 16> ArgLocs; 2875 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2876 2877 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2878 2879 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2880 // If the stack arguments for this call do not fit into our own save area then 2881 // the call cannot be made tail. 2882 // TODO: Is this really necessary? 2883 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2884 return false; 2885 2886 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2887 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2888 } 2889 2890 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2891 if (!CI->isTailCall()) 2892 return false; 2893 2894 const Function *ParentFn = CI->getParent()->getParent(); 2895 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2896 return false; 2897 return true; 2898 } 2899 2900 // The wave scratch offset register is used as the global base pointer. 2901 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2902 SmallVectorImpl<SDValue> &InVals) const { 2903 SelectionDAG &DAG = CLI.DAG; 2904 const SDLoc &DL = CLI.DL; 2905 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2906 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2907 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2908 SDValue Chain = CLI.Chain; 2909 SDValue Callee = CLI.Callee; 2910 bool &IsTailCall = CLI.IsTailCall; 2911 CallingConv::ID CallConv = CLI.CallConv; 2912 bool IsVarArg = CLI.IsVarArg; 2913 bool IsSibCall = false; 2914 bool IsThisReturn = false; 2915 MachineFunction &MF = DAG.getMachineFunction(); 2916 2917 if (Callee.isUndef() || isNullConstant(Callee)) { 2918 if (!CLI.IsTailCall) { 2919 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2920 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2921 } 2922 2923 return Chain; 2924 } 2925 2926 if (IsVarArg) { 2927 return lowerUnhandledCall(CLI, InVals, 2928 "unsupported call to variadic function "); 2929 } 2930 2931 if (!CLI.CB) 2932 report_fatal_error("unsupported libcall legalization"); 2933 2934 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2935 !CLI.CB->getCalledFunction()) { 2936 return lowerUnhandledCall(CLI, InVals, 2937 "unsupported indirect call to function "); 2938 } 2939 2940 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2941 return lowerUnhandledCall(CLI, InVals, 2942 "unsupported required tail call to function "); 2943 } 2944 2945 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2946 // Note the issue is with the CC of the calling function, not of the call 2947 // itself. 2948 return lowerUnhandledCall(CLI, InVals, 2949 "unsupported call from graphics shader of function "); 2950 } 2951 2952 if (IsTailCall) { 2953 IsTailCall = isEligibleForTailCallOptimization( 2954 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2955 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2956 report_fatal_error("failed to perform tail call elimination on a call " 2957 "site marked musttail"); 2958 } 2959 2960 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2961 2962 // A sibling call is one where we're under the usual C ABI and not planning 2963 // to change that but can still do a tail call: 2964 if (!TailCallOpt && IsTailCall) 2965 IsSibCall = true; 2966 2967 if (IsTailCall) 2968 ++NumTailCalls; 2969 } 2970 2971 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2972 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2973 SmallVector<SDValue, 8> MemOpChains; 2974 2975 // Analyze operands of the call, assigning locations to each operand. 2976 SmallVector<CCValAssign, 16> ArgLocs; 2977 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2978 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2979 2980 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2981 // With a fixed ABI, allocate fixed registers before user arguments. 2982 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2983 } 2984 2985 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2986 2987 // Get a count of how many bytes are to be pushed on the stack. 2988 unsigned NumBytes = CCInfo.getNextStackOffset(); 2989 2990 if (IsSibCall) { 2991 // Since we're not changing the ABI to make this a tail call, the memory 2992 // operands are already available in the caller's incoming argument space. 2993 NumBytes = 0; 2994 } 2995 2996 // FPDiff is the byte offset of the call's argument area from the callee's. 2997 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2998 // by this amount for a tail call. In a sibling call it must be 0 because the 2999 // caller will deallocate the entire stack and the callee still expects its 3000 // arguments to begin at SP+0. Completely unused for non-tail calls. 3001 int32_t FPDiff = 0; 3002 MachineFrameInfo &MFI = MF.getFrameInfo(); 3003 3004 // Adjust the stack pointer for the new arguments... 3005 // These operations are automatically eliminated by the prolog/epilog pass 3006 if (!IsSibCall) { 3007 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3008 3009 SmallVector<SDValue, 4> CopyFromChains; 3010 3011 // In the HSA case, this should be an identity copy. 3012 SDValue ScratchRSrcReg 3013 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3014 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3015 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3016 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3017 } 3018 3019 MVT PtrVT = MVT::i32; 3020 3021 // Walk the register/memloc assignments, inserting copies/loads. 3022 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3023 CCValAssign &VA = ArgLocs[i]; 3024 SDValue Arg = OutVals[i]; 3025 3026 // Promote the value if needed. 3027 switch (VA.getLocInfo()) { 3028 case CCValAssign::Full: 3029 break; 3030 case CCValAssign::BCvt: 3031 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3032 break; 3033 case CCValAssign::ZExt: 3034 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3035 break; 3036 case CCValAssign::SExt: 3037 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3038 break; 3039 case CCValAssign::AExt: 3040 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3041 break; 3042 case CCValAssign::FPExt: 3043 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3044 break; 3045 default: 3046 llvm_unreachable("Unknown loc info!"); 3047 } 3048 3049 if (VA.isRegLoc()) { 3050 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3051 } else { 3052 assert(VA.isMemLoc()); 3053 3054 SDValue DstAddr; 3055 MachinePointerInfo DstInfo; 3056 3057 unsigned LocMemOffset = VA.getLocMemOffset(); 3058 int32_t Offset = LocMemOffset; 3059 3060 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3061 MaybeAlign Alignment; 3062 3063 if (IsTailCall) { 3064 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3065 unsigned OpSize = Flags.isByVal() ? 3066 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3067 3068 // FIXME: We can have better than the minimum byval required alignment. 3069 Alignment = 3070 Flags.isByVal() 3071 ? Flags.getNonZeroByValAlign() 3072 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3073 3074 Offset = Offset + FPDiff; 3075 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3076 3077 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3078 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3079 3080 // Make sure any stack arguments overlapping with where we're storing 3081 // are loaded before this eventual operation. Otherwise they'll be 3082 // clobbered. 3083 3084 // FIXME: Why is this really necessary? This seems to just result in a 3085 // lot of code to copy the stack and write them back to the same 3086 // locations, which are supposed to be immutable? 3087 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3088 } else { 3089 DstAddr = PtrOff; 3090 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3091 Alignment = 3092 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3093 } 3094 3095 if (Outs[i].Flags.isByVal()) { 3096 SDValue SizeNode = 3097 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3098 SDValue Cpy = 3099 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3100 Outs[i].Flags.getNonZeroByValAlign(), 3101 /*isVol = */ false, /*AlwaysInline = */ true, 3102 /*isTailCall = */ false, DstInfo, 3103 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3104 3105 MemOpChains.push_back(Cpy); 3106 } else { 3107 SDValue Store = 3108 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3109 MemOpChains.push_back(Store); 3110 } 3111 } 3112 } 3113 3114 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3115 // Copy special input registers after user input arguments. 3116 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3117 } 3118 3119 if (!MemOpChains.empty()) 3120 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3121 3122 // Build a sequence of copy-to-reg nodes chained together with token chain 3123 // and flag operands which copy the outgoing args into the appropriate regs. 3124 SDValue InFlag; 3125 for (auto &RegToPass : RegsToPass) { 3126 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3127 RegToPass.second, InFlag); 3128 InFlag = Chain.getValue(1); 3129 } 3130 3131 3132 SDValue PhysReturnAddrReg; 3133 if (IsTailCall) { 3134 // Since the return is being combined with the call, we need to pass on the 3135 // return address. 3136 3137 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3138 SDValue ReturnAddrReg = CreateLiveInRegister( 3139 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3140 3141 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3142 MVT::i64); 3143 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3144 InFlag = Chain.getValue(1); 3145 } 3146 3147 // We don't usually want to end the call-sequence here because we would tidy 3148 // the frame up *after* the call, however in the ABI-changing tail-call case 3149 // we've carefully laid out the parameters so that when sp is reset they'll be 3150 // in the correct location. 3151 if (IsTailCall && !IsSibCall) { 3152 Chain = DAG.getCALLSEQ_END(Chain, 3153 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3154 DAG.getTargetConstant(0, DL, MVT::i32), 3155 InFlag, DL); 3156 InFlag = Chain.getValue(1); 3157 } 3158 3159 std::vector<SDValue> Ops; 3160 Ops.push_back(Chain); 3161 Ops.push_back(Callee); 3162 // Add a redundant copy of the callee global which will not be legalized, as 3163 // we need direct access to the callee later. 3164 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3165 const GlobalValue *GV = GSD->getGlobal(); 3166 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3167 } else { 3168 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3169 } 3170 3171 if (IsTailCall) { 3172 // Each tail call may have to adjust the stack by a different amount, so 3173 // this information must travel along with the operation for eventual 3174 // consumption by emitEpilogue. 3175 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3176 3177 Ops.push_back(PhysReturnAddrReg); 3178 } 3179 3180 // Add argument registers to the end of the list so that they are known live 3181 // into the call. 3182 for (auto &RegToPass : RegsToPass) { 3183 Ops.push_back(DAG.getRegister(RegToPass.first, 3184 RegToPass.second.getValueType())); 3185 } 3186 3187 // Add a register mask operand representing the call-preserved registers. 3188 3189 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3190 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3191 assert(Mask && "Missing call preserved mask for calling convention"); 3192 Ops.push_back(DAG.getRegisterMask(Mask)); 3193 3194 if (InFlag.getNode()) 3195 Ops.push_back(InFlag); 3196 3197 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3198 3199 // If we're doing a tall call, use a TC_RETURN here rather than an 3200 // actual call instruction. 3201 if (IsTailCall) { 3202 MFI.setHasTailCall(); 3203 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3204 } 3205 3206 // Returns a chain and a flag for retval copy to use. 3207 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3208 Chain = Call.getValue(0); 3209 InFlag = Call.getValue(1); 3210 3211 uint64_t CalleePopBytes = NumBytes; 3212 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3213 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3214 InFlag, DL); 3215 if (!Ins.empty()) 3216 InFlag = Chain.getValue(1); 3217 3218 // Handle result values, copying them out of physregs into vregs that we 3219 // return. 3220 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3221 InVals, IsThisReturn, 3222 IsThisReturn ? OutVals[0] : SDValue()); 3223 } 3224 3225 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3226 // except for applying the wave size scale to the increment amount. 3227 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3228 SDValue Op, SelectionDAG &DAG) const { 3229 const MachineFunction &MF = DAG.getMachineFunction(); 3230 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3231 3232 SDLoc dl(Op); 3233 EVT VT = Op.getValueType(); 3234 SDValue Tmp1 = Op; 3235 SDValue Tmp2 = Op.getValue(1); 3236 SDValue Tmp3 = Op.getOperand(2); 3237 SDValue Chain = Tmp1.getOperand(0); 3238 3239 Register SPReg = Info->getStackPtrOffsetReg(); 3240 3241 // Chain the dynamic stack allocation so that it doesn't modify the stack 3242 // pointer when other instructions are using the stack. 3243 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3244 3245 SDValue Size = Tmp2.getOperand(1); 3246 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3247 Chain = SP.getValue(1); 3248 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3249 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3250 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3251 unsigned Opc = 3252 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3253 ISD::ADD : ISD::SUB; 3254 3255 SDValue ScaledSize = DAG.getNode( 3256 ISD::SHL, dl, VT, Size, 3257 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3258 3259 Align StackAlign = TFL->getStackAlign(); 3260 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3261 if (Alignment && *Alignment > StackAlign) { 3262 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3263 DAG.getConstant(-(uint64_t)Alignment->value() 3264 << ST.getWavefrontSizeLog2(), 3265 dl, VT)); 3266 } 3267 3268 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3269 Tmp2 = DAG.getCALLSEQ_END( 3270 Chain, DAG.getIntPtrConstant(0, dl, true), 3271 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3272 3273 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3274 } 3275 3276 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3277 SelectionDAG &DAG) const { 3278 // We only handle constant sizes here to allow non-entry block, static sized 3279 // allocas. A truly dynamic value is more difficult to support because we 3280 // don't know if the size value is uniform or not. If the size isn't uniform, 3281 // we would need to do a wave reduction to get the maximum size to know how 3282 // much to increment the uniform stack pointer. 3283 SDValue Size = Op.getOperand(1); 3284 if (isa<ConstantSDNode>(Size)) 3285 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3286 3287 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3288 } 3289 3290 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3291 const MachineFunction &MF) const { 3292 Register Reg = StringSwitch<Register>(RegName) 3293 .Case("m0", AMDGPU::M0) 3294 .Case("exec", AMDGPU::EXEC) 3295 .Case("exec_lo", AMDGPU::EXEC_LO) 3296 .Case("exec_hi", AMDGPU::EXEC_HI) 3297 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3298 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3299 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3300 .Default(Register()); 3301 3302 if (Reg == AMDGPU::NoRegister) { 3303 report_fatal_error(Twine("invalid register name \"" 3304 + StringRef(RegName) + "\".")); 3305 3306 } 3307 3308 if (!Subtarget->hasFlatScrRegister() && 3309 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3310 report_fatal_error(Twine("invalid register \"" 3311 + StringRef(RegName) + "\" for subtarget.")); 3312 } 3313 3314 switch (Reg) { 3315 case AMDGPU::M0: 3316 case AMDGPU::EXEC_LO: 3317 case AMDGPU::EXEC_HI: 3318 case AMDGPU::FLAT_SCR_LO: 3319 case AMDGPU::FLAT_SCR_HI: 3320 if (VT.getSizeInBits() == 32) 3321 return Reg; 3322 break; 3323 case AMDGPU::EXEC: 3324 case AMDGPU::FLAT_SCR: 3325 if (VT.getSizeInBits() == 64) 3326 return Reg; 3327 break; 3328 default: 3329 llvm_unreachable("missing register type checking"); 3330 } 3331 3332 report_fatal_error(Twine("invalid type for register \"" 3333 + StringRef(RegName) + "\".")); 3334 } 3335 3336 // If kill is not the last instruction, split the block so kill is always a 3337 // proper terminator. 3338 MachineBasicBlock * 3339 SITargetLowering::splitKillBlock(MachineInstr &MI, 3340 MachineBasicBlock *BB) const { 3341 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3342 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3343 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3344 return SplitBB; 3345 } 3346 3347 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3348 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3349 // be the first instruction in the remainder block. 3350 // 3351 /// \returns { LoopBody, Remainder } 3352 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3353 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3354 MachineFunction *MF = MBB.getParent(); 3355 MachineBasicBlock::iterator I(&MI); 3356 3357 // To insert the loop we need to split the block. Move everything after this 3358 // point to a new block, and insert a new empty block between the two. 3359 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3360 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3361 MachineFunction::iterator MBBI(MBB); 3362 ++MBBI; 3363 3364 MF->insert(MBBI, LoopBB); 3365 MF->insert(MBBI, RemainderBB); 3366 3367 LoopBB->addSuccessor(LoopBB); 3368 LoopBB->addSuccessor(RemainderBB); 3369 3370 // Move the rest of the block into a new block. 3371 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3372 3373 if (InstInLoop) { 3374 auto Next = std::next(I); 3375 3376 // Move instruction to loop body. 3377 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3378 3379 // Move the rest of the block. 3380 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3381 } else { 3382 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3383 } 3384 3385 MBB.addSuccessor(LoopBB); 3386 3387 return std::make_pair(LoopBB, RemainderBB); 3388 } 3389 3390 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3391 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3392 MachineBasicBlock *MBB = MI.getParent(); 3393 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3394 auto I = MI.getIterator(); 3395 auto E = std::next(I); 3396 3397 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3398 .addImm(0); 3399 3400 MIBundleBuilder Bundler(*MBB, I, E); 3401 finalizeBundle(*MBB, Bundler.begin()); 3402 } 3403 3404 MachineBasicBlock * 3405 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3406 MachineBasicBlock *BB) const { 3407 const DebugLoc &DL = MI.getDebugLoc(); 3408 3409 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3410 3411 MachineBasicBlock *LoopBB; 3412 MachineBasicBlock *RemainderBB; 3413 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3414 3415 // Apparently kill flags are only valid if the def is in the same block? 3416 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3417 Src->setIsKill(false); 3418 3419 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3420 3421 MachineBasicBlock::iterator I = LoopBB->end(); 3422 3423 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3424 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3425 3426 // Clear TRAP_STS.MEM_VIOL 3427 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3428 .addImm(0) 3429 .addImm(EncodedReg); 3430 3431 bundleInstWithWaitcnt(MI); 3432 3433 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3434 3435 // Load and check TRAP_STS.MEM_VIOL 3436 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3437 .addImm(EncodedReg); 3438 3439 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3440 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3441 .addReg(Reg, RegState::Kill) 3442 .addImm(0); 3443 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3444 .addMBB(LoopBB); 3445 3446 return RemainderBB; 3447 } 3448 3449 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3450 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3451 // will only do one iteration. In the worst case, this will loop 64 times. 3452 // 3453 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3454 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3455 const SIInstrInfo *TII, 3456 MachineRegisterInfo &MRI, 3457 MachineBasicBlock &OrigBB, 3458 MachineBasicBlock &LoopBB, 3459 const DebugLoc &DL, 3460 const MachineOperand &IdxReg, 3461 unsigned InitReg, 3462 unsigned ResultReg, 3463 unsigned PhiReg, 3464 unsigned InitSaveExecReg, 3465 int Offset, 3466 bool UseGPRIdxMode, 3467 bool IsIndirectSrc) { 3468 MachineFunction *MF = OrigBB.getParent(); 3469 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3470 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3471 MachineBasicBlock::iterator I = LoopBB.begin(); 3472 3473 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3474 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3475 Register NewExec = MRI.createVirtualRegister(BoolRC); 3476 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3477 Register CondReg = MRI.createVirtualRegister(BoolRC); 3478 3479 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3480 .addReg(InitReg) 3481 .addMBB(&OrigBB) 3482 .addReg(ResultReg) 3483 .addMBB(&LoopBB); 3484 3485 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3486 .addReg(InitSaveExecReg) 3487 .addMBB(&OrigBB) 3488 .addReg(NewExec) 3489 .addMBB(&LoopBB); 3490 3491 // Read the next variant <- also loop target. 3492 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3493 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3494 3495 // Compare the just read M0 value to all possible Idx values. 3496 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3497 .addReg(CurrentIdxReg) 3498 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3499 3500 // Update EXEC, save the original EXEC value to VCC. 3501 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3502 : AMDGPU::S_AND_SAVEEXEC_B64), 3503 NewExec) 3504 .addReg(CondReg, RegState::Kill); 3505 3506 MRI.setSimpleHint(NewExec, CondReg); 3507 3508 if (UseGPRIdxMode) { 3509 unsigned IdxReg; 3510 if (Offset == 0) { 3511 IdxReg = CurrentIdxReg; 3512 } else { 3513 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3514 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3515 .addReg(CurrentIdxReg, RegState::Kill) 3516 .addImm(Offset); 3517 } 3518 unsigned IdxMode = IsIndirectSrc ? 3519 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3520 MachineInstr *SetOn = 3521 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3522 .addReg(IdxReg, RegState::Kill) 3523 .addImm(IdxMode); 3524 SetOn->getOperand(3).setIsUndef(); 3525 } else { 3526 // Move index from VCC into M0 3527 if (Offset == 0) { 3528 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3529 .addReg(CurrentIdxReg, RegState::Kill); 3530 } else { 3531 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3532 .addReg(CurrentIdxReg, RegState::Kill) 3533 .addImm(Offset); 3534 } 3535 } 3536 3537 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3538 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3539 MachineInstr *InsertPt = 3540 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3541 : AMDGPU::S_XOR_B64_term), Exec) 3542 .addReg(Exec) 3543 .addReg(NewExec); 3544 3545 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3546 // s_cbranch_scc0? 3547 3548 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3549 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3550 .addMBB(&LoopBB); 3551 3552 return InsertPt->getIterator(); 3553 } 3554 3555 // This has slightly sub-optimal regalloc when the source vector is killed by 3556 // the read. The register allocator does not understand that the kill is 3557 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3558 // subregister from it, using 1 more VGPR than necessary. This was saved when 3559 // this was expanded after register allocation. 3560 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3561 MachineBasicBlock &MBB, 3562 MachineInstr &MI, 3563 unsigned InitResultReg, 3564 unsigned PhiReg, 3565 int Offset, 3566 bool UseGPRIdxMode, 3567 bool IsIndirectSrc) { 3568 MachineFunction *MF = MBB.getParent(); 3569 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3570 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3571 MachineRegisterInfo &MRI = MF->getRegInfo(); 3572 const DebugLoc &DL = MI.getDebugLoc(); 3573 MachineBasicBlock::iterator I(&MI); 3574 3575 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3576 Register DstReg = MI.getOperand(0).getReg(); 3577 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3578 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3579 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3580 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3581 3582 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3583 3584 // Save the EXEC mask 3585 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3586 .addReg(Exec); 3587 3588 MachineBasicBlock *LoopBB; 3589 MachineBasicBlock *RemainderBB; 3590 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3591 3592 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3593 3594 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3595 InitResultReg, DstReg, PhiReg, TmpExec, 3596 Offset, UseGPRIdxMode, IsIndirectSrc); 3597 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3598 MachineFunction::iterator MBBI(LoopBB); 3599 ++MBBI; 3600 MF->insert(MBBI, LandingPad); 3601 LoopBB->removeSuccessor(RemainderBB); 3602 LandingPad->addSuccessor(RemainderBB); 3603 LoopBB->addSuccessor(LandingPad); 3604 MachineBasicBlock::iterator First = LandingPad->begin(); 3605 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3606 .addReg(SaveExec); 3607 3608 return InsPt; 3609 } 3610 3611 // Returns subreg index, offset 3612 static std::pair<unsigned, int> 3613 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3614 const TargetRegisterClass *SuperRC, 3615 unsigned VecReg, 3616 int Offset) { 3617 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3618 3619 // Skip out of bounds offsets, or else we would end up using an undefined 3620 // register. 3621 if (Offset >= NumElts || Offset < 0) 3622 return std::make_pair(AMDGPU::sub0, Offset); 3623 3624 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3625 } 3626 3627 // Return true if the index is an SGPR and was set. 3628 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3629 MachineRegisterInfo &MRI, 3630 MachineInstr &MI, 3631 int Offset, 3632 bool UseGPRIdxMode, 3633 bool IsIndirectSrc) { 3634 MachineBasicBlock *MBB = MI.getParent(); 3635 const DebugLoc &DL = MI.getDebugLoc(); 3636 MachineBasicBlock::iterator I(&MI); 3637 3638 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3639 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3640 3641 assert(Idx->getReg() != AMDGPU::NoRegister); 3642 3643 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3644 return false; 3645 3646 if (UseGPRIdxMode) { 3647 unsigned IdxMode = IsIndirectSrc ? 3648 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3649 if (Offset == 0) { 3650 MachineInstr *SetOn = 3651 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3652 .add(*Idx) 3653 .addImm(IdxMode); 3654 3655 SetOn->getOperand(3).setIsUndef(); 3656 } else { 3657 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3658 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3659 .add(*Idx) 3660 .addImm(Offset); 3661 MachineInstr *SetOn = 3662 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3663 .addReg(Tmp, RegState::Kill) 3664 .addImm(IdxMode); 3665 3666 SetOn->getOperand(3).setIsUndef(); 3667 } 3668 3669 return true; 3670 } 3671 3672 if (Offset == 0) { 3673 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3674 .add(*Idx); 3675 } else { 3676 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3677 .add(*Idx) 3678 .addImm(Offset); 3679 } 3680 3681 return true; 3682 } 3683 3684 // Control flow needs to be inserted if indexing with a VGPR. 3685 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3686 MachineBasicBlock &MBB, 3687 const GCNSubtarget &ST) { 3688 const SIInstrInfo *TII = ST.getInstrInfo(); 3689 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3690 MachineFunction *MF = MBB.getParent(); 3691 MachineRegisterInfo &MRI = MF->getRegInfo(); 3692 3693 Register Dst = MI.getOperand(0).getReg(); 3694 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3695 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3696 3697 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3698 3699 unsigned SubReg; 3700 std::tie(SubReg, Offset) 3701 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3702 3703 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3704 3705 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3706 MachineBasicBlock::iterator I(&MI); 3707 const DebugLoc &DL = MI.getDebugLoc(); 3708 3709 if (UseGPRIdxMode) { 3710 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3711 // to avoid interfering with other uses, so probably requires a new 3712 // optimization pass. 3713 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3714 .addReg(SrcReg, 0, SubReg) 3715 .addReg(SrcReg, RegState::Implicit) 3716 .addReg(AMDGPU::M0, RegState::Implicit); 3717 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3718 } else { 3719 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3720 .addReg(SrcReg, 0, SubReg) 3721 .addReg(SrcReg, RegState::Implicit); 3722 } 3723 3724 MI.eraseFromParent(); 3725 3726 return &MBB; 3727 } 3728 3729 const DebugLoc &DL = MI.getDebugLoc(); 3730 MachineBasicBlock::iterator I(&MI); 3731 3732 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3733 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3734 3735 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3736 3737 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3738 Offset, UseGPRIdxMode, true); 3739 MachineBasicBlock *LoopBB = InsPt->getParent(); 3740 3741 if (UseGPRIdxMode) { 3742 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3743 .addReg(SrcReg, 0, SubReg) 3744 .addReg(SrcReg, RegState::Implicit) 3745 .addReg(AMDGPU::M0, RegState::Implicit); 3746 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3747 } else { 3748 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3749 .addReg(SrcReg, 0, SubReg) 3750 .addReg(SrcReg, RegState::Implicit); 3751 } 3752 3753 MI.eraseFromParent(); 3754 3755 return LoopBB; 3756 } 3757 3758 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3759 MachineBasicBlock &MBB, 3760 const GCNSubtarget &ST) { 3761 const SIInstrInfo *TII = ST.getInstrInfo(); 3762 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3763 MachineFunction *MF = MBB.getParent(); 3764 MachineRegisterInfo &MRI = MF->getRegInfo(); 3765 3766 Register Dst = MI.getOperand(0).getReg(); 3767 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3768 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3769 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3770 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3771 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3772 3773 // This can be an immediate, but will be folded later. 3774 assert(Val->getReg()); 3775 3776 unsigned SubReg; 3777 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3778 SrcVec->getReg(), 3779 Offset); 3780 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3781 3782 if (Idx->getReg() == AMDGPU::NoRegister) { 3783 MachineBasicBlock::iterator I(&MI); 3784 const DebugLoc &DL = MI.getDebugLoc(); 3785 3786 assert(Offset == 0); 3787 3788 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3789 .add(*SrcVec) 3790 .add(*Val) 3791 .addImm(SubReg); 3792 3793 MI.eraseFromParent(); 3794 return &MBB; 3795 } 3796 3797 const MCInstrDesc &MovRelDesc 3798 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3799 3800 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3801 MachineBasicBlock::iterator I(&MI); 3802 const DebugLoc &DL = MI.getDebugLoc(); 3803 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3804 .addReg(SrcVec->getReg()) 3805 .add(*Val) 3806 .addImm(SubReg); 3807 if (UseGPRIdxMode) 3808 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3809 3810 MI.eraseFromParent(); 3811 return &MBB; 3812 } 3813 3814 if (Val->isReg()) 3815 MRI.clearKillFlags(Val->getReg()); 3816 3817 const DebugLoc &DL = MI.getDebugLoc(); 3818 3819 Register PhiReg = MRI.createVirtualRegister(VecRC); 3820 3821 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3822 Offset, UseGPRIdxMode, false); 3823 MachineBasicBlock *LoopBB = InsPt->getParent(); 3824 3825 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3826 .addReg(PhiReg) 3827 .add(*Val) 3828 .addImm(AMDGPU::sub0); 3829 if (UseGPRIdxMode) 3830 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3831 3832 MI.eraseFromParent(); 3833 return LoopBB; 3834 } 3835 3836 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3837 MachineInstr &MI, MachineBasicBlock *BB) const { 3838 3839 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3840 MachineFunction *MF = BB->getParent(); 3841 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3842 3843 switch (MI.getOpcode()) { 3844 case AMDGPU::S_UADDO_PSEUDO: 3845 case AMDGPU::S_USUBO_PSEUDO: { 3846 const DebugLoc &DL = MI.getDebugLoc(); 3847 MachineOperand &Dest0 = MI.getOperand(0); 3848 MachineOperand &Dest1 = MI.getOperand(1); 3849 MachineOperand &Src0 = MI.getOperand(2); 3850 MachineOperand &Src1 = MI.getOperand(3); 3851 3852 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3853 ? AMDGPU::S_ADD_I32 3854 : AMDGPU::S_SUB_I32; 3855 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3856 3857 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3858 .addImm(1) 3859 .addImm(0); 3860 3861 MI.eraseFromParent(); 3862 return BB; 3863 } 3864 case AMDGPU::S_ADD_U64_PSEUDO: 3865 case AMDGPU::S_SUB_U64_PSEUDO: { 3866 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3867 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3868 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3869 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3870 const DebugLoc &DL = MI.getDebugLoc(); 3871 3872 MachineOperand &Dest = MI.getOperand(0); 3873 MachineOperand &Src0 = MI.getOperand(1); 3874 MachineOperand &Src1 = MI.getOperand(2); 3875 3876 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3877 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3878 3879 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3880 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3881 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3882 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3883 3884 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3885 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3886 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3887 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3888 3889 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3890 3891 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3892 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3893 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3894 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3895 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3896 .addReg(DestSub0) 3897 .addImm(AMDGPU::sub0) 3898 .addReg(DestSub1) 3899 .addImm(AMDGPU::sub1); 3900 MI.eraseFromParent(); 3901 return BB; 3902 } 3903 case AMDGPU::V_ADD_U64_PSEUDO: 3904 case AMDGPU::V_SUB_U64_PSEUDO: { 3905 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3906 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3907 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3908 const DebugLoc &DL = MI.getDebugLoc(); 3909 3910 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3911 3912 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3913 3914 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3915 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3916 3917 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3918 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3919 3920 MachineOperand &Dest = MI.getOperand(0); 3921 MachineOperand &Src0 = MI.getOperand(1); 3922 MachineOperand &Src1 = MI.getOperand(2); 3923 3924 const TargetRegisterClass *Src0RC = Src0.isReg() 3925 ? MRI.getRegClass(Src0.getReg()) 3926 : &AMDGPU::VReg_64RegClass; 3927 const TargetRegisterClass *Src1RC = Src1.isReg() 3928 ? MRI.getRegClass(Src1.getReg()) 3929 : &AMDGPU::VReg_64RegClass; 3930 3931 const TargetRegisterClass *Src0SubRC = 3932 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3933 const TargetRegisterClass *Src1SubRC = 3934 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3935 3936 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3937 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3938 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3939 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3940 3941 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3942 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3943 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3944 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3945 3946 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3947 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3948 .addReg(CarryReg, RegState::Define) 3949 .add(SrcReg0Sub0) 3950 .add(SrcReg1Sub0) 3951 .addImm(0); // clamp bit 3952 3953 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3954 MachineInstr *HiHalf = 3955 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3956 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3957 .add(SrcReg0Sub1) 3958 .add(SrcReg1Sub1) 3959 .addReg(CarryReg, RegState::Kill) 3960 .addImm(0); // clamp bit 3961 3962 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3963 .addReg(DestSub0) 3964 .addImm(AMDGPU::sub0) 3965 .addReg(DestSub1) 3966 .addImm(AMDGPU::sub1); 3967 TII->legalizeOperands(*LoHalf); 3968 TII->legalizeOperands(*HiHalf); 3969 MI.eraseFromParent(); 3970 return BB; 3971 } 3972 case AMDGPU::S_ADD_CO_PSEUDO: 3973 case AMDGPU::S_SUB_CO_PSEUDO: { 3974 // This pseudo has a chance to be selected 3975 // only from uniform add/subcarry node. All the VGPR operands 3976 // therefore assumed to be splat vectors. 3977 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3978 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3979 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3980 MachineBasicBlock::iterator MII = MI; 3981 const DebugLoc &DL = MI.getDebugLoc(); 3982 MachineOperand &Dest = MI.getOperand(0); 3983 MachineOperand &CarryDest = MI.getOperand(1); 3984 MachineOperand &Src0 = MI.getOperand(2); 3985 MachineOperand &Src1 = MI.getOperand(3); 3986 MachineOperand &Src2 = MI.getOperand(4); 3987 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3988 ? AMDGPU::S_ADDC_U32 3989 : AMDGPU::S_SUBB_U32; 3990 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3991 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3992 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3993 .addReg(Src0.getReg()); 3994 Src0.setReg(RegOp0); 3995 } 3996 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3997 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3998 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3999 .addReg(Src1.getReg()); 4000 Src1.setReg(RegOp1); 4001 } 4002 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4003 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4004 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4005 .addReg(Src2.getReg()); 4006 Src2.setReg(RegOp2); 4007 } 4008 4009 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 4010 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4011 .addReg(Src2.getReg()) 4012 .addImm(0); 4013 } else { 4014 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4015 .addReg(Src2.getReg()) 4016 .addImm(0); 4017 } 4018 4019 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4020 4021 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4022 .addReg(AMDGPU::SCC); 4023 MI.eraseFromParent(); 4024 return BB; 4025 } 4026 case AMDGPU::SI_INIT_M0: { 4027 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4028 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4029 .add(MI.getOperand(0)); 4030 MI.eraseFromParent(); 4031 return BB; 4032 } 4033 case AMDGPU::SI_INIT_EXEC: 4034 // This should be before all vector instructions. 4035 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4036 AMDGPU::EXEC) 4037 .addImm(MI.getOperand(0).getImm()); 4038 MI.eraseFromParent(); 4039 return BB; 4040 4041 case AMDGPU::SI_INIT_EXEC_LO: 4042 // This should be before all vector instructions. 4043 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4044 AMDGPU::EXEC_LO) 4045 .addImm(MI.getOperand(0).getImm()); 4046 MI.eraseFromParent(); 4047 return BB; 4048 4049 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4050 // Extract the thread count from an SGPR input and set EXEC accordingly. 4051 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4052 // 4053 // S_BFE_U32 count, input, {shift, 7} 4054 // S_BFM_B64 exec, count, 0 4055 // S_CMP_EQ_U32 count, 64 4056 // S_CMOV_B64 exec, -1 4057 MachineInstr *FirstMI = &*BB->begin(); 4058 MachineRegisterInfo &MRI = MF->getRegInfo(); 4059 Register InputReg = MI.getOperand(0).getReg(); 4060 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4061 bool Found = false; 4062 4063 // Move the COPY of the input reg to the beginning, so that we can use it. 4064 for (auto I = BB->begin(); I != &MI; I++) { 4065 if (I->getOpcode() != TargetOpcode::COPY || 4066 I->getOperand(0).getReg() != InputReg) 4067 continue; 4068 4069 if (I == FirstMI) { 4070 FirstMI = &*++BB->begin(); 4071 } else { 4072 I->removeFromParent(); 4073 BB->insert(FirstMI, &*I); 4074 } 4075 Found = true; 4076 break; 4077 } 4078 assert(Found); 4079 (void)Found; 4080 4081 // This should be before all vector instructions. 4082 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4083 bool isWave32 = getSubtarget()->isWave32(); 4084 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4085 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4086 .addReg(InputReg) 4087 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4088 BuildMI(*BB, FirstMI, DebugLoc(), 4089 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4090 Exec) 4091 .addReg(CountReg) 4092 .addImm(0); 4093 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4094 .addReg(CountReg, RegState::Kill) 4095 .addImm(getSubtarget()->getWavefrontSize()); 4096 BuildMI(*BB, FirstMI, DebugLoc(), 4097 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4098 Exec) 4099 .addImm(-1); 4100 MI.eraseFromParent(); 4101 return BB; 4102 } 4103 4104 case AMDGPU::GET_GROUPSTATICSIZE: { 4105 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4106 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4107 DebugLoc DL = MI.getDebugLoc(); 4108 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4109 .add(MI.getOperand(0)) 4110 .addImm(MFI->getLDSSize()); 4111 MI.eraseFromParent(); 4112 return BB; 4113 } 4114 case AMDGPU::SI_INDIRECT_SRC_V1: 4115 case AMDGPU::SI_INDIRECT_SRC_V2: 4116 case AMDGPU::SI_INDIRECT_SRC_V4: 4117 case AMDGPU::SI_INDIRECT_SRC_V8: 4118 case AMDGPU::SI_INDIRECT_SRC_V16: 4119 case AMDGPU::SI_INDIRECT_SRC_V32: 4120 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4121 case AMDGPU::SI_INDIRECT_DST_V1: 4122 case AMDGPU::SI_INDIRECT_DST_V2: 4123 case AMDGPU::SI_INDIRECT_DST_V4: 4124 case AMDGPU::SI_INDIRECT_DST_V8: 4125 case AMDGPU::SI_INDIRECT_DST_V16: 4126 case AMDGPU::SI_INDIRECT_DST_V32: 4127 return emitIndirectDst(MI, *BB, *getSubtarget()); 4128 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4129 case AMDGPU::SI_KILL_I1_PSEUDO: 4130 return splitKillBlock(MI, BB); 4131 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4132 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4133 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4134 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4135 4136 Register Dst = MI.getOperand(0).getReg(); 4137 Register Src0 = MI.getOperand(1).getReg(); 4138 Register Src1 = MI.getOperand(2).getReg(); 4139 const DebugLoc &DL = MI.getDebugLoc(); 4140 Register SrcCond = MI.getOperand(3).getReg(); 4141 4142 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4143 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4144 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4145 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4146 4147 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4148 .addReg(SrcCond); 4149 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4150 .addImm(0) 4151 .addReg(Src0, 0, AMDGPU::sub0) 4152 .addImm(0) 4153 .addReg(Src1, 0, AMDGPU::sub0) 4154 .addReg(SrcCondCopy); 4155 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4156 .addImm(0) 4157 .addReg(Src0, 0, AMDGPU::sub1) 4158 .addImm(0) 4159 .addReg(Src1, 0, AMDGPU::sub1) 4160 .addReg(SrcCondCopy); 4161 4162 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4163 .addReg(DstLo) 4164 .addImm(AMDGPU::sub0) 4165 .addReg(DstHi) 4166 .addImm(AMDGPU::sub1); 4167 MI.eraseFromParent(); 4168 return BB; 4169 } 4170 case AMDGPU::SI_BR_UNDEF: { 4171 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4172 const DebugLoc &DL = MI.getDebugLoc(); 4173 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4174 .add(MI.getOperand(0)); 4175 Br->getOperand(1).setIsUndef(true); // read undef SCC 4176 MI.eraseFromParent(); 4177 return BB; 4178 } 4179 case AMDGPU::ADJCALLSTACKUP: 4180 case AMDGPU::ADJCALLSTACKDOWN: { 4181 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4182 MachineInstrBuilder MIB(*MF, &MI); 4183 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4184 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4185 return BB; 4186 } 4187 case AMDGPU::SI_CALL_ISEL: { 4188 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4189 const DebugLoc &DL = MI.getDebugLoc(); 4190 4191 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4192 4193 MachineInstrBuilder MIB; 4194 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4195 4196 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4197 MIB.add(MI.getOperand(I)); 4198 4199 MIB.cloneMemRefs(MI); 4200 MI.eraseFromParent(); 4201 return BB; 4202 } 4203 case AMDGPU::V_ADD_CO_U32_e32: 4204 case AMDGPU::V_SUB_CO_U32_e32: 4205 case AMDGPU::V_SUBREV_CO_U32_e32: { 4206 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4207 const DebugLoc &DL = MI.getDebugLoc(); 4208 unsigned Opc = MI.getOpcode(); 4209 4210 bool NeedClampOperand = false; 4211 if (TII->pseudoToMCOpcode(Opc) == -1) { 4212 Opc = AMDGPU::getVOPe64(Opc); 4213 NeedClampOperand = true; 4214 } 4215 4216 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4217 if (TII->isVOP3(*I)) { 4218 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4219 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4220 I.addReg(TRI->getVCC(), RegState::Define); 4221 } 4222 I.add(MI.getOperand(1)) 4223 .add(MI.getOperand(2)); 4224 if (NeedClampOperand) 4225 I.addImm(0); // clamp bit for e64 encoding 4226 4227 TII->legalizeOperands(*I); 4228 4229 MI.eraseFromParent(); 4230 return BB; 4231 } 4232 case AMDGPU::DS_GWS_INIT: 4233 case AMDGPU::DS_GWS_SEMA_V: 4234 case AMDGPU::DS_GWS_SEMA_BR: 4235 case AMDGPU::DS_GWS_SEMA_P: 4236 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4237 case AMDGPU::DS_GWS_BARRIER: 4238 // A s_waitcnt 0 is required to be the instruction immediately following. 4239 if (getSubtarget()->hasGWSAutoReplay()) { 4240 bundleInstWithWaitcnt(MI); 4241 return BB; 4242 } 4243 4244 return emitGWSMemViolTestLoop(MI, BB); 4245 case AMDGPU::S_SETREG_B32: { 4246 // Try to optimize cases that only set the denormal mode or rounding mode. 4247 // 4248 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4249 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4250 // instead. 4251 // 4252 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4253 // allow you to have a no side effect instruction in the output of a 4254 // sideeffecting pattern. 4255 unsigned ID, Offset, Width; 4256 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4257 if (ID != AMDGPU::Hwreg::ID_MODE) 4258 return BB; 4259 4260 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4261 const unsigned SetMask = WidthMask << Offset; 4262 4263 if (getSubtarget()->hasDenormModeInst()) { 4264 unsigned SetDenormOp = 0; 4265 unsigned SetRoundOp = 0; 4266 4267 // The dedicated instructions can only set the whole denorm or round mode 4268 // at once, not a subset of bits in either. 4269 if (SetMask == 4270 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4271 // If this fully sets both the round and denorm mode, emit the two 4272 // dedicated instructions for these. 4273 SetRoundOp = AMDGPU::S_ROUND_MODE; 4274 SetDenormOp = AMDGPU::S_DENORM_MODE; 4275 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4276 SetRoundOp = AMDGPU::S_ROUND_MODE; 4277 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4278 SetDenormOp = AMDGPU::S_DENORM_MODE; 4279 } 4280 4281 if (SetRoundOp || SetDenormOp) { 4282 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4283 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4284 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4285 unsigned ImmVal = Def->getOperand(1).getImm(); 4286 if (SetRoundOp) { 4287 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4288 .addImm(ImmVal & 0xf); 4289 4290 // If we also have the denorm mode, get just the denorm mode bits. 4291 ImmVal >>= 4; 4292 } 4293 4294 if (SetDenormOp) { 4295 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4296 .addImm(ImmVal & 0xf); 4297 } 4298 4299 MI.eraseFromParent(); 4300 return BB; 4301 } 4302 } 4303 } 4304 4305 // If only FP bits are touched, used the no side effects pseudo. 4306 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4307 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4308 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4309 4310 return BB; 4311 } 4312 default: 4313 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4314 } 4315 } 4316 4317 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4318 return isTypeLegal(VT.getScalarType()); 4319 } 4320 4321 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4322 // This currently forces unfolding various combinations of fsub into fma with 4323 // free fneg'd operands. As long as we have fast FMA (controlled by 4324 // isFMAFasterThanFMulAndFAdd), we should perform these. 4325 4326 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4327 // most of these combines appear to be cycle neutral but save on instruction 4328 // count / code size. 4329 return true; 4330 } 4331 4332 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4333 EVT VT) const { 4334 if (!VT.isVector()) { 4335 return MVT::i1; 4336 } 4337 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4338 } 4339 4340 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4341 // TODO: Should i16 be used always if legal? For now it would force VALU 4342 // shifts. 4343 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4344 } 4345 4346 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4347 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4348 ? Ty.changeElementSize(16) 4349 : Ty.changeElementSize(32); 4350 } 4351 4352 // Answering this is somewhat tricky and depends on the specific device which 4353 // have different rates for fma or all f64 operations. 4354 // 4355 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4356 // regardless of which device (although the number of cycles differs between 4357 // devices), so it is always profitable for f64. 4358 // 4359 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4360 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4361 // which we can always do even without fused FP ops since it returns the same 4362 // result as the separate operations and since it is always full 4363 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4364 // however does not support denormals, so we do report fma as faster if we have 4365 // a fast fma device and require denormals. 4366 // 4367 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4368 EVT VT) const { 4369 VT = VT.getScalarType(); 4370 4371 switch (VT.getSimpleVT().SimpleTy) { 4372 case MVT::f32: { 4373 // If mad is not available this depends only on if f32 fma is full rate. 4374 if (!Subtarget->hasMadMacF32Insts()) 4375 return Subtarget->hasFastFMAF32(); 4376 4377 // Otherwise f32 mad is always full rate and returns the same result as 4378 // the separate operations so should be preferred over fma. 4379 // However does not support denomals. 4380 if (hasFP32Denormals(MF)) 4381 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4382 4383 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4384 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4385 } 4386 case MVT::f64: 4387 return true; 4388 case MVT::f16: 4389 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4390 default: 4391 break; 4392 } 4393 4394 return false; 4395 } 4396 4397 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4398 const SDNode *N) const { 4399 // TODO: Check future ftz flag 4400 // v_mad_f32/v_mac_f32 do not support denormals. 4401 EVT VT = N->getValueType(0); 4402 if (VT == MVT::f32) 4403 return Subtarget->hasMadMacF32Insts() && 4404 !hasFP32Denormals(DAG.getMachineFunction()); 4405 if (VT == MVT::f16) { 4406 return Subtarget->hasMadF16() && 4407 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4408 } 4409 4410 return false; 4411 } 4412 4413 //===----------------------------------------------------------------------===// 4414 // Custom DAG Lowering Operations 4415 //===----------------------------------------------------------------------===// 4416 4417 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4418 // wider vector type is legal. 4419 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4420 SelectionDAG &DAG) const { 4421 unsigned Opc = Op.getOpcode(); 4422 EVT VT = Op.getValueType(); 4423 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4424 4425 SDValue Lo, Hi; 4426 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4427 4428 SDLoc SL(Op); 4429 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4430 Op->getFlags()); 4431 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4432 Op->getFlags()); 4433 4434 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4435 } 4436 4437 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4438 // wider vector type is legal. 4439 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4440 SelectionDAG &DAG) const { 4441 unsigned Opc = Op.getOpcode(); 4442 EVT VT = Op.getValueType(); 4443 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4444 4445 SDValue Lo0, Hi0; 4446 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4447 SDValue Lo1, Hi1; 4448 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4449 4450 SDLoc SL(Op); 4451 4452 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4453 Op->getFlags()); 4454 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4455 Op->getFlags()); 4456 4457 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4458 } 4459 4460 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4461 SelectionDAG &DAG) const { 4462 unsigned Opc = Op.getOpcode(); 4463 EVT VT = Op.getValueType(); 4464 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4465 4466 SDValue Lo0, Hi0; 4467 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4468 SDValue Lo1, Hi1; 4469 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4470 SDValue Lo2, Hi2; 4471 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4472 4473 SDLoc SL(Op); 4474 4475 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4476 Op->getFlags()); 4477 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4478 Op->getFlags()); 4479 4480 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4481 } 4482 4483 4484 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4485 switch (Op.getOpcode()) { 4486 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4487 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4488 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4489 case ISD::LOAD: { 4490 SDValue Result = LowerLOAD(Op, DAG); 4491 assert((!Result.getNode() || 4492 Result.getNode()->getNumValues() == 2) && 4493 "Load should return a value and a chain"); 4494 return Result; 4495 } 4496 4497 case ISD::FSIN: 4498 case ISD::FCOS: 4499 return LowerTrig(Op, DAG); 4500 case ISD::SELECT: return LowerSELECT(Op, DAG); 4501 case ISD::FDIV: return LowerFDIV(Op, DAG); 4502 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4503 case ISD::STORE: return LowerSTORE(Op, DAG); 4504 case ISD::GlobalAddress: { 4505 MachineFunction &MF = DAG.getMachineFunction(); 4506 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4507 return LowerGlobalAddress(MFI, Op, DAG); 4508 } 4509 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4510 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4511 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4512 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4513 case ISD::INSERT_SUBVECTOR: 4514 return lowerINSERT_SUBVECTOR(Op, DAG); 4515 case ISD::INSERT_VECTOR_ELT: 4516 return lowerINSERT_VECTOR_ELT(Op, DAG); 4517 case ISD::EXTRACT_VECTOR_ELT: 4518 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4519 case ISD::VECTOR_SHUFFLE: 4520 return lowerVECTOR_SHUFFLE(Op, DAG); 4521 case ISD::BUILD_VECTOR: 4522 return lowerBUILD_VECTOR(Op, DAG); 4523 case ISD::FP_ROUND: 4524 return lowerFP_ROUND(Op, DAG); 4525 case ISD::TRAP: 4526 return lowerTRAP(Op, DAG); 4527 case ISD::DEBUGTRAP: 4528 return lowerDEBUGTRAP(Op, DAG); 4529 case ISD::FABS: 4530 case ISD::FNEG: 4531 case ISD::FCANONICALIZE: 4532 case ISD::BSWAP: 4533 return splitUnaryVectorOp(Op, DAG); 4534 case ISD::FMINNUM: 4535 case ISD::FMAXNUM: 4536 return lowerFMINNUM_FMAXNUM(Op, DAG); 4537 case ISD::FMA: 4538 return splitTernaryVectorOp(Op, DAG); 4539 case ISD::SHL: 4540 case ISD::SRA: 4541 case ISD::SRL: 4542 case ISD::ADD: 4543 case ISD::SUB: 4544 case ISD::MUL: 4545 case ISD::SMIN: 4546 case ISD::SMAX: 4547 case ISD::UMIN: 4548 case ISD::UMAX: 4549 case ISD::FADD: 4550 case ISD::FMUL: 4551 case ISD::FMINNUM_IEEE: 4552 case ISD::FMAXNUM_IEEE: 4553 case ISD::UADDSAT: 4554 case ISD::USUBSAT: 4555 case ISD::SADDSAT: 4556 case ISD::SSUBSAT: 4557 return splitBinaryVectorOp(Op, DAG); 4558 case ISD::SMULO: 4559 case ISD::UMULO: 4560 return lowerXMULO(Op, DAG); 4561 case ISD::DYNAMIC_STACKALLOC: 4562 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4563 } 4564 return SDValue(); 4565 } 4566 4567 // Used for D16: Casts the result of an instruction into the right vector, 4568 // packs values if loads return unpacked values. 4569 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4570 const SDLoc &DL, 4571 SelectionDAG &DAG, bool Unpacked) { 4572 if (!LoadVT.isVector()) 4573 return Result; 4574 4575 // Cast back to the original packed type or to a larger type that is a 4576 // multiple of 32 bit for D16. Widening the return type is a required for 4577 // legalization. 4578 EVT FittingLoadVT = LoadVT; 4579 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4580 FittingLoadVT = 4581 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4582 LoadVT.getVectorNumElements() + 1); 4583 } 4584 4585 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4586 // Truncate to v2i16/v4i16. 4587 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4588 4589 // Workaround legalizer not scalarizing truncate after vector op 4590 // legalization but not creating intermediate vector trunc. 4591 SmallVector<SDValue, 4> Elts; 4592 DAG.ExtractVectorElements(Result, Elts); 4593 for (SDValue &Elt : Elts) 4594 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4595 4596 // Pad illegal v1i16/v3fi6 to v4i16 4597 if ((LoadVT.getVectorNumElements() % 2) == 1) 4598 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4599 4600 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4601 4602 // Bitcast to original type (v2f16/v4f16). 4603 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4604 } 4605 4606 // Cast back to the original packed type. 4607 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4608 } 4609 4610 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4611 MemSDNode *M, 4612 SelectionDAG &DAG, 4613 ArrayRef<SDValue> Ops, 4614 bool IsIntrinsic) const { 4615 SDLoc DL(M); 4616 4617 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4618 EVT LoadVT = M->getValueType(0); 4619 4620 EVT EquivLoadVT = LoadVT; 4621 if (LoadVT.isVector()) { 4622 if (Unpacked) { 4623 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4624 LoadVT.getVectorNumElements()); 4625 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4626 // Widen v3f16 to legal type 4627 EquivLoadVT = 4628 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4629 LoadVT.getVectorNumElements() + 1); 4630 } 4631 } 4632 4633 // Change from v4f16/v2f16 to EquivLoadVT. 4634 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4635 4636 SDValue Load 4637 = DAG.getMemIntrinsicNode( 4638 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4639 VTList, Ops, M->getMemoryVT(), 4640 M->getMemOperand()); 4641 4642 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4643 4644 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4645 } 4646 4647 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4648 SelectionDAG &DAG, 4649 ArrayRef<SDValue> Ops) const { 4650 SDLoc DL(M); 4651 EVT LoadVT = M->getValueType(0); 4652 EVT EltType = LoadVT.getScalarType(); 4653 EVT IntVT = LoadVT.changeTypeToInteger(); 4654 4655 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4656 4657 unsigned Opc = 4658 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4659 4660 if (IsD16) { 4661 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4662 } 4663 4664 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4665 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4666 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4667 4668 if (isTypeLegal(LoadVT)) { 4669 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4670 M->getMemOperand(), DAG); 4671 } 4672 4673 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4674 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4675 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4676 M->getMemOperand(), DAG); 4677 return DAG.getMergeValues( 4678 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4679 DL); 4680 } 4681 4682 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4683 SDNode *N, SelectionDAG &DAG) { 4684 EVT VT = N->getValueType(0); 4685 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4686 unsigned CondCode = CD->getZExtValue(); 4687 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4688 return DAG.getUNDEF(VT); 4689 4690 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4691 4692 SDValue LHS = N->getOperand(1); 4693 SDValue RHS = N->getOperand(2); 4694 4695 SDLoc DL(N); 4696 4697 EVT CmpVT = LHS.getValueType(); 4698 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4699 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4700 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4701 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4702 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4703 } 4704 4705 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4706 4707 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4708 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4709 4710 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4711 DAG.getCondCode(CCOpcode)); 4712 if (VT.bitsEq(CCVT)) 4713 return SetCC; 4714 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4715 } 4716 4717 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4718 SDNode *N, SelectionDAG &DAG) { 4719 EVT VT = N->getValueType(0); 4720 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4721 4722 unsigned CondCode = CD->getZExtValue(); 4723 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4724 return DAG.getUNDEF(VT); 4725 4726 SDValue Src0 = N->getOperand(1); 4727 SDValue Src1 = N->getOperand(2); 4728 EVT CmpVT = Src0.getValueType(); 4729 SDLoc SL(N); 4730 4731 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4732 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4733 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4734 } 4735 4736 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4737 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4738 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4739 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4740 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4741 Src1, DAG.getCondCode(CCOpcode)); 4742 if (VT.bitsEq(CCVT)) 4743 return SetCC; 4744 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4745 } 4746 4747 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4748 SelectionDAG &DAG) { 4749 EVT VT = N->getValueType(0); 4750 SDValue Src = N->getOperand(1); 4751 SDLoc SL(N); 4752 4753 if (Src.getOpcode() == ISD::SETCC) { 4754 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4755 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4756 Src.getOperand(1), Src.getOperand(2)); 4757 } 4758 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4759 // (ballot 0) -> 0 4760 if (Arg->isNullValue()) 4761 return DAG.getConstant(0, SL, VT); 4762 4763 // (ballot 1) -> EXEC/EXEC_LO 4764 if (Arg->isOne()) { 4765 Register Exec; 4766 if (VT.getScalarSizeInBits() == 32) 4767 Exec = AMDGPU::EXEC_LO; 4768 else if (VT.getScalarSizeInBits() == 64) 4769 Exec = AMDGPU::EXEC; 4770 else 4771 return SDValue(); 4772 4773 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4774 } 4775 } 4776 4777 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4778 // ISD::SETNE) 4779 return DAG.getNode( 4780 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4781 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4782 } 4783 4784 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4785 SmallVectorImpl<SDValue> &Results, 4786 SelectionDAG &DAG) const { 4787 switch (N->getOpcode()) { 4788 case ISD::INSERT_VECTOR_ELT: { 4789 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4790 Results.push_back(Res); 4791 return; 4792 } 4793 case ISD::EXTRACT_VECTOR_ELT: { 4794 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4795 Results.push_back(Res); 4796 return; 4797 } 4798 case ISD::INTRINSIC_WO_CHAIN: { 4799 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4800 switch (IID) { 4801 case Intrinsic::amdgcn_cvt_pkrtz: { 4802 SDValue Src0 = N->getOperand(1); 4803 SDValue Src1 = N->getOperand(2); 4804 SDLoc SL(N); 4805 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4806 Src0, Src1); 4807 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4808 return; 4809 } 4810 case Intrinsic::amdgcn_cvt_pknorm_i16: 4811 case Intrinsic::amdgcn_cvt_pknorm_u16: 4812 case Intrinsic::amdgcn_cvt_pk_i16: 4813 case Intrinsic::amdgcn_cvt_pk_u16: { 4814 SDValue Src0 = N->getOperand(1); 4815 SDValue Src1 = N->getOperand(2); 4816 SDLoc SL(N); 4817 unsigned Opcode; 4818 4819 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4820 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4821 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4822 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4823 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4824 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4825 else 4826 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4827 4828 EVT VT = N->getValueType(0); 4829 if (isTypeLegal(VT)) 4830 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4831 else { 4832 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4833 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4834 } 4835 return; 4836 } 4837 } 4838 break; 4839 } 4840 case ISD::INTRINSIC_W_CHAIN: { 4841 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4842 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4843 // FIXME: Hacky 4844 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4845 Results.push_back(Res.getOperand(I)); 4846 } 4847 } else { 4848 Results.push_back(Res); 4849 Results.push_back(Res.getValue(1)); 4850 } 4851 return; 4852 } 4853 4854 break; 4855 } 4856 case ISD::SELECT: { 4857 SDLoc SL(N); 4858 EVT VT = N->getValueType(0); 4859 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4860 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4861 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4862 4863 EVT SelectVT = NewVT; 4864 if (NewVT.bitsLT(MVT::i32)) { 4865 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4866 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4867 SelectVT = MVT::i32; 4868 } 4869 4870 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4871 N->getOperand(0), LHS, RHS); 4872 4873 if (NewVT != SelectVT) 4874 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4875 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4876 return; 4877 } 4878 case ISD::FNEG: { 4879 if (N->getValueType(0) != MVT::v2f16) 4880 break; 4881 4882 SDLoc SL(N); 4883 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4884 4885 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4886 BC, 4887 DAG.getConstant(0x80008000, SL, MVT::i32)); 4888 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4889 return; 4890 } 4891 case ISD::FABS: { 4892 if (N->getValueType(0) != MVT::v2f16) 4893 break; 4894 4895 SDLoc SL(N); 4896 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4897 4898 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4899 BC, 4900 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4901 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4902 return; 4903 } 4904 default: 4905 break; 4906 } 4907 } 4908 4909 /// Helper function for LowerBRCOND 4910 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4911 4912 SDNode *Parent = Value.getNode(); 4913 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4914 I != E; ++I) { 4915 4916 if (I.getUse().get() != Value) 4917 continue; 4918 4919 if (I->getOpcode() == Opcode) 4920 return *I; 4921 } 4922 return nullptr; 4923 } 4924 4925 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4926 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4927 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4928 case Intrinsic::amdgcn_if: 4929 return AMDGPUISD::IF; 4930 case Intrinsic::amdgcn_else: 4931 return AMDGPUISD::ELSE; 4932 case Intrinsic::amdgcn_loop: 4933 return AMDGPUISD::LOOP; 4934 case Intrinsic::amdgcn_end_cf: 4935 llvm_unreachable("should not occur"); 4936 default: 4937 return 0; 4938 } 4939 } 4940 4941 // break, if_break, else_break are all only used as inputs to loop, not 4942 // directly as branch conditions. 4943 return 0; 4944 } 4945 4946 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4947 const Triple &TT = getTargetMachine().getTargetTriple(); 4948 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4949 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4950 AMDGPU::shouldEmitConstantsToTextSection(TT); 4951 } 4952 4953 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4954 // FIXME: Either avoid relying on address space here or change the default 4955 // address space for functions to avoid the explicit check. 4956 return (GV->getValueType()->isFunctionTy() || 4957 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4958 !shouldEmitFixup(GV) && 4959 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4960 } 4961 4962 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4963 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4964 } 4965 4966 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4967 if (!GV->hasExternalLinkage()) 4968 return true; 4969 4970 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4971 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4972 } 4973 4974 /// This transforms the control flow intrinsics to get the branch destination as 4975 /// last parameter, also switches branch target with BR if the need arise 4976 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4977 SelectionDAG &DAG) const { 4978 SDLoc DL(BRCOND); 4979 4980 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4981 SDValue Target = BRCOND.getOperand(2); 4982 SDNode *BR = nullptr; 4983 SDNode *SetCC = nullptr; 4984 4985 if (Intr->getOpcode() == ISD::SETCC) { 4986 // As long as we negate the condition everything is fine 4987 SetCC = Intr; 4988 Intr = SetCC->getOperand(0).getNode(); 4989 4990 } else { 4991 // Get the target from BR if we don't negate the condition 4992 BR = findUser(BRCOND, ISD::BR); 4993 assert(BR && "brcond missing unconditional branch user"); 4994 Target = BR->getOperand(1); 4995 } 4996 4997 unsigned CFNode = isCFIntrinsic(Intr); 4998 if (CFNode == 0) { 4999 // This is a uniform branch so we don't need to legalize. 5000 return BRCOND; 5001 } 5002 5003 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5004 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5005 5006 assert(!SetCC || 5007 (SetCC->getConstantOperandVal(1) == 1 && 5008 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5009 ISD::SETNE)); 5010 5011 // operands of the new intrinsic call 5012 SmallVector<SDValue, 4> Ops; 5013 if (HaveChain) 5014 Ops.push_back(BRCOND.getOperand(0)); 5015 5016 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5017 Ops.push_back(Target); 5018 5019 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5020 5021 // build the new intrinsic call 5022 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5023 5024 if (!HaveChain) { 5025 SDValue Ops[] = { 5026 SDValue(Result, 0), 5027 BRCOND.getOperand(0) 5028 }; 5029 5030 Result = DAG.getMergeValues(Ops, DL).getNode(); 5031 } 5032 5033 if (BR) { 5034 // Give the branch instruction our target 5035 SDValue Ops[] = { 5036 BR->getOperand(0), 5037 BRCOND.getOperand(2) 5038 }; 5039 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5040 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5041 } 5042 5043 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5044 5045 // Copy the intrinsic results to registers 5046 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5047 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5048 if (!CopyToReg) 5049 continue; 5050 5051 Chain = DAG.getCopyToReg( 5052 Chain, DL, 5053 CopyToReg->getOperand(1), 5054 SDValue(Result, i - 1), 5055 SDValue()); 5056 5057 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5058 } 5059 5060 // Remove the old intrinsic from the chain 5061 DAG.ReplaceAllUsesOfValueWith( 5062 SDValue(Intr, Intr->getNumValues() - 1), 5063 Intr->getOperand(0)); 5064 5065 return Chain; 5066 } 5067 5068 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5069 SelectionDAG &DAG) const { 5070 MVT VT = Op.getSimpleValueType(); 5071 SDLoc DL(Op); 5072 // Checking the depth 5073 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5074 return DAG.getConstant(0, DL, VT); 5075 5076 MachineFunction &MF = DAG.getMachineFunction(); 5077 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5078 // Check for kernel and shader functions 5079 if (Info->isEntryFunction()) 5080 return DAG.getConstant(0, DL, VT); 5081 5082 MachineFrameInfo &MFI = MF.getFrameInfo(); 5083 // There is a call to @llvm.returnaddress in this function 5084 MFI.setReturnAddressIsTaken(true); 5085 5086 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5087 // Get the return address reg and mark it as an implicit live-in 5088 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5089 5090 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5091 } 5092 5093 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5094 SDValue Op, 5095 const SDLoc &DL, 5096 EVT VT) const { 5097 return Op.getValueType().bitsLE(VT) ? 5098 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5099 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5100 DAG.getTargetConstant(0, DL, MVT::i32)); 5101 } 5102 5103 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5104 assert(Op.getValueType() == MVT::f16 && 5105 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5106 5107 SDValue Src = Op.getOperand(0); 5108 EVT SrcVT = Src.getValueType(); 5109 if (SrcVT != MVT::f64) 5110 return Op; 5111 5112 SDLoc DL(Op); 5113 5114 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5115 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5116 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5117 } 5118 5119 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5120 SelectionDAG &DAG) const { 5121 EVT VT = Op.getValueType(); 5122 const MachineFunction &MF = DAG.getMachineFunction(); 5123 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5124 bool IsIEEEMode = Info->getMode().IEEE; 5125 5126 // FIXME: Assert during selection that this is only selected for 5127 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5128 // mode functions, but this happens to be OK since it's only done in cases 5129 // where there is known no sNaN. 5130 if (IsIEEEMode) 5131 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5132 5133 if (VT == MVT::v4f16) 5134 return splitBinaryVectorOp(Op, DAG); 5135 return Op; 5136 } 5137 5138 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5139 EVT VT = Op.getValueType(); 5140 SDLoc SL(Op); 5141 SDValue LHS = Op.getOperand(0); 5142 SDValue RHS = Op.getOperand(1); 5143 bool isSigned = Op.getOpcode() == ISD::SMULO; 5144 5145 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5146 const APInt &C = RHSC->getAPIntValue(); 5147 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5148 if (C.isPowerOf2()) { 5149 // smulo(x, signed_min) is same as umulo(x, signed_min). 5150 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5151 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5152 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5153 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5154 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5155 SL, VT, Result, ShiftAmt), 5156 LHS, ISD::SETNE); 5157 return DAG.getMergeValues({ Result, Overflow }, SL); 5158 } 5159 } 5160 5161 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5162 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5163 SL, VT, LHS, RHS); 5164 5165 SDValue Sign = isSigned 5166 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5167 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5168 : DAG.getConstant(0, SL, VT); 5169 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5170 5171 return DAG.getMergeValues({ Result, Overflow }, SL); 5172 } 5173 5174 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5175 SDLoc SL(Op); 5176 SDValue Chain = Op.getOperand(0); 5177 5178 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5179 !Subtarget->isTrapHandlerEnabled()) 5180 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5181 5182 MachineFunction &MF = DAG.getMachineFunction(); 5183 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5184 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5185 assert(UserSGPR != AMDGPU::NoRegister); 5186 SDValue QueuePtr = CreateLiveInRegister( 5187 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5188 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5189 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5190 QueuePtr, SDValue()); 5191 SDValue Ops[] = { 5192 ToReg, 5193 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5194 SGPR01, 5195 ToReg.getValue(1) 5196 }; 5197 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5198 } 5199 5200 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5201 SDLoc SL(Op); 5202 SDValue Chain = Op.getOperand(0); 5203 MachineFunction &MF = DAG.getMachineFunction(); 5204 5205 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5206 !Subtarget->isTrapHandlerEnabled()) { 5207 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5208 "debugtrap handler not supported", 5209 Op.getDebugLoc(), 5210 DS_Warning); 5211 LLVMContext &Ctx = MF.getFunction().getContext(); 5212 Ctx.diagnose(NoTrap); 5213 return Chain; 5214 } 5215 5216 SDValue Ops[] = { 5217 Chain, 5218 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5219 }; 5220 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5221 } 5222 5223 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5224 SelectionDAG &DAG) const { 5225 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5226 if (Subtarget->hasApertureRegs()) { 5227 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5228 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5229 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5230 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5231 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5232 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5233 unsigned Encoding = 5234 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5235 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5236 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5237 5238 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5239 SDValue ApertureReg = SDValue( 5240 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5241 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5242 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5243 } 5244 5245 MachineFunction &MF = DAG.getMachineFunction(); 5246 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5247 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5248 assert(UserSGPR != AMDGPU::NoRegister); 5249 5250 SDValue QueuePtr = CreateLiveInRegister( 5251 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5252 5253 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5254 // private_segment_aperture_base_hi. 5255 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5256 5257 SDValue Ptr = 5258 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5259 5260 // TODO: Use custom target PseudoSourceValue. 5261 // TODO: We should use the value from the IR intrinsic call, but it might not 5262 // be available and how do we get it? 5263 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5264 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5265 commonAlignment(Align(64), StructOffset), 5266 MachineMemOperand::MODereferenceable | 5267 MachineMemOperand::MOInvariant); 5268 } 5269 5270 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5271 SelectionDAG &DAG) const { 5272 SDLoc SL(Op); 5273 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5274 5275 SDValue Src = ASC->getOperand(0); 5276 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5277 5278 const AMDGPUTargetMachine &TM = 5279 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5280 5281 // flat -> local/private 5282 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5283 unsigned DestAS = ASC->getDestAddressSpace(); 5284 5285 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5286 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5287 unsigned NullVal = TM.getNullPointerValue(DestAS); 5288 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5289 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5290 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5291 5292 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5293 NonNull, Ptr, SegmentNullPtr); 5294 } 5295 } 5296 5297 // local/private -> flat 5298 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5299 unsigned SrcAS = ASC->getSrcAddressSpace(); 5300 5301 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5302 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5303 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5304 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5305 5306 SDValue NonNull 5307 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5308 5309 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5310 SDValue CvtPtr 5311 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5312 5313 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5314 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5315 FlatNullPtr); 5316 } 5317 } 5318 5319 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5320 Src.getValueType() == MVT::i64) 5321 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5322 5323 // global <-> flat are no-ops and never emitted. 5324 5325 const MachineFunction &MF = DAG.getMachineFunction(); 5326 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5327 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5328 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5329 5330 return DAG.getUNDEF(ASC->getValueType(0)); 5331 } 5332 5333 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5334 // the small vector and inserting them into the big vector. That is better than 5335 // the default expansion of doing it via a stack slot. Even though the use of 5336 // the stack slot would be optimized away afterwards, the stack slot itself 5337 // remains. 5338 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5339 SelectionDAG &DAG) const { 5340 SDValue Vec = Op.getOperand(0); 5341 SDValue Ins = Op.getOperand(1); 5342 SDValue Idx = Op.getOperand(2); 5343 EVT VecVT = Vec.getValueType(); 5344 EVT InsVT = Ins.getValueType(); 5345 EVT EltVT = VecVT.getVectorElementType(); 5346 unsigned InsNumElts = InsVT.getVectorNumElements(); 5347 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5348 SDLoc SL(Op); 5349 5350 for (unsigned I = 0; I != InsNumElts; ++I) { 5351 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5352 DAG.getConstant(I, SL, MVT::i32)); 5353 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5354 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5355 } 5356 return Vec; 5357 } 5358 5359 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5360 SelectionDAG &DAG) const { 5361 SDValue Vec = Op.getOperand(0); 5362 SDValue InsVal = Op.getOperand(1); 5363 SDValue Idx = Op.getOperand(2); 5364 EVT VecVT = Vec.getValueType(); 5365 EVT EltVT = VecVT.getVectorElementType(); 5366 unsigned VecSize = VecVT.getSizeInBits(); 5367 unsigned EltSize = EltVT.getSizeInBits(); 5368 5369 5370 assert(VecSize <= 64); 5371 5372 unsigned NumElts = VecVT.getVectorNumElements(); 5373 SDLoc SL(Op); 5374 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5375 5376 if (NumElts == 4 && EltSize == 16 && KIdx) { 5377 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5378 5379 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5380 DAG.getConstant(0, SL, MVT::i32)); 5381 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5382 DAG.getConstant(1, SL, MVT::i32)); 5383 5384 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5385 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5386 5387 unsigned Idx = KIdx->getZExtValue(); 5388 bool InsertLo = Idx < 2; 5389 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5390 InsertLo ? LoVec : HiVec, 5391 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5392 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5393 5394 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5395 5396 SDValue Concat = InsertLo ? 5397 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5398 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5399 5400 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5401 } 5402 5403 if (isa<ConstantSDNode>(Idx)) 5404 return SDValue(); 5405 5406 MVT IntVT = MVT::getIntegerVT(VecSize); 5407 5408 // Avoid stack access for dynamic indexing. 5409 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5410 5411 // Create a congruent vector with the target value in each element so that 5412 // the required element can be masked and ORed into the target vector. 5413 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5414 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5415 5416 assert(isPowerOf2_32(EltSize)); 5417 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5418 5419 // Convert vector index to bit-index. 5420 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5421 5422 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5423 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5424 DAG.getConstant(0xffff, SL, IntVT), 5425 ScaledIdx); 5426 5427 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5428 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5429 DAG.getNOT(SL, BFM, IntVT), BCVec); 5430 5431 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5432 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5433 } 5434 5435 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5436 SelectionDAG &DAG) const { 5437 SDLoc SL(Op); 5438 5439 EVT ResultVT = Op.getValueType(); 5440 SDValue Vec = Op.getOperand(0); 5441 SDValue Idx = Op.getOperand(1); 5442 EVT VecVT = Vec.getValueType(); 5443 unsigned VecSize = VecVT.getSizeInBits(); 5444 EVT EltVT = VecVT.getVectorElementType(); 5445 assert(VecSize <= 64); 5446 5447 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5448 5449 // Make sure we do any optimizations that will make it easier to fold 5450 // source modifiers before obscuring it with bit operations. 5451 5452 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5453 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5454 return Combined; 5455 5456 unsigned EltSize = EltVT.getSizeInBits(); 5457 assert(isPowerOf2_32(EltSize)); 5458 5459 MVT IntVT = MVT::getIntegerVT(VecSize); 5460 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5461 5462 // Convert vector index to bit-index (* EltSize) 5463 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5464 5465 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5466 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5467 5468 if (ResultVT == MVT::f16) { 5469 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5470 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5471 } 5472 5473 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5474 } 5475 5476 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5477 assert(Elt % 2 == 0); 5478 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5479 } 5480 5481 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5482 SelectionDAG &DAG) const { 5483 SDLoc SL(Op); 5484 EVT ResultVT = Op.getValueType(); 5485 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5486 5487 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5488 EVT EltVT = PackVT.getVectorElementType(); 5489 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5490 5491 // vector_shuffle <0,1,6,7> lhs, rhs 5492 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5493 // 5494 // vector_shuffle <6,7,2,3> lhs, rhs 5495 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5496 // 5497 // vector_shuffle <6,7,0,1> lhs, rhs 5498 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5499 5500 // Avoid scalarizing when both halves are reading from consecutive elements. 5501 SmallVector<SDValue, 4> Pieces; 5502 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5503 if (elementPairIsContiguous(SVN->getMask(), I)) { 5504 const int Idx = SVN->getMaskElt(I); 5505 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5506 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5507 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5508 PackVT, SVN->getOperand(VecIdx), 5509 DAG.getConstant(EltIdx, SL, MVT::i32)); 5510 Pieces.push_back(SubVec); 5511 } else { 5512 const int Idx0 = SVN->getMaskElt(I); 5513 const int Idx1 = SVN->getMaskElt(I + 1); 5514 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5515 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5516 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5517 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5518 5519 SDValue Vec0 = SVN->getOperand(VecIdx0); 5520 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5521 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5522 5523 SDValue Vec1 = SVN->getOperand(VecIdx1); 5524 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5525 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5526 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5527 } 5528 } 5529 5530 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5531 } 5532 5533 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5534 SelectionDAG &DAG) const { 5535 SDLoc SL(Op); 5536 EVT VT = Op.getValueType(); 5537 5538 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5539 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5540 5541 // Turn into pair of packed build_vectors. 5542 // TODO: Special case for constants that can be materialized with s_mov_b64. 5543 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5544 { Op.getOperand(0), Op.getOperand(1) }); 5545 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5546 { Op.getOperand(2), Op.getOperand(3) }); 5547 5548 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5549 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5550 5551 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5552 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5553 } 5554 5555 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5556 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5557 5558 SDValue Lo = Op.getOperand(0); 5559 SDValue Hi = Op.getOperand(1); 5560 5561 // Avoid adding defined bits with the zero_extend. 5562 if (Hi.isUndef()) { 5563 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5564 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5565 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5566 } 5567 5568 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5569 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5570 5571 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5572 DAG.getConstant(16, SL, MVT::i32)); 5573 if (Lo.isUndef()) 5574 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5575 5576 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5577 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5578 5579 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5580 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5581 } 5582 5583 bool 5584 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5585 // We can fold offsets for anything that doesn't require a GOT relocation. 5586 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5587 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5588 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5589 !shouldEmitGOTReloc(GA->getGlobal()); 5590 } 5591 5592 static SDValue 5593 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5594 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5595 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5596 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5597 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5598 // lowered to the following code sequence: 5599 // 5600 // For constant address space: 5601 // s_getpc_b64 s[0:1] 5602 // s_add_u32 s0, s0, $symbol 5603 // s_addc_u32 s1, s1, 0 5604 // 5605 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5606 // a fixup or relocation is emitted to replace $symbol with a literal 5607 // constant, which is a pc-relative offset from the encoding of the $symbol 5608 // operand to the global variable. 5609 // 5610 // For global address space: 5611 // s_getpc_b64 s[0:1] 5612 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5613 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5614 // 5615 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5616 // fixups or relocations are emitted to replace $symbol@*@lo and 5617 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5618 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5619 // operand to the global variable. 5620 // 5621 // What we want here is an offset from the value returned by s_getpc 5622 // (which is the address of the s_add_u32 instruction) to the global 5623 // variable, but since the encoding of $symbol starts 4 bytes after the start 5624 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5625 // small. This requires us to add 4 to the global variable offset in order to 5626 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5627 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5628 // instruction. 5629 SDValue PtrLo = 5630 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5631 SDValue PtrHi; 5632 if (GAFlags == SIInstrInfo::MO_NONE) { 5633 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5634 } else { 5635 PtrHi = 5636 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5637 } 5638 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5639 } 5640 5641 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5642 SDValue Op, 5643 SelectionDAG &DAG) const { 5644 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5645 SDLoc DL(GSD); 5646 EVT PtrVT = Op.getValueType(); 5647 5648 const GlobalValue *GV = GSD->getGlobal(); 5649 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5650 shouldUseLDSConstAddress(GV)) || 5651 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5652 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5653 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5654 GV->hasExternalLinkage()) { 5655 Type *Ty = GV->getValueType(); 5656 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5657 // zero-sized type in other languages to declare the dynamic shared 5658 // memory which size is not known at the compile time. They will be 5659 // allocated by the runtime and placed directly after the static 5660 // allocated ones. They all share the same offset. 5661 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5662 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5663 // Adjust alignment for that dynamic shared memory array. 5664 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5665 return SDValue( 5666 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5667 } 5668 } 5669 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5670 } 5671 5672 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5673 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5674 SIInstrInfo::MO_ABS32_LO); 5675 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5676 } 5677 5678 if (shouldEmitFixup(GV)) 5679 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5680 else if (shouldEmitPCReloc(GV)) 5681 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5682 SIInstrInfo::MO_REL32); 5683 5684 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5685 SIInstrInfo::MO_GOTPCREL32); 5686 5687 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5688 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5689 const DataLayout &DataLayout = DAG.getDataLayout(); 5690 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5691 MachinePointerInfo PtrInfo 5692 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5693 5694 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5695 MachineMemOperand::MODereferenceable | 5696 MachineMemOperand::MOInvariant); 5697 } 5698 5699 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5700 const SDLoc &DL, SDValue V) const { 5701 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5702 // the destination register. 5703 // 5704 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5705 // so we will end up with redundant moves to m0. 5706 // 5707 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5708 5709 // A Null SDValue creates a glue result. 5710 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5711 V, Chain); 5712 return SDValue(M0, 0); 5713 } 5714 5715 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5716 SDValue Op, 5717 MVT VT, 5718 unsigned Offset) const { 5719 SDLoc SL(Op); 5720 SDValue Param = lowerKernargMemParameter( 5721 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5722 // The local size values will have the hi 16-bits as zero. 5723 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5724 DAG.getValueType(VT)); 5725 } 5726 5727 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5728 EVT VT) { 5729 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5730 "non-hsa intrinsic with hsa target", 5731 DL.getDebugLoc()); 5732 DAG.getContext()->diagnose(BadIntrin); 5733 return DAG.getUNDEF(VT); 5734 } 5735 5736 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5737 EVT VT) { 5738 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5739 "intrinsic not supported on subtarget", 5740 DL.getDebugLoc()); 5741 DAG.getContext()->diagnose(BadIntrin); 5742 return DAG.getUNDEF(VT); 5743 } 5744 5745 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5746 ArrayRef<SDValue> Elts) { 5747 assert(!Elts.empty()); 5748 MVT Type; 5749 unsigned NumElts; 5750 5751 if (Elts.size() == 1) { 5752 Type = MVT::f32; 5753 NumElts = 1; 5754 } else if (Elts.size() == 2) { 5755 Type = MVT::v2f32; 5756 NumElts = 2; 5757 } else if (Elts.size() == 3) { 5758 Type = MVT::v3f32; 5759 NumElts = 3; 5760 } else if (Elts.size() <= 4) { 5761 Type = MVT::v4f32; 5762 NumElts = 4; 5763 } else if (Elts.size() <= 8) { 5764 Type = MVT::v8f32; 5765 NumElts = 8; 5766 } else { 5767 assert(Elts.size() <= 16); 5768 Type = MVT::v16f32; 5769 NumElts = 16; 5770 } 5771 5772 SmallVector<SDValue, 16> VecElts(NumElts); 5773 for (unsigned i = 0; i < Elts.size(); ++i) { 5774 SDValue Elt = Elts[i]; 5775 if (Elt.getValueType() != MVT::f32) 5776 Elt = DAG.getBitcast(MVT::f32, Elt); 5777 VecElts[i] = Elt; 5778 } 5779 for (unsigned i = Elts.size(); i < NumElts; ++i) 5780 VecElts[i] = DAG.getUNDEF(MVT::f32); 5781 5782 if (NumElts == 1) 5783 return VecElts[0]; 5784 return DAG.getBuildVector(Type, DL, VecElts); 5785 } 5786 5787 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5788 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5789 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5790 5791 uint64_t Value = CachePolicyConst->getZExtValue(); 5792 SDLoc DL(CachePolicy); 5793 if (GLC) { 5794 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5795 Value &= ~(uint64_t)0x1; 5796 } 5797 if (SLC) { 5798 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5799 Value &= ~(uint64_t)0x2; 5800 } 5801 if (DLC) { 5802 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5803 Value &= ~(uint64_t)0x4; 5804 } 5805 5806 return Value == 0; 5807 } 5808 5809 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5810 SDValue Src, int ExtraElts) { 5811 EVT SrcVT = Src.getValueType(); 5812 5813 SmallVector<SDValue, 8> Elts; 5814 5815 if (SrcVT.isVector()) 5816 DAG.ExtractVectorElements(Src, Elts); 5817 else 5818 Elts.push_back(Src); 5819 5820 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5821 while (ExtraElts--) 5822 Elts.push_back(Undef); 5823 5824 return DAG.getBuildVector(CastVT, DL, Elts); 5825 } 5826 5827 // Re-construct the required return value for a image load intrinsic. 5828 // This is more complicated due to the optional use TexFailCtrl which means the required 5829 // return type is an aggregate 5830 static SDValue constructRetValue(SelectionDAG &DAG, 5831 MachineSDNode *Result, 5832 ArrayRef<EVT> ResultTypes, 5833 bool IsTexFail, bool Unpacked, bool IsD16, 5834 int DMaskPop, int NumVDataDwords, 5835 const SDLoc &DL, LLVMContext &Context) { 5836 // Determine the required return type. This is the same regardless of IsTexFail flag 5837 EVT ReqRetVT = ResultTypes[0]; 5838 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5839 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5840 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5841 5842 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5843 DMaskPop : (DMaskPop + 1) / 2; 5844 5845 MVT DataDwordVT = NumDataDwords == 1 ? 5846 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5847 5848 MVT MaskPopVT = MaskPopDwords == 1 ? 5849 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5850 5851 SDValue Data(Result, 0); 5852 SDValue TexFail; 5853 5854 if (IsTexFail) { 5855 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5856 if (MaskPopVT.isVector()) { 5857 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5858 SDValue(Result, 0), ZeroIdx); 5859 } else { 5860 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5861 SDValue(Result, 0), ZeroIdx); 5862 } 5863 5864 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5865 SDValue(Result, 0), 5866 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5867 } 5868 5869 if (DataDwordVT.isVector()) 5870 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5871 NumDataDwords - MaskPopDwords); 5872 5873 if (IsD16) 5874 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5875 5876 EVT LegalReqRetVT = ReqRetVT; 5877 if (!ReqRetVT.isVector()) { 5878 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5879 } else { 5880 // We need to widen the return vector to a legal type 5881 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5882 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5883 LegalReqRetVT = 5884 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5885 ReqRetVT.getVectorNumElements() + 1); 5886 } 5887 } 5888 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5889 5890 if (TexFail) 5891 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5892 5893 if (Result->getNumValues() == 1) 5894 return Data; 5895 5896 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5897 } 5898 5899 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5900 SDValue *LWE, bool &IsTexFail) { 5901 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5902 5903 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5904 if (Value) { 5905 IsTexFail = true; 5906 } 5907 5908 SDLoc DL(TexFailCtrlConst); 5909 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5910 Value &= ~(uint64_t)0x1; 5911 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5912 Value &= ~(uint64_t)0x2; 5913 5914 return Value == 0; 5915 } 5916 5917 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5918 MVT PackVectorVT, 5919 SmallVectorImpl<SDValue> &PackedAddrs, 5920 unsigned DimIdx, unsigned EndIdx, 5921 unsigned NumGradients) { 5922 SDLoc DL(Op); 5923 for (unsigned I = DimIdx; I < EndIdx; I++) { 5924 SDValue Addr = Op.getOperand(I); 5925 5926 // Gradients are packed with undef for each coordinate. 5927 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5928 // 1D: undef,dx/dh; undef,dx/dv 5929 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5930 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5931 if (((I + 1) >= EndIdx) || 5932 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5933 I == DimIdx + NumGradients - 1))) { 5934 if (Addr.getValueType() != MVT::i16) 5935 Addr = DAG.getBitcast(MVT::i16, Addr); 5936 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5937 } else { 5938 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5939 I++; 5940 } 5941 Addr = DAG.getBitcast(MVT::f32, Addr); 5942 PackedAddrs.push_back(Addr); 5943 } 5944 } 5945 5946 SDValue SITargetLowering::lowerImage(SDValue Op, 5947 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5948 SelectionDAG &DAG, bool WithChain) const { 5949 SDLoc DL(Op); 5950 MachineFunction &MF = DAG.getMachineFunction(); 5951 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5952 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5953 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5954 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5955 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5956 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5957 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5958 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5959 unsigned IntrOpcode = Intr->BaseOpcode; 5960 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5961 5962 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5963 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5964 bool IsD16 = false; 5965 bool IsG16 = false; 5966 bool IsA16 = false; 5967 SDValue VData; 5968 int NumVDataDwords; 5969 bool AdjustRetType = false; 5970 5971 // Offset of intrinsic arguments 5972 const unsigned ArgOffset = WithChain ? 2 : 1; 5973 5974 unsigned DMask; 5975 unsigned DMaskLanes = 0; 5976 5977 if (BaseOpcode->Atomic) { 5978 VData = Op.getOperand(2); 5979 5980 bool Is64Bit = VData.getValueType() == MVT::i64; 5981 if (BaseOpcode->AtomicX2) { 5982 SDValue VData2 = Op.getOperand(3); 5983 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5984 {VData, VData2}); 5985 if (Is64Bit) 5986 VData = DAG.getBitcast(MVT::v4i32, VData); 5987 5988 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5989 DMask = Is64Bit ? 0xf : 0x3; 5990 NumVDataDwords = Is64Bit ? 4 : 2; 5991 } else { 5992 DMask = Is64Bit ? 0x3 : 0x1; 5993 NumVDataDwords = Is64Bit ? 2 : 1; 5994 } 5995 } else { 5996 auto *DMaskConst = 5997 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 5998 DMask = DMaskConst->getZExtValue(); 5999 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6000 6001 if (BaseOpcode->Store) { 6002 VData = Op.getOperand(2); 6003 6004 MVT StoreVT = VData.getSimpleValueType(); 6005 if (StoreVT.getScalarType() == MVT::f16) { 6006 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6007 return Op; // D16 is unsupported for this instruction 6008 6009 IsD16 = true; 6010 VData = handleD16VData(VData, DAG); 6011 } 6012 6013 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6014 } else { 6015 // Work out the num dwords based on the dmask popcount and underlying type 6016 // and whether packing is supported. 6017 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6018 if (LoadVT.getScalarType() == MVT::f16) { 6019 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6020 return Op; // D16 is unsupported for this instruction 6021 6022 IsD16 = true; 6023 } 6024 6025 // Confirm that the return type is large enough for the dmask specified 6026 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6027 (!LoadVT.isVector() && DMaskLanes > 1)) 6028 return Op; 6029 6030 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 6031 NumVDataDwords = (DMaskLanes + 1) / 2; 6032 else 6033 NumVDataDwords = DMaskLanes; 6034 6035 AdjustRetType = true; 6036 } 6037 } 6038 6039 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6040 SmallVector<SDValue, 4> VAddrs; 6041 6042 // Optimize _L to _LZ when _L is zero 6043 if (LZMappingInfo) { 6044 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6045 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6046 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6047 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6048 VAddrEnd--; // remove 'lod' 6049 } 6050 } 6051 } 6052 6053 // Optimize _mip away, when 'lod' is zero 6054 if (MIPMappingInfo) { 6055 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6056 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6057 if (ConstantLod->isNullValue()) { 6058 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6059 VAddrEnd--; // remove 'mip' 6060 } 6061 } 6062 } 6063 6064 // Push back extra arguments. 6065 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6066 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6067 6068 // Check for 16 bit addresses or derivatives and pack if true. 6069 MVT VAddrVT = 6070 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6071 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6072 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6073 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6074 6075 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6076 VAddrScalarVT = VAddrVT.getScalarType(); 6077 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6078 if (IsA16 || IsG16) { 6079 if (IsA16) { 6080 if (!ST->hasA16()) { 6081 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6082 "support 16 bit addresses\n"); 6083 return Op; 6084 } 6085 if (!IsG16) { 6086 LLVM_DEBUG( 6087 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6088 "need 16 bit derivatives but got 32 bit derivatives\n"); 6089 return Op; 6090 } 6091 } else if (!ST->hasG16()) { 6092 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6093 "support 16 bit derivatives\n"); 6094 return Op; 6095 } 6096 6097 if (BaseOpcode->Gradients && !IsA16) { 6098 if (!ST->hasG16()) { 6099 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6100 "support 16 bit derivatives\n"); 6101 return Op; 6102 } 6103 // Activate g16 6104 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6105 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6106 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6107 } 6108 6109 // Don't compress addresses for G16 6110 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6111 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6112 ArgOffset + Intr->GradientStart, PackEndIdx, 6113 Intr->NumGradients); 6114 6115 if (!IsA16) { 6116 // Add uncompressed address 6117 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6118 VAddrs.push_back(Op.getOperand(I)); 6119 } 6120 } else { 6121 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6122 VAddrs.push_back(Op.getOperand(I)); 6123 } 6124 6125 // If the register allocator cannot place the address registers contiguously 6126 // without introducing moves, then using the non-sequential address encoding 6127 // is always preferable, since it saves VALU instructions and is usually a 6128 // wash in terms of code size or even better. 6129 // 6130 // However, we currently have no way of hinting to the register allocator that 6131 // MIMG addresses should be placed contiguously when it is possible to do so, 6132 // so force non-NSA for the common 2-address case as a heuristic. 6133 // 6134 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6135 // allocation when possible. 6136 bool UseNSA = 6137 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6138 SDValue VAddr; 6139 if (!UseNSA) 6140 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6141 6142 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6143 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6144 SDValue Unorm; 6145 if (!BaseOpcode->Sampler) { 6146 Unorm = True; 6147 } else { 6148 auto UnormConst = 6149 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6150 6151 Unorm = UnormConst->getZExtValue() ? True : False; 6152 } 6153 6154 SDValue TFE; 6155 SDValue LWE; 6156 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6157 bool IsTexFail = false; 6158 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6159 return Op; 6160 6161 if (IsTexFail) { 6162 if (!DMaskLanes) { 6163 // Expecting to get an error flag since TFC is on - and dmask is 0 6164 // Force dmask to be at least 1 otherwise the instruction will fail 6165 DMask = 0x1; 6166 DMaskLanes = 1; 6167 NumVDataDwords = 1; 6168 } 6169 NumVDataDwords += 1; 6170 AdjustRetType = true; 6171 } 6172 6173 // Has something earlier tagged that the return type needs adjusting 6174 // This happens if the instruction is a load or has set TexFailCtrl flags 6175 if (AdjustRetType) { 6176 // NumVDataDwords reflects the true number of dwords required in the return type 6177 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6178 // This is a no-op load. This can be eliminated 6179 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6180 if (isa<MemSDNode>(Op)) 6181 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6182 return Undef; 6183 } 6184 6185 EVT NewVT = NumVDataDwords > 1 ? 6186 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6187 : MVT::i32; 6188 6189 ResultTypes[0] = NewVT; 6190 if (ResultTypes.size() == 3) { 6191 // Original result was aggregate type used for TexFailCtrl results 6192 // The actual instruction returns as a vector type which has now been 6193 // created. Remove the aggregate result. 6194 ResultTypes.erase(&ResultTypes[1]); 6195 } 6196 } 6197 6198 SDValue GLC; 6199 SDValue SLC; 6200 SDValue DLC; 6201 if (BaseOpcode->Atomic) { 6202 GLC = True; // TODO no-return optimization 6203 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6204 DAG, nullptr, &SLC, IsGFX10 ? &DLC : nullptr)) 6205 return Op; 6206 } else { 6207 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6208 DAG, &GLC, &SLC, IsGFX10 ? &DLC : nullptr)) 6209 return Op; 6210 } 6211 6212 SmallVector<SDValue, 26> Ops; 6213 if (BaseOpcode->Store || BaseOpcode->Atomic) 6214 Ops.push_back(VData); // vdata 6215 if (UseNSA) { 6216 for (const SDValue &Addr : VAddrs) 6217 Ops.push_back(Addr); 6218 } else { 6219 Ops.push_back(VAddr); 6220 } 6221 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6222 if (BaseOpcode->Sampler) 6223 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6224 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6225 if (IsGFX10) 6226 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6227 Ops.push_back(Unorm); 6228 if (IsGFX10) 6229 Ops.push_back(DLC); 6230 Ops.push_back(GLC); 6231 Ops.push_back(SLC); 6232 Ops.push_back(IsA16 && // r128, a16 for gfx9 6233 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6234 if (IsGFX10) 6235 Ops.push_back(IsA16 ? True : False); 6236 Ops.push_back(TFE); 6237 Ops.push_back(LWE); 6238 if (!IsGFX10) 6239 Ops.push_back(DimInfo->DA ? True : False); 6240 if (BaseOpcode->HasD16) 6241 Ops.push_back(IsD16 ? True : False); 6242 if (isa<MemSDNode>(Op)) 6243 Ops.push_back(Op.getOperand(0)); // chain 6244 6245 int NumVAddrDwords = 6246 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6247 int Opcode = -1; 6248 6249 if (IsGFX10) { 6250 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6251 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6252 : AMDGPU::MIMGEncGfx10Default, 6253 NumVDataDwords, NumVAddrDwords); 6254 } else { 6255 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6256 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6257 NumVDataDwords, NumVAddrDwords); 6258 if (Opcode == -1) 6259 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6260 NumVDataDwords, NumVAddrDwords); 6261 } 6262 assert(Opcode != -1); 6263 6264 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6265 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6266 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6267 DAG.setNodeMemRefs(NewNode, {MemRef}); 6268 } 6269 6270 if (BaseOpcode->AtomicX2) { 6271 SmallVector<SDValue, 1> Elt; 6272 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6273 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6274 } else if (!BaseOpcode->Store) { 6275 return constructRetValue(DAG, NewNode, 6276 OrigResultTypes, IsTexFail, 6277 Subtarget->hasUnpackedD16VMem(), IsD16, 6278 DMaskLanes, NumVDataDwords, DL, 6279 *DAG.getContext()); 6280 } 6281 6282 return SDValue(NewNode, 0); 6283 } 6284 6285 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6286 SDValue Offset, SDValue CachePolicy, 6287 SelectionDAG &DAG) const { 6288 MachineFunction &MF = DAG.getMachineFunction(); 6289 6290 const DataLayout &DataLayout = DAG.getDataLayout(); 6291 Align Alignment = 6292 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6293 6294 MachineMemOperand *MMO = MF.getMachineMemOperand( 6295 MachinePointerInfo(), 6296 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6297 MachineMemOperand::MOInvariant, 6298 VT.getStoreSize(), Alignment); 6299 6300 if (!Offset->isDivergent()) { 6301 SDValue Ops[] = { 6302 Rsrc, 6303 Offset, // Offset 6304 CachePolicy 6305 }; 6306 6307 // Widen vec3 load to vec4. 6308 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6309 EVT WidenedVT = 6310 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6311 auto WidenedOp = DAG.getMemIntrinsicNode( 6312 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6313 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6314 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6315 DAG.getVectorIdxConstant(0, DL)); 6316 return Subvector; 6317 } 6318 6319 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6320 DAG.getVTList(VT), Ops, VT, MMO); 6321 } 6322 6323 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6324 // assume that the buffer is unswizzled. 6325 SmallVector<SDValue, 4> Loads; 6326 unsigned NumLoads = 1; 6327 MVT LoadVT = VT.getSimpleVT(); 6328 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6329 assert((LoadVT.getScalarType() == MVT::i32 || 6330 LoadVT.getScalarType() == MVT::f32)); 6331 6332 if (NumElts == 8 || NumElts == 16) { 6333 NumLoads = NumElts / 4; 6334 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6335 } 6336 6337 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6338 SDValue Ops[] = { 6339 DAG.getEntryNode(), // Chain 6340 Rsrc, // rsrc 6341 DAG.getConstant(0, DL, MVT::i32), // vindex 6342 {}, // voffset 6343 {}, // soffset 6344 {}, // offset 6345 CachePolicy, // cachepolicy 6346 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6347 }; 6348 6349 // Use the alignment to ensure that the required offsets will fit into the 6350 // immediate offsets. 6351 setBufferOffsets(Offset, DAG, &Ops[3], 6352 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6353 6354 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6355 for (unsigned i = 0; i < NumLoads; ++i) { 6356 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6357 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6358 LoadVT, MMO, DAG)); 6359 } 6360 6361 if (NumElts == 8 || NumElts == 16) 6362 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6363 6364 return Loads[0]; 6365 } 6366 6367 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6368 SelectionDAG &DAG) const { 6369 MachineFunction &MF = DAG.getMachineFunction(); 6370 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6371 6372 EVT VT = Op.getValueType(); 6373 SDLoc DL(Op); 6374 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6375 6376 // TODO: Should this propagate fast-math-flags? 6377 6378 switch (IntrinsicID) { 6379 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6380 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6381 return emitNonHSAIntrinsicError(DAG, DL, VT); 6382 return getPreloadedValue(DAG, *MFI, VT, 6383 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6384 } 6385 case Intrinsic::amdgcn_dispatch_ptr: 6386 case Intrinsic::amdgcn_queue_ptr: { 6387 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6388 DiagnosticInfoUnsupported BadIntrin( 6389 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6390 DL.getDebugLoc()); 6391 DAG.getContext()->diagnose(BadIntrin); 6392 return DAG.getUNDEF(VT); 6393 } 6394 6395 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6396 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6397 return getPreloadedValue(DAG, *MFI, VT, RegID); 6398 } 6399 case Intrinsic::amdgcn_implicitarg_ptr: { 6400 if (MFI->isEntryFunction()) 6401 return getImplicitArgPtr(DAG, DL); 6402 return getPreloadedValue(DAG, *MFI, VT, 6403 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6404 } 6405 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6406 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6407 // This only makes sense to call in a kernel, so just lower to null. 6408 return DAG.getConstant(0, DL, VT); 6409 } 6410 6411 return getPreloadedValue(DAG, *MFI, VT, 6412 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6413 } 6414 case Intrinsic::amdgcn_dispatch_id: { 6415 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6416 } 6417 case Intrinsic::amdgcn_rcp: 6418 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6419 case Intrinsic::amdgcn_rsq: 6420 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6421 case Intrinsic::amdgcn_rsq_legacy: 6422 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6423 return emitRemovedIntrinsicError(DAG, DL, VT); 6424 return SDValue(); 6425 case Intrinsic::amdgcn_rcp_legacy: 6426 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6427 return emitRemovedIntrinsicError(DAG, DL, VT); 6428 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6429 case Intrinsic::amdgcn_rsq_clamp: { 6430 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6431 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6432 6433 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6434 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6435 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6436 6437 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6438 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6439 DAG.getConstantFP(Max, DL, VT)); 6440 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6441 DAG.getConstantFP(Min, DL, VT)); 6442 } 6443 case Intrinsic::r600_read_ngroups_x: 6444 if (Subtarget->isAmdHsaOS()) 6445 return emitNonHSAIntrinsicError(DAG, DL, VT); 6446 6447 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6448 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6449 false); 6450 case Intrinsic::r600_read_ngroups_y: 6451 if (Subtarget->isAmdHsaOS()) 6452 return emitNonHSAIntrinsicError(DAG, DL, VT); 6453 6454 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6455 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6456 false); 6457 case Intrinsic::r600_read_ngroups_z: 6458 if (Subtarget->isAmdHsaOS()) 6459 return emitNonHSAIntrinsicError(DAG, DL, VT); 6460 6461 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6462 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6463 false); 6464 case Intrinsic::r600_read_global_size_x: 6465 if (Subtarget->isAmdHsaOS()) 6466 return emitNonHSAIntrinsicError(DAG, DL, VT); 6467 6468 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6469 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6470 Align(4), false); 6471 case Intrinsic::r600_read_global_size_y: 6472 if (Subtarget->isAmdHsaOS()) 6473 return emitNonHSAIntrinsicError(DAG, DL, VT); 6474 6475 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6476 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6477 Align(4), false); 6478 case Intrinsic::r600_read_global_size_z: 6479 if (Subtarget->isAmdHsaOS()) 6480 return emitNonHSAIntrinsicError(DAG, DL, VT); 6481 6482 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6483 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6484 Align(4), false); 6485 case Intrinsic::r600_read_local_size_x: 6486 if (Subtarget->isAmdHsaOS()) 6487 return emitNonHSAIntrinsicError(DAG, DL, VT); 6488 6489 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6490 SI::KernelInputOffsets::LOCAL_SIZE_X); 6491 case Intrinsic::r600_read_local_size_y: 6492 if (Subtarget->isAmdHsaOS()) 6493 return emitNonHSAIntrinsicError(DAG, DL, VT); 6494 6495 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6496 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6497 case Intrinsic::r600_read_local_size_z: 6498 if (Subtarget->isAmdHsaOS()) 6499 return emitNonHSAIntrinsicError(DAG, DL, VT); 6500 6501 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6502 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6503 case Intrinsic::amdgcn_workgroup_id_x: 6504 return getPreloadedValue(DAG, *MFI, VT, 6505 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6506 case Intrinsic::amdgcn_workgroup_id_y: 6507 return getPreloadedValue(DAG, *MFI, VT, 6508 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6509 case Intrinsic::amdgcn_workgroup_id_z: 6510 return getPreloadedValue(DAG, *MFI, VT, 6511 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6512 case Intrinsic::amdgcn_workitem_id_x: 6513 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6514 SDLoc(DAG.getEntryNode()), 6515 MFI->getArgInfo().WorkItemIDX); 6516 case Intrinsic::amdgcn_workitem_id_y: 6517 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6518 SDLoc(DAG.getEntryNode()), 6519 MFI->getArgInfo().WorkItemIDY); 6520 case Intrinsic::amdgcn_workitem_id_z: 6521 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6522 SDLoc(DAG.getEntryNode()), 6523 MFI->getArgInfo().WorkItemIDZ); 6524 case Intrinsic::amdgcn_wavefrontsize: 6525 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6526 SDLoc(Op), MVT::i32); 6527 case Intrinsic::amdgcn_s_buffer_load: { 6528 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6529 SDValue GLC; 6530 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6531 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6532 IsGFX10 ? &DLC : nullptr)) 6533 return Op; 6534 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6535 DAG); 6536 } 6537 case Intrinsic::amdgcn_fdiv_fast: 6538 return lowerFDIV_FAST(Op, DAG); 6539 case Intrinsic::amdgcn_sin: 6540 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6541 6542 case Intrinsic::amdgcn_cos: 6543 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6544 6545 case Intrinsic::amdgcn_mul_u24: 6546 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6547 case Intrinsic::amdgcn_mul_i24: 6548 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6549 6550 case Intrinsic::amdgcn_log_clamp: { 6551 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6552 return SDValue(); 6553 6554 DiagnosticInfoUnsupported BadIntrin( 6555 MF.getFunction(), "intrinsic not supported on subtarget", 6556 DL.getDebugLoc()); 6557 DAG.getContext()->diagnose(BadIntrin); 6558 return DAG.getUNDEF(VT); 6559 } 6560 case Intrinsic::amdgcn_ldexp: 6561 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6562 Op.getOperand(1), Op.getOperand(2)); 6563 6564 case Intrinsic::amdgcn_fract: 6565 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6566 6567 case Intrinsic::amdgcn_class: 6568 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6569 Op.getOperand(1), Op.getOperand(2)); 6570 case Intrinsic::amdgcn_div_fmas: 6571 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6572 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6573 Op.getOperand(4)); 6574 6575 case Intrinsic::amdgcn_div_fixup: 6576 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6577 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6578 6579 case Intrinsic::amdgcn_div_scale: { 6580 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6581 6582 // Translate to the operands expected by the machine instruction. The 6583 // first parameter must be the same as the first instruction. 6584 SDValue Numerator = Op.getOperand(1); 6585 SDValue Denominator = Op.getOperand(2); 6586 6587 // Note this order is opposite of the machine instruction's operations, 6588 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6589 // intrinsic has the numerator as the first operand to match a normal 6590 // division operation. 6591 6592 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6593 6594 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6595 Denominator, Numerator); 6596 } 6597 case Intrinsic::amdgcn_icmp: { 6598 // There is a Pat that handles this variant, so return it as-is. 6599 if (Op.getOperand(1).getValueType() == MVT::i1 && 6600 Op.getConstantOperandVal(2) == 0 && 6601 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6602 return Op; 6603 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6604 } 6605 case Intrinsic::amdgcn_fcmp: { 6606 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6607 } 6608 case Intrinsic::amdgcn_ballot: 6609 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6610 case Intrinsic::amdgcn_fmed3: 6611 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6612 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6613 case Intrinsic::amdgcn_fdot2: 6614 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6615 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6616 Op.getOperand(4)); 6617 case Intrinsic::amdgcn_fmul_legacy: 6618 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6619 Op.getOperand(1), Op.getOperand(2)); 6620 case Intrinsic::amdgcn_sffbh: 6621 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6622 case Intrinsic::amdgcn_sbfe: 6623 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6624 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6625 case Intrinsic::amdgcn_ubfe: 6626 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6627 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6628 case Intrinsic::amdgcn_cvt_pkrtz: 6629 case Intrinsic::amdgcn_cvt_pknorm_i16: 6630 case Intrinsic::amdgcn_cvt_pknorm_u16: 6631 case Intrinsic::amdgcn_cvt_pk_i16: 6632 case Intrinsic::amdgcn_cvt_pk_u16: { 6633 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6634 EVT VT = Op.getValueType(); 6635 unsigned Opcode; 6636 6637 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6638 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6639 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6640 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6641 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6642 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6643 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6644 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6645 else 6646 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6647 6648 if (isTypeLegal(VT)) 6649 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6650 6651 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6652 Op.getOperand(1), Op.getOperand(2)); 6653 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6654 } 6655 case Intrinsic::amdgcn_fmad_ftz: 6656 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6657 Op.getOperand(2), Op.getOperand(3)); 6658 6659 case Intrinsic::amdgcn_if_break: 6660 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6661 Op->getOperand(1), Op->getOperand(2)), 0); 6662 6663 case Intrinsic::amdgcn_groupstaticsize: { 6664 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6665 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6666 return Op; 6667 6668 const Module *M = MF.getFunction().getParent(); 6669 const GlobalValue *GV = 6670 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6671 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6672 SIInstrInfo::MO_ABS32_LO); 6673 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6674 } 6675 case Intrinsic::amdgcn_is_shared: 6676 case Intrinsic::amdgcn_is_private: { 6677 SDLoc SL(Op); 6678 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6679 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6680 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6681 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6682 Op.getOperand(1)); 6683 6684 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6685 DAG.getConstant(1, SL, MVT::i32)); 6686 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6687 } 6688 case Intrinsic::amdgcn_alignbit: 6689 return DAG.getNode(ISD::FSHR, DL, VT, 6690 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6691 case Intrinsic::amdgcn_reloc_constant: { 6692 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6693 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6694 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6695 auto RelocSymbol = cast<GlobalVariable>( 6696 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6697 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6698 SIInstrInfo::MO_ABS32_LO); 6699 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6700 } 6701 default: 6702 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6703 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6704 return lowerImage(Op, ImageDimIntr, DAG, false); 6705 6706 return Op; 6707 } 6708 } 6709 6710 // This function computes an appropriate offset to pass to 6711 // MachineMemOperand::setOffset() based on the offset inputs to 6712 // an intrinsic. If any of the offsets are non-contstant or 6713 // if VIndex is non-zero then this function returns 0. Otherwise, 6714 // it returns the sum of VOffset, SOffset, and Offset. 6715 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6716 SDValue SOffset, 6717 SDValue Offset, 6718 SDValue VIndex = SDValue()) { 6719 6720 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6721 !isa<ConstantSDNode>(Offset)) 6722 return 0; 6723 6724 if (VIndex) { 6725 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6726 return 0; 6727 } 6728 6729 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6730 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6731 cast<ConstantSDNode>(Offset)->getSExtValue(); 6732 } 6733 6734 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6735 SelectionDAG &DAG, 6736 unsigned NewOpcode) const { 6737 SDLoc DL(Op); 6738 6739 SDValue VData = Op.getOperand(2); 6740 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6741 SDValue Ops[] = { 6742 Op.getOperand(0), // Chain 6743 VData, // vdata 6744 Op.getOperand(3), // rsrc 6745 DAG.getConstant(0, DL, MVT::i32), // vindex 6746 Offsets.first, // voffset 6747 Op.getOperand(5), // soffset 6748 Offsets.second, // offset 6749 Op.getOperand(6), // cachepolicy 6750 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6751 }; 6752 6753 auto *M = cast<MemSDNode>(Op); 6754 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6755 6756 EVT MemVT = VData.getValueType(); 6757 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6758 M->getMemOperand()); 6759 } 6760 6761 SDValue 6762 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6763 unsigned NewOpcode) const { 6764 SDLoc DL(Op); 6765 6766 SDValue VData = Op.getOperand(2); 6767 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6768 SDValue Ops[] = { 6769 Op.getOperand(0), // Chain 6770 VData, // vdata 6771 Op.getOperand(3), // rsrc 6772 Op.getOperand(4), // vindex 6773 Offsets.first, // voffset 6774 Op.getOperand(6), // soffset 6775 Offsets.second, // offset 6776 Op.getOperand(7), // cachepolicy 6777 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6778 }; 6779 6780 auto *M = cast<MemSDNode>(Op); 6781 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6782 Ops[3])); 6783 6784 EVT MemVT = VData.getValueType(); 6785 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6786 M->getMemOperand()); 6787 } 6788 6789 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6790 SelectionDAG &DAG) const { 6791 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6792 SDLoc DL(Op); 6793 6794 switch (IntrID) { 6795 case Intrinsic::amdgcn_ds_ordered_add: 6796 case Intrinsic::amdgcn_ds_ordered_swap: { 6797 MemSDNode *M = cast<MemSDNode>(Op); 6798 SDValue Chain = M->getOperand(0); 6799 SDValue M0 = M->getOperand(2); 6800 SDValue Value = M->getOperand(3); 6801 unsigned IndexOperand = M->getConstantOperandVal(7); 6802 unsigned WaveRelease = M->getConstantOperandVal(8); 6803 unsigned WaveDone = M->getConstantOperandVal(9); 6804 6805 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6806 IndexOperand &= ~0x3f; 6807 unsigned CountDw = 0; 6808 6809 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6810 CountDw = (IndexOperand >> 24) & 0xf; 6811 IndexOperand &= ~(0xf << 24); 6812 6813 if (CountDw < 1 || CountDw > 4) { 6814 report_fatal_error( 6815 "ds_ordered_count: dword count must be between 1 and 4"); 6816 } 6817 } 6818 6819 if (IndexOperand) 6820 report_fatal_error("ds_ordered_count: bad index operand"); 6821 6822 if (WaveDone && !WaveRelease) 6823 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6824 6825 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6826 unsigned ShaderType = 6827 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6828 unsigned Offset0 = OrderedCountIndex << 2; 6829 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6830 (Instruction << 4); 6831 6832 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6833 Offset1 |= (CountDw - 1) << 6; 6834 6835 unsigned Offset = Offset0 | (Offset1 << 8); 6836 6837 SDValue Ops[] = { 6838 Chain, 6839 Value, 6840 DAG.getTargetConstant(Offset, DL, MVT::i16), 6841 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6842 }; 6843 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6844 M->getVTList(), Ops, M->getMemoryVT(), 6845 M->getMemOperand()); 6846 } 6847 case Intrinsic::amdgcn_ds_fadd: { 6848 MemSDNode *M = cast<MemSDNode>(Op); 6849 unsigned Opc; 6850 switch (IntrID) { 6851 case Intrinsic::amdgcn_ds_fadd: 6852 Opc = ISD::ATOMIC_LOAD_FADD; 6853 break; 6854 } 6855 6856 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6857 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6858 M->getMemOperand()); 6859 } 6860 case Intrinsic::amdgcn_atomic_inc: 6861 case Intrinsic::amdgcn_atomic_dec: 6862 case Intrinsic::amdgcn_ds_fmin: 6863 case Intrinsic::amdgcn_ds_fmax: { 6864 MemSDNode *M = cast<MemSDNode>(Op); 6865 unsigned Opc; 6866 switch (IntrID) { 6867 case Intrinsic::amdgcn_atomic_inc: 6868 Opc = AMDGPUISD::ATOMIC_INC; 6869 break; 6870 case Intrinsic::amdgcn_atomic_dec: 6871 Opc = AMDGPUISD::ATOMIC_DEC; 6872 break; 6873 case Intrinsic::amdgcn_ds_fmin: 6874 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6875 break; 6876 case Intrinsic::amdgcn_ds_fmax: 6877 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6878 break; 6879 default: 6880 llvm_unreachable("Unknown intrinsic!"); 6881 } 6882 SDValue Ops[] = { 6883 M->getOperand(0), // Chain 6884 M->getOperand(2), // Ptr 6885 M->getOperand(3) // Value 6886 }; 6887 6888 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6889 M->getMemoryVT(), M->getMemOperand()); 6890 } 6891 case Intrinsic::amdgcn_buffer_load: 6892 case Intrinsic::amdgcn_buffer_load_format: { 6893 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6894 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6895 unsigned IdxEn = 1; 6896 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6897 IdxEn = Idx->getZExtValue() != 0; 6898 SDValue Ops[] = { 6899 Op.getOperand(0), // Chain 6900 Op.getOperand(2), // rsrc 6901 Op.getOperand(3), // vindex 6902 SDValue(), // voffset -- will be set by setBufferOffsets 6903 SDValue(), // soffset -- will be set by setBufferOffsets 6904 SDValue(), // offset -- will be set by setBufferOffsets 6905 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6906 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6907 }; 6908 6909 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6910 // We don't know the offset if vindex is non-zero, so clear it. 6911 if (IdxEn) 6912 Offset = 0; 6913 6914 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6915 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6916 6917 EVT VT = Op.getValueType(); 6918 EVT IntVT = VT.changeTypeToInteger(); 6919 auto *M = cast<MemSDNode>(Op); 6920 M->getMemOperand()->setOffset(Offset); 6921 EVT LoadVT = Op.getValueType(); 6922 6923 if (LoadVT.getScalarType() == MVT::f16) 6924 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6925 M, DAG, Ops); 6926 6927 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6928 if (LoadVT.getScalarType() == MVT::i8 || 6929 LoadVT.getScalarType() == MVT::i16) 6930 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6931 6932 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6933 M->getMemOperand(), DAG); 6934 } 6935 case Intrinsic::amdgcn_raw_buffer_load: 6936 case Intrinsic::amdgcn_raw_buffer_load_format: { 6937 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6938 6939 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6940 SDValue Ops[] = { 6941 Op.getOperand(0), // Chain 6942 Op.getOperand(2), // rsrc 6943 DAG.getConstant(0, DL, MVT::i32), // vindex 6944 Offsets.first, // voffset 6945 Op.getOperand(4), // soffset 6946 Offsets.second, // offset 6947 Op.getOperand(5), // cachepolicy, swizzled buffer 6948 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6949 }; 6950 6951 auto *M = cast<MemSDNode>(Op); 6952 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6953 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6954 } 6955 case Intrinsic::amdgcn_struct_buffer_load: 6956 case Intrinsic::amdgcn_struct_buffer_load_format: { 6957 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6958 6959 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6960 SDValue Ops[] = { 6961 Op.getOperand(0), // Chain 6962 Op.getOperand(2), // rsrc 6963 Op.getOperand(3), // vindex 6964 Offsets.first, // voffset 6965 Op.getOperand(5), // soffset 6966 Offsets.second, // offset 6967 Op.getOperand(6), // cachepolicy, swizzled buffer 6968 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6969 }; 6970 6971 auto *M = cast<MemSDNode>(Op); 6972 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6973 Ops[2])); 6974 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6975 } 6976 case Intrinsic::amdgcn_tbuffer_load: { 6977 MemSDNode *M = cast<MemSDNode>(Op); 6978 EVT LoadVT = Op.getValueType(); 6979 6980 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6981 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6982 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6983 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6984 unsigned IdxEn = 1; 6985 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6986 IdxEn = Idx->getZExtValue() != 0; 6987 SDValue Ops[] = { 6988 Op.getOperand(0), // Chain 6989 Op.getOperand(2), // rsrc 6990 Op.getOperand(3), // vindex 6991 Op.getOperand(4), // voffset 6992 Op.getOperand(5), // soffset 6993 Op.getOperand(6), // offset 6994 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6995 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6996 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6997 }; 6998 6999 if (LoadVT.getScalarType() == MVT::f16) 7000 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7001 M, DAG, Ops); 7002 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7003 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7004 DAG); 7005 } 7006 case Intrinsic::amdgcn_raw_tbuffer_load: { 7007 MemSDNode *M = cast<MemSDNode>(Op); 7008 EVT LoadVT = Op.getValueType(); 7009 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7010 7011 SDValue Ops[] = { 7012 Op.getOperand(0), // Chain 7013 Op.getOperand(2), // rsrc 7014 DAG.getConstant(0, DL, MVT::i32), // vindex 7015 Offsets.first, // voffset 7016 Op.getOperand(4), // soffset 7017 Offsets.second, // offset 7018 Op.getOperand(5), // format 7019 Op.getOperand(6), // cachepolicy, swizzled buffer 7020 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7021 }; 7022 7023 if (LoadVT.getScalarType() == MVT::f16) 7024 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7025 M, DAG, Ops); 7026 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7027 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7028 DAG); 7029 } 7030 case Intrinsic::amdgcn_struct_tbuffer_load: { 7031 MemSDNode *M = cast<MemSDNode>(Op); 7032 EVT LoadVT = Op.getValueType(); 7033 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7034 7035 SDValue Ops[] = { 7036 Op.getOperand(0), // Chain 7037 Op.getOperand(2), // rsrc 7038 Op.getOperand(3), // vindex 7039 Offsets.first, // voffset 7040 Op.getOperand(5), // soffset 7041 Offsets.second, // offset 7042 Op.getOperand(6), // format 7043 Op.getOperand(7), // cachepolicy, swizzled buffer 7044 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7045 }; 7046 7047 if (LoadVT.getScalarType() == MVT::f16) 7048 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7049 M, DAG, Ops); 7050 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7051 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7052 DAG); 7053 } 7054 case Intrinsic::amdgcn_buffer_atomic_swap: 7055 case Intrinsic::amdgcn_buffer_atomic_add: 7056 case Intrinsic::amdgcn_buffer_atomic_sub: 7057 case Intrinsic::amdgcn_buffer_atomic_csub: 7058 case Intrinsic::amdgcn_buffer_atomic_smin: 7059 case Intrinsic::amdgcn_buffer_atomic_umin: 7060 case Intrinsic::amdgcn_buffer_atomic_smax: 7061 case Intrinsic::amdgcn_buffer_atomic_umax: 7062 case Intrinsic::amdgcn_buffer_atomic_and: 7063 case Intrinsic::amdgcn_buffer_atomic_or: 7064 case Intrinsic::amdgcn_buffer_atomic_xor: 7065 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7066 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7067 unsigned IdxEn = 1; 7068 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7069 IdxEn = Idx->getZExtValue() != 0; 7070 SDValue Ops[] = { 7071 Op.getOperand(0), // Chain 7072 Op.getOperand(2), // vdata 7073 Op.getOperand(3), // rsrc 7074 Op.getOperand(4), // vindex 7075 SDValue(), // voffset -- will be set by setBufferOffsets 7076 SDValue(), // soffset -- will be set by setBufferOffsets 7077 SDValue(), // offset -- will be set by setBufferOffsets 7078 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7079 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7080 }; 7081 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7082 // We don't know the offset if vindex is non-zero, so clear it. 7083 if (IdxEn) 7084 Offset = 0; 7085 EVT VT = Op.getValueType(); 7086 7087 auto *M = cast<MemSDNode>(Op); 7088 M->getMemOperand()->setOffset(Offset); 7089 unsigned Opcode = 0; 7090 7091 switch (IntrID) { 7092 case Intrinsic::amdgcn_buffer_atomic_swap: 7093 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7094 break; 7095 case Intrinsic::amdgcn_buffer_atomic_add: 7096 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7097 break; 7098 case Intrinsic::amdgcn_buffer_atomic_sub: 7099 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7100 break; 7101 case Intrinsic::amdgcn_buffer_atomic_csub: 7102 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7103 break; 7104 case Intrinsic::amdgcn_buffer_atomic_smin: 7105 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7106 break; 7107 case Intrinsic::amdgcn_buffer_atomic_umin: 7108 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7109 break; 7110 case Intrinsic::amdgcn_buffer_atomic_smax: 7111 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7112 break; 7113 case Intrinsic::amdgcn_buffer_atomic_umax: 7114 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7115 break; 7116 case Intrinsic::amdgcn_buffer_atomic_and: 7117 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7118 break; 7119 case Intrinsic::amdgcn_buffer_atomic_or: 7120 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7121 break; 7122 case Intrinsic::amdgcn_buffer_atomic_xor: 7123 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7124 break; 7125 case Intrinsic::amdgcn_buffer_atomic_fadd: 7126 if (!Op.getValue(0).use_empty()) { 7127 DiagnosticInfoUnsupported 7128 NoFpRet(DAG.getMachineFunction().getFunction(), 7129 "return versions of fp atomics not supported", 7130 DL.getDebugLoc(), DS_Error); 7131 DAG.getContext()->diagnose(NoFpRet); 7132 return SDValue(); 7133 } 7134 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7135 break; 7136 default: 7137 llvm_unreachable("unhandled atomic opcode"); 7138 } 7139 7140 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7141 M->getMemOperand()); 7142 } 7143 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7144 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7145 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7146 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7147 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7148 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7149 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7150 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7151 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7152 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7153 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7154 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7155 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7156 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7157 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7158 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7159 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7160 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7161 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7162 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7163 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7164 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7165 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7166 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7167 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7168 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7169 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7170 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7171 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7172 return lowerStructBufferAtomicIntrin(Op, DAG, 7173 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7174 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7175 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7176 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7177 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7178 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7179 return lowerStructBufferAtomicIntrin(Op, DAG, 7180 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7181 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7182 return lowerStructBufferAtomicIntrin(Op, DAG, 7183 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7184 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7185 return lowerStructBufferAtomicIntrin(Op, DAG, 7186 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7187 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7188 return lowerStructBufferAtomicIntrin(Op, DAG, 7189 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7190 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7191 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7192 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7193 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7194 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7195 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7196 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7197 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7198 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7199 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7200 7201 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7202 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7203 unsigned IdxEn = 1; 7204 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7205 IdxEn = Idx->getZExtValue() != 0; 7206 SDValue Ops[] = { 7207 Op.getOperand(0), // Chain 7208 Op.getOperand(2), // src 7209 Op.getOperand(3), // cmp 7210 Op.getOperand(4), // rsrc 7211 Op.getOperand(5), // vindex 7212 SDValue(), // voffset -- will be set by setBufferOffsets 7213 SDValue(), // soffset -- will be set by setBufferOffsets 7214 SDValue(), // offset -- will be set by setBufferOffsets 7215 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7216 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7217 }; 7218 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7219 // We don't know the offset if vindex is non-zero, so clear it. 7220 if (IdxEn) 7221 Offset = 0; 7222 EVT VT = Op.getValueType(); 7223 auto *M = cast<MemSDNode>(Op); 7224 M->getMemOperand()->setOffset(Offset); 7225 7226 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7227 Op->getVTList(), Ops, VT, M->getMemOperand()); 7228 } 7229 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7230 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7231 SDValue Ops[] = { 7232 Op.getOperand(0), // Chain 7233 Op.getOperand(2), // src 7234 Op.getOperand(3), // cmp 7235 Op.getOperand(4), // rsrc 7236 DAG.getConstant(0, DL, MVT::i32), // vindex 7237 Offsets.first, // voffset 7238 Op.getOperand(6), // soffset 7239 Offsets.second, // offset 7240 Op.getOperand(7), // cachepolicy 7241 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7242 }; 7243 EVT VT = Op.getValueType(); 7244 auto *M = cast<MemSDNode>(Op); 7245 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7246 7247 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7248 Op->getVTList(), Ops, VT, M->getMemOperand()); 7249 } 7250 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7251 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7252 SDValue Ops[] = { 7253 Op.getOperand(0), // Chain 7254 Op.getOperand(2), // src 7255 Op.getOperand(3), // cmp 7256 Op.getOperand(4), // rsrc 7257 Op.getOperand(5), // vindex 7258 Offsets.first, // voffset 7259 Op.getOperand(7), // soffset 7260 Offsets.second, // offset 7261 Op.getOperand(8), // cachepolicy 7262 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7263 }; 7264 EVT VT = Op.getValueType(); 7265 auto *M = cast<MemSDNode>(Op); 7266 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7267 Ops[4])); 7268 7269 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7270 Op->getVTList(), Ops, VT, M->getMemOperand()); 7271 } 7272 case Intrinsic::amdgcn_global_atomic_fadd: { 7273 if (!Op.getValue(0).use_empty()) { 7274 DiagnosticInfoUnsupported 7275 NoFpRet(DAG.getMachineFunction().getFunction(), 7276 "return versions of fp atomics not supported", 7277 DL.getDebugLoc(), DS_Error); 7278 DAG.getContext()->diagnose(NoFpRet); 7279 return SDValue(); 7280 } 7281 MemSDNode *M = cast<MemSDNode>(Op); 7282 SDValue Ops[] = { 7283 M->getOperand(0), // Chain 7284 M->getOperand(2), // Ptr 7285 M->getOperand(3) // Value 7286 }; 7287 7288 EVT VT = Op.getOperand(3).getValueType(); 7289 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7290 DAG.getVTList(VT, MVT::Other), Ops, 7291 M->getMemOperand()); 7292 } 7293 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7294 SDLoc DL(Op); 7295 MemSDNode *M = cast<MemSDNode>(Op); 7296 SDValue NodePtr = M->getOperand(2); 7297 SDValue RayExtent = M->getOperand(3); 7298 SDValue RayOrigin = M->getOperand(4); 7299 SDValue RayDir = M->getOperand(5); 7300 SDValue RayInvDir = M->getOperand(6); 7301 SDValue TDescr = M->getOperand(7); 7302 7303 assert(NodePtr.getValueType() == MVT::i32 || 7304 NodePtr.getValueType() == MVT::i64); 7305 assert(RayDir.getValueType() == MVT::v4f16 || 7306 RayDir.getValueType() == MVT::v4f32); 7307 7308 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7309 bool Is64 = NodePtr.getValueType() == MVT::i64; 7310 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7311 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7312 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7313 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7314 7315 SmallVector<SDValue, 16> Ops; 7316 7317 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7318 SmallVector<SDValue, 3> Lanes; 7319 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7320 if (Lanes[0].getValueSizeInBits() == 32) { 7321 for (unsigned I = 0; I < 3; ++I) 7322 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7323 } else { 7324 if (IsAligned) { 7325 Ops.push_back( 7326 DAG.getBitcast(MVT::i32, 7327 DAG.getBuildVector(MVT::v2f16, DL, 7328 { Lanes[0], Lanes[1] }))); 7329 Ops.push_back(Lanes[2]); 7330 } else { 7331 SDValue Elt0 = Ops.pop_back_val(); 7332 Ops.push_back( 7333 DAG.getBitcast(MVT::i32, 7334 DAG.getBuildVector(MVT::v2f16, DL, 7335 { Elt0, Lanes[0] }))); 7336 Ops.push_back( 7337 DAG.getBitcast(MVT::i32, 7338 DAG.getBuildVector(MVT::v2f16, DL, 7339 { Lanes[1], Lanes[2] }))); 7340 } 7341 } 7342 }; 7343 7344 if (Is64) 7345 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7346 else 7347 Ops.push_back(NodePtr); 7348 7349 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7350 packLanes(RayOrigin, true); 7351 packLanes(RayDir, true); 7352 packLanes(RayInvDir, false); 7353 Ops.push_back(TDescr); 7354 if (IsA16) 7355 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7356 Ops.push_back(M->getChain()); 7357 7358 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7359 MachineMemOperand *MemRef = M->getMemOperand(); 7360 DAG.setNodeMemRefs(NewNode, {MemRef}); 7361 return SDValue(NewNode, 0); 7362 } 7363 default: 7364 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7365 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7366 return lowerImage(Op, ImageDimIntr, DAG, true); 7367 7368 return SDValue(); 7369 } 7370 } 7371 7372 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7373 // dwordx4 if on SI. 7374 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7375 SDVTList VTList, 7376 ArrayRef<SDValue> Ops, EVT MemVT, 7377 MachineMemOperand *MMO, 7378 SelectionDAG &DAG) const { 7379 EVT VT = VTList.VTs[0]; 7380 EVT WidenedVT = VT; 7381 EVT WidenedMemVT = MemVT; 7382 if (!Subtarget->hasDwordx3LoadStores() && 7383 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7384 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7385 WidenedVT.getVectorElementType(), 4); 7386 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7387 WidenedMemVT.getVectorElementType(), 4); 7388 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7389 } 7390 7391 assert(VTList.NumVTs == 2); 7392 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7393 7394 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7395 WidenedMemVT, MMO); 7396 if (WidenedVT != VT) { 7397 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7398 DAG.getVectorIdxConstant(0, DL)); 7399 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7400 } 7401 return NewOp; 7402 } 7403 7404 SDValue SITargetLowering::handleD16VData(SDValue VData, 7405 SelectionDAG &DAG) const { 7406 EVT StoreVT = VData.getValueType(); 7407 7408 // No change for f16 and legal vector D16 types. 7409 if (!StoreVT.isVector()) 7410 return VData; 7411 7412 SDLoc DL(VData); 7413 unsigned NumElements = StoreVT.getVectorNumElements(); 7414 7415 if (Subtarget->hasUnpackedD16VMem()) { 7416 // We need to unpack the packed data to store. 7417 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7418 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7419 7420 EVT EquivStoreVT = 7421 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7422 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7423 return DAG.UnrollVectorOp(ZExt.getNode()); 7424 } else if (NumElements == 3) { 7425 EVT IntStoreVT = 7426 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7427 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7428 7429 EVT WidenedStoreVT = EVT::getVectorVT( 7430 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7431 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7432 WidenedStoreVT.getStoreSizeInBits()); 7433 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7434 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7435 } 7436 7437 assert(isTypeLegal(StoreVT)); 7438 return VData; 7439 } 7440 7441 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7442 SelectionDAG &DAG) const { 7443 SDLoc DL(Op); 7444 SDValue Chain = Op.getOperand(0); 7445 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7446 MachineFunction &MF = DAG.getMachineFunction(); 7447 7448 switch (IntrinsicID) { 7449 case Intrinsic::amdgcn_exp_compr: { 7450 SDValue Src0 = Op.getOperand(4); 7451 SDValue Src1 = Op.getOperand(5); 7452 // Hack around illegal type on SI by directly selecting it. 7453 if (isTypeLegal(Src0.getValueType())) 7454 return SDValue(); 7455 7456 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7457 SDValue Undef = DAG.getUNDEF(MVT::f32); 7458 const SDValue Ops[] = { 7459 Op.getOperand(2), // tgt 7460 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7461 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7462 Undef, // src2 7463 Undef, // src3 7464 Op.getOperand(7), // vm 7465 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7466 Op.getOperand(3), // en 7467 Op.getOperand(0) // Chain 7468 }; 7469 7470 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7471 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7472 } 7473 case Intrinsic::amdgcn_s_barrier: { 7474 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7475 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7476 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7477 if (WGSize <= ST.getWavefrontSize()) 7478 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7479 Op.getOperand(0)), 0); 7480 } 7481 return SDValue(); 7482 }; 7483 case Intrinsic::amdgcn_tbuffer_store: { 7484 SDValue VData = Op.getOperand(2); 7485 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7486 if (IsD16) 7487 VData = handleD16VData(VData, DAG); 7488 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7489 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7490 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7491 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7492 unsigned IdxEn = 1; 7493 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7494 IdxEn = Idx->getZExtValue() != 0; 7495 SDValue Ops[] = { 7496 Chain, 7497 VData, // vdata 7498 Op.getOperand(3), // rsrc 7499 Op.getOperand(4), // vindex 7500 Op.getOperand(5), // voffset 7501 Op.getOperand(6), // soffset 7502 Op.getOperand(7), // offset 7503 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7504 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7505 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7506 }; 7507 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7508 AMDGPUISD::TBUFFER_STORE_FORMAT; 7509 MemSDNode *M = cast<MemSDNode>(Op); 7510 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7511 M->getMemoryVT(), M->getMemOperand()); 7512 } 7513 7514 case Intrinsic::amdgcn_struct_tbuffer_store: { 7515 SDValue VData = Op.getOperand(2); 7516 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7517 if (IsD16) 7518 VData = handleD16VData(VData, DAG); 7519 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7520 SDValue Ops[] = { 7521 Chain, 7522 VData, // vdata 7523 Op.getOperand(3), // rsrc 7524 Op.getOperand(4), // vindex 7525 Offsets.first, // voffset 7526 Op.getOperand(6), // soffset 7527 Offsets.second, // offset 7528 Op.getOperand(7), // format 7529 Op.getOperand(8), // cachepolicy, swizzled buffer 7530 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7531 }; 7532 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7533 AMDGPUISD::TBUFFER_STORE_FORMAT; 7534 MemSDNode *M = cast<MemSDNode>(Op); 7535 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7536 M->getMemoryVT(), M->getMemOperand()); 7537 } 7538 7539 case Intrinsic::amdgcn_raw_tbuffer_store: { 7540 SDValue VData = Op.getOperand(2); 7541 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7542 if (IsD16) 7543 VData = handleD16VData(VData, DAG); 7544 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7545 SDValue Ops[] = { 7546 Chain, 7547 VData, // vdata 7548 Op.getOperand(3), // rsrc 7549 DAG.getConstant(0, DL, MVT::i32), // vindex 7550 Offsets.first, // voffset 7551 Op.getOperand(5), // soffset 7552 Offsets.second, // offset 7553 Op.getOperand(6), // format 7554 Op.getOperand(7), // cachepolicy, swizzled buffer 7555 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7556 }; 7557 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7558 AMDGPUISD::TBUFFER_STORE_FORMAT; 7559 MemSDNode *M = cast<MemSDNode>(Op); 7560 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7561 M->getMemoryVT(), M->getMemOperand()); 7562 } 7563 7564 case Intrinsic::amdgcn_buffer_store: 7565 case Intrinsic::amdgcn_buffer_store_format: { 7566 SDValue VData = Op.getOperand(2); 7567 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7568 if (IsD16) 7569 VData = handleD16VData(VData, DAG); 7570 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7571 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7572 unsigned IdxEn = 1; 7573 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7574 IdxEn = Idx->getZExtValue() != 0; 7575 SDValue Ops[] = { 7576 Chain, 7577 VData, 7578 Op.getOperand(3), // rsrc 7579 Op.getOperand(4), // vindex 7580 SDValue(), // voffset -- will be set by setBufferOffsets 7581 SDValue(), // soffset -- will be set by setBufferOffsets 7582 SDValue(), // offset -- will be set by setBufferOffsets 7583 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7584 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7585 }; 7586 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7587 // We don't know the offset if vindex is non-zero, so clear it. 7588 if (IdxEn) 7589 Offset = 0; 7590 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7591 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7592 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7593 MemSDNode *M = cast<MemSDNode>(Op); 7594 M->getMemOperand()->setOffset(Offset); 7595 7596 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7597 EVT VDataType = VData.getValueType().getScalarType(); 7598 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7599 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7600 7601 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7602 M->getMemoryVT(), M->getMemOperand()); 7603 } 7604 7605 case Intrinsic::amdgcn_raw_buffer_store: 7606 case Intrinsic::amdgcn_raw_buffer_store_format: { 7607 const bool IsFormat = 7608 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7609 7610 SDValue VData = Op.getOperand(2); 7611 EVT VDataVT = VData.getValueType(); 7612 EVT EltType = VDataVT.getScalarType(); 7613 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7614 if (IsD16) { 7615 VData = handleD16VData(VData, DAG); 7616 VDataVT = VData.getValueType(); 7617 } 7618 7619 if (!isTypeLegal(VDataVT)) { 7620 VData = 7621 DAG.getNode(ISD::BITCAST, DL, 7622 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7623 } 7624 7625 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7626 SDValue Ops[] = { 7627 Chain, 7628 VData, 7629 Op.getOperand(3), // rsrc 7630 DAG.getConstant(0, DL, MVT::i32), // vindex 7631 Offsets.first, // voffset 7632 Op.getOperand(5), // soffset 7633 Offsets.second, // offset 7634 Op.getOperand(6), // cachepolicy, swizzled buffer 7635 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7636 }; 7637 unsigned Opc = 7638 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7639 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7640 MemSDNode *M = cast<MemSDNode>(Op); 7641 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7642 7643 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7644 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7645 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7646 7647 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7648 M->getMemoryVT(), M->getMemOperand()); 7649 } 7650 7651 case Intrinsic::amdgcn_struct_buffer_store: 7652 case Intrinsic::amdgcn_struct_buffer_store_format: { 7653 const bool IsFormat = 7654 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7655 7656 SDValue VData = Op.getOperand(2); 7657 EVT VDataVT = VData.getValueType(); 7658 EVT EltType = VDataVT.getScalarType(); 7659 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7660 7661 if (IsD16) { 7662 VData = handleD16VData(VData, DAG); 7663 VDataVT = VData.getValueType(); 7664 } 7665 7666 if (!isTypeLegal(VDataVT)) { 7667 VData = 7668 DAG.getNode(ISD::BITCAST, DL, 7669 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7670 } 7671 7672 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7673 SDValue Ops[] = { 7674 Chain, 7675 VData, 7676 Op.getOperand(3), // rsrc 7677 Op.getOperand(4), // vindex 7678 Offsets.first, // voffset 7679 Op.getOperand(6), // soffset 7680 Offsets.second, // offset 7681 Op.getOperand(7), // cachepolicy, swizzled buffer 7682 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7683 }; 7684 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7685 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7686 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7687 MemSDNode *M = cast<MemSDNode>(Op); 7688 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7689 Ops[3])); 7690 7691 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7692 EVT VDataType = VData.getValueType().getScalarType(); 7693 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7694 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7695 7696 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7697 M->getMemoryVT(), M->getMemOperand()); 7698 } 7699 case Intrinsic::amdgcn_end_cf: 7700 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7701 Op->getOperand(2), Chain), 0); 7702 7703 default: { 7704 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7705 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7706 return lowerImage(Op, ImageDimIntr, DAG, true); 7707 7708 return Op; 7709 } 7710 } 7711 } 7712 7713 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7714 // offset (the offset that is included in bounds checking and swizzling, to be 7715 // split between the instruction's voffset and immoffset fields) and soffset 7716 // (the offset that is excluded from bounds checking and swizzling, to go in 7717 // the instruction's soffset field). This function takes the first kind of 7718 // offset and figures out how to split it between voffset and immoffset. 7719 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7720 SDValue Offset, SelectionDAG &DAG) const { 7721 SDLoc DL(Offset); 7722 const unsigned MaxImm = 4095; 7723 SDValue N0 = Offset; 7724 ConstantSDNode *C1 = nullptr; 7725 7726 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7727 N0 = SDValue(); 7728 else if (DAG.isBaseWithConstantOffset(N0)) { 7729 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7730 N0 = N0.getOperand(0); 7731 } 7732 7733 if (C1) { 7734 unsigned ImmOffset = C1->getZExtValue(); 7735 // If the immediate value is too big for the immoffset field, put the value 7736 // and -4096 into the immoffset field so that the value that is copied/added 7737 // for the voffset field is a multiple of 4096, and it stands more chance 7738 // of being CSEd with the copy/add for another similar load/store. 7739 // However, do not do that rounding down to a multiple of 4096 if that is a 7740 // negative number, as it appears to be illegal to have a negative offset 7741 // in the vgpr, even if adding the immediate offset makes it positive. 7742 unsigned Overflow = ImmOffset & ~MaxImm; 7743 ImmOffset -= Overflow; 7744 if ((int32_t)Overflow < 0) { 7745 Overflow += ImmOffset; 7746 ImmOffset = 0; 7747 } 7748 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7749 if (Overflow) { 7750 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7751 if (!N0) 7752 N0 = OverflowVal; 7753 else { 7754 SDValue Ops[] = { N0, OverflowVal }; 7755 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7756 } 7757 } 7758 } 7759 if (!N0) 7760 N0 = DAG.getConstant(0, DL, MVT::i32); 7761 if (!C1) 7762 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7763 return {N0, SDValue(C1, 0)}; 7764 } 7765 7766 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7767 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7768 // pointed to by Offsets. 7769 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7770 SelectionDAG &DAG, SDValue *Offsets, 7771 Align Alignment) const { 7772 SDLoc DL(CombinedOffset); 7773 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7774 uint32_t Imm = C->getZExtValue(); 7775 uint32_t SOffset, ImmOffset; 7776 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7777 Alignment)) { 7778 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7779 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7780 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7781 return SOffset + ImmOffset; 7782 } 7783 } 7784 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7785 SDValue N0 = CombinedOffset.getOperand(0); 7786 SDValue N1 = CombinedOffset.getOperand(1); 7787 uint32_t SOffset, ImmOffset; 7788 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7789 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7790 Subtarget, Alignment)) { 7791 Offsets[0] = N0; 7792 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7793 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7794 return 0; 7795 } 7796 } 7797 Offsets[0] = CombinedOffset; 7798 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7799 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7800 return 0; 7801 } 7802 7803 // Handle 8 bit and 16 bit buffer loads 7804 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7805 EVT LoadVT, SDLoc DL, 7806 ArrayRef<SDValue> Ops, 7807 MemSDNode *M) const { 7808 EVT IntVT = LoadVT.changeTypeToInteger(); 7809 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7810 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7811 7812 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7813 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7814 Ops, IntVT, 7815 M->getMemOperand()); 7816 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7817 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7818 7819 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7820 } 7821 7822 // Handle 8 bit and 16 bit buffer stores 7823 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7824 EVT VDataType, SDLoc DL, 7825 SDValue Ops[], 7826 MemSDNode *M) const { 7827 if (VDataType == MVT::f16) 7828 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7829 7830 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7831 Ops[1] = BufferStoreExt; 7832 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7833 AMDGPUISD::BUFFER_STORE_SHORT; 7834 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7835 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7836 M->getMemOperand()); 7837 } 7838 7839 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7840 ISD::LoadExtType ExtType, SDValue Op, 7841 const SDLoc &SL, EVT VT) { 7842 if (VT.bitsLT(Op.getValueType())) 7843 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7844 7845 switch (ExtType) { 7846 case ISD::SEXTLOAD: 7847 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7848 case ISD::ZEXTLOAD: 7849 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7850 case ISD::EXTLOAD: 7851 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7852 case ISD::NON_EXTLOAD: 7853 return Op; 7854 } 7855 7856 llvm_unreachable("invalid ext type"); 7857 } 7858 7859 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7860 SelectionDAG &DAG = DCI.DAG; 7861 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7862 return SDValue(); 7863 7864 // FIXME: Constant loads should all be marked invariant. 7865 unsigned AS = Ld->getAddressSpace(); 7866 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7867 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7868 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7869 return SDValue(); 7870 7871 // Don't do this early, since it may interfere with adjacent load merging for 7872 // illegal types. We can avoid losing alignment information for exotic types 7873 // pre-legalize. 7874 EVT MemVT = Ld->getMemoryVT(); 7875 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7876 MemVT.getSizeInBits() >= 32) 7877 return SDValue(); 7878 7879 SDLoc SL(Ld); 7880 7881 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7882 "unexpected vector extload"); 7883 7884 // TODO: Drop only high part of range. 7885 SDValue Ptr = Ld->getBasePtr(); 7886 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7887 MVT::i32, SL, Ld->getChain(), Ptr, 7888 Ld->getOffset(), 7889 Ld->getPointerInfo(), MVT::i32, 7890 Ld->getAlignment(), 7891 Ld->getMemOperand()->getFlags(), 7892 Ld->getAAInfo(), 7893 nullptr); // Drop ranges 7894 7895 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7896 if (MemVT.isFloatingPoint()) { 7897 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7898 "unexpected fp extload"); 7899 TruncVT = MemVT.changeTypeToInteger(); 7900 } 7901 7902 SDValue Cvt = NewLoad; 7903 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7904 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7905 DAG.getValueType(TruncVT)); 7906 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7907 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7908 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7909 } else { 7910 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7911 } 7912 7913 EVT VT = Ld->getValueType(0); 7914 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7915 7916 DCI.AddToWorklist(Cvt.getNode()); 7917 7918 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7919 // the appropriate extension from the 32-bit load. 7920 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7921 DCI.AddToWorklist(Cvt.getNode()); 7922 7923 // Handle conversion back to floating point if necessary. 7924 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7925 7926 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7927 } 7928 7929 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7930 SDLoc DL(Op); 7931 LoadSDNode *Load = cast<LoadSDNode>(Op); 7932 ISD::LoadExtType ExtType = Load->getExtensionType(); 7933 EVT MemVT = Load->getMemoryVT(); 7934 7935 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7936 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7937 return SDValue(); 7938 7939 // FIXME: Copied from PPC 7940 // First, load into 32 bits, then truncate to 1 bit. 7941 7942 SDValue Chain = Load->getChain(); 7943 SDValue BasePtr = Load->getBasePtr(); 7944 MachineMemOperand *MMO = Load->getMemOperand(); 7945 7946 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7947 7948 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7949 BasePtr, RealMemVT, MMO); 7950 7951 if (!MemVT.isVector()) { 7952 SDValue Ops[] = { 7953 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7954 NewLD.getValue(1) 7955 }; 7956 7957 return DAG.getMergeValues(Ops, DL); 7958 } 7959 7960 SmallVector<SDValue, 3> Elts; 7961 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7962 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7963 DAG.getConstant(I, DL, MVT::i32)); 7964 7965 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7966 } 7967 7968 SDValue Ops[] = { 7969 DAG.getBuildVector(MemVT, DL, Elts), 7970 NewLD.getValue(1) 7971 }; 7972 7973 return DAG.getMergeValues(Ops, DL); 7974 } 7975 7976 if (!MemVT.isVector()) 7977 return SDValue(); 7978 7979 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7980 "Custom lowering for non-i32 vectors hasn't been implemented."); 7981 7982 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7983 MemVT, *Load->getMemOperand())) { 7984 SDValue Ops[2]; 7985 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7986 return DAG.getMergeValues(Ops, DL); 7987 } 7988 7989 unsigned Alignment = Load->getAlignment(); 7990 unsigned AS = Load->getAddressSpace(); 7991 if (Subtarget->hasLDSMisalignedBug() && 7992 AS == AMDGPUAS::FLAT_ADDRESS && 7993 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7994 return SplitVectorLoad(Op, DAG); 7995 } 7996 7997 MachineFunction &MF = DAG.getMachineFunction(); 7998 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7999 // If there is a possibilty that flat instruction access scratch memory 8000 // then we need to use the same legalization rules we use for private. 8001 if (AS == AMDGPUAS::FLAT_ADDRESS && 8002 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8003 AS = MFI->hasFlatScratchInit() ? 8004 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8005 8006 unsigned NumElements = MemVT.getVectorNumElements(); 8007 8008 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8009 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8010 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8011 if (MemVT.isPow2VectorType()) 8012 return SDValue(); 8013 if (NumElements == 3) 8014 return WidenVectorLoad(Op, DAG); 8015 return SplitVectorLoad(Op, DAG); 8016 } 8017 // Non-uniform loads will be selected to MUBUF instructions, so they 8018 // have the same legalization requirements as global and private 8019 // loads. 8020 // 8021 } 8022 8023 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8024 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8025 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8026 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8027 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8028 Alignment >= 4 && NumElements < 32) { 8029 if (MemVT.isPow2VectorType()) 8030 return SDValue(); 8031 if (NumElements == 3) 8032 return WidenVectorLoad(Op, DAG); 8033 return SplitVectorLoad(Op, DAG); 8034 } 8035 // Non-uniform loads will be selected to MUBUF instructions, so they 8036 // have the same legalization requirements as global and private 8037 // loads. 8038 // 8039 } 8040 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8041 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8042 AS == AMDGPUAS::GLOBAL_ADDRESS || 8043 AS == AMDGPUAS::FLAT_ADDRESS) { 8044 if (NumElements > 4) 8045 return SplitVectorLoad(Op, DAG); 8046 // v3 loads not supported on SI. 8047 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8048 return WidenVectorLoad(Op, DAG); 8049 // v3 and v4 loads are supported for private and global memory. 8050 return SDValue(); 8051 } 8052 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8053 // Depending on the setting of the private_element_size field in the 8054 // resource descriptor, we can only make private accesses up to a certain 8055 // size. 8056 switch (Subtarget->getMaxPrivateElementSize()) { 8057 case 4: { 8058 SDValue Ops[2]; 8059 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8060 return DAG.getMergeValues(Ops, DL); 8061 } 8062 case 8: 8063 if (NumElements > 2) 8064 return SplitVectorLoad(Op, DAG); 8065 return SDValue(); 8066 case 16: 8067 // Same as global/flat 8068 if (NumElements > 4) 8069 return SplitVectorLoad(Op, DAG); 8070 // v3 loads not supported on SI. 8071 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8072 return WidenVectorLoad(Op, DAG); 8073 return SDValue(); 8074 default: 8075 llvm_unreachable("unsupported private_element_size"); 8076 } 8077 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8078 // Use ds_read_b128 or ds_read_b96 when possible. 8079 if (Subtarget->hasDS96AndDS128() && 8080 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8081 MemVT.getStoreSize() == 12) && 8082 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8083 Load->getAlign())) 8084 return SDValue(); 8085 8086 if (NumElements > 2) 8087 return SplitVectorLoad(Op, DAG); 8088 8089 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8090 // address is negative, then the instruction is incorrectly treated as 8091 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8092 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8093 // load later in the SILoadStoreOptimizer. 8094 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8095 NumElements == 2 && MemVT.getStoreSize() == 8 && 8096 Load->getAlignment() < 8) { 8097 return SplitVectorLoad(Op, DAG); 8098 } 8099 } 8100 return SDValue(); 8101 } 8102 8103 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8104 EVT VT = Op.getValueType(); 8105 assert(VT.getSizeInBits() == 64); 8106 8107 SDLoc DL(Op); 8108 SDValue Cond = Op.getOperand(0); 8109 8110 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8111 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8112 8113 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8114 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8115 8116 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8117 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8118 8119 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8120 8121 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8122 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8123 8124 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8125 8126 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8127 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8128 } 8129 8130 // Catch division cases where we can use shortcuts with rcp and rsq 8131 // instructions. 8132 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8133 SelectionDAG &DAG) const { 8134 SDLoc SL(Op); 8135 SDValue LHS = Op.getOperand(0); 8136 SDValue RHS = Op.getOperand(1); 8137 EVT VT = Op.getValueType(); 8138 const SDNodeFlags Flags = Op->getFlags(); 8139 8140 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8141 Flags.hasApproximateFuncs(); 8142 8143 // Without !fpmath accuracy information, we can't do more because we don't 8144 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8145 if (!AllowInaccurateRcp) 8146 return SDValue(); 8147 8148 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8149 if (CLHS->isExactlyValue(1.0)) { 8150 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8151 // the CI documentation has a worst case error of 1 ulp. 8152 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8153 // use it as long as we aren't trying to use denormals. 8154 // 8155 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8156 8157 // 1.0 / sqrt(x) -> rsq(x) 8158 8159 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8160 // error seems really high at 2^29 ULP. 8161 if (RHS.getOpcode() == ISD::FSQRT) 8162 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8163 8164 // 1.0 / x -> rcp(x) 8165 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8166 } 8167 8168 // Same as for 1.0, but expand the sign out of the constant. 8169 if (CLHS->isExactlyValue(-1.0)) { 8170 // -1.0 / x -> rcp (fneg x) 8171 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8172 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8173 } 8174 } 8175 8176 // Turn into multiply by the reciprocal. 8177 // x / y -> x * (1.0 / y) 8178 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8179 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8180 } 8181 8182 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8183 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8184 SDNodeFlags Flags) { 8185 if (GlueChain->getNumValues() <= 1) { 8186 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8187 } 8188 8189 assert(GlueChain->getNumValues() == 3); 8190 8191 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8192 switch (Opcode) { 8193 default: llvm_unreachable("no chain equivalent for opcode"); 8194 case ISD::FMUL: 8195 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8196 break; 8197 } 8198 8199 return DAG.getNode(Opcode, SL, VTList, 8200 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8201 Flags); 8202 } 8203 8204 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8205 EVT VT, SDValue A, SDValue B, SDValue C, 8206 SDValue GlueChain, SDNodeFlags Flags) { 8207 if (GlueChain->getNumValues() <= 1) { 8208 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8209 } 8210 8211 assert(GlueChain->getNumValues() == 3); 8212 8213 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8214 switch (Opcode) { 8215 default: llvm_unreachable("no chain equivalent for opcode"); 8216 case ISD::FMA: 8217 Opcode = AMDGPUISD::FMA_W_CHAIN; 8218 break; 8219 } 8220 8221 return DAG.getNode(Opcode, SL, VTList, 8222 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8223 Flags); 8224 } 8225 8226 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8227 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8228 return FastLowered; 8229 8230 SDLoc SL(Op); 8231 SDValue Src0 = Op.getOperand(0); 8232 SDValue Src1 = Op.getOperand(1); 8233 8234 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8235 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8236 8237 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8238 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8239 8240 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8241 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8242 8243 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8244 } 8245 8246 // Faster 2.5 ULP division that does not support denormals. 8247 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8248 SDLoc SL(Op); 8249 SDValue LHS = Op.getOperand(1); 8250 SDValue RHS = Op.getOperand(2); 8251 8252 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8253 8254 const APFloat K0Val(BitsToFloat(0x6f800000)); 8255 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8256 8257 const APFloat K1Val(BitsToFloat(0x2f800000)); 8258 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8259 8260 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8261 8262 EVT SetCCVT = 8263 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8264 8265 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8266 8267 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8268 8269 // TODO: Should this propagate fast-math-flags? 8270 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8271 8272 // rcp does not support denormals. 8273 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8274 8275 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8276 8277 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8278 } 8279 8280 // Returns immediate value for setting the F32 denorm mode when using the 8281 // S_DENORM_MODE instruction. 8282 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8283 const SDLoc &SL, const GCNSubtarget *ST) { 8284 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8285 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8286 ? FP_DENORM_FLUSH_NONE 8287 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8288 8289 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8290 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8291 } 8292 8293 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8294 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8295 return FastLowered; 8296 8297 // The selection matcher assumes anything with a chain selecting to a 8298 // mayRaiseFPException machine instruction. Since we're introducing a chain 8299 // here, we need to explicitly report nofpexcept for the regular fdiv 8300 // lowering. 8301 SDNodeFlags Flags = Op->getFlags(); 8302 Flags.setNoFPExcept(true); 8303 8304 SDLoc SL(Op); 8305 SDValue LHS = Op.getOperand(0); 8306 SDValue RHS = Op.getOperand(1); 8307 8308 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8309 8310 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8311 8312 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8313 {RHS, RHS, LHS}, Flags); 8314 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8315 {LHS, RHS, LHS}, Flags); 8316 8317 // Denominator is scaled to not be denormal, so using rcp is ok. 8318 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8319 DenominatorScaled, Flags); 8320 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8321 DenominatorScaled, Flags); 8322 8323 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8324 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8325 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8326 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8327 8328 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8329 8330 if (!HasFP32Denormals) { 8331 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8332 // lowering. The chain dependence is insufficient, and we need glue. We do 8333 // not need the glue variants in a strictfp function. 8334 8335 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8336 8337 SDNode *EnableDenorm; 8338 if (Subtarget->hasDenormModeInst()) { 8339 const SDValue EnableDenormValue = 8340 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8341 8342 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8343 DAG.getEntryNode(), EnableDenormValue).getNode(); 8344 } else { 8345 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8346 SL, MVT::i32); 8347 EnableDenorm = 8348 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8349 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8350 } 8351 8352 SDValue Ops[3] = { 8353 NegDivScale0, 8354 SDValue(EnableDenorm, 0), 8355 SDValue(EnableDenorm, 1) 8356 }; 8357 8358 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8359 } 8360 8361 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8362 ApproxRcp, One, NegDivScale0, Flags); 8363 8364 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8365 ApproxRcp, Fma0, Flags); 8366 8367 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8368 Fma1, Fma1, Flags); 8369 8370 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8371 NumeratorScaled, Mul, Flags); 8372 8373 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8374 Fma2, Fma1, Mul, Fma2, Flags); 8375 8376 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8377 NumeratorScaled, Fma3, Flags); 8378 8379 if (!HasFP32Denormals) { 8380 SDNode *DisableDenorm; 8381 if (Subtarget->hasDenormModeInst()) { 8382 const SDValue DisableDenormValue = 8383 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8384 8385 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8386 Fma4.getValue(1), DisableDenormValue, 8387 Fma4.getValue(2)).getNode(); 8388 } else { 8389 const SDValue DisableDenormValue = 8390 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8391 8392 DisableDenorm = DAG.getMachineNode( 8393 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8394 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8395 } 8396 8397 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8398 SDValue(DisableDenorm, 0), DAG.getRoot()); 8399 DAG.setRoot(OutputChain); 8400 } 8401 8402 SDValue Scale = NumeratorScaled.getValue(1); 8403 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8404 {Fma4, Fma1, Fma3, Scale}, Flags); 8405 8406 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8407 } 8408 8409 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8410 if (DAG.getTarget().Options.UnsafeFPMath) 8411 return lowerFastUnsafeFDIV(Op, DAG); 8412 8413 SDLoc SL(Op); 8414 SDValue X = Op.getOperand(0); 8415 SDValue Y = Op.getOperand(1); 8416 8417 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8418 8419 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8420 8421 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8422 8423 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8424 8425 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8426 8427 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8428 8429 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8430 8431 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8432 8433 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8434 8435 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8436 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8437 8438 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8439 NegDivScale0, Mul, DivScale1); 8440 8441 SDValue Scale; 8442 8443 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8444 // Workaround a hardware bug on SI where the condition output from div_scale 8445 // is not usable. 8446 8447 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8448 8449 // Figure out if the scale to use for div_fmas. 8450 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8451 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8452 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8453 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8454 8455 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8456 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8457 8458 SDValue Scale0Hi 8459 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8460 SDValue Scale1Hi 8461 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8462 8463 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8464 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8465 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8466 } else { 8467 Scale = DivScale1.getValue(1); 8468 } 8469 8470 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8471 Fma4, Fma3, Mul, Scale); 8472 8473 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8474 } 8475 8476 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8477 EVT VT = Op.getValueType(); 8478 8479 if (VT == MVT::f32) 8480 return LowerFDIV32(Op, DAG); 8481 8482 if (VT == MVT::f64) 8483 return LowerFDIV64(Op, DAG); 8484 8485 if (VT == MVT::f16) 8486 return LowerFDIV16(Op, DAG); 8487 8488 llvm_unreachable("Unexpected type for fdiv"); 8489 } 8490 8491 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8492 SDLoc DL(Op); 8493 StoreSDNode *Store = cast<StoreSDNode>(Op); 8494 EVT VT = Store->getMemoryVT(); 8495 8496 if (VT == MVT::i1) { 8497 return DAG.getTruncStore(Store->getChain(), DL, 8498 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8499 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8500 } 8501 8502 assert(VT.isVector() && 8503 Store->getValue().getValueType().getScalarType() == MVT::i32); 8504 8505 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8506 VT, *Store->getMemOperand())) { 8507 return expandUnalignedStore(Store, DAG); 8508 } 8509 8510 unsigned AS = Store->getAddressSpace(); 8511 if (Subtarget->hasLDSMisalignedBug() && 8512 AS == AMDGPUAS::FLAT_ADDRESS && 8513 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8514 return SplitVectorStore(Op, DAG); 8515 } 8516 8517 MachineFunction &MF = DAG.getMachineFunction(); 8518 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8519 // If there is a possibilty that flat instruction access scratch memory 8520 // then we need to use the same legalization rules we use for private. 8521 if (AS == AMDGPUAS::FLAT_ADDRESS && 8522 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8523 AS = MFI->hasFlatScratchInit() ? 8524 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8525 8526 unsigned NumElements = VT.getVectorNumElements(); 8527 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8528 AS == AMDGPUAS::FLAT_ADDRESS) { 8529 if (NumElements > 4) 8530 return SplitVectorStore(Op, DAG); 8531 // v3 stores not supported on SI. 8532 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8533 return SplitVectorStore(Op, DAG); 8534 return SDValue(); 8535 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8536 switch (Subtarget->getMaxPrivateElementSize()) { 8537 case 4: 8538 return scalarizeVectorStore(Store, DAG); 8539 case 8: 8540 if (NumElements > 2) 8541 return SplitVectorStore(Op, DAG); 8542 return SDValue(); 8543 case 16: 8544 if (NumElements > 4 || NumElements == 3) 8545 return SplitVectorStore(Op, DAG); 8546 return SDValue(); 8547 default: 8548 llvm_unreachable("unsupported private_element_size"); 8549 } 8550 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8551 // Use ds_write_b128 or ds_write_b96 when possible. 8552 if (Subtarget->hasDS96AndDS128() && 8553 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8554 (VT.getStoreSize() == 12)) && 8555 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8556 Store->getAlign())) 8557 return SDValue(); 8558 8559 if (NumElements > 2) 8560 return SplitVectorStore(Op, DAG); 8561 8562 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8563 // address is negative, then the instruction is incorrectly treated as 8564 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8565 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8566 // store later in the SILoadStoreOptimizer. 8567 if (!Subtarget->hasUsableDSOffset() && 8568 NumElements == 2 && VT.getStoreSize() == 8 && 8569 Store->getAlignment() < 8) { 8570 return SplitVectorStore(Op, DAG); 8571 } 8572 8573 return SDValue(); 8574 } else { 8575 llvm_unreachable("unhandled address space"); 8576 } 8577 } 8578 8579 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8580 SDLoc DL(Op); 8581 EVT VT = Op.getValueType(); 8582 SDValue Arg = Op.getOperand(0); 8583 SDValue TrigVal; 8584 8585 // Propagate fast-math flags so that the multiply we introduce can be folded 8586 // if Arg is already the result of a multiply by constant. 8587 auto Flags = Op->getFlags(); 8588 8589 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8590 8591 if (Subtarget->hasTrigReducedRange()) { 8592 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8593 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8594 } else { 8595 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8596 } 8597 8598 switch (Op.getOpcode()) { 8599 case ISD::FCOS: 8600 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8601 case ISD::FSIN: 8602 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8603 default: 8604 llvm_unreachable("Wrong trig opcode"); 8605 } 8606 } 8607 8608 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8609 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8610 assert(AtomicNode->isCompareAndSwap()); 8611 unsigned AS = AtomicNode->getAddressSpace(); 8612 8613 // No custom lowering required for local address space 8614 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8615 return Op; 8616 8617 // Non-local address space requires custom lowering for atomic compare 8618 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8619 SDLoc DL(Op); 8620 SDValue ChainIn = Op.getOperand(0); 8621 SDValue Addr = Op.getOperand(1); 8622 SDValue Old = Op.getOperand(2); 8623 SDValue New = Op.getOperand(3); 8624 EVT VT = Op.getValueType(); 8625 MVT SimpleVT = VT.getSimpleVT(); 8626 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8627 8628 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8629 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8630 8631 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8632 Ops, VT, AtomicNode->getMemOperand()); 8633 } 8634 8635 //===----------------------------------------------------------------------===// 8636 // Custom DAG optimizations 8637 //===----------------------------------------------------------------------===// 8638 8639 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8640 DAGCombinerInfo &DCI) const { 8641 EVT VT = N->getValueType(0); 8642 EVT ScalarVT = VT.getScalarType(); 8643 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8644 return SDValue(); 8645 8646 SelectionDAG &DAG = DCI.DAG; 8647 SDLoc DL(N); 8648 8649 SDValue Src = N->getOperand(0); 8650 EVT SrcVT = Src.getValueType(); 8651 8652 // TODO: We could try to match extracting the higher bytes, which would be 8653 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8654 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8655 // about in practice. 8656 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8657 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8658 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8659 DCI.AddToWorklist(Cvt.getNode()); 8660 8661 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8662 if (ScalarVT != MVT::f32) { 8663 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8664 DAG.getTargetConstant(0, DL, MVT::i32)); 8665 } 8666 return Cvt; 8667 } 8668 } 8669 8670 return SDValue(); 8671 } 8672 8673 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8674 8675 // This is a variant of 8676 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8677 // 8678 // The normal DAG combiner will do this, but only if the add has one use since 8679 // that would increase the number of instructions. 8680 // 8681 // This prevents us from seeing a constant offset that can be folded into a 8682 // memory instruction's addressing mode. If we know the resulting add offset of 8683 // a pointer can be folded into an addressing offset, we can replace the pointer 8684 // operand with the add of new constant offset. This eliminates one of the uses, 8685 // and may allow the remaining use to also be simplified. 8686 // 8687 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8688 unsigned AddrSpace, 8689 EVT MemVT, 8690 DAGCombinerInfo &DCI) const { 8691 SDValue N0 = N->getOperand(0); 8692 SDValue N1 = N->getOperand(1); 8693 8694 // We only do this to handle cases where it's profitable when there are 8695 // multiple uses of the add, so defer to the standard combine. 8696 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8697 N0->hasOneUse()) 8698 return SDValue(); 8699 8700 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8701 if (!CN1) 8702 return SDValue(); 8703 8704 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8705 if (!CAdd) 8706 return SDValue(); 8707 8708 // If the resulting offset is too large, we can't fold it into the addressing 8709 // mode offset. 8710 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8711 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8712 8713 AddrMode AM; 8714 AM.HasBaseReg = true; 8715 AM.BaseOffs = Offset.getSExtValue(); 8716 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8717 return SDValue(); 8718 8719 SelectionDAG &DAG = DCI.DAG; 8720 SDLoc SL(N); 8721 EVT VT = N->getValueType(0); 8722 8723 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8724 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8725 8726 SDNodeFlags Flags; 8727 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8728 (N0.getOpcode() == ISD::OR || 8729 N0->getFlags().hasNoUnsignedWrap())); 8730 8731 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8732 } 8733 8734 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8735 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8736 /// specific intrinsic, but they all place the pointer operand first. 8737 static unsigned getBasePtrIndex(const MemSDNode *N) { 8738 switch (N->getOpcode()) { 8739 case ISD::STORE: 8740 case ISD::INTRINSIC_W_CHAIN: 8741 case ISD::INTRINSIC_VOID: 8742 return 2; 8743 default: 8744 return 1; 8745 } 8746 } 8747 8748 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8749 DAGCombinerInfo &DCI) const { 8750 SelectionDAG &DAG = DCI.DAG; 8751 SDLoc SL(N); 8752 8753 unsigned PtrIdx = getBasePtrIndex(N); 8754 SDValue Ptr = N->getOperand(PtrIdx); 8755 8756 // TODO: We could also do this for multiplies. 8757 if (Ptr.getOpcode() == ISD::SHL) { 8758 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8759 N->getMemoryVT(), DCI); 8760 if (NewPtr) { 8761 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8762 8763 NewOps[PtrIdx] = NewPtr; 8764 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8765 } 8766 } 8767 8768 return SDValue(); 8769 } 8770 8771 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8772 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8773 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8774 (Opc == ISD::XOR && Val == 0); 8775 } 8776 8777 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8778 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8779 // integer combine opportunities since most 64-bit operations are decomposed 8780 // this way. TODO: We won't want this for SALU especially if it is an inline 8781 // immediate. 8782 SDValue SITargetLowering::splitBinaryBitConstantOp( 8783 DAGCombinerInfo &DCI, 8784 const SDLoc &SL, 8785 unsigned Opc, SDValue LHS, 8786 const ConstantSDNode *CRHS) const { 8787 uint64_t Val = CRHS->getZExtValue(); 8788 uint32_t ValLo = Lo_32(Val); 8789 uint32_t ValHi = Hi_32(Val); 8790 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8791 8792 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8793 bitOpWithConstantIsReducible(Opc, ValHi)) || 8794 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8795 // If we need to materialize a 64-bit immediate, it will be split up later 8796 // anyway. Avoid creating the harder to understand 64-bit immediate 8797 // materialization. 8798 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8799 } 8800 8801 return SDValue(); 8802 } 8803 8804 // Returns true if argument is a boolean value which is not serialized into 8805 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8806 static bool isBoolSGPR(SDValue V) { 8807 if (V.getValueType() != MVT::i1) 8808 return false; 8809 switch (V.getOpcode()) { 8810 default: break; 8811 case ISD::SETCC: 8812 case ISD::AND: 8813 case ISD::OR: 8814 case ISD::XOR: 8815 case AMDGPUISD::FP_CLASS: 8816 return true; 8817 } 8818 return false; 8819 } 8820 8821 // If a constant has all zeroes or all ones within each byte return it. 8822 // Otherwise return 0. 8823 static uint32_t getConstantPermuteMask(uint32_t C) { 8824 // 0xff for any zero byte in the mask 8825 uint32_t ZeroByteMask = 0; 8826 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8827 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8828 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8829 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8830 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8831 if ((NonZeroByteMask & C) != NonZeroByteMask) 8832 return 0; // Partial bytes selected. 8833 return C; 8834 } 8835 8836 // Check if a node selects whole bytes from its operand 0 starting at a byte 8837 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8838 // or -1 if not succeeded. 8839 // Note byte select encoding: 8840 // value 0-3 selects corresponding source byte; 8841 // value 0xc selects zero; 8842 // value 0xff selects 0xff. 8843 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8844 assert(V.getValueSizeInBits() == 32); 8845 8846 if (V.getNumOperands() != 2) 8847 return ~0; 8848 8849 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8850 if (!N1) 8851 return ~0; 8852 8853 uint32_t C = N1->getZExtValue(); 8854 8855 switch (V.getOpcode()) { 8856 default: 8857 break; 8858 case ISD::AND: 8859 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8860 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8861 } 8862 break; 8863 8864 case ISD::OR: 8865 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8866 return (0x03020100 & ~ConstMask) | ConstMask; 8867 } 8868 break; 8869 8870 case ISD::SHL: 8871 if (C % 8) 8872 return ~0; 8873 8874 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8875 8876 case ISD::SRL: 8877 if (C % 8) 8878 return ~0; 8879 8880 return uint32_t(0x0c0c0c0c03020100ull >> C); 8881 } 8882 8883 return ~0; 8884 } 8885 8886 SDValue SITargetLowering::performAndCombine(SDNode *N, 8887 DAGCombinerInfo &DCI) const { 8888 if (DCI.isBeforeLegalize()) 8889 return SDValue(); 8890 8891 SelectionDAG &DAG = DCI.DAG; 8892 EVT VT = N->getValueType(0); 8893 SDValue LHS = N->getOperand(0); 8894 SDValue RHS = N->getOperand(1); 8895 8896 8897 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8898 if (VT == MVT::i64 && CRHS) { 8899 if (SDValue Split 8900 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8901 return Split; 8902 } 8903 8904 if (CRHS && VT == MVT::i32) { 8905 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8906 // nb = number of trailing zeroes in mask 8907 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8908 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8909 uint64_t Mask = CRHS->getZExtValue(); 8910 unsigned Bits = countPopulation(Mask); 8911 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8912 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8913 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8914 unsigned Shift = CShift->getZExtValue(); 8915 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8916 unsigned Offset = NB + Shift; 8917 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8918 SDLoc SL(N); 8919 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8920 LHS->getOperand(0), 8921 DAG.getConstant(Offset, SL, MVT::i32), 8922 DAG.getConstant(Bits, SL, MVT::i32)); 8923 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8924 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8925 DAG.getValueType(NarrowVT)); 8926 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8927 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8928 return Shl; 8929 } 8930 } 8931 } 8932 8933 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8934 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8935 isa<ConstantSDNode>(LHS.getOperand(2))) { 8936 uint32_t Sel = getConstantPermuteMask(Mask); 8937 if (!Sel) 8938 return SDValue(); 8939 8940 // Select 0xc for all zero bytes 8941 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8942 SDLoc DL(N); 8943 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8944 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8945 } 8946 } 8947 8948 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8949 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8950 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8951 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8952 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8953 8954 SDValue X = LHS.getOperand(0); 8955 SDValue Y = RHS.getOperand(0); 8956 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8957 return SDValue(); 8958 8959 if (LCC == ISD::SETO) { 8960 if (X != LHS.getOperand(1)) 8961 return SDValue(); 8962 8963 if (RCC == ISD::SETUNE) { 8964 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8965 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8966 return SDValue(); 8967 8968 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8969 SIInstrFlags::N_SUBNORMAL | 8970 SIInstrFlags::N_ZERO | 8971 SIInstrFlags::P_ZERO | 8972 SIInstrFlags::P_SUBNORMAL | 8973 SIInstrFlags::P_NORMAL; 8974 8975 static_assert(((~(SIInstrFlags::S_NAN | 8976 SIInstrFlags::Q_NAN | 8977 SIInstrFlags::N_INFINITY | 8978 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8979 "mask not equal"); 8980 8981 SDLoc DL(N); 8982 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8983 X, DAG.getConstant(Mask, DL, MVT::i32)); 8984 } 8985 } 8986 } 8987 8988 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8989 std::swap(LHS, RHS); 8990 8991 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8992 RHS.hasOneUse()) { 8993 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8994 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8995 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8996 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8997 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8998 (RHS.getOperand(0) == LHS.getOperand(0) && 8999 LHS.getOperand(0) == LHS.getOperand(1))) { 9000 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9001 unsigned NewMask = LCC == ISD::SETO ? 9002 Mask->getZExtValue() & ~OrdMask : 9003 Mask->getZExtValue() & OrdMask; 9004 9005 SDLoc DL(N); 9006 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9007 DAG.getConstant(NewMask, DL, MVT::i32)); 9008 } 9009 } 9010 9011 if (VT == MVT::i32 && 9012 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9013 // and x, (sext cc from i1) => select cc, x, 0 9014 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9015 std::swap(LHS, RHS); 9016 if (isBoolSGPR(RHS.getOperand(0))) 9017 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9018 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9019 } 9020 9021 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9022 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9023 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9024 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9025 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9026 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9027 if (LHSMask != ~0u && RHSMask != ~0u) { 9028 // Canonicalize the expression in an attempt to have fewer unique masks 9029 // and therefore fewer registers used to hold the masks. 9030 if (LHSMask > RHSMask) { 9031 std::swap(LHSMask, RHSMask); 9032 std::swap(LHS, RHS); 9033 } 9034 9035 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9036 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9037 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9038 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9039 9040 // Check of we need to combine values from two sources within a byte. 9041 if (!(LHSUsedLanes & RHSUsedLanes) && 9042 // If we select high and lower word keep it for SDWA. 9043 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9044 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9045 // Each byte in each mask is either selector mask 0-3, or has higher 9046 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9047 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9048 // mask which is not 0xff wins. By anding both masks we have a correct 9049 // result except that 0x0c shall be corrected to give 0x0c only. 9050 uint32_t Mask = LHSMask & RHSMask; 9051 for (unsigned I = 0; I < 32; I += 8) { 9052 uint32_t ByteSel = 0xff << I; 9053 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9054 Mask &= (0x0c << I) & 0xffffffff; 9055 } 9056 9057 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9058 // or 0x0c. 9059 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9060 SDLoc DL(N); 9061 9062 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9063 LHS.getOperand(0), RHS.getOperand(0), 9064 DAG.getConstant(Sel, DL, MVT::i32)); 9065 } 9066 } 9067 } 9068 9069 return SDValue(); 9070 } 9071 9072 SDValue SITargetLowering::performOrCombine(SDNode *N, 9073 DAGCombinerInfo &DCI) const { 9074 SelectionDAG &DAG = DCI.DAG; 9075 SDValue LHS = N->getOperand(0); 9076 SDValue RHS = N->getOperand(1); 9077 9078 EVT VT = N->getValueType(0); 9079 if (VT == MVT::i1) { 9080 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9081 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9082 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9083 SDValue Src = LHS.getOperand(0); 9084 if (Src != RHS.getOperand(0)) 9085 return SDValue(); 9086 9087 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9088 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9089 if (!CLHS || !CRHS) 9090 return SDValue(); 9091 9092 // Only 10 bits are used. 9093 static const uint32_t MaxMask = 0x3ff; 9094 9095 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9096 SDLoc DL(N); 9097 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9098 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9099 } 9100 9101 return SDValue(); 9102 } 9103 9104 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9105 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9106 LHS.getOpcode() == AMDGPUISD::PERM && 9107 isa<ConstantSDNode>(LHS.getOperand(2))) { 9108 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9109 if (!Sel) 9110 return SDValue(); 9111 9112 Sel |= LHS.getConstantOperandVal(2); 9113 SDLoc DL(N); 9114 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9115 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9116 } 9117 9118 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9119 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9120 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9121 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9122 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9123 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9124 if (LHSMask != ~0u && RHSMask != ~0u) { 9125 // Canonicalize the expression in an attempt to have fewer unique masks 9126 // and therefore fewer registers used to hold the masks. 9127 if (LHSMask > RHSMask) { 9128 std::swap(LHSMask, RHSMask); 9129 std::swap(LHS, RHS); 9130 } 9131 9132 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9133 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9134 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9135 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9136 9137 // Check of we need to combine values from two sources within a byte. 9138 if (!(LHSUsedLanes & RHSUsedLanes) && 9139 // If we select high and lower word keep it for SDWA. 9140 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9141 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9142 // Kill zero bytes selected by other mask. Zero value is 0xc. 9143 LHSMask &= ~RHSUsedLanes; 9144 RHSMask &= ~LHSUsedLanes; 9145 // Add 4 to each active LHS lane 9146 LHSMask |= LHSUsedLanes & 0x04040404; 9147 // Combine masks 9148 uint32_t Sel = LHSMask | RHSMask; 9149 SDLoc DL(N); 9150 9151 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9152 LHS.getOperand(0), RHS.getOperand(0), 9153 DAG.getConstant(Sel, DL, MVT::i32)); 9154 } 9155 } 9156 } 9157 9158 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9159 return SDValue(); 9160 9161 // TODO: This could be a generic combine with a predicate for extracting the 9162 // high half of an integer being free. 9163 9164 // (or i64:x, (zero_extend i32:y)) -> 9165 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9166 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9167 RHS.getOpcode() != ISD::ZERO_EXTEND) 9168 std::swap(LHS, RHS); 9169 9170 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9171 SDValue ExtSrc = RHS.getOperand(0); 9172 EVT SrcVT = ExtSrc.getValueType(); 9173 if (SrcVT == MVT::i32) { 9174 SDLoc SL(N); 9175 SDValue LowLHS, HiBits; 9176 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9177 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9178 9179 DCI.AddToWorklist(LowOr.getNode()); 9180 DCI.AddToWorklist(HiBits.getNode()); 9181 9182 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9183 LowOr, HiBits); 9184 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9185 } 9186 } 9187 9188 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9189 if (CRHS) { 9190 if (SDValue Split 9191 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9192 return Split; 9193 } 9194 9195 return SDValue(); 9196 } 9197 9198 SDValue SITargetLowering::performXorCombine(SDNode *N, 9199 DAGCombinerInfo &DCI) const { 9200 EVT VT = N->getValueType(0); 9201 if (VT != MVT::i64) 9202 return SDValue(); 9203 9204 SDValue LHS = N->getOperand(0); 9205 SDValue RHS = N->getOperand(1); 9206 9207 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9208 if (CRHS) { 9209 if (SDValue Split 9210 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9211 return Split; 9212 } 9213 9214 return SDValue(); 9215 } 9216 9217 // Instructions that will be lowered with a final instruction that zeros the 9218 // high result bits. 9219 // XXX - probably only need to list legal operations. 9220 static bool fp16SrcZerosHighBits(unsigned Opc) { 9221 switch (Opc) { 9222 case ISD::FADD: 9223 case ISD::FSUB: 9224 case ISD::FMUL: 9225 case ISD::FDIV: 9226 case ISD::FREM: 9227 case ISD::FMA: 9228 case ISD::FMAD: 9229 case ISD::FCANONICALIZE: 9230 case ISD::FP_ROUND: 9231 case ISD::UINT_TO_FP: 9232 case ISD::SINT_TO_FP: 9233 case ISD::FABS: 9234 // Fabs is lowered to a bit operation, but it's an and which will clear the 9235 // high bits anyway. 9236 case ISD::FSQRT: 9237 case ISD::FSIN: 9238 case ISD::FCOS: 9239 case ISD::FPOWI: 9240 case ISD::FPOW: 9241 case ISD::FLOG: 9242 case ISD::FLOG2: 9243 case ISD::FLOG10: 9244 case ISD::FEXP: 9245 case ISD::FEXP2: 9246 case ISD::FCEIL: 9247 case ISD::FTRUNC: 9248 case ISD::FRINT: 9249 case ISD::FNEARBYINT: 9250 case ISD::FROUND: 9251 case ISD::FFLOOR: 9252 case ISD::FMINNUM: 9253 case ISD::FMAXNUM: 9254 case AMDGPUISD::FRACT: 9255 case AMDGPUISD::CLAMP: 9256 case AMDGPUISD::COS_HW: 9257 case AMDGPUISD::SIN_HW: 9258 case AMDGPUISD::FMIN3: 9259 case AMDGPUISD::FMAX3: 9260 case AMDGPUISD::FMED3: 9261 case AMDGPUISD::FMAD_FTZ: 9262 case AMDGPUISD::RCP: 9263 case AMDGPUISD::RSQ: 9264 case AMDGPUISD::RCP_IFLAG: 9265 case AMDGPUISD::LDEXP: 9266 return true; 9267 default: 9268 // fcopysign, select and others may be lowered to 32-bit bit operations 9269 // which don't zero the high bits. 9270 return false; 9271 } 9272 } 9273 9274 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9275 DAGCombinerInfo &DCI) const { 9276 if (!Subtarget->has16BitInsts() || 9277 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9278 return SDValue(); 9279 9280 EVT VT = N->getValueType(0); 9281 if (VT != MVT::i32) 9282 return SDValue(); 9283 9284 SDValue Src = N->getOperand(0); 9285 if (Src.getValueType() != MVT::i16) 9286 return SDValue(); 9287 9288 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9289 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9290 if (Src.getOpcode() == ISD::BITCAST) { 9291 SDValue BCSrc = Src.getOperand(0); 9292 if (BCSrc.getValueType() == MVT::f16 && 9293 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9294 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9295 } 9296 9297 return SDValue(); 9298 } 9299 9300 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9301 DAGCombinerInfo &DCI) 9302 const { 9303 SDValue Src = N->getOperand(0); 9304 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9305 9306 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9307 VTSign->getVT() == MVT::i8) || 9308 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9309 VTSign->getVT() == MVT::i16)) && 9310 Src.hasOneUse()) { 9311 auto *M = cast<MemSDNode>(Src); 9312 SDValue Ops[] = { 9313 Src.getOperand(0), // Chain 9314 Src.getOperand(1), // rsrc 9315 Src.getOperand(2), // vindex 9316 Src.getOperand(3), // voffset 9317 Src.getOperand(4), // soffset 9318 Src.getOperand(5), // offset 9319 Src.getOperand(6), 9320 Src.getOperand(7) 9321 }; 9322 // replace with BUFFER_LOAD_BYTE/SHORT 9323 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9324 Src.getOperand(0).getValueType()); 9325 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9326 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9327 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9328 ResList, 9329 Ops, M->getMemoryVT(), 9330 M->getMemOperand()); 9331 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9332 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9333 } 9334 return SDValue(); 9335 } 9336 9337 SDValue SITargetLowering::performClassCombine(SDNode *N, 9338 DAGCombinerInfo &DCI) const { 9339 SelectionDAG &DAG = DCI.DAG; 9340 SDValue Mask = N->getOperand(1); 9341 9342 // fp_class x, 0 -> false 9343 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9344 if (CMask->isNullValue()) 9345 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9346 } 9347 9348 if (N->getOperand(0).isUndef()) 9349 return DAG.getUNDEF(MVT::i1); 9350 9351 return SDValue(); 9352 } 9353 9354 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9355 DAGCombinerInfo &DCI) const { 9356 EVT VT = N->getValueType(0); 9357 SDValue N0 = N->getOperand(0); 9358 9359 if (N0.isUndef()) 9360 return N0; 9361 9362 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9363 N0.getOpcode() == ISD::SINT_TO_FP)) { 9364 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9365 N->getFlags()); 9366 } 9367 9368 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9369 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9370 N0.getOperand(0), N->getFlags()); 9371 } 9372 9373 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9374 } 9375 9376 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9377 unsigned MaxDepth) const { 9378 unsigned Opcode = Op.getOpcode(); 9379 if (Opcode == ISD::FCANONICALIZE) 9380 return true; 9381 9382 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9383 auto F = CFP->getValueAPF(); 9384 if (F.isNaN() && F.isSignaling()) 9385 return false; 9386 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9387 } 9388 9389 // If source is a result of another standard FP operation it is already in 9390 // canonical form. 9391 if (MaxDepth == 0) 9392 return false; 9393 9394 switch (Opcode) { 9395 // These will flush denorms if required. 9396 case ISD::FADD: 9397 case ISD::FSUB: 9398 case ISD::FMUL: 9399 case ISD::FCEIL: 9400 case ISD::FFLOOR: 9401 case ISD::FMA: 9402 case ISD::FMAD: 9403 case ISD::FSQRT: 9404 case ISD::FDIV: 9405 case ISD::FREM: 9406 case ISD::FP_ROUND: 9407 case ISD::FP_EXTEND: 9408 case AMDGPUISD::FMUL_LEGACY: 9409 case AMDGPUISD::FMAD_FTZ: 9410 case AMDGPUISD::RCP: 9411 case AMDGPUISD::RSQ: 9412 case AMDGPUISD::RSQ_CLAMP: 9413 case AMDGPUISD::RCP_LEGACY: 9414 case AMDGPUISD::RCP_IFLAG: 9415 case AMDGPUISD::DIV_SCALE: 9416 case AMDGPUISD::DIV_FMAS: 9417 case AMDGPUISD::DIV_FIXUP: 9418 case AMDGPUISD::FRACT: 9419 case AMDGPUISD::LDEXP: 9420 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9421 case AMDGPUISD::CVT_F32_UBYTE0: 9422 case AMDGPUISD::CVT_F32_UBYTE1: 9423 case AMDGPUISD::CVT_F32_UBYTE2: 9424 case AMDGPUISD::CVT_F32_UBYTE3: 9425 return true; 9426 9427 // It can/will be lowered or combined as a bit operation. 9428 // Need to check their input recursively to handle. 9429 case ISD::FNEG: 9430 case ISD::FABS: 9431 case ISD::FCOPYSIGN: 9432 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9433 9434 case ISD::FSIN: 9435 case ISD::FCOS: 9436 case ISD::FSINCOS: 9437 return Op.getValueType().getScalarType() != MVT::f16; 9438 9439 case ISD::FMINNUM: 9440 case ISD::FMAXNUM: 9441 case ISD::FMINNUM_IEEE: 9442 case ISD::FMAXNUM_IEEE: 9443 case AMDGPUISD::CLAMP: 9444 case AMDGPUISD::FMED3: 9445 case AMDGPUISD::FMAX3: 9446 case AMDGPUISD::FMIN3: { 9447 // FIXME: Shouldn't treat the generic operations different based these. 9448 // However, we aren't really required to flush the result from 9449 // minnum/maxnum.. 9450 9451 // snans will be quieted, so we only need to worry about denormals. 9452 if (Subtarget->supportsMinMaxDenormModes() || 9453 denormalsEnabledForType(DAG, Op.getValueType())) 9454 return true; 9455 9456 // Flushing may be required. 9457 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9458 // targets need to check their input recursively. 9459 9460 // FIXME: Does this apply with clamp? It's implemented with max. 9461 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9462 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9463 return false; 9464 } 9465 9466 return true; 9467 } 9468 case ISD::SELECT: { 9469 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9470 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9471 } 9472 case ISD::BUILD_VECTOR: { 9473 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9474 SDValue SrcOp = Op.getOperand(i); 9475 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9476 return false; 9477 } 9478 9479 return true; 9480 } 9481 case ISD::EXTRACT_VECTOR_ELT: 9482 case ISD::EXTRACT_SUBVECTOR: { 9483 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9484 } 9485 case ISD::INSERT_VECTOR_ELT: { 9486 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9487 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9488 } 9489 case ISD::UNDEF: 9490 // Could be anything. 9491 return false; 9492 9493 case ISD::BITCAST: { 9494 // Hack round the mess we make when legalizing extract_vector_elt 9495 SDValue Src = Op.getOperand(0); 9496 if (Src.getValueType() == MVT::i16 && 9497 Src.getOpcode() == ISD::TRUNCATE) { 9498 SDValue TruncSrc = Src.getOperand(0); 9499 if (TruncSrc.getValueType() == MVT::i32 && 9500 TruncSrc.getOpcode() == ISD::BITCAST && 9501 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9502 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9503 } 9504 } 9505 9506 return false; 9507 } 9508 case ISD::INTRINSIC_WO_CHAIN: { 9509 unsigned IntrinsicID 9510 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9511 // TODO: Handle more intrinsics 9512 switch (IntrinsicID) { 9513 case Intrinsic::amdgcn_cvt_pkrtz: 9514 case Intrinsic::amdgcn_cubeid: 9515 case Intrinsic::amdgcn_frexp_mant: 9516 case Intrinsic::amdgcn_fdot2: 9517 case Intrinsic::amdgcn_rcp: 9518 case Intrinsic::amdgcn_rsq: 9519 case Intrinsic::amdgcn_rsq_clamp: 9520 case Intrinsic::amdgcn_rcp_legacy: 9521 case Intrinsic::amdgcn_rsq_legacy: 9522 case Intrinsic::amdgcn_trig_preop: 9523 return true; 9524 default: 9525 break; 9526 } 9527 9528 LLVM_FALLTHROUGH; 9529 } 9530 default: 9531 return denormalsEnabledForType(DAG, Op.getValueType()) && 9532 DAG.isKnownNeverSNaN(Op); 9533 } 9534 9535 llvm_unreachable("invalid operation"); 9536 } 9537 9538 // Constant fold canonicalize. 9539 SDValue SITargetLowering::getCanonicalConstantFP( 9540 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9541 // Flush denormals to 0 if not enabled. 9542 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9543 return DAG.getConstantFP(0.0, SL, VT); 9544 9545 if (C.isNaN()) { 9546 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9547 if (C.isSignaling()) { 9548 // Quiet a signaling NaN. 9549 // FIXME: Is this supposed to preserve payload bits? 9550 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9551 } 9552 9553 // Make sure it is the canonical NaN bitpattern. 9554 // 9555 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9556 // immediate? 9557 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9558 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9559 } 9560 9561 // Already canonical. 9562 return DAG.getConstantFP(C, SL, VT); 9563 } 9564 9565 static bool vectorEltWillFoldAway(SDValue Op) { 9566 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9567 } 9568 9569 SDValue SITargetLowering::performFCanonicalizeCombine( 9570 SDNode *N, 9571 DAGCombinerInfo &DCI) const { 9572 SelectionDAG &DAG = DCI.DAG; 9573 SDValue N0 = N->getOperand(0); 9574 EVT VT = N->getValueType(0); 9575 9576 // fcanonicalize undef -> qnan 9577 if (N0.isUndef()) { 9578 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9579 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9580 } 9581 9582 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9583 EVT VT = N->getValueType(0); 9584 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9585 } 9586 9587 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9588 // (fcanonicalize k) 9589 // 9590 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9591 9592 // TODO: This could be better with wider vectors that will be split to v2f16, 9593 // and to consider uses since there aren't that many packed operations. 9594 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9595 isTypeLegal(MVT::v2f16)) { 9596 SDLoc SL(N); 9597 SDValue NewElts[2]; 9598 SDValue Lo = N0.getOperand(0); 9599 SDValue Hi = N0.getOperand(1); 9600 EVT EltVT = Lo.getValueType(); 9601 9602 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9603 for (unsigned I = 0; I != 2; ++I) { 9604 SDValue Op = N0.getOperand(I); 9605 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9606 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9607 CFP->getValueAPF()); 9608 } else if (Op.isUndef()) { 9609 // Handled below based on what the other operand is. 9610 NewElts[I] = Op; 9611 } else { 9612 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9613 } 9614 } 9615 9616 // If one half is undef, and one is constant, perfer a splat vector rather 9617 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9618 // cheaper to use and may be free with a packed operation. 9619 if (NewElts[0].isUndef()) { 9620 if (isa<ConstantFPSDNode>(NewElts[1])) 9621 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9622 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9623 } 9624 9625 if (NewElts[1].isUndef()) { 9626 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9627 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9628 } 9629 9630 return DAG.getBuildVector(VT, SL, NewElts); 9631 } 9632 } 9633 9634 unsigned SrcOpc = N0.getOpcode(); 9635 9636 // If it's free to do so, push canonicalizes further up the source, which may 9637 // find a canonical source. 9638 // 9639 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9640 // sNaNs. 9641 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9642 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9643 if (CRHS && N0.hasOneUse()) { 9644 SDLoc SL(N); 9645 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9646 N0.getOperand(0)); 9647 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9648 DCI.AddToWorklist(Canon0.getNode()); 9649 9650 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9651 } 9652 } 9653 9654 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9655 } 9656 9657 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9658 switch (Opc) { 9659 case ISD::FMAXNUM: 9660 case ISD::FMAXNUM_IEEE: 9661 return AMDGPUISD::FMAX3; 9662 case ISD::SMAX: 9663 return AMDGPUISD::SMAX3; 9664 case ISD::UMAX: 9665 return AMDGPUISD::UMAX3; 9666 case ISD::FMINNUM: 9667 case ISD::FMINNUM_IEEE: 9668 return AMDGPUISD::FMIN3; 9669 case ISD::SMIN: 9670 return AMDGPUISD::SMIN3; 9671 case ISD::UMIN: 9672 return AMDGPUISD::UMIN3; 9673 default: 9674 llvm_unreachable("Not a min/max opcode"); 9675 } 9676 } 9677 9678 SDValue SITargetLowering::performIntMed3ImmCombine( 9679 SelectionDAG &DAG, const SDLoc &SL, 9680 SDValue Op0, SDValue Op1, bool Signed) const { 9681 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9682 if (!K1) 9683 return SDValue(); 9684 9685 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9686 if (!K0) 9687 return SDValue(); 9688 9689 if (Signed) { 9690 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9691 return SDValue(); 9692 } else { 9693 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9694 return SDValue(); 9695 } 9696 9697 EVT VT = K0->getValueType(0); 9698 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9699 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9700 return DAG.getNode(Med3Opc, SL, VT, 9701 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9702 } 9703 9704 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9705 MVT NVT = MVT::i32; 9706 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9707 9708 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9709 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9710 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9711 9712 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9713 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9714 } 9715 9716 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9717 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9718 return C; 9719 9720 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9721 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9722 return C; 9723 } 9724 9725 return nullptr; 9726 } 9727 9728 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9729 const SDLoc &SL, 9730 SDValue Op0, 9731 SDValue Op1) const { 9732 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9733 if (!K1) 9734 return SDValue(); 9735 9736 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9737 if (!K0) 9738 return SDValue(); 9739 9740 // Ordered >= (although NaN inputs should have folded away by now). 9741 if (K0->getValueAPF() > K1->getValueAPF()) 9742 return SDValue(); 9743 9744 const MachineFunction &MF = DAG.getMachineFunction(); 9745 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9746 9747 // TODO: Check IEEE bit enabled? 9748 EVT VT = Op0.getValueType(); 9749 if (Info->getMode().DX10Clamp) { 9750 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9751 // hardware fmed3 behavior converting to a min. 9752 // FIXME: Should this be allowing -0.0? 9753 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9754 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9755 } 9756 9757 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9758 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9759 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9760 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9761 // then give the other result, which is different from med3 with a NaN 9762 // input. 9763 SDValue Var = Op0.getOperand(0); 9764 if (!DAG.isKnownNeverSNaN(Var)) 9765 return SDValue(); 9766 9767 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9768 9769 if ((!K0->hasOneUse() || 9770 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9771 (!K1->hasOneUse() || 9772 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9773 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9774 Var, SDValue(K0, 0), SDValue(K1, 0)); 9775 } 9776 } 9777 9778 return SDValue(); 9779 } 9780 9781 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9782 DAGCombinerInfo &DCI) const { 9783 SelectionDAG &DAG = DCI.DAG; 9784 9785 EVT VT = N->getValueType(0); 9786 unsigned Opc = N->getOpcode(); 9787 SDValue Op0 = N->getOperand(0); 9788 SDValue Op1 = N->getOperand(1); 9789 9790 // Only do this if the inner op has one use since this will just increases 9791 // register pressure for no benefit. 9792 9793 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9794 !VT.isVector() && 9795 (VT == MVT::i32 || VT == MVT::f32 || 9796 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9797 // max(max(a, b), c) -> max3(a, b, c) 9798 // min(min(a, b), c) -> min3(a, b, c) 9799 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9800 SDLoc DL(N); 9801 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9802 DL, 9803 N->getValueType(0), 9804 Op0.getOperand(0), 9805 Op0.getOperand(1), 9806 Op1); 9807 } 9808 9809 // Try commuted. 9810 // max(a, max(b, c)) -> max3(a, b, c) 9811 // min(a, min(b, c)) -> min3(a, b, c) 9812 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9813 SDLoc DL(N); 9814 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9815 DL, 9816 N->getValueType(0), 9817 Op0, 9818 Op1.getOperand(0), 9819 Op1.getOperand(1)); 9820 } 9821 } 9822 9823 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9824 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9825 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9826 return Med3; 9827 } 9828 9829 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9830 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9831 return Med3; 9832 } 9833 9834 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9835 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9836 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9837 (Opc == AMDGPUISD::FMIN_LEGACY && 9838 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9839 (VT == MVT::f32 || VT == MVT::f64 || 9840 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9841 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9842 Op0.hasOneUse()) { 9843 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9844 return Res; 9845 } 9846 9847 return SDValue(); 9848 } 9849 9850 static bool isClampZeroToOne(SDValue A, SDValue B) { 9851 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9852 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9853 // FIXME: Should this be allowing -0.0? 9854 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9855 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9856 } 9857 } 9858 9859 return false; 9860 } 9861 9862 // FIXME: Should only worry about snans for version with chain. 9863 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9864 DAGCombinerInfo &DCI) const { 9865 EVT VT = N->getValueType(0); 9866 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9867 // NaNs. With a NaN input, the order of the operands may change the result. 9868 9869 SelectionDAG &DAG = DCI.DAG; 9870 SDLoc SL(N); 9871 9872 SDValue Src0 = N->getOperand(0); 9873 SDValue Src1 = N->getOperand(1); 9874 SDValue Src2 = N->getOperand(2); 9875 9876 if (isClampZeroToOne(Src0, Src1)) { 9877 // const_a, const_b, x -> clamp is safe in all cases including signaling 9878 // nans. 9879 // FIXME: Should this be allowing -0.0? 9880 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9881 } 9882 9883 const MachineFunction &MF = DAG.getMachineFunction(); 9884 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9885 9886 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9887 // handling no dx10-clamp? 9888 if (Info->getMode().DX10Clamp) { 9889 // If NaNs is clamped to 0, we are free to reorder the inputs. 9890 9891 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9892 std::swap(Src0, Src1); 9893 9894 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9895 std::swap(Src1, Src2); 9896 9897 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9898 std::swap(Src0, Src1); 9899 9900 if (isClampZeroToOne(Src1, Src2)) 9901 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9902 } 9903 9904 return SDValue(); 9905 } 9906 9907 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9908 DAGCombinerInfo &DCI) const { 9909 SDValue Src0 = N->getOperand(0); 9910 SDValue Src1 = N->getOperand(1); 9911 if (Src0.isUndef() && Src1.isUndef()) 9912 return DCI.DAG.getUNDEF(N->getValueType(0)); 9913 return SDValue(); 9914 } 9915 9916 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9917 // expanded into a set of cmp/select instructions. 9918 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9919 unsigned NumElem, 9920 bool IsDivergentIdx) { 9921 if (UseDivergentRegisterIndexing) 9922 return false; 9923 9924 unsigned VecSize = EltSize * NumElem; 9925 9926 // Sub-dword vectors of size 2 dword or less have better implementation. 9927 if (VecSize <= 64 && EltSize < 32) 9928 return false; 9929 9930 // Always expand the rest of sub-dword instructions, otherwise it will be 9931 // lowered via memory. 9932 if (EltSize < 32) 9933 return true; 9934 9935 // Always do this if var-idx is divergent, otherwise it will become a loop. 9936 if (IsDivergentIdx) 9937 return true; 9938 9939 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9940 unsigned NumInsts = NumElem /* Number of compares */ + 9941 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9942 return NumInsts <= 16; 9943 } 9944 9945 static bool shouldExpandVectorDynExt(SDNode *N) { 9946 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9947 if (isa<ConstantSDNode>(Idx)) 9948 return false; 9949 9950 SDValue Vec = N->getOperand(0); 9951 EVT VecVT = Vec.getValueType(); 9952 EVT EltVT = VecVT.getVectorElementType(); 9953 unsigned EltSize = EltVT.getSizeInBits(); 9954 unsigned NumElem = VecVT.getVectorNumElements(); 9955 9956 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9957 Idx->isDivergent()); 9958 } 9959 9960 SDValue SITargetLowering::performExtractVectorEltCombine( 9961 SDNode *N, DAGCombinerInfo &DCI) const { 9962 SDValue Vec = N->getOperand(0); 9963 SelectionDAG &DAG = DCI.DAG; 9964 9965 EVT VecVT = Vec.getValueType(); 9966 EVT EltVT = VecVT.getVectorElementType(); 9967 9968 if ((Vec.getOpcode() == ISD::FNEG || 9969 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9970 SDLoc SL(N); 9971 EVT EltVT = N->getValueType(0); 9972 SDValue Idx = N->getOperand(1); 9973 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9974 Vec.getOperand(0), Idx); 9975 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9976 } 9977 9978 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9979 // => 9980 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9981 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9982 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9983 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9984 SDLoc SL(N); 9985 EVT EltVT = N->getValueType(0); 9986 SDValue Idx = N->getOperand(1); 9987 unsigned Opc = Vec.getOpcode(); 9988 9989 switch(Opc) { 9990 default: 9991 break; 9992 // TODO: Support other binary operations. 9993 case ISD::FADD: 9994 case ISD::FSUB: 9995 case ISD::FMUL: 9996 case ISD::ADD: 9997 case ISD::UMIN: 9998 case ISD::UMAX: 9999 case ISD::SMIN: 10000 case ISD::SMAX: 10001 case ISD::FMAXNUM: 10002 case ISD::FMINNUM: 10003 case ISD::FMAXNUM_IEEE: 10004 case ISD::FMINNUM_IEEE: { 10005 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10006 Vec.getOperand(0), Idx); 10007 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10008 Vec.getOperand(1), Idx); 10009 10010 DCI.AddToWorklist(Elt0.getNode()); 10011 DCI.AddToWorklist(Elt1.getNode()); 10012 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10013 } 10014 } 10015 } 10016 10017 unsigned VecSize = VecVT.getSizeInBits(); 10018 unsigned EltSize = EltVT.getSizeInBits(); 10019 10020 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10021 if (::shouldExpandVectorDynExt(N)) { 10022 SDLoc SL(N); 10023 SDValue Idx = N->getOperand(1); 10024 SDValue V; 10025 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10026 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10027 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10028 if (I == 0) 10029 V = Elt; 10030 else 10031 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10032 } 10033 return V; 10034 } 10035 10036 if (!DCI.isBeforeLegalize()) 10037 return SDValue(); 10038 10039 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10040 // elements. This exposes more load reduction opportunities by replacing 10041 // multiple small extract_vector_elements with a single 32-bit extract. 10042 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10043 if (isa<MemSDNode>(Vec) && 10044 EltSize <= 16 && 10045 EltVT.isByteSized() && 10046 VecSize > 32 && 10047 VecSize % 32 == 0 && 10048 Idx) { 10049 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10050 10051 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10052 unsigned EltIdx = BitIndex / 32; 10053 unsigned LeftoverBitIdx = BitIndex % 32; 10054 SDLoc SL(N); 10055 10056 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10057 DCI.AddToWorklist(Cast.getNode()); 10058 10059 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10060 DAG.getConstant(EltIdx, SL, MVT::i32)); 10061 DCI.AddToWorklist(Elt.getNode()); 10062 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10063 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10064 DCI.AddToWorklist(Srl.getNode()); 10065 10066 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10067 DCI.AddToWorklist(Trunc.getNode()); 10068 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10069 } 10070 10071 return SDValue(); 10072 } 10073 10074 SDValue 10075 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10076 DAGCombinerInfo &DCI) const { 10077 SDValue Vec = N->getOperand(0); 10078 SDValue Idx = N->getOperand(2); 10079 EVT VecVT = Vec.getValueType(); 10080 EVT EltVT = VecVT.getVectorElementType(); 10081 10082 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10083 // => BUILD_VECTOR n x select (e, const-idx) 10084 if (!::shouldExpandVectorDynExt(N)) 10085 return SDValue(); 10086 10087 SelectionDAG &DAG = DCI.DAG; 10088 SDLoc SL(N); 10089 SDValue Ins = N->getOperand(1); 10090 EVT IdxVT = Idx.getValueType(); 10091 10092 SmallVector<SDValue, 16> Ops; 10093 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10094 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10095 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10096 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10097 Ops.push_back(V); 10098 } 10099 10100 return DAG.getBuildVector(VecVT, SL, Ops); 10101 } 10102 10103 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10104 const SDNode *N0, 10105 const SDNode *N1) const { 10106 EVT VT = N0->getValueType(0); 10107 10108 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10109 // support denormals ever. 10110 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10111 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10112 getSubtarget()->hasMadF16())) && 10113 isOperationLegal(ISD::FMAD, VT)) 10114 return ISD::FMAD; 10115 10116 const TargetOptions &Options = DAG.getTarget().Options; 10117 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10118 (N0->getFlags().hasAllowContract() && 10119 N1->getFlags().hasAllowContract())) && 10120 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10121 return ISD::FMA; 10122 } 10123 10124 return 0; 10125 } 10126 10127 // For a reassociatable opcode perform: 10128 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10129 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10130 SelectionDAG &DAG) const { 10131 EVT VT = N->getValueType(0); 10132 if (VT != MVT::i32 && VT != MVT::i64) 10133 return SDValue(); 10134 10135 unsigned Opc = N->getOpcode(); 10136 SDValue Op0 = N->getOperand(0); 10137 SDValue Op1 = N->getOperand(1); 10138 10139 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10140 return SDValue(); 10141 10142 if (Op0->isDivergent()) 10143 std::swap(Op0, Op1); 10144 10145 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10146 return SDValue(); 10147 10148 SDValue Op2 = Op1.getOperand(1); 10149 Op1 = Op1.getOperand(0); 10150 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10151 return SDValue(); 10152 10153 if (Op1->isDivergent()) 10154 std::swap(Op1, Op2); 10155 10156 // If either operand is constant this will conflict with 10157 // DAGCombiner::ReassociateOps(). 10158 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10159 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10160 return SDValue(); 10161 10162 SDLoc SL(N); 10163 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10164 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10165 } 10166 10167 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10168 EVT VT, 10169 SDValue N0, SDValue N1, SDValue N2, 10170 bool Signed) { 10171 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10172 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10173 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10174 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10175 } 10176 10177 SDValue SITargetLowering::performAddCombine(SDNode *N, 10178 DAGCombinerInfo &DCI) const { 10179 SelectionDAG &DAG = DCI.DAG; 10180 EVT VT = N->getValueType(0); 10181 SDLoc SL(N); 10182 SDValue LHS = N->getOperand(0); 10183 SDValue RHS = N->getOperand(1); 10184 10185 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10186 && Subtarget->hasMad64_32() && 10187 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10188 VT.getScalarSizeInBits() <= 64) { 10189 if (LHS.getOpcode() != ISD::MUL) 10190 std::swap(LHS, RHS); 10191 10192 SDValue MulLHS = LHS.getOperand(0); 10193 SDValue MulRHS = LHS.getOperand(1); 10194 SDValue AddRHS = RHS; 10195 10196 // TODO: Maybe restrict if SGPR inputs. 10197 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10198 numBitsUnsigned(MulRHS, DAG) <= 32) { 10199 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10200 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10201 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10202 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10203 } 10204 10205 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10206 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10207 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10208 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10209 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10210 } 10211 10212 return SDValue(); 10213 } 10214 10215 if (SDValue V = reassociateScalarOps(N, DAG)) { 10216 return V; 10217 } 10218 10219 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10220 return SDValue(); 10221 10222 // add x, zext (setcc) => addcarry x, 0, setcc 10223 // add x, sext (setcc) => subcarry x, 0, setcc 10224 unsigned Opc = LHS.getOpcode(); 10225 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10226 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10227 std::swap(RHS, LHS); 10228 10229 Opc = RHS.getOpcode(); 10230 switch (Opc) { 10231 default: break; 10232 case ISD::ZERO_EXTEND: 10233 case ISD::SIGN_EXTEND: 10234 case ISD::ANY_EXTEND: { 10235 auto Cond = RHS.getOperand(0); 10236 // If this won't be a real VOPC output, we would still need to insert an 10237 // extra instruction anyway. 10238 if (!isBoolSGPR(Cond)) 10239 break; 10240 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10241 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10242 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10243 return DAG.getNode(Opc, SL, VTList, Args); 10244 } 10245 case ISD::ADDCARRY: { 10246 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10247 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10248 if (!C || C->getZExtValue() != 0) break; 10249 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10250 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10251 } 10252 } 10253 return SDValue(); 10254 } 10255 10256 SDValue SITargetLowering::performSubCombine(SDNode *N, 10257 DAGCombinerInfo &DCI) const { 10258 SelectionDAG &DAG = DCI.DAG; 10259 EVT VT = N->getValueType(0); 10260 10261 if (VT != MVT::i32) 10262 return SDValue(); 10263 10264 SDLoc SL(N); 10265 SDValue LHS = N->getOperand(0); 10266 SDValue RHS = N->getOperand(1); 10267 10268 // sub x, zext (setcc) => subcarry x, 0, setcc 10269 // sub x, sext (setcc) => addcarry x, 0, setcc 10270 unsigned Opc = RHS.getOpcode(); 10271 switch (Opc) { 10272 default: break; 10273 case ISD::ZERO_EXTEND: 10274 case ISD::SIGN_EXTEND: 10275 case ISD::ANY_EXTEND: { 10276 auto Cond = RHS.getOperand(0); 10277 // If this won't be a real VOPC output, we would still need to insert an 10278 // extra instruction anyway. 10279 if (!isBoolSGPR(Cond)) 10280 break; 10281 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10282 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10283 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10284 return DAG.getNode(Opc, SL, VTList, Args); 10285 } 10286 } 10287 10288 if (LHS.getOpcode() == ISD::SUBCARRY) { 10289 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10290 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10291 if (!C || !C->isNullValue()) 10292 return SDValue(); 10293 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10294 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10295 } 10296 return SDValue(); 10297 } 10298 10299 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10300 DAGCombinerInfo &DCI) const { 10301 10302 if (N->getValueType(0) != MVT::i32) 10303 return SDValue(); 10304 10305 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10306 if (!C || C->getZExtValue() != 0) 10307 return SDValue(); 10308 10309 SelectionDAG &DAG = DCI.DAG; 10310 SDValue LHS = N->getOperand(0); 10311 10312 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10313 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10314 unsigned LHSOpc = LHS.getOpcode(); 10315 unsigned Opc = N->getOpcode(); 10316 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10317 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10318 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10319 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10320 } 10321 return SDValue(); 10322 } 10323 10324 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10325 DAGCombinerInfo &DCI) const { 10326 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10327 return SDValue(); 10328 10329 SelectionDAG &DAG = DCI.DAG; 10330 EVT VT = N->getValueType(0); 10331 10332 SDLoc SL(N); 10333 SDValue LHS = N->getOperand(0); 10334 SDValue RHS = N->getOperand(1); 10335 10336 // These should really be instruction patterns, but writing patterns with 10337 // source modiifiers is a pain. 10338 10339 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10340 if (LHS.getOpcode() == ISD::FADD) { 10341 SDValue A = LHS.getOperand(0); 10342 if (A == LHS.getOperand(1)) { 10343 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10344 if (FusedOp != 0) { 10345 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10346 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10347 } 10348 } 10349 } 10350 10351 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10352 if (RHS.getOpcode() == ISD::FADD) { 10353 SDValue A = RHS.getOperand(0); 10354 if (A == RHS.getOperand(1)) { 10355 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10356 if (FusedOp != 0) { 10357 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10358 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10359 } 10360 } 10361 } 10362 10363 return SDValue(); 10364 } 10365 10366 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10367 DAGCombinerInfo &DCI) const { 10368 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10369 return SDValue(); 10370 10371 SelectionDAG &DAG = DCI.DAG; 10372 SDLoc SL(N); 10373 EVT VT = N->getValueType(0); 10374 assert(!VT.isVector()); 10375 10376 // Try to get the fneg to fold into the source modifier. This undoes generic 10377 // DAG combines and folds them into the mad. 10378 // 10379 // Only do this if we are not trying to support denormals. v_mad_f32 does 10380 // not support denormals ever. 10381 SDValue LHS = N->getOperand(0); 10382 SDValue RHS = N->getOperand(1); 10383 if (LHS.getOpcode() == ISD::FADD) { 10384 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10385 SDValue A = LHS.getOperand(0); 10386 if (A == LHS.getOperand(1)) { 10387 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10388 if (FusedOp != 0){ 10389 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10390 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10391 10392 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10393 } 10394 } 10395 } 10396 10397 if (RHS.getOpcode() == ISD::FADD) { 10398 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10399 10400 SDValue A = RHS.getOperand(0); 10401 if (A == RHS.getOperand(1)) { 10402 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10403 if (FusedOp != 0){ 10404 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10405 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10406 } 10407 } 10408 } 10409 10410 return SDValue(); 10411 } 10412 10413 SDValue SITargetLowering::performFMACombine(SDNode *N, 10414 DAGCombinerInfo &DCI) const { 10415 SelectionDAG &DAG = DCI.DAG; 10416 EVT VT = N->getValueType(0); 10417 SDLoc SL(N); 10418 10419 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10420 return SDValue(); 10421 10422 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10423 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10424 SDValue Op1 = N->getOperand(0); 10425 SDValue Op2 = N->getOperand(1); 10426 SDValue FMA = N->getOperand(2); 10427 10428 if (FMA.getOpcode() != ISD::FMA || 10429 Op1.getOpcode() != ISD::FP_EXTEND || 10430 Op2.getOpcode() != ISD::FP_EXTEND) 10431 return SDValue(); 10432 10433 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10434 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10435 // is sufficient to allow generaing fdot2. 10436 const TargetOptions &Options = DAG.getTarget().Options; 10437 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10438 (N->getFlags().hasAllowContract() && 10439 FMA->getFlags().hasAllowContract())) { 10440 Op1 = Op1.getOperand(0); 10441 Op2 = Op2.getOperand(0); 10442 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10443 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10444 return SDValue(); 10445 10446 SDValue Vec1 = Op1.getOperand(0); 10447 SDValue Idx1 = Op1.getOperand(1); 10448 SDValue Vec2 = Op2.getOperand(0); 10449 10450 SDValue FMAOp1 = FMA.getOperand(0); 10451 SDValue FMAOp2 = FMA.getOperand(1); 10452 SDValue FMAAcc = FMA.getOperand(2); 10453 10454 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10455 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10456 return SDValue(); 10457 10458 FMAOp1 = FMAOp1.getOperand(0); 10459 FMAOp2 = FMAOp2.getOperand(0); 10460 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10461 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10462 return SDValue(); 10463 10464 SDValue Vec3 = FMAOp1.getOperand(0); 10465 SDValue Vec4 = FMAOp2.getOperand(0); 10466 SDValue Idx2 = FMAOp1.getOperand(1); 10467 10468 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10469 // Idx1 and Idx2 cannot be the same. 10470 Idx1 == Idx2) 10471 return SDValue(); 10472 10473 if (Vec1 == Vec2 || Vec3 == Vec4) 10474 return SDValue(); 10475 10476 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10477 return SDValue(); 10478 10479 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10480 (Vec1 == Vec4 && Vec2 == Vec3)) { 10481 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10482 DAG.getTargetConstant(0, SL, MVT::i1)); 10483 } 10484 } 10485 return SDValue(); 10486 } 10487 10488 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10489 DAGCombinerInfo &DCI) const { 10490 SelectionDAG &DAG = DCI.DAG; 10491 SDLoc SL(N); 10492 10493 SDValue LHS = N->getOperand(0); 10494 SDValue RHS = N->getOperand(1); 10495 EVT VT = LHS.getValueType(); 10496 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10497 10498 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10499 if (!CRHS) { 10500 CRHS = dyn_cast<ConstantSDNode>(LHS); 10501 if (CRHS) { 10502 std::swap(LHS, RHS); 10503 CC = getSetCCSwappedOperands(CC); 10504 } 10505 } 10506 10507 if (CRHS) { 10508 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10509 isBoolSGPR(LHS.getOperand(0))) { 10510 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10511 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10512 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10513 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10514 if ((CRHS->isAllOnesValue() && 10515 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10516 (CRHS->isNullValue() && 10517 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10518 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10519 DAG.getConstant(-1, SL, MVT::i1)); 10520 if ((CRHS->isAllOnesValue() && 10521 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10522 (CRHS->isNullValue() && 10523 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10524 return LHS.getOperand(0); 10525 } 10526 10527 uint64_t CRHSVal = CRHS->getZExtValue(); 10528 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10529 LHS.getOpcode() == ISD::SELECT && 10530 isa<ConstantSDNode>(LHS.getOperand(1)) && 10531 isa<ConstantSDNode>(LHS.getOperand(2)) && 10532 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10533 isBoolSGPR(LHS.getOperand(0))) { 10534 // Given CT != FT: 10535 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10536 // setcc (select cc, CT, CF), CF, ne => cc 10537 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10538 // setcc (select cc, CT, CF), CT, eq => cc 10539 uint64_t CT = LHS.getConstantOperandVal(1); 10540 uint64_t CF = LHS.getConstantOperandVal(2); 10541 10542 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10543 (CT == CRHSVal && CC == ISD::SETNE)) 10544 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10545 DAG.getConstant(-1, SL, MVT::i1)); 10546 if ((CF == CRHSVal && CC == ISD::SETNE) || 10547 (CT == CRHSVal && CC == ISD::SETEQ)) 10548 return LHS.getOperand(0); 10549 } 10550 } 10551 10552 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10553 VT != MVT::f16)) 10554 return SDValue(); 10555 10556 // Match isinf/isfinite pattern 10557 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10558 // (fcmp one (fabs x), inf) -> (fp_class x, 10559 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10560 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10561 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10562 if (!CRHS) 10563 return SDValue(); 10564 10565 const APFloat &APF = CRHS->getValueAPF(); 10566 if (APF.isInfinity() && !APF.isNegative()) { 10567 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10568 SIInstrFlags::N_INFINITY; 10569 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10570 SIInstrFlags::P_ZERO | 10571 SIInstrFlags::N_NORMAL | 10572 SIInstrFlags::P_NORMAL | 10573 SIInstrFlags::N_SUBNORMAL | 10574 SIInstrFlags::P_SUBNORMAL; 10575 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10576 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10577 DAG.getConstant(Mask, SL, MVT::i32)); 10578 } 10579 } 10580 10581 return SDValue(); 10582 } 10583 10584 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10585 DAGCombinerInfo &DCI) const { 10586 SelectionDAG &DAG = DCI.DAG; 10587 SDLoc SL(N); 10588 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10589 10590 SDValue Src = N->getOperand(0); 10591 SDValue Shift = N->getOperand(0); 10592 10593 // TODO: Extend type shouldn't matter (assuming legal types). 10594 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10595 Shift = Shift.getOperand(0); 10596 10597 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10598 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10599 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10600 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10601 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10602 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10603 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10604 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10605 SDLoc(Shift.getOperand(0)), MVT::i32); 10606 10607 unsigned ShiftOffset = 8 * Offset; 10608 if (Shift.getOpcode() == ISD::SHL) 10609 ShiftOffset -= C->getZExtValue(); 10610 else 10611 ShiftOffset += C->getZExtValue(); 10612 10613 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10614 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10615 MVT::f32, Shift); 10616 } 10617 } 10618 } 10619 10620 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10621 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10622 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10623 // We simplified Src. If this node is not dead, visit it again so it is 10624 // folded properly. 10625 if (N->getOpcode() != ISD::DELETED_NODE) 10626 DCI.AddToWorklist(N); 10627 return SDValue(N, 0); 10628 } 10629 10630 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10631 if (SDValue DemandedSrc = 10632 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10633 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10634 10635 return SDValue(); 10636 } 10637 10638 SDValue SITargetLowering::performClampCombine(SDNode *N, 10639 DAGCombinerInfo &DCI) const { 10640 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10641 if (!CSrc) 10642 return SDValue(); 10643 10644 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10645 const APFloat &F = CSrc->getValueAPF(); 10646 APFloat Zero = APFloat::getZero(F.getSemantics()); 10647 if (F < Zero || 10648 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10649 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10650 } 10651 10652 APFloat One(F.getSemantics(), "1.0"); 10653 if (F > One) 10654 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10655 10656 return SDValue(CSrc, 0); 10657 } 10658 10659 10660 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10661 DAGCombinerInfo &DCI) const { 10662 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10663 return SDValue(); 10664 switch (N->getOpcode()) { 10665 case ISD::ADD: 10666 return performAddCombine(N, DCI); 10667 case ISD::SUB: 10668 return performSubCombine(N, DCI); 10669 case ISD::ADDCARRY: 10670 case ISD::SUBCARRY: 10671 return performAddCarrySubCarryCombine(N, DCI); 10672 case ISD::FADD: 10673 return performFAddCombine(N, DCI); 10674 case ISD::FSUB: 10675 return performFSubCombine(N, DCI); 10676 case ISD::SETCC: 10677 return performSetCCCombine(N, DCI); 10678 case ISD::FMAXNUM: 10679 case ISD::FMINNUM: 10680 case ISD::FMAXNUM_IEEE: 10681 case ISD::FMINNUM_IEEE: 10682 case ISD::SMAX: 10683 case ISD::SMIN: 10684 case ISD::UMAX: 10685 case ISD::UMIN: 10686 case AMDGPUISD::FMIN_LEGACY: 10687 case AMDGPUISD::FMAX_LEGACY: 10688 return performMinMaxCombine(N, DCI); 10689 case ISD::FMA: 10690 return performFMACombine(N, DCI); 10691 case ISD::AND: 10692 return performAndCombine(N, DCI); 10693 case ISD::OR: 10694 return performOrCombine(N, DCI); 10695 case ISD::XOR: 10696 return performXorCombine(N, DCI); 10697 case ISD::ZERO_EXTEND: 10698 return performZeroExtendCombine(N, DCI); 10699 case ISD::SIGN_EXTEND_INREG: 10700 return performSignExtendInRegCombine(N , DCI); 10701 case AMDGPUISD::FP_CLASS: 10702 return performClassCombine(N, DCI); 10703 case ISD::FCANONICALIZE: 10704 return performFCanonicalizeCombine(N, DCI); 10705 case AMDGPUISD::RCP: 10706 return performRcpCombine(N, DCI); 10707 case AMDGPUISD::FRACT: 10708 case AMDGPUISD::RSQ: 10709 case AMDGPUISD::RCP_LEGACY: 10710 case AMDGPUISD::RCP_IFLAG: 10711 case AMDGPUISD::RSQ_CLAMP: 10712 case AMDGPUISD::LDEXP: { 10713 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10714 SDValue Src = N->getOperand(0); 10715 if (Src.isUndef()) 10716 return Src; 10717 break; 10718 } 10719 case ISD::SINT_TO_FP: 10720 case ISD::UINT_TO_FP: 10721 return performUCharToFloatCombine(N, DCI); 10722 case AMDGPUISD::CVT_F32_UBYTE0: 10723 case AMDGPUISD::CVT_F32_UBYTE1: 10724 case AMDGPUISD::CVT_F32_UBYTE2: 10725 case AMDGPUISD::CVT_F32_UBYTE3: 10726 return performCvtF32UByteNCombine(N, DCI); 10727 case AMDGPUISD::FMED3: 10728 return performFMed3Combine(N, DCI); 10729 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10730 return performCvtPkRTZCombine(N, DCI); 10731 case AMDGPUISD::CLAMP: 10732 return performClampCombine(N, DCI); 10733 case ISD::SCALAR_TO_VECTOR: { 10734 SelectionDAG &DAG = DCI.DAG; 10735 EVT VT = N->getValueType(0); 10736 10737 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10738 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10739 SDLoc SL(N); 10740 SDValue Src = N->getOperand(0); 10741 EVT EltVT = Src.getValueType(); 10742 if (EltVT == MVT::f16) 10743 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10744 10745 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10746 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10747 } 10748 10749 break; 10750 } 10751 case ISD::EXTRACT_VECTOR_ELT: 10752 return performExtractVectorEltCombine(N, DCI); 10753 case ISD::INSERT_VECTOR_ELT: 10754 return performInsertVectorEltCombine(N, DCI); 10755 case ISD::LOAD: { 10756 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10757 return Widended; 10758 LLVM_FALLTHROUGH; 10759 } 10760 default: { 10761 if (!DCI.isBeforeLegalize()) { 10762 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10763 return performMemSDNodeCombine(MemNode, DCI); 10764 } 10765 10766 break; 10767 } 10768 } 10769 10770 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10771 } 10772 10773 /// Helper function for adjustWritemask 10774 static unsigned SubIdx2Lane(unsigned Idx) { 10775 switch (Idx) { 10776 default: return 0; 10777 case AMDGPU::sub0: return 0; 10778 case AMDGPU::sub1: return 1; 10779 case AMDGPU::sub2: return 2; 10780 case AMDGPU::sub3: return 3; 10781 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10782 } 10783 } 10784 10785 /// Adjust the writemask of MIMG instructions 10786 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10787 SelectionDAG &DAG) const { 10788 unsigned Opcode = Node->getMachineOpcode(); 10789 10790 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10791 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10792 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10793 return Node; // not implemented for D16 10794 10795 SDNode *Users[5] = { nullptr }; 10796 unsigned Lane = 0; 10797 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10798 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10799 unsigned NewDmask = 0; 10800 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10801 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10802 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10803 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10804 unsigned TFCLane = 0; 10805 bool HasChain = Node->getNumValues() > 1; 10806 10807 if (OldDmask == 0) { 10808 // These are folded out, but on the chance it happens don't assert. 10809 return Node; 10810 } 10811 10812 unsigned OldBitsSet = countPopulation(OldDmask); 10813 // Work out which is the TFE/LWE lane if that is enabled. 10814 if (UsesTFC) { 10815 TFCLane = OldBitsSet; 10816 } 10817 10818 // Try to figure out the used register components 10819 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10820 I != E; ++I) { 10821 10822 // Don't look at users of the chain. 10823 if (I.getUse().getResNo() != 0) 10824 continue; 10825 10826 // Abort if we can't understand the usage 10827 if (!I->isMachineOpcode() || 10828 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10829 return Node; 10830 10831 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10832 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10833 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10834 // set, etc. 10835 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10836 10837 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10838 if (UsesTFC && Lane == TFCLane) { 10839 Users[Lane] = *I; 10840 } else { 10841 // Set which texture component corresponds to the lane. 10842 unsigned Comp; 10843 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10844 Comp = countTrailingZeros(Dmask); 10845 Dmask &= ~(1 << Comp); 10846 } 10847 10848 // Abort if we have more than one user per component. 10849 if (Users[Lane]) 10850 return Node; 10851 10852 Users[Lane] = *I; 10853 NewDmask |= 1 << Comp; 10854 } 10855 } 10856 10857 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10858 bool NoChannels = !NewDmask; 10859 if (NoChannels) { 10860 if (!UsesTFC) { 10861 // No uses of the result and not using TFC. Then do nothing. 10862 return Node; 10863 } 10864 // If the original dmask has one channel - then nothing to do 10865 if (OldBitsSet == 1) 10866 return Node; 10867 // Use an arbitrary dmask - required for the instruction to work 10868 NewDmask = 1; 10869 } 10870 // Abort if there's no change 10871 if (NewDmask == OldDmask) 10872 return Node; 10873 10874 unsigned BitsSet = countPopulation(NewDmask); 10875 10876 // Check for TFE or LWE - increase the number of channels by one to account 10877 // for the extra return value 10878 // This will need adjustment for D16 if this is also included in 10879 // adjustWriteMask (this function) but at present D16 are excluded. 10880 unsigned NewChannels = BitsSet + UsesTFC; 10881 10882 int NewOpcode = 10883 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10884 assert(NewOpcode != -1 && 10885 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10886 "failed to find equivalent MIMG op"); 10887 10888 // Adjust the writemask in the node 10889 SmallVector<SDValue, 12> Ops; 10890 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10891 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10892 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10893 10894 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10895 10896 MVT ResultVT = NewChannels == 1 ? 10897 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10898 NewChannels == 5 ? 8 : NewChannels); 10899 SDVTList NewVTList = HasChain ? 10900 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10901 10902 10903 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10904 NewVTList, Ops); 10905 10906 if (HasChain) { 10907 // Update chain. 10908 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10909 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10910 } 10911 10912 if (NewChannels == 1) { 10913 assert(Node->hasNUsesOfValue(1, 0)); 10914 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10915 SDLoc(Node), Users[Lane]->getValueType(0), 10916 SDValue(NewNode, 0)); 10917 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10918 return nullptr; 10919 } 10920 10921 // Update the users of the node with the new indices 10922 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10923 SDNode *User = Users[i]; 10924 if (!User) { 10925 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10926 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10927 if (i || !NoChannels) 10928 continue; 10929 } else { 10930 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10931 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10932 } 10933 10934 switch (Idx) { 10935 default: break; 10936 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10937 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10938 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10939 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10940 } 10941 } 10942 10943 DAG.RemoveDeadNode(Node); 10944 return nullptr; 10945 } 10946 10947 static bool isFrameIndexOp(SDValue Op) { 10948 if (Op.getOpcode() == ISD::AssertZext) 10949 Op = Op.getOperand(0); 10950 10951 return isa<FrameIndexSDNode>(Op); 10952 } 10953 10954 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10955 /// with frame index operands. 10956 /// LLVM assumes that inputs are to these instructions are registers. 10957 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10958 SelectionDAG &DAG) const { 10959 if (Node->getOpcode() == ISD::CopyToReg) { 10960 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10961 SDValue SrcVal = Node->getOperand(2); 10962 10963 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10964 // to try understanding copies to physical registers. 10965 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 10966 SDLoc SL(Node); 10967 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10968 SDValue VReg = DAG.getRegister( 10969 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10970 10971 SDNode *Glued = Node->getGluedNode(); 10972 SDValue ToVReg 10973 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10974 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10975 SDValue ToResultReg 10976 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10977 VReg, ToVReg.getValue(1)); 10978 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10979 DAG.RemoveDeadNode(Node); 10980 return ToResultReg.getNode(); 10981 } 10982 } 10983 10984 SmallVector<SDValue, 8> Ops; 10985 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10986 if (!isFrameIndexOp(Node->getOperand(i))) { 10987 Ops.push_back(Node->getOperand(i)); 10988 continue; 10989 } 10990 10991 SDLoc DL(Node); 10992 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10993 Node->getOperand(i).getValueType(), 10994 Node->getOperand(i)), 0)); 10995 } 10996 10997 return DAG.UpdateNodeOperands(Node, Ops); 10998 } 10999 11000 /// Fold the instructions after selecting them. 11001 /// Returns null if users were already updated. 11002 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11003 SelectionDAG &DAG) const { 11004 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11005 unsigned Opcode = Node->getMachineOpcode(); 11006 11007 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11008 !TII->isGather4(Opcode) && 11009 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11010 return adjustWritemask(Node, DAG); 11011 } 11012 11013 if (Opcode == AMDGPU::INSERT_SUBREG || 11014 Opcode == AMDGPU::REG_SEQUENCE) { 11015 legalizeTargetIndependentNode(Node, DAG); 11016 return Node; 11017 } 11018 11019 switch (Opcode) { 11020 case AMDGPU::V_DIV_SCALE_F32: 11021 case AMDGPU::V_DIV_SCALE_F64: { 11022 // Satisfy the operand register constraint when one of the inputs is 11023 // undefined. Ordinarily each undef value will have its own implicit_def of 11024 // a vreg, so force these to use a single register. 11025 SDValue Src0 = Node->getOperand(0); 11026 SDValue Src1 = Node->getOperand(1); 11027 SDValue Src2 = Node->getOperand(2); 11028 11029 if ((Src0.isMachineOpcode() && 11030 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11031 (Src0 == Src1 || Src0 == Src2)) 11032 break; 11033 11034 MVT VT = Src0.getValueType().getSimpleVT(); 11035 const TargetRegisterClass *RC = 11036 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11037 11038 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11039 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11040 11041 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11042 UndefReg, Src0, SDValue()); 11043 11044 // src0 must be the same register as src1 or src2, even if the value is 11045 // undefined, so make sure we don't violate this constraint. 11046 if (Src0.isMachineOpcode() && 11047 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11048 if (Src1.isMachineOpcode() && 11049 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11050 Src0 = Src1; 11051 else if (Src2.isMachineOpcode() && 11052 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11053 Src0 = Src2; 11054 else { 11055 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11056 Src0 = UndefReg; 11057 Src1 = UndefReg; 11058 } 11059 } else 11060 break; 11061 11062 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 11063 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 11064 Ops.push_back(Node->getOperand(I)); 11065 11066 Ops.push_back(ImpDef.getValue(1)); 11067 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11068 } 11069 default: 11070 break; 11071 } 11072 11073 return Node; 11074 } 11075 11076 /// Assign the register class depending on the number of 11077 /// bits set in the writemask 11078 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11079 SDNode *Node) const { 11080 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11081 11082 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11083 11084 if (TII->isVOP3(MI.getOpcode())) { 11085 // Make sure constant bus requirements are respected. 11086 TII->legalizeOperandsVOP3(MRI, MI); 11087 11088 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11089 // This saves a chain-copy of registers and better ballance register 11090 // use between vgpr and agpr as agpr tuples tend to be big. 11091 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11092 unsigned Opc = MI.getOpcode(); 11093 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11094 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11095 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11096 if (I == -1) 11097 break; 11098 MachineOperand &Op = MI.getOperand(I); 11099 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11100 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11101 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11102 continue; 11103 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11104 if (!Src || !Src->isCopy() || 11105 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11106 continue; 11107 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11108 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11109 // All uses of agpr64 and agpr32 can also accept vgpr except for 11110 // v_accvgpr_read, but we do not produce agpr reads during selection, 11111 // so no use checks are needed. 11112 MRI.setRegClass(Op.getReg(), NewRC); 11113 } 11114 } 11115 11116 return; 11117 } 11118 11119 // Replace unused atomics with the no return version. 11120 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11121 if (NoRetAtomicOp != -1) { 11122 if (!Node->hasAnyUseOfValue(0)) { 11123 MI.setDesc(TII->get(NoRetAtomicOp)); 11124 MI.RemoveOperand(0); 11125 return; 11126 } 11127 11128 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11129 // instruction, because the return type of these instructions is a vec2 of 11130 // the memory type, so it can be tied to the input operand. 11131 // This means these instructions always have a use, so we need to add a 11132 // special case to check if the atomic has only one extract_subreg use, 11133 // which itself has no uses. 11134 if ((Node->hasNUsesOfValue(1, 0) && 11135 Node->use_begin()->isMachineOpcode() && 11136 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11137 !Node->use_begin()->hasAnyUseOfValue(0))) { 11138 Register Def = MI.getOperand(0).getReg(); 11139 11140 // Change this into a noret atomic. 11141 MI.setDesc(TII->get(NoRetAtomicOp)); 11142 MI.RemoveOperand(0); 11143 11144 // If we only remove the def operand from the atomic instruction, the 11145 // extract_subreg will be left with a use of a vreg without a def. 11146 // So we need to insert an implicit_def to avoid machine verifier 11147 // errors. 11148 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11149 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11150 } 11151 return; 11152 } 11153 } 11154 11155 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11156 uint64_t Val) { 11157 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11158 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11159 } 11160 11161 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11162 const SDLoc &DL, 11163 SDValue Ptr) const { 11164 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11165 11166 // Build the half of the subregister with the constants before building the 11167 // full 128-bit register. If we are building multiple resource descriptors, 11168 // this will allow CSEing of the 2-component register. 11169 const SDValue Ops0[] = { 11170 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11171 buildSMovImm32(DAG, DL, 0), 11172 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11173 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11174 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11175 }; 11176 11177 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11178 MVT::v2i32, Ops0), 0); 11179 11180 // Combine the constants and the pointer. 11181 const SDValue Ops1[] = { 11182 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11183 Ptr, 11184 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11185 SubRegHi, 11186 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11187 }; 11188 11189 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11190 } 11191 11192 /// Return a resource descriptor with the 'Add TID' bit enabled 11193 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11194 /// of the resource descriptor) to create an offset, which is added to 11195 /// the resource pointer. 11196 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11197 SDValue Ptr, uint32_t RsrcDword1, 11198 uint64_t RsrcDword2And3) const { 11199 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11200 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11201 if (RsrcDword1) { 11202 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11203 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11204 0); 11205 } 11206 11207 SDValue DataLo = buildSMovImm32(DAG, DL, 11208 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11209 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11210 11211 const SDValue Ops[] = { 11212 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11213 PtrLo, 11214 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11215 PtrHi, 11216 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11217 DataLo, 11218 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11219 DataHi, 11220 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11221 }; 11222 11223 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11224 } 11225 11226 //===----------------------------------------------------------------------===// 11227 // SI Inline Assembly Support 11228 //===----------------------------------------------------------------------===// 11229 11230 std::pair<unsigned, const TargetRegisterClass *> 11231 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11232 StringRef Constraint, 11233 MVT VT) const { 11234 const TargetRegisterClass *RC = nullptr; 11235 if (Constraint.size() == 1) { 11236 const unsigned BitWidth = VT.getSizeInBits(); 11237 switch (Constraint[0]) { 11238 default: 11239 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11240 case 's': 11241 case 'r': 11242 switch (BitWidth) { 11243 case 16: 11244 RC = &AMDGPU::SReg_32RegClass; 11245 break; 11246 case 64: 11247 RC = &AMDGPU::SGPR_64RegClass; 11248 break; 11249 default: 11250 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11251 if (!RC) 11252 return std::make_pair(0U, nullptr); 11253 break; 11254 } 11255 break; 11256 case 'v': 11257 switch (BitWidth) { 11258 case 16: 11259 RC = &AMDGPU::VGPR_32RegClass; 11260 break; 11261 default: 11262 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11263 if (!RC) 11264 return std::make_pair(0U, nullptr); 11265 break; 11266 } 11267 break; 11268 case 'a': 11269 if (!Subtarget->hasMAIInsts()) 11270 break; 11271 switch (BitWidth) { 11272 case 16: 11273 RC = &AMDGPU::AGPR_32RegClass; 11274 break; 11275 default: 11276 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11277 if (!RC) 11278 return std::make_pair(0U, nullptr); 11279 break; 11280 } 11281 break; 11282 } 11283 // We actually support i128, i16 and f16 as inline parameters 11284 // even if they are not reported as legal 11285 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11286 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11287 return std::make_pair(0U, RC); 11288 } 11289 11290 if (Constraint.size() > 1) { 11291 if (Constraint[1] == 'v') { 11292 RC = &AMDGPU::VGPR_32RegClass; 11293 } else if (Constraint[1] == 's') { 11294 RC = &AMDGPU::SGPR_32RegClass; 11295 } else if (Constraint[1] == 'a') { 11296 RC = &AMDGPU::AGPR_32RegClass; 11297 } 11298 11299 if (RC) { 11300 uint32_t Idx; 11301 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11302 if (!Failed && Idx < RC->getNumRegs()) 11303 return std::make_pair(RC->getRegister(Idx), RC); 11304 } 11305 } 11306 11307 // FIXME: Returns VS_32 for physical SGPR constraints 11308 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11309 } 11310 11311 static bool isImmConstraint(StringRef Constraint) { 11312 if (Constraint.size() == 1) { 11313 switch (Constraint[0]) { 11314 default: break; 11315 case 'I': 11316 case 'J': 11317 case 'A': 11318 case 'B': 11319 case 'C': 11320 return true; 11321 } 11322 } else if (Constraint == "DA" || 11323 Constraint == "DB") { 11324 return true; 11325 } 11326 return false; 11327 } 11328 11329 SITargetLowering::ConstraintType 11330 SITargetLowering::getConstraintType(StringRef Constraint) const { 11331 if (Constraint.size() == 1) { 11332 switch (Constraint[0]) { 11333 default: break; 11334 case 's': 11335 case 'v': 11336 case 'a': 11337 return C_RegisterClass; 11338 } 11339 } 11340 if (isImmConstraint(Constraint)) { 11341 return C_Other; 11342 } 11343 return TargetLowering::getConstraintType(Constraint); 11344 } 11345 11346 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11347 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11348 Val = Val & maskTrailingOnes<uint64_t>(Size); 11349 } 11350 return Val; 11351 } 11352 11353 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11354 std::string &Constraint, 11355 std::vector<SDValue> &Ops, 11356 SelectionDAG &DAG) const { 11357 if (isImmConstraint(Constraint)) { 11358 uint64_t Val; 11359 if (getAsmOperandConstVal(Op, Val) && 11360 checkAsmConstraintVal(Op, Constraint, Val)) { 11361 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11362 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11363 } 11364 } else { 11365 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11366 } 11367 } 11368 11369 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11370 unsigned Size = Op.getScalarValueSizeInBits(); 11371 if (Size > 64) 11372 return false; 11373 11374 if (Size == 16 && !Subtarget->has16BitInsts()) 11375 return false; 11376 11377 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11378 Val = C->getSExtValue(); 11379 return true; 11380 } 11381 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11382 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11383 return true; 11384 } 11385 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11386 if (Size != 16 || Op.getNumOperands() != 2) 11387 return false; 11388 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11389 return false; 11390 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11391 Val = C->getSExtValue(); 11392 return true; 11393 } 11394 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11395 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11396 return true; 11397 } 11398 } 11399 11400 return false; 11401 } 11402 11403 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11404 const std::string &Constraint, 11405 uint64_t Val) const { 11406 if (Constraint.size() == 1) { 11407 switch (Constraint[0]) { 11408 case 'I': 11409 return AMDGPU::isInlinableIntLiteral(Val); 11410 case 'J': 11411 return isInt<16>(Val); 11412 case 'A': 11413 return checkAsmConstraintValA(Op, Val); 11414 case 'B': 11415 return isInt<32>(Val); 11416 case 'C': 11417 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11418 AMDGPU::isInlinableIntLiteral(Val); 11419 default: 11420 break; 11421 } 11422 } else if (Constraint.size() == 2) { 11423 if (Constraint == "DA") { 11424 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11425 int64_t LoBits = static_cast<int32_t>(Val); 11426 return checkAsmConstraintValA(Op, HiBits, 32) && 11427 checkAsmConstraintValA(Op, LoBits, 32); 11428 } 11429 if (Constraint == "DB") { 11430 return true; 11431 } 11432 } 11433 llvm_unreachable("Invalid asm constraint"); 11434 } 11435 11436 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11437 uint64_t Val, 11438 unsigned MaxSize) const { 11439 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11440 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11441 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11442 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11443 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11444 return true; 11445 } 11446 return false; 11447 } 11448 11449 // Figure out which registers should be reserved for stack access. Only after 11450 // the function is legalized do we know all of the non-spill stack objects or if 11451 // calls are present. 11452 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11453 MachineRegisterInfo &MRI = MF.getRegInfo(); 11454 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11455 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11456 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11457 11458 if (Info->isEntryFunction()) { 11459 // Callable functions have fixed registers used for stack access. 11460 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11461 } 11462 11463 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11464 Info->getStackPtrOffsetReg())); 11465 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11466 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11467 11468 // We need to worry about replacing the default register with itself in case 11469 // of MIR testcases missing the MFI. 11470 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11471 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11472 11473 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11474 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11475 11476 Info->limitOccupancy(MF); 11477 11478 if (ST.isWave32() && !MF.empty()) { 11479 // Add VCC_HI def because many instructions marked as imp-use VCC where 11480 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11481 // having a use of undef. 11482 11483 const SIInstrInfo *TII = ST.getInstrInfo(); 11484 DebugLoc DL; 11485 11486 MachineBasicBlock &MBB = MF.front(); 11487 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11488 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11489 11490 for (auto &MBB : MF) { 11491 for (auto &MI : MBB) { 11492 TII->fixImplicitOperands(MI); 11493 } 11494 } 11495 } 11496 11497 TargetLoweringBase::finalizeLowering(MF); 11498 11499 // Allocate a VGPR for future SGPR Spill if 11500 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11501 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11502 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11503 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11504 Info->reserveVGPRforSGPRSpills(MF); 11505 } 11506 11507 void SITargetLowering::computeKnownBitsForFrameIndex( 11508 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11509 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11510 11511 // Set the high bits to zero based on the maximum allowed scratch size per 11512 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11513 // calculation won't overflow, so assume the sign bit is never set. 11514 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11515 } 11516 11517 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11518 KnownBits &Known, unsigned Dim) { 11519 unsigned MaxValue = 11520 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11521 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11522 } 11523 11524 void SITargetLowering::computeKnownBitsForTargetInstr( 11525 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11526 const MachineRegisterInfo &MRI, unsigned Depth) const { 11527 const MachineInstr *MI = MRI.getVRegDef(R); 11528 switch (MI->getOpcode()) { 11529 case AMDGPU::G_INTRINSIC: { 11530 switch (MI->getIntrinsicID()) { 11531 case Intrinsic::amdgcn_workitem_id_x: 11532 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11533 break; 11534 case Intrinsic::amdgcn_workitem_id_y: 11535 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11536 break; 11537 case Intrinsic::amdgcn_workitem_id_z: 11538 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11539 break; 11540 case Intrinsic::amdgcn_mbcnt_lo: 11541 case Intrinsic::amdgcn_mbcnt_hi: { 11542 // These return at most the wavefront size - 1. 11543 unsigned Size = MRI.getType(R).getSizeInBits(); 11544 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11545 break; 11546 } 11547 case Intrinsic::amdgcn_groupstaticsize: { 11548 // We can report everything over the maximum size as 0. We can't report 11549 // based on the actual size because we don't know if it's accurate or not 11550 // at any given point. 11551 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11552 break; 11553 } 11554 default: 11555 break; 11556 } 11557 } 11558 } 11559 } 11560 11561 Align SITargetLowering::computeKnownAlignForTargetInstr( 11562 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11563 unsigned Depth) const { 11564 const MachineInstr *MI = MRI.getVRegDef(R); 11565 switch (MI->getOpcode()) { 11566 case AMDGPU::G_INTRINSIC: 11567 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11568 // FIXME: Can this move to generic code? What about the case where the call 11569 // site specifies a lower alignment? 11570 Intrinsic::ID IID = MI->getIntrinsicID(); 11571 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11572 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11573 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11574 return *RetAlign; 11575 return Align(1); 11576 } 11577 default: 11578 return Align(1); 11579 } 11580 } 11581 11582 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11583 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11584 const Align CacheLineAlign = Align(64); 11585 11586 // Pre-GFX10 target did not benefit from loop alignment 11587 if (!ML || DisableLoopAlignment || 11588 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11589 getSubtarget()->hasInstFwdPrefetchBug()) 11590 return PrefAlign; 11591 11592 // On GFX10 I$ is 4 x 64 bytes cache lines. 11593 // By default prefetcher keeps one cache line behind and reads two ahead. 11594 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11595 // behind and one ahead. 11596 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11597 // If loop fits 64 bytes it always spans no more than two cache lines and 11598 // does not need an alignment. 11599 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11600 // Else if loop is less or equal 192 bytes we need two lines behind. 11601 11602 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11603 const MachineBasicBlock *Header = ML->getHeader(); 11604 if (Header->getAlignment() != PrefAlign) 11605 return Header->getAlignment(); // Already processed. 11606 11607 unsigned LoopSize = 0; 11608 for (const MachineBasicBlock *MBB : ML->blocks()) { 11609 // If inner loop block is aligned assume in average half of the alignment 11610 // size to be added as nops. 11611 if (MBB != Header) 11612 LoopSize += MBB->getAlignment().value() / 2; 11613 11614 for (const MachineInstr &MI : *MBB) { 11615 LoopSize += TII->getInstSizeInBytes(MI); 11616 if (LoopSize > 192) 11617 return PrefAlign; 11618 } 11619 } 11620 11621 if (LoopSize <= 64) 11622 return PrefAlign; 11623 11624 if (LoopSize <= 128) 11625 return CacheLineAlign; 11626 11627 // If any of parent loops is surrounded by prefetch instructions do not 11628 // insert new for inner loop, which would reset parent's settings. 11629 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11630 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11631 auto I = Exit->getFirstNonDebugInstr(); 11632 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11633 return CacheLineAlign; 11634 } 11635 } 11636 11637 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11638 MachineBasicBlock *Exit = ML->getExitBlock(); 11639 11640 if (Pre && Exit) { 11641 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11642 TII->get(AMDGPU::S_INST_PREFETCH)) 11643 .addImm(1); // prefetch 2 lines behind PC 11644 11645 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11646 TII->get(AMDGPU::S_INST_PREFETCH)) 11647 .addImm(2); // prefetch 1 line behind PC 11648 } 11649 11650 return CacheLineAlign; 11651 } 11652 11653 LLVM_ATTRIBUTE_UNUSED 11654 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11655 assert(N->getOpcode() == ISD::CopyFromReg); 11656 do { 11657 // Follow the chain until we find an INLINEASM node. 11658 N = N->getOperand(0).getNode(); 11659 if (N->getOpcode() == ISD::INLINEASM || 11660 N->getOpcode() == ISD::INLINEASM_BR) 11661 return true; 11662 } while (N->getOpcode() == ISD::CopyFromReg); 11663 return false; 11664 } 11665 11666 bool SITargetLowering::isSDNodeSourceOfDivergence( 11667 const SDNode *N, FunctionLoweringInfo *FLI, 11668 LegacyDivergenceAnalysis *KDA) const { 11669 switch (N->getOpcode()) { 11670 case ISD::CopyFromReg: { 11671 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11672 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11673 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11674 Register Reg = R->getReg(); 11675 11676 // FIXME: Why does this need to consider isLiveIn? 11677 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11678 return !TRI->isSGPRReg(MRI, Reg); 11679 11680 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11681 return KDA->isDivergent(V); 11682 11683 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11684 return !TRI->isSGPRReg(MRI, Reg); 11685 } 11686 case ISD::LOAD: { 11687 const LoadSDNode *L = cast<LoadSDNode>(N); 11688 unsigned AS = L->getAddressSpace(); 11689 // A flat load may access private memory. 11690 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11691 } 11692 case ISD::CALLSEQ_END: 11693 return true; 11694 case ISD::INTRINSIC_WO_CHAIN: 11695 return AMDGPU::isIntrinsicSourceOfDivergence( 11696 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11697 case ISD::INTRINSIC_W_CHAIN: 11698 return AMDGPU::isIntrinsicSourceOfDivergence( 11699 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11700 } 11701 return false; 11702 } 11703 11704 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11705 EVT VT) const { 11706 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11707 case MVT::f32: 11708 return hasFP32Denormals(DAG.getMachineFunction()); 11709 case MVT::f64: 11710 case MVT::f16: 11711 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11712 default: 11713 return false; 11714 } 11715 } 11716 11717 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11718 const SelectionDAG &DAG, 11719 bool SNaN, 11720 unsigned Depth) const { 11721 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11722 const MachineFunction &MF = DAG.getMachineFunction(); 11723 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11724 11725 if (Info->getMode().DX10Clamp) 11726 return true; // Clamped to 0. 11727 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11728 } 11729 11730 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11731 SNaN, Depth); 11732 } 11733 11734 // Global FP atomic instructions have a hardcoded FP mode and do not support 11735 // FP32 denormals, and only support v2f16 denormals. 11736 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11737 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11738 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11739 if (&Flt == &APFloat::IEEEsingle()) 11740 return DenormMode == DenormalMode::getPreserveSign(); 11741 return DenormMode == DenormalMode::getIEEE(); 11742 } 11743 11744 TargetLowering::AtomicExpansionKind 11745 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11746 switch (RMW->getOperation()) { 11747 case AtomicRMWInst::FAdd: { 11748 Type *Ty = RMW->getType(); 11749 11750 // We don't have a way to support 16-bit atomics now, so just leave them 11751 // as-is. 11752 if (Ty->isHalfTy()) 11753 return AtomicExpansionKind::None; 11754 11755 if (!Ty->isFloatTy()) 11756 return AtomicExpansionKind::CmpXChg; 11757 11758 // TODO: Do have these for flat. Older targets also had them for buffers. 11759 unsigned AS = RMW->getPointerAddressSpace(); 11760 11761 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11762 if (!fpModeMatchesGlobalFPAtomicMode(RMW)) 11763 return AtomicExpansionKind::CmpXChg; 11764 11765 return RMW->use_empty() ? AtomicExpansionKind::None : 11766 AtomicExpansionKind::CmpXChg; 11767 } 11768 11769 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11770 // to round-to-nearest-even. 11771 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11772 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11773 } 11774 default: 11775 break; 11776 } 11777 11778 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11779 } 11780 11781 const TargetRegisterClass * 11782 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11783 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11784 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11785 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11786 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11787 : &AMDGPU::SReg_32RegClass; 11788 if (!TRI->isSGPRClass(RC) && !isDivergent) 11789 return TRI->getEquivalentSGPRClass(RC); 11790 else if (TRI->isSGPRClass(RC) && isDivergent) 11791 return TRI->getEquivalentVGPRClass(RC); 11792 11793 return RC; 11794 } 11795 11796 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11797 // uniform values (as produced by the mask results of control flow intrinsics) 11798 // used outside of divergent blocks. The phi users need to also be treated as 11799 // always uniform. 11800 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11801 unsigned WaveSize) { 11802 // FIXME: We asssume we never cast the mask results of a control flow 11803 // intrinsic. 11804 // Early exit if the type won't be consistent as a compile time hack. 11805 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11806 if (!IT || IT->getBitWidth() != WaveSize) 11807 return false; 11808 11809 if (!isa<Instruction>(V)) 11810 return false; 11811 if (!Visited.insert(V).second) 11812 return false; 11813 bool Result = false; 11814 for (auto U : V->users()) { 11815 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11816 if (V == U->getOperand(1)) { 11817 switch (Intrinsic->getIntrinsicID()) { 11818 default: 11819 Result = false; 11820 break; 11821 case Intrinsic::amdgcn_if_break: 11822 case Intrinsic::amdgcn_if: 11823 case Intrinsic::amdgcn_else: 11824 Result = true; 11825 break; 11826 } 11827 } 11828 if (V == U->getOperand(0)) { 11829 switch (Intrinsic->getIntrinsicID()) { 11830 default: 11831 Result = false; 11832 break; 11833 case Intrinsic::amdgcn_end_cf: 11834 case Intrinsic::amdgcn_loop: 11835 Result = true; 11836 break; 11837 } 11838 } 11839 } else { 11840 Result = hasCFUser(U, Visited, WaveSize); 11841 } 11842 if (Result) 11843 break; 11844 } 11845 return Result; 11846 } 11847 11848 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11849 const Value *V) const { 11850 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11851 if (CI->isInlineAsm()) { 11852 // FIXME: This cannot give a correct answer. This should only trigger in 11853 // the case where inline asm returns mixed SGPR and VGPR results, used 11854 // outside the defining block. We don't have a specific result to 11855 // consider, so this assumes if any value is SGPR, the overall register 11856 // also needs to be SGPR. 11857 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11858 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11859 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11860 for (auto &TC : TargetConstraints) { 11861 if (TC.Type == InlineAsm::isOutput) { 11862 ComputeConstraintToUse(TC, SDValue()); 11863 unsigned AssignedReg; 11864 const TargetRegisterClass *RC; 11865 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11866 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11867 if (RC) { 11868 MachineRegisterInfo &MRI = MF.getRegInfo(); 11869 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11870 return true; 11871 else if (SIRI->isSGPRClass(RC)) 11872 return true; 11873 } 11874 } 11875 } 11876 } 11877 } 11878 SmallPtrSet<const Value *, 16> Visited; 11879 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11880 } 11881 11882 std::pair<int, MVT> 11883 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11884 Type *Ty) const { 11885 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11886 auto Size = DL.getTypeSizeInBits(Ty); 11887 // Maximum load or store can handle 8 dwords for scalar and 4 for 11888 // vector ALU. Let's assume anything above 8 dwords is expensive 11889 // even if legal. 11890 if (Size <= 256) 11891 return Cost; 11892 11893 Cost.first = (Size + 255) / 256; 11894 return Cost; 11895 } 11896