1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUSubtarget.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 19 #include "SIDefines.h" 20 #include "SIInstrInfo.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "SIRegisterInfo.h" 23 #include "Utils/AMDGPUBaseInfo.h" 24 #include "llvm/ADT/APFloat.h" 25 #include "llvm/ADT/APInt.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/BitVector.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/ADT/StringSwitch.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CallingConvLower.h" 36 #include "llvm/CodeGen/DAGCombine.h" 37 #include "llvm/CodeGen/FunctionLoweringInfo.h" 38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetCallingConv.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/ValueTypes.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugLoc.h" 58 #include "llvm/IR/DerivedTypes.h" 59 #include "llvm/IR/DiagnosticInfo.h" 60 #include "llvm/IR/Function.h" 61 #include "llvm/IR/GlobalValue.h" 62 #include "llvm/IR/InstrTypes.h" 63 #include "llvm/IR/Instruction.h" 64 #include "llvm/IR/Instructions.h" 65 #include "llvm/IR/IntrinsicInst.h" 66 #include "llvm/IR/Type.h" 67 #include "llvm/Support/Casting.h" 68 #include "llvm/Support/CodeGen.h" 69 #include "llvm/Support/CommandLine.h" 70 #include "llvm/Support/Compiler.h" 71 #include "llvm/Support/ErrorHandling.h" 72 #include "llvm/Support/KnownBits.h" 73 #include "llvm/Support/MachineValueType.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Target/TargetOptions.h" 76 #include <cassert> 77 #include <cmath> 78 #include <cstdint> 79 #include <iterator> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 86 #define DEBUG_TYPE "si-lower" 87 88 STATISTIC(NumTailCalls, "Number of tail calls"); 89 90 static cl::opt<bool> DisableLoopAlignment( 91 "amdgpu-disable-loop-alignment", 92 cl::desc("Do not align and prefetch loops"), 93 cl::init(false)); 94 95 static cl::opt<bool> VGPRReserveforSGPRSpill( 96 "amdgpu-reserve-vgpr-for-sgpr-spill", 97 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 98 99 static cl::opt<bool> UseDivergentRegisterIndexing( 100 "amdgpu-use-divergent-register-indexing", 101 cl::Hidden, 102 cl::desc("Use indirect register addressing for divergent indexes"), 103 cl::init(false)); 104 105 static bool hasFP32Denormals(const MachineFunction &MF) { 106 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 107 return Info->getMode().allFP32Denormals(); 108 } 109 110 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 111 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 112 return Info->getMode().allFP64FP16Denormals(); 113 } 114 115 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 116 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 117 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 118 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 119 return AMDGPU::SGPR0 + Reg; 120 } 121 } 122 llvm_unreachable("Cannot allocate sgpr"); 123 } 124 125 SITargetLowering::SITargetLowering(const TargetMachine &TM, 126 const GCNSubtarget &STI) 127 : AMDGPUTargetLowering(TM, STI), 128 Subtarget(&STI) { 129 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 130 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 131 132 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 133 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 134 135 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 136 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 137 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 138 139 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 140 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 141 142 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 143 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 144 145 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 146 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 147 148 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 149 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 150 151 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 152 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 153 154 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 155 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 156 157 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 158 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 159 160 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 161 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 162 163 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 164 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 165 166 if (Subtarget->has16BitInsts()) { 167 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 168 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 169 170 // Unless there are also VOP3P operations, not operations are really legal. 171 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 172 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 173 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 174 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 175 } 176 177 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 178 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 179 180 computeRegisterProperties(Subtarget->getRegisterInfo()); 181 182 // The boolean content concept here is too inflexible. Compares only ever 183 // really produce a 1-bit result. Any copy/extend from these will turn into a 184 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 185 // it's what most targets use. 186 setBooleanContents(ZeroOrOneBooleanContent); 187 setBooleanVectorContents(ZeroOrOneBooleanContent); 188 189 // We need to custom lower vector stores from local memory 190 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 196 setOperationAction(ISD::LOAD, MVT::i1, Custom); 197 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 198 199 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 204 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 205 setOperationAction(ISD::STORE, MVT::i1, Custom); 206 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 207 208 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 209 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 210 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 211 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 212 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 213 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 214 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 215 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 216 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 217 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 218 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 219 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 220 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 221 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 222 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 223 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 224 225 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 227 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 228 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 229 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 230 231 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 232 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 233 234 setOperationAction(ISD::SELECT, MVT::i1, Promote); 235 setOperationAction(ISD::SELECT, MVT::i64, Custom); 236 setOperationAction(ISD::SELECT, MVT::f64, Promote); 237 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 238 239 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 242 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 243 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 244 245 setOperationAction(ISD::SETCC, MVT::i1, Promote); 246 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 247 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 248 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 249 250 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 251 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 252 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 253 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 254 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 255 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 256 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 257 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 258 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 267 268 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 269 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 270 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 271 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 272 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 273 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 274 275 setOperationAction(ISD::UADDO, MVT::i32, Legal); 276 setOperationAction(ISD::USUBO, MVT::i32, Legal); 277 278 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 279 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 280 281 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 282 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 283 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 284 285 #if 0 286 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 287 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 288 #endif 289 290 // We only support LOAD/STORE and vector manipulation ops for vectors 291 // with > 4 elements. 292 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 293 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 294 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 295 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 296 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 297 switch (Op) { 298 case ISD::LOAD: 299 case ISD::STORE: 300 case ISD::BUILD_VECTOR: 301 case ISD::BITCAST: 302 case ISD::EXTRACT_VECTOR_ELT: 303 case ISD::INSERT_VECTOR_ELT: 304 case ISD::INSERT_SUBVECTOR: 305 case ISD::EXTRACT_SUBVECTOR: 306 case ISD::SCALAR_TO_VECTOR: 307 break; 308 case ISD::CONCAT_VECTORS: 309 setOperationAction(Op, VT, Custom); 310 break; 311 default: 312 setOperationAction(Op, VT, Expand); 313 break; 314 } 315 } 316 } 317 318 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 319 320 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 321 // is expanded to avoid having two separate loops in case the index is a VGPR. 322 323 // Most operations are naturally 32-bit vector operations. We only support 324 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 325 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 326 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 327 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 328 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 330 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 331 332 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 333 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 334 335 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 336 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 337 } 338 339 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 340 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 341 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 344 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 345 346 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 347 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 348 349 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 350 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 351 } 352 353 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 354 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 355 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 358 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 359 360 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 361 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 362 363 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 364 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 365 } 366 367 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 368 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 369 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 372 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 373 374 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 375 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 376 377 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 378 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 379 } 380 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 383 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 384 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 385 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 387 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 388 389 // Avoid stack access for these. 390 // TODO: Generalize to more vector types. 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 395 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 401 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 404 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 405 406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 409 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 410 411 // Deal with vec3 vector operations when widened to vec4. 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 416 417 // Deal with vec5 vector operations when widened to vec8. 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 420 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 421 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 422 423 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 424 // and output demarshalling 425 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 426 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 427 428 // We can't return success/failure, only the old value, 429 // let LLVM add the comparison 430 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 431 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 432 433 if (Subtarget->hasFlatAddressSpace()) { 434 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 435 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 436 } 437 438 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 439 440 // FIXME: This should be narrowed to i32, but that only happens if i64 is 441 // illegal. 442 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 443 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 444 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 445 446 // On SI this is s_memtime and s_memrealtime on VI. 447 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 448 setOperationAction(ISD::TRAP, MVT::Other, Custom); 449 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 450 451 if (Subtarget->has16BitInsts()) { 452 setOperationAction(ISD::FPOW, MVT::f16, Promote); 453 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 454 setOperationAction(ISD::FLOG, MVT::f16, Custom); 455 setOperationAction(ISD::FEXP, MVT::f16, Custom); 456 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 457 } 458 459 if (Subtarget->hasMadMacF32Insts()) 460 setOperationAction(ISD::FMAD, MVT::f32, Legal); 461 462 if (!Subtarget->hasBFI()) { 463 // fcopysign can be done in a single instruction with BFI. 464 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 465 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 466 } 467 468 if (!Subtarget->hasBCNT(32)) 469 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 470 471 if (!Subtarget->hasBCNT(64)) 472 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 473 474 if (Subtarget->hasFFBH()) 475 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 476 477 if (Subtarget->hasFFBL()) 478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 479 480 // We only really have 32-bit BFE instructions (and 16-bit on VI). 481 // 482 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 483 // effort to match them now. We want this to be false for i64 cases when the 484 // extraction isn't restricted to the upper or lower half. Ideally we would 485 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 486 // span the midpoint are probably relatively rare, so don't worry about them 487 // for now. 488 if (Subtarget->hasBFE()) 489 setHasExtractBitsInsn(true); 490 491 // Clamp modifier on add/sub 492 if (Subtarget->hasIntClamp()) { 493 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 494 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 495 } 496 497 if (Subtarget->hasAddNoCarry()) { 498 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 502 } 503 504 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 508 509 510 // These are really only legal for ieee_mode functions. We should be avoiding 511 // them for functions that don't have ieee_mode enabled, so just say they are 512 // legal. 513 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 517 518 519 if (Subtarget->haveRoundOpsF64()) { 520 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 521 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 522 setOperationAction(ISD::FRINT, MVT::f64, Legal); 523 } else { 524 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 525 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 526 setOperationAction(ISD::FRINT, MVT::f64, Custom); 527 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 528 } 529 530 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 531 532 setOperationAction(ISD::FSIN, MVT::f32, Custom); 533 setOperationAction(ISD::FCOS, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f64, Custom); 536 537 if (Subtarget->has16BitInsts()) { 538 setOperationAction(ISD::Constant, MVT::i16, Legal); 539 540 setOperationAction(ISD::SMIN, MVT::i16, Legal); 541 setOperationAction(ISD::SMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::UMIN, MVT::i16, Legal); 544 setOperationAction(ISD::UMAX, MVT::i16, Legal); 545 546 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 547 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 548 549 setOperationAction(ISD::ROTR, MVT::i16, Expand); 550 setOperationAction(ISD::ROTL, MVT::i16, Expand); 551 552 setOperationAction(ISD::SDIV, MVT::i16, Promote); 553 setOperationAction(ISD::UDIV, MVT::i16, Promote); 554 setOperationAction(ISD::SREM, MVT::i16, Promote); 555 setOperationAction(ISD::UREM, MVT::i16, Promote); 556 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 557 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 558 559 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 560 561 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 566 567 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 568 569 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::LOAD, MVT::i16, Custom); 572 573 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 574 575 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 576 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 577 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 579 580 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 582 583 // F16 - Constant Actions. 584 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 585 586 // F16 - Load/Store Actions. 587 setOperationAction(ISD::LOAD, MVT::f16, Promote); 588 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 589 setOperationAction(ISD::STORE, MVT::f16, Promote); 590 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 591 592 // F16 - VOP1 Actions. 593 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 594 setOperationAction(ISD::FCOS, MVT::f16, Custom); 595 setOperationAction(ISD::FSIN, MVT::f16, Custom); 596 597 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 598 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 599 600 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 601 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 602 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 604 setOperationAction(ISD::FROUND, MVT::f16, Custom); 605 606 // F16 - VOP2 Actions. 607 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 608 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 609 610 setOperationAction(ISD::FDIV, MVT::f16, Custom); 611 612 // F16 - VOP3 Actions. 613 setOperationAction(ISD::FMA, MVT::f16, Legal); 614 if (STI.hasMadF16()) 615 setOperationAction(ISD::FMAD, MVT::f16, Legal); 616 617 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 618 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 619 switch (Op) { 620 case ISD::LOAD: 621 case ISD::STORE: 622 case ISD::BUILD_VECTOR: 623 case ISD::BITCAST: 624 case ISD::EXTRACT_VECTOR_ELT: 625 case ISD::INSERT_VECTOR_ELT: 626 case ISD::INSERT_SUBVECTOR: 627 case ISD::EXTRACT_SUBVECTOR: 628 case ISD::SCALAR_TO_VECTOR: 629 break; 630 case ISD::CONCAT_VECTORS: 631 setOperationAction(Op, VT, Custom); 632 break; 633 default: 634 setOperationAction(Op, VT, Expand); 635 break; 636 } 637 } 638 } 639 640 // v_perm_b32 can handle either of these. 641 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 643 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 644 645 // XXX - Do these do anything? Vector constants turn into build_vector. 646 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 647 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 648 649 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 650 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 653 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 654 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 655 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 656 657 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 658 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 659 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 660 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 661 662 setOperationAction(ISD::AND, MVT::v2i16, Promote); 663 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 664 setOperationAction(ISD::OR, MVT::v2i16, Promote); 665 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 666 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 668 669 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 670 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 671 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 672 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 673 674 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 675 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 676 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 677 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 678 679 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 682 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 683 684 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 686 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 687 688 if (!Subtarget->hasVOP3PInsts()) { 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 690 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 691 } 692 693 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 694 // This isn't really legal, but this avoids the legalizer unrolling it (and 695 // allows matching fneg (fabs x) patterns) 696 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 697 698 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 700 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 701 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 702 703 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 704 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 705 706 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 707 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 708 } 709 710 if (Subtarget->hasVOP3PInsts()) { 711 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 712 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 713 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 716 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 717 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 719 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 720 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 721 722 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 725 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 726 727 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 730 731 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 732 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 733 734 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 735 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 741 742 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 744 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 745 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 746 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 747 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 748 749 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 750 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 752 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 753 754 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 757 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 758 759 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 762 763 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 764 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 765 766 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 768 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 769 770 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 772 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 773 } 774 775 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 776 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 777 778 if (Subtarget->has16BitInsts()) { 779 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 780 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 781 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 782 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 783 } else { 784 // Legalization hack. 785 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 786 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 787 788 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 789 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 790 } 791 792 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 793 setOperationAction(ISD::SELECT, VT, Custom); 794 } 795 796 setOperationAction(ISD::SMULO, MVT::i64, Custom); 797 setOperationAction(ISD::UMULO, MVT::i64, Custom); 798 799 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 801 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 802 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 803 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 805 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 806 807 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 808 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 809 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 810 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 811 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 812 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 813 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 815 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 816 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 817 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 818 819 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 820 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 821 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 822 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 823 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 824 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 825 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 826 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 827 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 828 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 829 830 setTargetDAGCombine(ISD::ADD); 831 setTargetDAGCombine(ISD::ADDCARRY); 832 setTargetDAGCombine(ISD::SUB); 833 setTargetDAGCombine(ISD::SUBCARRY); 834 setTargetDAGCombine(ISD::FADD); 835 setTargetDAGCombine(ISD::FSUB); 836 setTargetDAGCombine(ISD::FMINNUM); 837 setTargetDAGCombine(ISD::FMAXNUM); 838 setTargetDAGCombine(ISD::FMINNUM_IEEE); 839 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 840 setTargetDAGCombine(ISD::FMA); 841 setTargetDAGCombine(ISD::SMIN); 842 setTargetDAGCombine(ISD::SMAX); 843 setTargetDAGCombine(ISD::UMIN); 844 setTargetDAGCombine(ISD::UMAX); 845 setTargetDAGCombine(ISD::SETCC); 846 setTargetDAGCombine(ISD::AND); 847 setTargetDAGCombine(ISD::OR); 848 setTargetDAGCombine(ISD::XOR); 849 setTargetDAGCombine(ISD::SINT_TO_FP); 850 setTargetDAGCombine(ISD::UINT_TO_FP); 851 setTargetDAGCombine(ISD::FCANONICALIZE); 852 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 853 setTargetDAGCombine(ISD::ZERO_EXTEND); 854 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 855 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 856 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 857 858 // All memory operations. Some folding on the pointer operand is done to help 859 // matching the constant offsets in the addressing modes. 860 setTargetDAGCombine(ISD::LOAD); 861 setTargetDAGCombine(ISD::STORE); 862 setTargetDAGCombine(ISD::ATOMIC_LOAD); 863 setTargetDAGCombine(ISD::ATOMIC_STORE); 864 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 865 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 866 setTargetDAGCombine(ISD::ATOMIC_SWAP); 867 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 868 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 870 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 871 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 872 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 873 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 874 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 875 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 876 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 877 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 878 setTargetDAGCombine(ISD::INTRINSIC_VOID); 879 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 880 881 // FIXME: In other contexts we pretend this is a per-function property. 882 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 883 884 setSchedulingPreference(Sched::RegPressure); 885 } 886 887 const GCNSubtarget *SITargetLowering::getSubtarget() const { 888 return Subtarget; 889 } 890 891 //===----------------------------------------------------------------------===// 892 // TargetLowering queries 893 //===----------------------------------------------------------------------===// 894 895 // v_mad_mix* support a conversion from f16 to f32. 896 // 897 // There is only one special case when denormals are enabled we don't currently, 898 // where this is OK to use. 899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 900 EVT DestVT, EVT SrcVT) const { 901 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 902 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 903 DestVT.getScalarType() == MVT::f32 && 904 SrcVT.getScalarType() == MVT::f16 && 905 // TODO: This probably only requires no input flushing? 906 !hasFP32Denormals(DAG.getMachineFunction()); 907 } 908 909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 910 // SI has some legal vector types, but no legal vector operations. Say no 911 // shuffles are legal in order to prefer scalarizing some vector operations. 912 return false; 913 } 914 915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 916 CallingConv::ID CC, 917 EVT VT) const { 918 if (CC == CallingConv::AMDGPU_KERNEL) 919 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 920 921 if (VT.isVector()) { 922 EVT ScalarVT = VT.getScalarType(); 923 unsigned Size = ScalarVT.getSizeInBits(); 924 if (Size == 16) { 925 if (Subtarget->has16BitInsts()) 926 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 927 return VT.isInteger() ? MVT::i32 : MVT::f32; 928 } 929 930 if (Size < 16) 931 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 932 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 933 } 934 935 if (VT.getSizeInBits() > 32) 936 return MVT::i32; 937 938 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 939 } 940 941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 942 CallingConv::ID CC, 943 EVT VT) const { 944 if (CC == CallingConv::AMDGPU_KERNEL) 945 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 946 947 if (VT.isVector()) { 948 unsigned NumElts = VT.getVectorNumElements(); 949 EVT ScalarVT = VT.getScalarType(); 950 unsigned Size = ScalarVT.getSizeInBits(); 951 952 // FIXME: Should probably promote 8-bit vectors to i16. 953 if (Size == 16 && Subtarget->has16BitInsts()) 954 return (NumElts + 1) / 2; 955 956 if (Size <= 32) 957 return NumElts; 958 959 if (Size > 32) 960 return NumElts * ((Size + 31) / 32); 961 } else if (VT.getSizeInBits() > 32) 962 return (VT.getSizeInBits() + 31) / 32; 963 964 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 965 } 966 967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 968 LLVMContext &Context, CallingConv::ID CC, 969 EVT VT, EVT &IntermediateVT, 970 unsigned &NumIntermediates, MVT &RegisterVT) const { 971 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 972 unsigned NumElts = VT.getVectorNumElements(); 973 EVT ScalarVT = VT.getScalarType(); 974 unsigned Size = ScalarVT.getSizeInBits(); 975 // FIXME: We should fix the ABI to be the same on targets without 16-bit 976 // support, but unless we can properly handle 3-vectors, it will be still be 977 // inconsistent. 978 if (Size == 16 && Subtarget->has16BitInsts()) { 979 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 980 IntermediateVT = RegisterVT; 981 NumIntermediates = (NumElts + 1) / 2; 982 return NumIntermediates; 983 } 984 985 if (Size == 32) { 986 RegisterVT = ScalarVT.getSimpleVT(); 987 IntermediateVT = RegisterVT; 988 NumIntermediates = NumElts; 989 return NumIntermediates; 990 } 991 992 if (Size < 16 && Subtarget->has16BitInsts()) { 993 // FIXME: Should probably form v2i16 pieces 994 RegisterVT = MVT::i16; 995 IntermediateVT = ScalarVT; 996 NumIntermediates = NumElts; 997 return NumIntermediates; 998 } 999 1000 1001 if (Size != 16 && Size <= 32) { 1002 RegisterVT = MVT::i32; 1003 IntermediateVT = ScalarVT; 1004 NumIntermediates = NumElts; 1005 return NumIntermediates; 1006 } 1007 1008 if (Size > 32) { 1009 RegisterVT = MVT::i32; 1010 IntermediateVT = RegisterVT; 1011 NumIntermediates = NumElts * ((Size + 31) / 32); 1012 return NumIntermediates; 1013 } 1014 } 1015 1016 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1017 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1018 } 1019 1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1021 assert(DMaskLanes != 0); 1022 1023 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1024 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1025 return EVT::getVectorVT(Ty->getContext(), 1026 EVT::getEVT(VT->getElementType()), 1027 NumElts); 1028 } 1029 1030 return EVT::getEVT(Ty); 1031 } 1032 1033 // Peek through TFE struct returns to only use the data size. 1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1035 auto *ST = dyn_cast<StructType>(Ty); 1036 if (!ST) 1037 return memVTFromImageData(Ty, DMaskLanes); 1038 1039 // Some intrinsics return an aggregate type - special case to work out the 1040 // correct memVT. 1041 // 1042 // Only limited forms of aggregate type currently expected. 1043 if (ST->getNumContainedTypes() != 2 || 1044 !ST->getContainedType(1)->isIntegerTy(32)) 1045 return EVT(); 1046 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1047 } 1048 1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1050 const CallInst &CI, 1051 MachineFunction &MF, 1052 unsigned IntrID) const { 1053 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1054 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1055 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1056 (Intrinsic::ID)IntrID); 1057 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1058 return false; 1059 1060 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1061 1062 if (RsrcIntr->IsImage) { 1063 Info.ptrVal = MFI->getImagePSV( 1064 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1065 CI.getArgOperand(RsrcIntr->RsrcArg)); 1066 Info.align.reset(); 1067 } else { 1068 Info.ptrVal = MFI->getBufferPSV( 1069 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1070 CI.getArgOperand(RsrcIntr->RsrcArg)); 1071 } 1072 1073 Info.flags = MachineMemOperand::MODereferenceable; 1074 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1075 unsigned DMaskLanes = 4; 1076 1077 if (RsrcIntr->IsImage) { 1078 const AMDGPU::ImageDimIntrinsicInfo *Intr 1079 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1080 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1081 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1082 1083 if (!BaseOpcode->Gather4) { 1084 // If this isn't a gather, we may have excess loaded elements in the 1085 // IR type. Check the dmask for the real number of elements loaded. 1086 unsigned DMask 1087 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1088 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1089 } 1090 1091 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1092 } else 1093 Info.memVT = EVT::getEVT(CI.getType()); 1094 1095 // FIXME: What does alignment mean for an image? 1096 Info.opc = ISD::INTRINSIC_W_CHAIN; 1097 Info.flags |= MachineMemOperand::MOLoad; 1098 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1099 Info.opc = ISD::INTRINSIC_VOID; 1100 1101 Type *DataTy = CI.getArgOperand(0)->getType(); 1102 if (RsrcIntr->IsImage) { 1103 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1104 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1105 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1106 } else 1107 Info.memVT = EVT::getEVT(DataTy); 1108 1109 Info.flags |= MachineMemOperand::MOStore; 1110 } else { 1111 // Atomic 1112 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1113 ISD::INTRINSIC_W_CHAIN; 1114 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1115 Info.flags = MachineMemOperand::MOLoad | 1116 MachineMemOperand::MOStore | 1117 MachineMemOperand::MODereferenceable; 1118 1119 // XXX - Should this be volatile without known ordering? 1120 Info.flags |= MachineMemOperand::MOVolatile; 1121 } 1122 return true; 1123 } 1124 1125 switch (IntrID) { 1126 case Intrinsic::amdgcn_atomic_inc: 1127 case Intrinsic::amdgcn_atomic_dec: 1128 case Intrinsic::amdgcn_ds_ordered_add: 1129 case Intrinsic::amdgcn_ds_ordered_swap: 1130 case Intrinsic::amdgcn_ds_fadd: 1131 case Intrinsic::amdgcn_ds_fmin: 1132 case Intrinsic::amdgcn_ds_fmax: { 1133 Info.opc = ISD::INTRINSIC_W_CHAIN; 1134 Info.memVT = MVT::getVT(CI.getType()); 1135 Info.ptrVal = CI.getOperand(0); 1136 Info.align.reset(); 1137 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1138 1139 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1140 if (!Vol->isZero()) 1141 Info.flags |= MachineMemOperand::MOVolatile; 1142 1143 return true; 1144 } 1145 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1146 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1147 1148 Info.opc = ISD::INTRINSIC_W_CHAIN; 1149 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1150 Info.ptrVal = MFI->getBufferPSV( 1151 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1152 CI.getArgOperand(1)); 1153 Info.align.reset(); 1154 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1155 1156 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1157 if (!Vol || !Vol->isZero()) 1158 Info.flags |= MachineMemOperand::MOVolatile; 1159 1160 return true; 1161 } 1162 case Intrinsic::amdgcn_ds_append: 1163 case Intrinsic::amdgcn_ds_consume: { 1164 Info.opc = ISD::INTRINSIC_W_CHAIN; 1165 Info.memVT = MVT::getVT(CI.getType()); 1166 Info.ptrVal = CI.getOperand(0); 1167 Info.align.reset(); 1168 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1169 1170 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1171 if (!Vol->isZero()) 1172 Info.flags |= MachineMemOperand::MOVolatile; 1173 1174 return true; 1175 } 1176 case Intrinsic::amdgcn_global_atomic_csub: { 1177 Info.opc = ISD::INTRINSIC_W_CHAIN; 1178 Info.memVT = MVT::getVT(CI.getType()); 1179 Info.ptrVal = CI.getOperand(0); 1180 Info.align.reset(); 1181 Info.flags = MachineMemOperand::MOLoad | 1182 MachineMemOperand::MOStore | 1183 MachineMemOperand::MOVolatile; 1184 return true; 1185 } 1186 case Intrinsic::amdgcn_global_atomic_fadd: { 1187 Info.opc = ISD::INTRINSIC_W_CHAIN; 1188 Info.memVT = MVT::getVT(CI.getType()); 1189 Info.ptrVal = CI.getOperand(0); 1190 Info.align.reset(); 1191 Info.flags = MachineMemOperand::MOLoad | 1192 MachineMemOperand::MOStore | 1193 MachineMemOperand::MODereferenceable | 1194 MachineMemOperand::MOVolatile; 1195 return true; 1196 } 1197 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1198 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1199 Info.opc = ISD::INTRINSIC_W_CHAIN; 1200 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1201 Info.ptrVal = MFI->getImagePSV( 1202 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5)); 1203 Info.align.reset(); 1204 Info.flags = MachineMemOperand::MOLoad | 1205 MachineMemOperand::MODereferenceable; 1206 return true; 1207 } 1208 case Intrinsic::amdgcn_ds_gws_init: 1209 case Intrinsic::amdgcn_ds_gws_barrier: 1210 case Intrinsic::amdgcn_ds_gws_sema_v: 1211 case Intrinsic::amdgcn_ds_gws_sema_br: 1212 case Intrinsic::amdgcn_ds_gws_sema_p: 1213 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1214 Info.opc = ISD::INTRINSIC_VOID; 1215 1216 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1217 Info.ptrVal = 1218 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1219 1220 // This is an abstract access, but we need to specify a type and size. 1221 Info.memVT = MVT::i32; 1222 Info.size = 4; 1223 Info.align = Align(4); 1224 1225 Info.flags = MachineMemOperand::MOStore; 1226 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1227 Info.flags = MachineMemOperand::MOLoad; 1228 return true; 1229 } 1230 default: 1231 return false; 1232 } 1233 } 1234 1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1236 SmallVectorImpl<Value*> &Ops, 1237 Type *&AccessTy) const { 1238 switch (II->getIntrinsicID()) { 1239 case Intrinsic::amdgcn_atomic_inc: 1240 case Intrinsic::amdgcn_atomic_dec: 1241 case Intrinsic::amdgcn_ds_ordered_add: 1242 case Intrinsic::amdgcn_ds_ordered_swap: 1243 case Intrinsic::amdgcn_ds_append: 1244 case Intrinsic::amdgcn_ds_consume: 1245 case Intrinsic::amdgcn_ds_fadd: 1246 case Intrinsic::amdgcn_ds_fmin: 1247 case Intrinsic::amdgcn_ds_fmax: 1248 case Intrinsic::amdgcn_global_atomic_fadd: 1249 case Intrinsic::amdgcn_global_atomic_csub: { 1250 Value *Ptr = II->getArgOperand(0); 1251 AccessTy = II->getType(); 1252 Ops.push_back(Ptr); 1253 return true; 1254 } 1255 default: 1256 return false; 1257 } 1258 } 1259 1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1261 if (!Subtarget->hasFlatInstOffsets()) { 1262 // Flat instructions do not have offsets, and only have the register 1263 // address. 1264 return AM.BaseOffs == 0 && AM.Scale == 0; 1265 } 1266 1267 return AM.Scale == 0 && 1268 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1269 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1270 /*Signed=*/false)); 1271 } 1272 1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1274 if (Subtarget->hasFlatGlobalInsts()) 1275 return AM.Scale == 0 && 1276 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1277 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1278 /*Signed=*/true)); 1279 1280 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1281 // Assume the we will use FLAT for all global memory accesses 1282 // on VI. 1283 // FIXME: This assumption is currently wrong. On VI we still use 1284 // MUBUF instructions for the r + i addressing mode. As currently 1285 // implemented, the MUBUF instructions only work on buffer < 4GB. 1286 // It may be possible to support > 4GB buffers with MUBUF instructions, 1287 // by setting the stride value in the resource descriptor which would 1288 // increase the size limit to (stride * 4GB). However, this is risky, 1289 // because it has never been validated. 1290 return isLegalFlatAddressingMode(AM); 1291 } 1292 1293 return isLegalMUBUFAddressingMode(AM); 1294 } 1295 1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1297 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1298 // additionally can do r + r + i with addr64. 32-bit has more addressing 1299 // mode options. Depending on the resource constant, it can also do 1300 // (i64 r0) + (i32 r1) * (i14 i). 1301 // 1302 // Private arrays end up using a scratch buffer most of the time, so also 1303 // assume those use MUBUF instructions. Scratch loads / stores are currently 1304 // implemented as mubuf instructions with offen bit set, so slightly 1305 // different than the normal addr64. 1306 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1307 return false; 1308 1309 // FIXME: Since we can split immediate into soffset and immediate offset, 1310 // would it make sense to allow any immediate? 1311 1312 switch (AM.Scale) { 1313 case 0: // r + i or just i, depending on HasBaseReg. 1314 return true; 1315 case 1: 1316 return true; // We have r + r or r + i. 1317 case 2: 1318 if (AM.HasBaseReg) { 1319 // Reject 2 * r + r. 1320 return false; 1321 } 1322 1323 // Allow 2 * r as r + r 1324 // Or 2 * r + i is allowed as r + r + i. 1325 return true; 1326 default: // Don't allow n * r 1327 return false; 1328 } 1329 } 1330 1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1332 const AddrMode &AM, Type *Ty, 1333 unsigned AS, Instruction *I) const { 1334 // No global is ever allowed as a base. 1335 if (AM.BaseGV) 1336 return false; 1337 1338 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1339 return isLegalGlobalAddressingMode(AM); 1340 1341 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1342 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1343 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1344 // If the offset isn't a multiple of 4, it probably isn't going to be 1345 // correctly aligned. 1346 // FIXME: Can we get the real alignment here? 1347 if (AM.BaseOffs % 4 != 0) 1348 return isLegalMUBUFAddressingMode(AM); 1349 1350 // There are no SMRD extloads, so if we have to do a small type access we 1351 // will use a MUBUF load. 1352 // FIXME?: We also need to do this if unaligned, but we don't know the 1353 // alignment here. 1354 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1355 return isLegalGlobalAddressingMode(AM); 1356 1357 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1358 // SMRD instructions have an 8-bit, dword offset on SI. 1359 if (!isUInt<8>(AM.BaseOffs / 4)) 1360 return false; 1361 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1362 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1363 // in 8-bits, it can use a smaller encoding. 1364 if (!isUInt<32>(AM.BaseOffs / 4)) 1365 return false; 1366 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1367 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1368 if (!isUInt<20>(AM.BaseOffs)) 1369 return false; 1370 } else 1371 llvm_unreachable("unhandled generation"); 1372 1373 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1374 return true; 1375 1376 if (AM.Scale == 1 && AM.HasBaseReg) 1377 return true; 1378 1379 return false; 1380 1381 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1382 return isLegalMUBUFAddressingMode(AM); 1383 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1384 AS == AMDGPUAS::REGION_ADDRESS) { 1385 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1386 // field. 1387 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1388 // an 8-bit dword offset but we don't know the alignment here. 1389 if (!isUInt<16>(AM.BaseOffs)) 1390 return false; 1391 1392 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1393 return true; 1394 1395 if (AM.Scale == 1 && AM.HasBaseReg) 1396 return true; 1397 1398 return false; 1399 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1400 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1401 // For an unknown address space, this usually means that this is for some 1402 // reason being used for pure arithmetic, and not based on some addressing 1403 // computation. We don't have instructions that compute pointers with any 1404 // addressing modes, so treat them as having no offset like flat 1405 // instructions. 1406 return isLegalFlatAddressingMode(AM); 1407 } 1408 1409 // Assume a user alias of global for unknown address spaces. 1410 return isLegalGlobalAddressingMode(AM); 1411 } 1412 1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1414 const SelectionDAG &DAG) const { 1415 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1416 return (MemVT.getSizeInBits() <= 4 * 32); 1417 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1418 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1419 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1420 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1421 return (MemVT.getSizeInBits() <= 2 * 32); 1422 } 1423 return true; 1424 } 1425 1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1427 unsigned Size, unsigned AddrSpace, Align Alignment, 1428 MachineMemOperand::Flags Flags, bool *IsFast) const { 1429 if (IsFast) 1430 *IsFast = false; 1431 1432 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1433 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1434 // Check if alignment requirements for ds_read/write instructions are 1435 // disabled. 1436 if (Subtarget->hasUnalignedDSAccess() && 1437 Subtarget->hasUnalignedAccessMode() && 1438 !Subtarget->hasLDSMisalignedBug()) { 1439 if (IsFast) 1440 *IsFast = Alignment != Align(2); 1441 return true; 1442 } 1443 1444 if (Size == 64) { 1445 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1446 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1447 // with adjacent offsets. 1448 bool AlignedBy4 = Alignment >= Align(4); 1449 if (IsFast) 1450 *IsFast = AlignedBy4; 1451 1452 return AlignedBy4; 1453 } 1454 if (Size == 96) { 1455 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1456 bool Aligned = Alignment >= Align(16); 1457 if (IsFast) 1458 *IsFast = Aligned; 1459 1460 return Aligned; 1461 } 1462 if (Size == 128) { 1463 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1464 // can do a 8 byte aligned, 16 byte access in a single operation using 1465 // ds_read2/write2_b64. 1466 bool Aligned = Alignment >= Align(8); 1467 if (IsFast) 1468 *IsFast = Aligned; 1469 1470 return Aligned; 1471 } 1472 } 1473 1474 // FIXME: We have to be conservative here and assume that flat operations 1475 // will access scratch. If we had access to the IR function, then we 1476 // could determine if any private memory was used in the function. 1477 if (!Subtarget->hasUnalignedScratchAccess() && 1478 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1479 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1480 bool AlignedBy4 = Alignment >= Align(4); 1481 if (IsFast) 1482 *IsFast = AlignedBy4; 1483 1484 return AlignedBy4; 1485 } 1486 1487 if (Subtarget->hasUnalignedBufferAccess() && 1488 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1489 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1490 // If we have an uniform constant load, it still requires using a slow 1491 // buffer instruction if unaligned. 1492 if (IsFast) { 1493 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1494 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1495 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1496 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1497 Alignment >= Align(4) : Alignment != Align(2); 1498 } 1499 1500 return true; 1501 } 1502 1503 // Smaller than dword value must be aligned. 1504 if (Size < 32) 1505 return false; 1506 1507 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1508 // byte-address are ignored, thus forcing Dword alignment. 1509 // This applies to private, global, and constant memory. 1510 if (IsFast) 1511 *IsFast = true; 1512 1513 return Size >= 32 && Alignment >= Align(4); 1514 } 1515 1516 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1517 EVT VT, unsigned AddrSpace, unsigned Alignment, 1518 MachineMemOperand::Flags Flags, bool *IsFast) const { 1519 if (IsFast) 1520 *IsFast = false; 1521 1522 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1523 // which isn't a simple VT. 1524 // Until MVT is extended to handle this, simply check for the size and 1525 // rely on the condition below: allow accesses if the size is a multiple of 4. 1526 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1527 VT.getStoreSize() > 16)) { 1528 return false; 1529 } 1530 1531 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1532 Align(Alignment), Flags, IsFast); 1533 } 1534 1535 EVT SITargetLowering::getOptimalMemOpType( 1536 const MemOp &Op, const AttributeList &FuncAttributes) const { 1537 // FIXME: Should account for address space here. 1538 1539 // The default fallback uses the private pointer size as a guess for a type to 1540 // use. Make sure we switch these to 64-bit accesses. 1541 1542 if (Op.size() >= 16 && 1543 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1544 return MVT::v4i32; 1545 1546 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1547 return MVT::v2i32; 1548 1549 // Use the default. 1550 return MVT::Other; 1551 } 1552 1553 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1554 const MemSDNode *MemNode = cast<MemSDNode>(N); 1555 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1556 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1557 return I && I->getMetadata("amdgpu.noclobber"); 1558 } 1559 1560 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1561 unsigned DestAS) const { 1562 // Flat -> private/local is a simple truncate. 1563 // Flat -> global is no-op 1564 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1565 return true; 1566 1567 const GCNTargetMachine &TM = 1568 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1569 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1570 } 1571 1572 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1573 const MemSDNode *MemNode = cast<MemSDNode>(N); 1574 1575 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1576 } 1577 1578 TargetLoweringBase::LegalizeTypeAction 1579 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1580 int NumElts = VT.getVectorNumElements(); 1581 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1582 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1583 return TargetLoweringBase::getPreferredVectorAction(VT); 1584 } 1585 1586 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1587 Type *Ty) const { 1588 // FIXME: Could be smarter if called for vector constants. 1589 return true; 1590 } 1591 1592 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1593 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1594 switch (Op) { 1595 case ISD::LOAD: 1596 case ISD::STORE: 1597 1598 // These operations are done with 32-bit instructions anyway. 1599 case ISD::AND: 1600 case ISD::OR: 1601 case ISD::XOR: 1602 case ISD::SELECT: 1603 // TODO: Extensions? 1604 return true; 1605 default: 1606 return false; 1607 } 1608 } 1609 1610 // SimplifySetCC uses this function to determine whether or not it should 1611 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1612 if (VT == MVT::i1 && Op == ISD::SETCC) 1613 return false; 1614 1615 return TargetLowering::isTypeDesirableForOp(Op, VT); 1616 } 1617 1618 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1619 const SDLoc &SL, 1620 SDValue Chain, 1621 uint64_t Offset) const { 1622 const DataLayout &DL = DAG.getDataLayout(); 1623 MachineFunction &MF = DAG.getMachineFunction(); 1624 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1625 1626 const ArgDescriptor *InputPtrReg; 1627 const TargetRegisterClass *RC; 1628 LLT ArgTy; 1629 1630 std::tie(InputPtrReg, RC, ArgTy) = 1631 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1632 1633 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1634 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1635 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1636 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1637 1638 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1639 } 1640 1641 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1642 const SDLoc &SL) const { 1643 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1644 FIRST_IMPLICIT); 1645 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1646 } 1647 1648 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1649 const SDLoc &SL, SDValue Val, 1650 bool Signed, 1651 const ISD::InputArg *Arg) const { 1652 // First, if it is a widened vector, narrow it. 1653 if (VT.isVector() && 1654 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1655 EVT NarrowedVT = 1656 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1657 VT.getVectorNumElements()); 1658 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1659 DAG.getConstant(0, SL, MVT::i32)); 1660 } 1661 1662 // Then convert the vector elements or scalar value. 1663 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1664 VT.bitsLT(MemVT)) { 1665 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1666 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1667 } 1668 1669 if (MemVT.isFloatingPoint()) 1670 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1671 else if (Signed) 1672 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1673 else 1674 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1675 1676 return Val; 1677 } 1678 1679 SDValue SITargetLowering::lowerKernargMemParameter( 1680 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1681 uint64_t Offset, Align Alignment, bool Signed, 1682 const ISD::InputArg *Arg) const { 1683 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1684 1685 // Try to avoid using an extload by loading earlier than the argument address, 1686 // and extracting the relevant bits. The load should hopefully be merged with 1687 // the previous argument. 1688 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1689 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1690 int64_t AlignDownOffset = alignDown(Offset, 4); 1691 int64_t OffsetDiff = Offset - AlignDownOffset; 1692 1693 EVT IntVT = MemVT.changeTypeToInteger(); 1694 1695 // TODO: If we passed in the base kernel offset we could have a better 1696 // alignment than 4, but we don't really need it. 1697 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1698 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1699 MachineMemOperand::MODereferenceable | 1700 MachineMemOperand::MOInvariant); 1701 1702 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1703 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1704 1705 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1706 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1707 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1708 1709 1710 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1711 } 1712 1713 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1714 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1715 MachineMemOperand::MODereferenceable | 1716 MachineMemOperand::MOInvariant); 1717 1718 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1719 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1720 } 1721 1722 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1723 const SDLoc &SL, SDValue Chain, 1724 const ISD::InputArg &Arg) const { 1725 MachineFunction &MF = DAG.getMachineFunction(); 1726 MachineFrameInfo &MFI = MF.getFrameInfo(); 1727 1728 if (Arg.Flags.isByVal()) { 1729 unsigned Size = Arg.Flags.getByValSize(); 1730 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1731 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1732 } 1733 1734 unsigned ArgOffset = VA.getLocMemOffset(); 1735 unsigned ArgSize = VA.getValVT().getStoreSize(); 1736 1737 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1738 1739 // Create load nodes to retrieve arguments from the stack. 1740 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1741 SDValue ArgValue; 1742 1743 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1744 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1745 MVT MemVT = VA.getValVT(); 1746 1747 switch (VA.getLocInfo()) { 1748 default: 1749 break; 1750 case CCValAssign::BCvt: 1751 MemVT = VA.getLocVT(); 1752 break; 1753 case CCValAssign::SExt: 1754 ExtType = ISD::SEXTLOAD; 1755 break; 1756 case CCValAssign::ZExt: 1757 ExtType = ISD::ZEXTLOAD; 1758 break; 1759 case CCValAssign::AExt: 1760 ExtType = ISD::EXTLOAD; 1761 break; 1762 } 1763 1764 ArgValue = DAG.getExtLoad( 1765 ExtType, SL, VA.getLocVT(), Chain, FIN, 1766 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1767 MemVT); 1768 return ArgValue; 1769 } 1770 1771 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1772 const SIMachineFunctionInfo &MFI, 1773 EVT VT, 1774 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1775 const ArgDescriptor *Reg; 1776 const TargetRegisterClass *RC; 1777 LLT Ty; 1778 1779 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1780 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1781 } 1782 1783 static void 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 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4010 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4011 if (ST.hasScalarCompareEq64()) { 4012 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4013 .addReg(Src2.getReg()) 4014 .addImm(0); 4015 } else { 4016 const TargetRegisterClass *SubRC = 4017 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4018 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4019 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4020 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4021 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4022 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4023 4024 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4025 .add(Src2Sub0) 4026 .add(Src2Sub1); 4027 4028 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4029 .addReg(Src2_32, RegState::Kill) 4030 .addImm(0); 4031 } 4032 } else { 4033 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4034 .addReg(Src2.getReg()) 4035 .addImm(0); 4036 } 4037 4038 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4039 4040 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4041 .addReg(AMDGPU::SCC); 4042 MI.eraseFromParent(); 4043 return BB; 4044 } 4045 case AMDGPU::SI_INIT_M0: { 4046 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4047 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4048 .add(MI.getOperand(0)); 4049 MI.eraseFromParent(); 4050 return BB; 4051 } 4052 case AMDGPU::SI_INIT_EXEC: 4053 // This should be before all vector instructions. 4054 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4055 AMDGPU::EXEC) 4056 .addImm(MI.getOperand(0).getImm()); 4057 MI.eraseFromParent(); 4058 return BB; 4059 4060 case AMDGPU::SI_INIT_EXEC_LO: 4061 // This should be before all vector instructions. 4062 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4063 AMDGPU::EXEC_LO) 4064 .addImm(MI.getOperand(0).getImm()); 4065 MI.eraseFromParent(); 4066 return BB; 4067 4068 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4069 // Extract the thread count from an SGPR input and set EXEC accordingly. 4070 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4071 // 4072 // S_BFE_U32 count, input, {shift, 7} 4073 // S_BFM_B64 exec, count, 0 4074 // S_CMP_EQ_U32 count, 64 4075 // S_CMOV_B64 exec, -1 4076 MachineInstr *FirstMI = &*BB->begin(); 4077 MachineRegisterInfo &MRI = MF->getRegInfo(); 4078 Register InputReg = MI.getOperand(0).getReg(); 4079 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4080 bool Found = false; 4081 4082 // Move the COPY of the input reg to the beginning, so that we can use it. 4083 for (auto I = BB->begin(); I != &MI; I++) { 4084 if (I->getOpcode() != TargetOpcode::COPY || 4085 I->getOperand(0).getReg() != InputReg) 4086 continue; 4087 4088 if (I == FirstMI) { 4089 FirstMI = &*++BB->begin(); 4090 } else { 4091 I->removeFromParent(); 4092 BB->insert(FirstMI, &*I); 4093 } 4094 Found = true; 4095 break; 4096 } 4097 assert(Found); 4098 (void)Found; 4099 4100 // This should be before all vector instructions. 4101 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4102 bool isWave32 = getSubtarget()->isWave32(); 4103 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4104 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4105 .addReg(InputReg) 4106 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4107 BuildMI(*BB, FirstMI, DebugLoc(), 4108 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4109 Exec) 4110 .addReg(CountReg) 4111 .addImm(0); 4112 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4113 .addReg(CountReg, RegState::Kill) 4114 .addImm(getSubtarget()->getWavefrontSize()); 4115 BuildMI(*BB, FirstMI, DebugLoc(), 4116 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4117 Exec) 4118 .addImm(-1); 4119 MI.eraseFromParent(); 4120 return BB; 4121 } 4122 4123 case AMDGPU::GET_GROUPSTATICSIZE: { 4124 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4125 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4126 DebugLoc DL = MI.getDebugLoc(); 4127 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4128 .add(MI.getOperand(0)) 4129 .addImm(MFI->getLDSSize()); 4130 MI.eraseFromParent(); 4131 return BB; 4132 } 4133 case AMDGPU::SI_INDIRECT_SRC_V1: 4134 case AMDGPU::SI_INDIRECT_SRC_V2: 4135 case AMDGPU::SI_INDIRECT_SRC_V4: 4136 case AMDGPU::SI_INDIRECT_SRC_V8: 4137 case AMDGPU::SI_INDIRECT_SRC_V16: 4138 case AMDGPU::SI_INDIRECT_SRC_V32: 4139 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4140 case AMDGPU::SI_INDIRECT_DST_V1: 4141 case AMDGPU::SI_INDIRECT_DST_V2: 4142 case AMDGPU::SI_INDIRECT_DST_V4: 4143 case AMDGPU::SI_INDIRECT_DST_V8: 4144 case AMDGPU::SI_INDIRECT_DST_V16: 4145 case AMDGPU::SI_INDIRECT_DST_V32: 4146 return emitIndirectDst(MI, *BB, *getSubtarget()); 4147 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4148 case AMDGPU::SI_KILL_I1_PSEUDO: 4149 return splitKillBlock(MI, BB); 4150 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4151 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4152 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4153 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4154 4155 Register Dst = MI.getOperand(0).getReg(); 4156 Register Src0 = MI.getOperand(1).getReg(); 4157 Register Src1 = MI.getOperand(2).getReg(); 4158 const DebugLoc &DL = MI.getDebugLoc(); 4159 Register SrcCond = MI.getOperand(3).getReg(); 4160 4161 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4162 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4163 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4164 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4165 4166 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4167 .addReg(SrcCond); 4168 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4169 .addImm(0) 4170 .addReg(Src0, 0, AMDGPU::sub0) 4171 .addImm(0) 4172 .addReg(Src1, 0, AMDGPU::sub0) 4173 .addReg(SrcCondCopy); 4174 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4175 .addImm(0) 4176 .addReg(Src0, 0, AMDGPU::sub1) 4177 .addImm(0) 4178 .addReg(Src1, 0, AMDGPU::sub1) 4179 .addReg(SrcCondCopy); 4180 4181 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4182 .addReg(DstLo) 4183 .addImm(AMDGPU::sub0) 4184 .addReg(DstHi) 4185 .addImm(AMDGPU::sub1); 4186 MI.eraseFromParent(); 4187 return BB; 4188 } 4189 case AMDGPU::SI_BR_UNDEF: { 4190 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4191 const DebugLoc &DL = MI.getDebugLoc(); 4192 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4193 .add(MI.getOperand(0)); 4194 Br->getOperand(1).setIsUndef(true); // read undef SCC 4195 MI.eraseFromParent(); 4196 return BB; 4197 } 4198 case AMDGPU::ADJCALLSTACKUP: 4199 case AMDGPU::ADJCALLSTACKDOWN: { 4200 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4201 MachineInstrBuilder MIB(*MF, &MI); 4202 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4203 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4204 return BB; 4205 } 4206 case AMDGPU::SI_CALL_ISEL: { 4207 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4208 const DebugLoc &DL = MI.getDebugLoc(); 4209 4210 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4211 4212 MachineInstrBuilder MIB; 4213 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4214 4215 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4216 MIB.add(MI.getOperand(I)); 4217 4218 MIB.cloneMemRefs(MI); 4219 MI.eraseFromParent(); 4220 return BB; 4221 } 4222 case AMDGPU::V_ADD_CO_U32_e32: 4223 case AMDGPU::V_SUB_CO_U32_e32: 4224 case AMDGPU::V_SUBREV_CO_U32_e32: { 4225 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4226 const DebugLoc &DL = MI.getDebugLoc(); 4227 unsigned Opc = MI.getOpcode(); 4228 4229 bool NeedClampOperand = false; 4230 if (TII->pseudoToMCOpcode(Opc) == -1) { 4231 Opc = AMDGPU::getVOPe64(Opc); 4232 NeedClampOperand = true; 4233 } 4234 4235 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4236 if (TII->isVOP3(*I)) { 4237 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4238 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4239 I.addReg(TRI->getVCC(), RegState::Define); 4240 } 4241 I.add(MI.getOperand(1)) 4242 .add(MI.getOperand(2)); 4243 if (NeedClampOperand) 4244 I.addImm(0); // clamp bit for e64 encoding 4245 4246 TII->legalizeOperands(*I); 4247 4248 MI.eraseFromParent(); 4249 return BB; 4250 } 4251 case AMDGPU::DS_GWS_INIT: 4252 case AMDGPU::DS_GWS_SEMA_V: 4253 case AMDGPU::DS_GWS_SEMA_BR: 4254 case AMDGPU::DS_GWS_SEMA_P: 4255 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4256 case AMDGPU::DS_GWS_BARRIER: 4257 // A s_waitcnt 0 is required to be the instruction immediately following. 4258 if (getSubtarget()->hasGWSAutoReplay()) { 4259 bundleInstWithWaitcnt(MI); 4260 return BB; 4261 } 4262 4263 return emitGWSMemViolTestLoop(MI, BB); 4264 case AMDGPU::S_SETREG_B32: { 4265 // Try to optimize cases that only set the denormal mode or rounding mode. 4266 // 4267 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4268 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4269 // instead. 4270 // 4271 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4272 // allow you to have a no side effect instruction in the output of a 4273 // sideeffecting pattern. 4274 unsigned ID, Offset, Width; 4275 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4276 if (ID != AMDGPU::Hwreg::ID_MODE) 4277 return BB; 4278 4279 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4280 const unsigned SetMask = WidthMask << Offset; 4281 4282 if (getSubtarget()->hasDenormModeInst()) { 4283 unsigned SetDenormOp = 0; 4284 unsigned SetRoundOp = 0; 4285 4286 // The dedicated instructions can only set the whole denorm or round mode 4287 // at once, not a subset of bits in either. 4288 if (SetMask == 4289 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4290 // If this fully sets both the round and denorm mode, emit the two 4291 // dedicated instructions for these. 4292 SetRoundOp = AMDGPU::S_ROUND_MODE; 4293 SetDenormOp = AMDGPU::S_DENORM_MODE; 4294 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4295 SetRoundOp = AMDGPU::S_ROUND_MODE; 4296 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4297 SetDenormOp = AMDGPU::S_DENORM_MODE; 4298 } 4299 4300 if (SetRoundOp || SetDenormOp) { 4301 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4302 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4303 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4304 unsigned ImmVal = Def->getOperand(1).getImm(); 4305 if (SetRoundOp) { 4306 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4307 .addImm(ImmVal & 0xf); 4308 4309 // If we also have the denorm mode, get just the denorm mode bits. 4310 ImmVal >>= 4; 4311 } 4312 4313 if (SetDenormOp) { 4314 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4315 .addImm(ImmVal & 0xf); 4316 } 4317 4318 MI.eraseFromParent(); 4319 return BB; 4320 } 4321 } 4322 } 4323 4324 // If only FP bits are touched, used the no side effects pseudo. 4325 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4326 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4327 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4328 4329 return BB; 4330 } 4331 default: 4332 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4333 } 4334 } 4335 4336 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4337 return isTypeLegal(VT.getScalarType()); 4338 } 4339 4340 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4341 // This currently forces unfolding various combinations of fsub into fma with 4342 // free fneg'd operands. As long as we have fast FMA (controlled by 4343 // isFMAFasterThanFMulAndFAdd), we should perform these. 4344 4345 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4346 // most of these combines appear to be cycle neutral but save on instruction 4347 // count / code size. 4348 return true; 4349 } 4350 4351 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4352 EVT VT) const { 4353 if (!VT.isVector()) { 4354 return MVT::i1; 4355 } 4356 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4357 } 4358 4359 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4360 // TODO: Should i16 be used always if legal? For now it would force VALU 4361 // shifts. 4362 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4363 } 4364 4365 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4366 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4367 ? Ty.changeElementSize(16) 4368 : Ty.changeElementSize(32); 4369 } 4370 4371 // Answering this is somewhat tricky and depends on the specific device which 4372 // have different rates for fma or all f64 operations. 4373 // 4374 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4375 // regardless of which device (although the number of cycles differs between 4376 // devices), so it is always profitable for f64. 4377 // 4378 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4379 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4380 // which we can always do even without fused FP ops since it returns the same 4381 // result as the separate operations and since it is always full 4382 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4383 // however does not support denormals, so we do report fma as faster if we have 4384 // a fast fma device and require denormals. 4385 // 4386 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4387 EVT VT) const { 4388 VT = VT.getScalarType(); 4389 4390 switch (VT.getSimpleVT().SimpleTy) { 4391 case MVT::f32: { 4392 // If mad is not available this depends only on if f32 fma is full rate. 4393 if (!Subtarget->hasMadMacF32Insts()) 4394 return Subtarget->hasFastFMAF32(); 4395 4396 // Otherwise f32 mad is always full rate and returns the same result as 4397 // the separate operations so should be preferred over fma. 4398 // However does not support denomals. 4399 if (hasFP32Denormals(MF)) 4400 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4401 4402 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4403 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4404 } 4405 case MVT::f64: 4406 return true; 4407 case MVT::f16: 4408 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4409 default: 4410 break; 4411 } 4412 4413 return false; 4414 } 4415 4416 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4417 const SDNode *N) const { 4418 // TODO: Check future ftz flag 4419 // v_mad_f32/v_mac_f32 do not support denormals. 4420 EVT VT = N->getValueType(0); 4421 if (VT == MVT::f32) 4422 return Subtarget->hasMadMacF32Insts() && 4423 !hasFP32Denormals(DAG.getMachineFunction()); 4424 if (VT == MVT::f16) { 4425 return Subtarget->hasMadF16() && 4426 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4427 } 4428 4429 return false; 4430 } 4431 4432 //===----------------------------------------------------------------------===// 4433 // Custom DAG Lowering Operations 4434 //===----------------------------------------------------------------------===// 4435 4436 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4437 // wider vector type is legal. 4438 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4439 SelectionDAG &DAG) const { 4440 unsigned Opc = Op.getOpcode(); 4441 EVT VT = Op.getValueType(); 4442 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4443 4444 SDValue Lo, Hi; 4445 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4446 4447 SDLoc SL(Op); 4448 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4449 Op->getFlags()); 4450 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4451 Op->getFlags()); 4452 4453 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4454 } 4455 4456 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4457 // wider vector type is legal. 4458 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4459 SelectionDAG &DAG) const { 4460 unsigned Opc = Op.getOpcode(); 4461 EVT VT = Op.getValueType(); 4462 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4463 4464 SDValue Lo0, Hi0; 4465 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4466 SDValue Lo1, Hi1; 4467 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4468 4469 SDLoc SL(Op); 4470 4471 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4472 Op->getFlags()); 4473 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4474 Op->getFlags()); 4475 4476 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4477 } 4478 4479 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4480 SelectionDAG &DAG) const { 4481 unsigned Opc = Op.getOpcode(); 4482 EVT VT = Op.getValueType(); 4483 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4484 4485 SDValue Lo0, Hi0; 4486 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4487 SDValue Lo1, Hi1; 4488 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4489 SDValue Lo2, Hi2; 4490 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4491 4492 SDLoc SL(Op); 4493 4494 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4495 Op->getFlags()); 4496 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4497 Op->getFlags()); 4498 4499 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4500 } 4501 4502 4503 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4504 switch (Op.getOpcode()) { 4505 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4506 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4507 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4508 case ISD::LOAD: { 4509 SDValue Result = LowerLOAD(Op, DAG); 4510 assert((!Result.getNode() || 4511 Result.getNode()->getNumValues() == 2) && 4512 "Load should return a value and a chain"); 4513 return Result; 4514 } 4515 4516 case ISD::FSIN: 4517 case ISD::FCOS: 4518 return LowerTrig(Op, DAG); 4519 case ISD::SELECT: return LowerSELECT(Op, DAG); 4520 case ISD::FDIV: return LowerFDIV(Op, DAG); 4521 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4522 case ISD::STORE: return LowerSTORE(Op, DAG); 4523 case ISD::GlobalAddress: { 4524 MachineFunction &MF = DAG.getMachineFunction(); 4525 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4526 return LowerGlobalAddress(MFI, Op, DAG); 4527 } 4528 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4529 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4530 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4531 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4532 case ISD::INSERT_SUBVECTOR: 4533 return lowerINSERT_SUBVECTOR(Op, DAG); 4534 case ISD::INSERT_VECTOR_ELT: 4535 return lowerINSERT_VECTOR_ELT(Op, DAG); 4536 case ISD::EXTRACT_VECTOR_ELT: 4537 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4538 case ISD::VECTOR_SHUFFLE: 4539 return lowerVECTOR_SHUFFLE(Op, DAG); 4540 case ISD::BUILD_VECTOR: 4541 return lowerBUILD_VECTOR(Op, DAG); 4542 case ISD::FP_ROUND: 4543 return lowerFP_ROUND(Op, DAG); 4544 case ISD::TRAP: 4545 return lowerTRAP(Op, DAG); 4546 case ISD::DEBUGTRAP: 4547 return lowerDEBUGTRAP(Op, DAG); 4548 case ISD::FABS: 4549 case ISD::FNEG: 4550 case ISD::FCANONICALIZE: 4551 case ISD::BSWAP: 4552 return splitUnaryVectorOp(Op, DAG); 4553 case ISD::FMINNUM: 4554 case ISD::FMAXNUM: 4555 return lowerFMINNUM_FMAXNUM(Op, DAG); 4556 case ISD::FMA: 4557 return splitTernaryVectorOp(Op, DAG); 4558 case ISD::SHL: 4559 case ISD::SRA: 4560 case ISD::SRL: 4561 case ISD::ADD: 4562 case ISD::SUB: 4563 case ISD::MUL: 4564 case ISD::SMIN: 4565 case ISD::SMAX: 4566 case ISD::UMIN: 4567 case ISD::UMAX: 4568 case ISD::FADD: 4569 case ISD::FMUL: 4570 case ISD::FMINNUM_IEEE: 4571 case ISD::FMAXNUM_IEEE: 4572 case ISD::UADDSAT: 4573 case ISD::USUBSAT: 4574 case ISD::SADDSAT: 4575 case ISD::SSUBSAT: 4576 return splitBinaryVectorOp(Op, DAG); 4577 case ISD::SMULO: 4578 case ISD::UMULO: 4579 return lowerXMULO(Op, DAG); 4580 case ISD::DYNAMIC_STACKALLOC: 4581 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4582 } 4583 return SDValue(); 4584 } 4585 4586 // Used for D16: Casts the result of an instruction into the right vector, 4587 // packs values if loads return unpacked values. 4588 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4589 const SDLoc &DL, 4590 SelectionDAG &DAG, bool Unpacked) { 4591 if (!LoadVT.isVector()) 4592 return Result; 4593 4594 // Cast back to the original packed type or to a larger type that is a 4595 // multiple of 32 bit for D16. Widening the return type is a required for 4596 // legalization. 4597 EVT FittingLoadVT = LoadVT; 4598 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4599 FittingLoadVT = 4600 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4601 LoadVT.getVectorNumElements() + 1); 4602 } 4603 4604 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4605 // Truncate to v2i16/v4i16. 4606 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4607 4608 // Workaround legalizer not scalarizing truncate after vector op 4609 // legalization but not creating intermediate vector trunc. 4610 SmallVector<SDValue, 4> Elts; 4611 DAG.ExtractVectorElements(Result, Elts); 4612 for (SDValue &Elt : Elts) 4613 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4614 4615 // Pad illegal v1i16/v3fi6 to v4i16 4616 if ((LoadVT.getVectorNumElements() % 2) == 1) 4617 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4618 4619 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4620 4621 // Bitcast to original type (v2f16/v4f16). 4622 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4623 } 4624 4625 // Cast back to the original packed type. 4626 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4627 } 4628 4629 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4630 MemSDNode *M, 4631 SelectionDAG &DAG, 4632 ArrayRef<SDValue> Ops, 4633 bool IsIntrinsic) const { 4634 SDLoc DL(M); 4635 4636 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4637 EVT LoadVT = M->getValueType(0); 4638 4639 EVT EquivLoadVT = LoadVT; 4640 if (LoadVT.isVector()) { 4641 if (Unpacked) { 4642 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4643 LoadVT.getVectorNumElements()); 4644 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4645 // Widen v3f16 to legal type 4646 EquivLoadVT = 4647 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4648 LoadVT.getVectorNumElements() + 1); 4649 } 4650 } 4651 4652 // Change from v4f16/v2f16 to EquivLoadVT. 4653 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4654 4655 SDValue Load 4656 = DAG.getMemIntrinsicNode( 4657 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4658 VTList, Ops, M->getMemoryVT(), 4659 M->getMemOperand()); 4660 4661 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4662 4663 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4664 } 4665 4666 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4667 SelectionDAG &DAG, 4668 ArrayRef<SDValue> Ops) const { 4669 SDLoc DL(M); 4670 EVT LoadVT = M->getValueType(0); 4671 EVT EltType = LoadVT.getScalarType(); 4672 EVT IntVT = LoadVT.changeTypeToInteger(); 4673 4674 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4675 4676 unsigned Opc = 4677 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4678 4679 if (IsD16) { 4680 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4681 } 4682 4683 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4684 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4685 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4686 4687 if (isTypeLegal(LoadVT)) { 4688 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4689 M->getMemOperand(), DAG); 4690 } 4691 4692 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4693 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4694 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4695 M->getMemOperand(), DAG); 4696 return DAG.getMergeValues( 4697 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4698 DL); 4699 } 4700 4701 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4702 SDNode *N, SelectionDAG &DAG) { 4703 EVT VT = N->getValueType(0); 4704 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4705 unsigned CondCode = CD->getZExtValue(); 4706 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4707 return DAG.getUNDEF(VT); 4708 4709 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4710 4711 SDValue LHS = N->getOperand(1); 4712 SDValue RHS = N->getOperand(2); 4713 4714 SDLoc DL(N); 4715 4716 EVT CmpVT = LHS.getValueType(); 4717 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4718 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4719 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4720 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4721 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4722 } 4723 4724 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4725 4726 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4727 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4728 4729 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4730 DAG.getCondCode(CCOpcode)); 4731 if (VT.bitsEq(CCVT)) 4732 return SetCC; 4733 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4734 } 4735 4736 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4737 SDNode *N, SelectionDAG &DAG) { 4738 EVT VT = N->getValueType(0); 4739 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4740 4741 unsigned CondCode = CD->getZExtValue(); 4742 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4743 return DAG.getUNDEF(VT); 4744 4745 SDValue Src0 = N->getOperand(1); 4746 SDValue Src1 = N->getOperand(2); 4747 EVT CmpVT = Src0.getValueType(); 4748 SDLoc SL(N); 4749 4750 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4751 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4752 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4753 } 4754 4755 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4756 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4757 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4758 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4759 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4760 Src1, DAG.getCondCode(CCOpcode)); 4761 if (VT.bitsEq(CCVT)) 4762 return SetCC; 4763 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4764 } 4765 4766 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4767 SelectionDAG &DAG) { 4768 EVT VT = N->getValueType(0); 4769 SDValue Src = N->getOperand(1); 4770 SDLoc SL(N); 4771 4772 if (Src.getOpcode() == ISD::SETCC) { 4773 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4774 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4775 Src.getOperand(1), Src.getOperand(2)); 4776 } 4777 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4778 // (ballot 0) -> 0 4779 if (Arg->isNullValue()) 4780 return DAG.getConstant(0, SL, VT); 4781 4782 // (ballot 1) -> EXEC/EXEC_LO 4783 if (Arg->isOne()) { 4784 Register Exec; 4785 if (VT.getScalarSizeInBits() == 32) 4786 Exec = AMDGPU::EXEC_LO; 4787 else if (VT.getScalarSizeInBits() == 64) 4788 Exec = AMDGPU::EXEC; 4789 else 4790 return SDValue(); 4791 4792 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4793 } 4794 } 4795 4796 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4797 // ISD::SETNE) 4798 return DAG.getNode( 4799 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4800 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4801 } 4802 4803 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4804 SmallVectorImpl<SDValue> &Results, 4805 SelectionDAG &DAG) const { 4806 switch (N->getOpcode()) { 4807 case ISD::INSERT_VECTOR_ELT: { 4808 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4809 Results.push_back(Res); 4810 return; 4811 } 4812 case ISD::EXTRACT_VECTOR_ELT: { 4813 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4814 Results.push_back(Res); 4815 return; 4816 } 4817 case ISD::INTRINSIC_WO_CHAIN: { 4818 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4819 switch (IID) { 4820 case Intrinsic::amdgcn_cvt_pkrtz: { 4821 SDValue Src0 = N->getOperand(1); 4822 SDValue Src1 = N->getOperand(2); 4823 SDLoc SL(N); 4824 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4825 Src0, Src1); 4826 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4827 return; 4828 } 4829 case Intrinsic::amdgcn_cvt_pknorm_i16: 4830 case Intrinsic::amdgcn_cvt_pknorm_u16: 4831 case Intrinsic::amdgcn_cvt_pk_i16: 4832 case Intrinsic::amdgcn_cvt_pk_u16: { 4833 SDValue Src0 = N->getOperand(1); 4834 SDValue Src1 = N->getOperand(2); 4835 SDLoc SL(N); 4836 unsigned Opcode; 4837 4838 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4839 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4840 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4841 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4842 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4843 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4844 else 4845 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4846 4847 EVT VT = N->getValueType(0); 4848 if (isTypeLegal(VT)) 4849 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4850 else { 4851 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4852 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4853 } 4854 return; 4855 } 4856 } 4857 break; 4858 } 4859 case ISD::INTRINSIC_W_CHAIN: { 4860 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4861 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4862 // FIXME: Hacky 4863 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4864 Results.push_back(Res.getOperand(I)); 4865 } 4866 } else { 4867 Results.push_back(Res); 4868 Results.push_back(Res.getValue(1)); 4869 } 4870 return; 4871 } 4872 4873 break; 4874 } 4875 case ISD::SELECT: { 4876 SDLoc SL(N); 4877 EVT VT = N->getValueType(0); 4878 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4879 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4880 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4881 4882 EVT SelectVT = NewVT; 4883 if (NewVT.bitsLT(MVT::i32)) { 4884 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4885 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4886 SelectVT = MVT::i32; 4887 } 4888 4889 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4890 N->getOperand(0), LHS, RHS); 4891 4892 if (NewVT != SelectVT) 4893 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4894 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4895 return; 4896 } 4897 case ISD::FNEG: { 4898 if (N->getValueType(0) != MVT::v2f16) 4899 break; 4900 4901 SDLoc SL(N); 4902 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4903 4904 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4905 BC, 4906 DAG.getConstant(0x80008000, SL, MVT::i32)); 4907 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4908 return; 4909 } 4910 case ISD::FABS: { 4911 if (N->getValueType(0) != MVT::v2f16) 4912 break; 4913 4914 SDLoc SL(N); 4915 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4916 4917 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4918 BC, 4919 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4920 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4921 return; 4922 } 4923 default: 4924 break; 4925 } 4926 } 4927 4928 /// Helper function for LowerBRCOND 4929 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4930 4931 SDNode *Parent = Value.getNode(); 4932 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4933 I != E; ++I) { 4934 4935 if (I.getUse().get() != Value) 4936 continue; 4937 4938 if (I->getOpcode() == Opcode) 4939 return *I; 4940 } 4941 return nullptr; 4942 } 4943 4944 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4945 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4946 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4947 case Intrinsic::amdgcn_if: 4948 return AMDGPUISD::IF; 4949 case Intrinsic::amdgcn_else: 4950 return AMDGPUISD::ELSE; 4951 case Intrinsic::amdgcn_loop: 4952 return AMDGPUISD::LOOP; 4953 case Intrinsic::amdgcn_end_cf: 4954 llvm_unreachable("should not occur"); 4955 default: 4956 return 0; 4957 } 4958 } 4959 4960 // break, if_break, else_break are all only used as inputs to loop, not 4961 // directly as branch conditions. 4962 return 0; 4963 } 4964 4965 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4966 const Triple &TT = getTargetMachine().getTargetTriple(); 4967 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4968 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4969 AMDGPU::shouldEmitConstantsToTextSection(TT); 4970 } 4971 4972 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4973 // FIXME: Either avoid relying on address space here or change the default 4974 // address space for functions to avoid the explicit check. 4975 return (GV->getValueType()->isFunctionTy() || 4976 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4977 !shouldEmitFixup(GV) && 4978 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4979 } 4980 4981 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4982 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4983 } 4984 4985 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4986 if (!GV->hasExternalLinkage()) 4987 return true; 4988 4989 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4990 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4991 } 4992 4993 /// This transforms the control flow intrinsics to get the branch destination as 4994 /// last parameter, also switches branch target with BR if the need arise 4995 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4996 SelectionDAG &DAG) const { 4997 SDLoc DL(BRCOND); 4998 4999 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5000 SDValue Target = BRCOND.getOperand(2); 5001 SDNode *BR = nullptr; 5002 SDNode *SetCC = nullptr; 5003 5004 if (Intr->getOpcode() == ISD::SETCC) { 5005 // As long as we negate the condition everything is fine 5006 SetCC = Intr; 5007 Intr = SetCC->getOperand(0).getNode(); 5008 5009 } else { 5010 // Get the target from BR if we don't negate the condition 5011 BR = findUser(BRCOND, ISD::BR); 5012 assert(BR && "brcond missing unconditional branch user"); 5013 Target = BR->getOperand(1); 5014 } 5015 5016 unsigned CFNode = isCFIntrinsic(Intr); 5017 if (CFNode == 0) { 5018 // This is a uniform branch so we don't need to legalize. 5019 return BRCOND; 5020 } 5021 5022 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5023 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5024 5025 assert(!SetCC || 5026 (SetCC->getConstantOperandVal(1) == 1 && 5027 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5028 ISD::SETNE)); 5029 5030 // operands of the new intrinsic call 5031 SmallVector<SDValue, 4> Ops; 5032 if (HaveChain) 5033 Ops.push_back(BRCOND.getOperand(0)); 5034 5035 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5036 Ops.push_back(Target); 5037 5038 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5039 5040 // build the new intrinsic call 5041 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5042 5043 if (!HaveChain) { 5044 SDValue Ops[] = { 5045 SDValue(Result, 0), 5046 BRCOND.getOperand(0) 5047 }; 5048 5049 Result = DAG.getMergeValues(Ops, DL).getNode(); 5050 } 5051 5052 if (BR) { 5053 // Give the branch instruction our target 5054 SDValue Ops[] = { 5055 BR->getOperand(0), 5056 BRCOND.getOperand(2) 5057 }; 5058 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5059 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5060 } 5061 5062 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5063 5064 // Copy the intrinsic results to registers 5065 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5066 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5067 if (!CopyToReg) 5068 continue; 5069 5070 Chain = DAG.getCopyToReg( 5071 Chain, DL, 5072 CopyToReg->getOperand(1), 5073 SDValue(Result, i - 1), 5074 SDValue()); 5075 5076 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5077 } 5078 5079 // Remove the old intrinsic from the chain 5080 DAG.ReplaceAllUsesOfValueWith( 5081 SDValue(Intr, Intr->getNumValues() - 1), 5082 Intr->getOperand(0)); 5083 5084 return Chain; 5085 } 5086 5087 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5088 SelectionDAG &DAG) const { 5089 MVT VT = Op.getSimpleValueType(); 5090 SDLoc DL(Op); 5091 // Checking the depth 5092 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5093 return DAG.getConstant(0, DL, VT); 5094 5095 MachineFunction &MF = DAG.getMachineFunction(); 5096 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5097 // Check for kernel and shader functions 5098 if (Info->isEntryFunction()) 5099 return DAG.getConstant(0, DL, VT); 5100 5101 MachineFrameInfo &MFI = MF.getFrameInfo(); 5102 // There is a call to @llvm.returnaddress in this function 5103 MFI.setReturnAddressIsTaken(true); 5104 5105 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5106 // Get the return address reg and mark it as an implicit live-in 5107 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5108 5109 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5110 } 5111 5112 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5113 SDValue Op, 5114 const SDLoc &DL, 5115 EVT VT) const { 5116 return Op.getValueType().bitsLE(VT) ? 5117 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5118 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5119 DAG.getTargetConstant(0, DL, MVT::i32)); 5120 } 5121 5122 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5123 assert(Op.getValueType() == MVT::f16 && 5124 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5125 5126 SDValue Src = Op.getOperand(0); 5127 EVT SrcVT = Src.getValueType(); 5128 if (SrcVT != MVT::f64) 5129 return Op; 5130 5131 SDLoc DL(Op); 5132 5133 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5134 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5135 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5136 } 5137 5138 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5139 SelectionDAG &DAG) const { 5140 EVT VT = Op.getValueType(); 5141 const MachineFunction &MF = DAG.getMachineFunction(); 5142 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5143 bool IsIEEEMode = Info->getMode().IEEE; 5144 5145 // FIXME: Assert during selection that this is only selected for 5146 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5147 // mode functions, but this happens to be OK since it's only done in cases 5148 // where there is known no sNaN. 5149 if (IsIEEEMode) 5150 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5151 5152 if (VT == MVT::v4f16) 5153 return splitBinaryVectorOp(Op, DAG); 5154 return Op; 5155 } 5156 5157 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5158 EVT VT = Op.getValueType(); 5159 SDLoc SL(Op); 5160 SDValue LHS = Op.getOperand(0); 5161 SDValue RHS = Op.getOperand(1); 5162 bool isSigned = Op.getOpcode() == ISD::SMULO; 5163 5164 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5165 const APInt &C = RHSC->getAPIntValue(); 5166 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5167 if (C.isPowerOf2()) { 5168 // smulo(x, signed_min) is same as umulo(x, signed_min). 5169 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5170 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5171 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5172 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5173 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5174 SL, VT, Result, ShiftAmt), 5175 LHS, ISD::SETNE); 5176 return DAG.getMergeValues({ Result, Overflow }, SL); 5177 } 5178 } 5179 5180 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5181 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5182 SL, VT, LHS, RHS); 5183 5184 SDValue Sign = isSigned 5185 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5186 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5187 : DAG.getConstant(0, SL, VT); 5188 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5189 5190 return DAG.getMergeValues({ Result, Overflow }, SL); 5191 } 5192 5193 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5194 SDLoc SL(Op); 5195 SDValue Chain = Op.getOperand(0); 5196 5197 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5198 !Subtarget->isTrapHandlerEnabled()) 5199 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5200 5201 MachineFunction &MF = DAG.getMachineFunction(); 5202 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5203 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5204 assert(UserSGPR != AMDGPU::NoRegister); 5205 SDValue QueuePtr = CreateLiveInRegister( 5206 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5207 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5208 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5209 QueuePtr, SDValue()); 5210 SDValue Ops[] = { 5211 ToReg, 5212 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5213 SGPR01, 5214 ToReg.getValue(1) 5215 }; 5216 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5217 } 5218 5219 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5220 SDLoc SL(Op); 5221 SDValue Chain = Op.getOperand(0); 5222 MachineFunction &MF = DAG.getMachineFunction(); 5223 5224 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5225 !Subtarget->isTrapHandlerEnabled()) { 5226 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5227 "debugtrap handler not supported", 5228 Op.getDebugLoc(), 5229 DS_Warning); 5230 LLVMContext &Ctx = MF.getFunction().getContext(); 5231 Ctx.diagnose(NoTrap); 5232 return Chain; 5233 } 5234 5235 SDValue Ops[] = { 5236 Chain, 5237 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5238 }; 5239 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5240 } 5241 5242 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5243 SelectionDAG &DAG) const { 5244 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5245 if (Subtarget->hasApertureRegs()) { 5246 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5247 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5248 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5249 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5250 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5251 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5252 unsigned Encoding = 5253 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5254 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5255 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5256 5257 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5258 SDValue ApertureReg = SDValue( 5259 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5260 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5261 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5262 } 5263 5264 MachineFunction &MF = DAG.getMachineFunction(); 5265 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5266 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5267 assert(UserSGPR != AMDGPU::NoRegister); 5268 5269 SDValue QueuePtr = CreateLiveInRegister( 5270 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5271 5272 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5273 // private_segment_aperture_base_hi. 5274 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5275 5276 SDValue Ptr = 5277 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5278 5279 // TODO: Use custom target PseudoSourceValue. 5280 // TODO: We should use the value from the IR intrinsic call, but it might not 5281 // be available and how do we get it? 5282 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5283 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5284 commonAlignment(Align(64), StructOffset), 5285 MachineMemOperand::MODereferenceable | 5286 MachineMemOperand::MOInvariant); 5287 } 5288 5289 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5290 SelectionDAG &DAG) const { 5291 SDLoc SL(Op); 5292 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5293 5294 SDValue Src = ASC->getOperand(0); 5295 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5296 5297 const AMDGPUTargetMachine &TM = 5298 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5299 5300 // flat -> local/private 5301 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5302 unsigned DestAS = ASC->getDestAddressSpace(); 5303 5304 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5305 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5306 unsigned NullVal = TM.getNullPointerValue(DestAS); 5307 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5308 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5309 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5310 5311 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5312 NonNull, Ptr, SegmentNullPtr); 5313 } 5314 } 5315 5316 // local/private -> flat 5317 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5318 unsigned SrcAS = ASC->getSrcAddressSpace(); 5319 5320 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5321 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5322 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5323 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5324 5325 SDValue NonNull 5326 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5327 5328 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5329 SDValue CvtPtr 5330 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5331 5332 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5333 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5334 FlatNullPtr); 5335 } 5336 } 5337 5338 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5339 Src.getValueType() == MVT::i64) 5340 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5341 5342 // global <-> flat are no-ops and never emitted. 5343 5344 const MachineFunction &MF = DAG.getMachineFunction(); 5345 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5346 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5347 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5348 5349 return DAG.getUNDEF(ASC->getValueType(0)); 5350 } 5351 5352 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5353 // the small vector and inserting them into the big vector. That is better than 5354 // the default expansion of doing it via a stack slot. Even though the use of 5355 // the stack slot would be optimized away afterwards, the stack slot itself 5356 // remains. 5357 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5358 SelectionDAG &DAG) const { 5359 SDValue Vec = Op.getOperand(0); 5360 SDValue Ins = Op.getOperand(1); 5361 SDValue Idx = Op.getOperand(2); 5362 EVT VecVT = Vec.getValueType(); 5363 EVT InsVT = Ins.getValueType(); 5364 EVT EltVT = VecVT.getVectorElementType(); 5365 unsigned InsNumElts = InsVT.getVectorNumElements(); 5366 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5367 SDLoc SL(Op); 5368 5369 for (unsigned I = 0; I != InsNumElts; ++I) { 5370 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5371 DAG.getConstant(I, SL, MVT::i32)); 5372 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5373 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5374 } 5375 return Vec; 5376 } 5377 5378 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5379 SelectionDAG &DAG) const { 5380 SDValue Vec = Op.getOperand(0); 5381 SDValue InsVal = Op.getOperand(1); 5382 SDValue Idx = Op.getOperand(2); 5383 EVT VecVT = Vec.getValueType(); 5384 EVT EltVT = VecVT.getVectorElementType(); 5385 unsigned VecSize = VecVT.getSizeInBits(); 5386 unsigned EltSize = EltVT.getSizeInBits(); 5387 5388 5389 assert(VecSize <= 64); 5390 5391 unsigned NumElts = VecVT.getVectorNumElements(); 5392 SDLoc SL(Op); 5393 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5394 5395 if (NumElts == 4 && EltSize == 16 && KIdx) { 5396 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5397 5398 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5399 DAG.getConstant(0, SL, MVT::i32)); 5400 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5401 DAG.getConstant(1, SL, MVT::i32)); 5402 5403 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5404 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5405 5406 unsigned Idx = KIdx->getZExtValue(); 5407 bool InsertLo = Idx < 2; 5408 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5409 InsertLo ? LoVec : HiVec, 5410 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5411 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5412 5413 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5414 5415 SDValue Concat = InsertLo ? 5416 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5417 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5418 5419 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5420 } 5421 5422 if (isa<ConstantSDNode>(Idx)) 5423 return SDValue(); 5424 5425 MVT IntVT = MVT::getIntegerVT(VecSize); 5426 5427 // Avoid stack access for dynamic indexing. 5428 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5429 5430 // Create a congruent vector with the target value in each element so that 5431 // the required element can be masked and ORed into the target vector. 5432 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5433 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5434 5435 assert(isPowerOf2_32(EltSize)); 5436 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5437 5438 // Convert vector index to bit-index. 5439 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5440 5441 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5442 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5443 DAG.getConstant(0xffff, SL, IntVT), 5444 ScaledIdx); 5445 5446 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5447 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5448 DAG.getNOT(SL, BFM, IntVT), BCVec); 5449 5450 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5451 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5452 } 5453 5454 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5455 SelectionDAG &DAG) const { 5456 SDLoc SL(Op); 5457 5458 EVT ResultVT = Op.getValueType(); 5459 SDValue Vec = Op.getOperand(0); 5460 SDValue Idx = Op.getOperand(1); 5461 EVT VecVT = Vec.getValueType(); 5462 unsigned VecSize = VecVT.getSizeInBits(); 5463 EVT EltVT = VecVT.getVectorElementType(); 5464 assert(VecSize <= 64); 5465 5466 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5467 5468 // Make sure we do any optimizations that will make it easier to fold 5469 // source modifiers before obscuring it with bit operations. 5470 5471 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5472 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5473 return Combined; 5474 5475 unsigned EltSize = EltVT.getSizeInBits(); 5476 assert(isPowerOf2_32(EltSize)); 5477 5478 MVT IntVT = MVT::getIntegerVT(VecSize); 5479 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5480 5481 // Convert vector index to bit-index (* EltSize) 5482 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5483 5484 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5485 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5486 5487 if (ResultVT == MVT::f16) { 5488 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5489 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5490 } 5491 5492 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5493 } 5494 5495 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5496 assert(Elt % 2 == 0); 5497 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5498 } 5499 5500 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5501 SelectionDAG &DAG) const { 5502 SDLoc SL(Op); 5503 EVT ResultVT = Op.getValueType(); 5504 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5505 5506 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5507 EVT EltVT = PackVT.getVectorElementType(); 5508 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5509 5510 // vector_shuffle <0,1,6,7> lhs, rhs 5511 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5512 // 5513 // vector_shuffle <6,7,2,3> lhs, rhs 5514 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5515 // 5516 // vector_shuffle <6,7,0,1> lhs, rhs 5517 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5518 5519 // Avoid scalarizing when both halves are reading from consecutive elements. 5520 SmallVector<SDValue, 4> Pieces; 5521 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5522 if (elementPairIsContiguous(SVN->getMask(), I)) { 5523 const int Idx = SVN->getMaskElt(I); 5524 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5525 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5526 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5527 PackVT, SVN->getOperand(VecIdx), 5528 DAG.getConstant(EltIdx, SL, MVT::i32)); 5529 Pieces.push_back(SubVec); 5530 } else { 5531 const int Idx0 = SVN->getMaskElt(I); 5532 const int Idx1 = SVN->getMaskElt(I + 1); 5533 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5534 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5535 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5536 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5537 5538 SDValue Vec0 = SVN->getOperand(VecIdx0); 5539 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5540 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5541 5542 SDValue Vec1 = SVN->getOperand(VecIdx1); 5543 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5544 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5545 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5546 } 5547 } 5548 5549 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5550 } 5551 5552 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5553 SelectionDAG &DAG) const { 5554 SDLoc SL(Op); 5555 EVT VT = Op.getValueType(); 5556 5557 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5558 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5559 5560 // Turn into pair of packed build_vectors. 5561 // TODO: Special case for constants that can be materialized with s_mov_b64. 5562 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5563 { Op.getOperand(0), Op.getOperand(1) }); 5564 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5565 { Op.getOperand(2), Op.getOperand(3) }); 5566 5567 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5568 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5569 5570 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5571 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5572 } 5573 5574 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5575 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5576 5577 SDValue Lo = Op.getOperand(0); 5578 SDValue Hi = Op.getOperand(1); 5579 5580 // Avoid adding defined bits with the zero_extend. 5581 if (Hi.isUndef()) { 5582 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5583 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5584 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5585 } 5586 5587 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5588 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5589 5590 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5591 DAG.getConstant(16, SL, MVT::i32)); 5592 if (Lo.isUndef()) 5593 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5594 5595 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5596 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5597 5598 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5599 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5600 } 5601 5602 bool 5603 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5604 // We can fold offsets for anything that doesn't require a GOT relocation. 5605 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5606 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5607 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5608 !shouldEmitGOTReloc(GA->getGlobal()); 5609 } 5610 5611 static SDValue 5612 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5613 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5614 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5615 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5616 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5617 // lowered to the following code sequence: 5618 // 5619 // For constant address space: 5620 // s_getpc_b64 s[0:1] 5621 // s_add_u32 s0, s0, $symbol 5622 // s_addc_u32 s1, s1, 0 5623 // 5624 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5625 // a fixup or relocation is emitted to replace $symbol with a literal 5626 // constant, which is a pc-relative offset from the encoding of the $symbol 5627 // operand to the global variable. 5628 // 5629 // For global address space: 5630 // s_getpc_b64 s[0:1] 5631 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5632 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5633 // 5634 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5635 // fixups or relocations are emitted to replace $symbol@*@lo and 5636 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5637 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5638 // operand to the global variable. 5639 // 5640 // What we want here is an offset from the value returned by s_getpc 5641 // (which is the address of the s_add_u32 instruction) to the global 5642 // variable, but since the encoding of $symbol starts 4 bytes after the start 5643 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5644 // small. This requires us to add 4 to the global variable offset in order to 5645 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5646 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5647 // instruction. 5648 SDValue PtrLo = 5649 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5650 SDValue PtrHi; 5651 if (GAFlags == SIInstrInfo::MO_NONE) { 5652 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5653 } else { 5654 PtrHi = 5655 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5656 } 5657 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5658 } 5659 5660 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5661 SDValue Op, 5662 SelectionDAG &DAG) const { 5663 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5664 SDLoc DL(GSD); 5665 EVT PtrVT = Op.getValueType(); 5666 5667 const GlobalValue *GV = GSD->getGlobal(); 5668 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5669 shouldUseLDSConstAddress(GV)) || 5670 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5671 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5672 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5673 GV->hasExternalLinkage()) { 5674 Type *Ty = GV->getValueType(); 5675 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5676 // zero-sized type in other languages to declare the dynamic shared 5677 // memory which size is not known at the compile time. They will be 5678 // allocated by the runtime and placed directly after the static 5679 // allocated ones. They all share the same offset. 5680 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5681 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5682 // Adjust alignment for that dynamic shared memory array. 5683 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5684 return SDValue( 5685 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5686 } 5687 } 5688 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5689 } 5690 5691 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5692 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5693 SIInstrInfo::MO_ABS32_LO); 5694 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5695 } 5696 5697 if (shouldEmitFixup(GV)) 5698 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5699 else if (shouldEmitPCReloc(GV)) 5700 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5701 SIInstrInfo::MO_REL32); 5702 5703 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5704 SIInstrInfo::MO_GOTPCREL32); 5705 5706 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5707 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5708 const DataLayout &DataLayout = DAG.getDataLayout(); 5709 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5710 MachinePointerInfo PtrInfo 5711 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5712 5713 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5714 MachineMemOperand::MODereferenceable | 5715 MachineMemOperand::MOInvariant); 5716 } 5717 5718 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5719 const SDLoc &DL, SDValue V) const { 5720 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5721 // the destination register. 5722 // 5723 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5724 // so we will end up with redundant moves to m0. 5725 // 5726 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5727 5728 // A Null SDValue creates a glue result. 5729 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5730 V, Chain); 5731 return SDValue(M0, 0); 5732 } 5733 5734 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5735 SDValue Op, 5736 MVT VT, 5737 unsigned Offset) const { 5738 SDLoc SL(Op); 5739 SDValue Param = lowerKernargMemParameter( 5740 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5741 // The local size values will have the hi 16-bits as zero. 5742 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5743 DAG.getValueType(VT)); 5744 } 5745 5746 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5747 EVT VT) { 5748 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5749 "non-hsa intrinsic with hsa target", 5750 DL.getDebugLoc()); 5751 DAG.getContext()->diagnose(BadIntrin); 5752 return DAG.getUNDEF(VT); 5753 } 5754 5755 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5756 EVT VT) { 5757 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5758 "intrinsic not supported on subtarget", 5759 DL.getDebugLoc()); 5760 DAG.getContext()->diagnose(BadIntrin); 5761 return DAG.getUNDEF(VT); 5762 } 5763 5764 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5765 ArrayRef<SDValue> Elts) { 5766 assert(!Elts.empty()); 5767 MVT Type; 5768 unsigned NumElts; 5769 5770 if (Elts.size() == 1) { 5771 Type = MVT::f32; 5772 NumElts = 1; 5773 } else if (Elts.size() == 2) { 5774 Type = MVT::v2f32; 5775 NumElts = 2; 5776 } else if (Elts.size() == 3) { 5777 Type = MVT::v3f32; 5778 NumElts = 3; 5779 } else if (Elts.size() <= 4) { 5780 Type = MVT::v4f32; 5781 NumElts = 4; 5782 } else if (Elts.size() <= 8) { 5783 Type = MVT::v8f32; 5784 NumElts = 8; 5785 } else { 5786 assert(Elts.size() <= 16); 5787 Type = MVT::v16f32; 5788 NumElts = 16; 5789 } 5790 5791 SmallVector<SDValue, 16> VecElts(NumElts); 5792 for (unsigned i = 0; i < Elts.size(); ++i) { 5793 SDValue Elt = Elts[i]; 5794 if (Elt.getValueType() != MVT::f32) 5795 Elt = DAG.getBitcast(MVT::f32, Elt); 5796 VecElts[i] = Elt; 5797 } 5798 for (unsigned i = Elts.size(); i < NumElts; ++i) 5799 VecElts[i] = DAG.getUNDEF(MVT::f32); 5800 5801 if (NumElts == 1) 5802 return VecElts[0]; 5803 return DAG.getBuildVector(Type, DL, VecElts); 5804 } 5805 5806 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5807 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5808 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5809 5810 uint64_t Value = CachePolicyConst->getZExtValue(); 5811 SDLoc DL(CachePolicy); 5812 if (GLC) { 5813 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5814 Value &= ~(uint64_t)0x1; 5815 } 5816 if (SLC) { 5817 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5818 Value &= ~(uint64_t)0x2; 5819 } 5820 if (DLC) { 5821 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5822 Value &= ~(uint64_t)0x4; 5823 } 5824 5825 return Value == 0; 5826 } 5827 5828 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5829 SDValue Src, int ExtraElts) { 5830 EVT SrcVT = Src.getValueType(); 5831 5832 SmallVector<SDValue, 8> Elts; 5833 5834 if (SrcVT.isVector()) 5835 DAG.ExtractVectorElements(Src, Elts); 5836 else 5837 Elts.push_back(Src); 5838 5839 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5840 while (ExtraElts--) 5841 Elts.push_back(Undef); 5842 5843 return DAG.getBuildVector(CastVT, DL, Elts); 5844 } 5845 5846 // Re-construct the required return value for a image load intrinsic. 5847 // This is more complicated due to the optional use TexFailCtrl which means the required 5848 // return type is an aggregate 5849 static SDValue constructRetValue(SelectionDAG &DAG, 5850 MachineSDNode *Result, 5851 ArrayRef<EVT> ResultTypes, 5852 bool IsTexFail, bool Unpacked, bool IsD16, 5853 int DMaskPop, int NumVDataDwords, 5854 const SDLoc &DL, LLVMContext &Context) { 5855 // Determine the required return type. This is the same regardless of IsTexFail flag 5856 EVT ReqRetVT = ResultTypes[0]; 5857 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5858 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5859 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5860 5861 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5862 DMaskPop : (DMaskPop + 1) / 2; 5863 5864 MVT DataDwordVT = NumDataDwords == 1 ? 5865 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5866 5867 MVT MaskPopVT = MaskPopDwords == 1 ? 5868 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5869 5870 SDValue Data(Result, 0); 5871 SDValue TexFail; 5872 5873 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5874 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5875 if (MaskPopVT.isVector()) { 5876 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5877 SDValue(Result, 0), ZeroIdx); 5878 } else { 5879 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5880 SDValue(Result, 0), ZeroIdx); 5881 } 5882 } 5883 5884 if (DataDwordVT.isVector()) 5885 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5886 NumDataDwords - MaskPopDwords); 5887 5888 if (IsD16) 5889 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5890 5891 EVT LegalReqRetVT = ReqRetVT; 5892 if (!ReqRetVT.isVector()) { 5893 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5894 } else { 5895 // We need to widen the return vector to a legal type 5896 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5897 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5898 LegalReqRetVT = 5899 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5900 ReqRetVT.getVectorNumElements() + 1); 5901 } 5902 } 5903 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5904 5905 if (IsTexFail) { 5906 TexFail = 5907 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5908 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5909 5910 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5911 } 5912 5913 if (Result->getNumValues() == 1) 5914 return Data; 5915 5916 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5917 } 5918 5919 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5920 SDValue *LWE, bool &IsTexFail) { 5921 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5922 5923 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5924 if (Value) { 5925 IsTexFail = true; 5926 } 5927 5928 SDLoc DL(TexFailCtrlConst); 5929 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5930 Value &= ~(uint64_t)0x1; 5931 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5932 Value &= ~(uint64_t)0x2; 5933 5934 return Value == 0; 5935 } 5936 5937 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5938 MVT PackVectorVT, 5939 SmallVectorImpl<SDValue> &PackedAddrs, 5940 unsigned DimIdx, unsigned EndIdx, 5941 unsigned NumGradients) { 5942 SDLoc DL(Op); 5943 for (unsigned I = DimIdx; I < EndIdx; I++) { 5944 SDValue Addr = Op.getOperand(I); 5945 5946 // Gradients are packed with undef for each coordinate. 5947 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5948 // 1D: undef,dx/dh; undef,dx/dv 5949 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5950 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5951 if (((I + 1) >= EndIdx) || 5952 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5953 I == DimIdx + NumGradients - 1))) { 5954 if (Addr.getValueType() != MVT::i16) 5955 Addr = DAG.getBitcast(MVT::i16, Addr); 5956 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5957 } else { 5958 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5959 I++; 5960 } 5961 Addr = DAG.getBitcast(MVT::f32, Addr); 5962 PackedAddrs.push_back(Addr); 5963 } 5964 } 5965 5966 SDValue SITargetLowering::lowerImage(SDValue Op, 5967 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5968 SelectionDAG &DAG, bool WithChain) const { 5969 SDLoc DL(Op); 5970 MachineFunction &MF = DAG.getMachineFunction(); 5971 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5972 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5973 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5974 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5975 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5976 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5977 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5978 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5979 unsigned IntrOpcode = Intr->BaseOpcode; 5980 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5981 5982 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5983 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5984 bool IsD16 = false; 5985 bool IsG16 = false; 5986 bool IsA16 = false; 5987 SDValue VData; 5988 int NumVDataDwords; 5989 bool AdjustRetType = false; 5990 5991 // Offset of intrinsic arguments 5992 const unsigned ArgOffset = WithChain ? 2 : 1; 5993 5994 unsigned DMask; 5995 unsigned DMaskLanes = 0; 5996 5997 if (BaseOpcode->Atomic) { 5998 VData = Op.getOperand(2); 5999 6000 bool Is64Bit = VData.getValueType() == MVT::i64; 6001 if (BaseOpcode->AtomicX2) { 6002 SDValue VData2 = Op.getOperand(3); 6003 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6004 {VData, VData2}); 6005 if (Is64Bit) 6006 VData = DAG.getBitcast(MVT::v4i32, VData); 6007 6008 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6009 DMask = Is64Bit ? 0xf : 0x3; 6010 NumVDataDwords = Is64Bit ? 4 : 2; 6011 } else { 6012 DMask = Is64Bit ? 0x3 : 0x1; 6013 NumVDataDwords = Is64Bit ? 2 : 1; 6014 } 6015 } else { 6016 auto *DMaskConst = 6017 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6018 DMask = DMaskConst->getZExtValue(); 6019 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6020 6021 if (BaseOpcode->Store) { 6022 VData = Op.getOperand(2); 6023 6024 MVT StoreVT = VData.getSimpleValueType(); 6025 if (StoreVT.getScalarType() == MVT::f16) { 6026 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6027 return Op; // D16 is unsupported for this instruction 6028 6029 IsD16 = true; 6030 VData = handleD16VData(VData, DAG, true); 6031 } 6032 6033 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6034 } else { 6035 // Work out the num dwords based on the dmask popcount and underlying type 6036 // and whether packing is supported. 6037 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6038 if (LoadVT.getScalarType() == MVT::f16) { 6039 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6040 return Op; // D16 is unsupported for this instruction 6041 6042 IsD16 = true; 6043 } 6044 6045 // Confirm that the return type is large enough for the dmask specified 6046 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6047 (!LoadVT.isVector() && DMaskLanes > 1)) 6048 return Op; 6049 6050 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6051 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6052 // instructions. 6053 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6054 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6055 NumVDataDwords = (DMaskLanes + 1) / 2; 6056 else 6057 NumVDataDwords = DMaskLanes; 6058 6059 AdjustRetType = true; 6060 } 6061 } 6062 6063 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6064 SmallVector<SDValue, 4> VAddrs; 6065 6066 // Optimize _L to _LZ when _L is zero 6067 if (LZMappingInfo) { 6068 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6069 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6070 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6071 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6072 VAddrEnd--; // remove 'lod' 6073 } 6074 } 6075 } 6076 6077 // Optimize _mip away, when 'lod' is zero 6078 if (MIPMappingInfo) { 6079 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6080 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6081 if (ConstantLod->isNullValue()) { 6082 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6083 VAddrEnd--; // remove 'mip' 6084 } 6085 } 6086 } 6087 6088 // Push back extra arguments. 6089 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6090 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6091 6092 // Check for 16 bit addresses or derivatives and pack if true. 6093 MVT VAddrVT = 6094 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6095 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6096 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6097 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6098 6099 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6100 VAddrScalarVT = VAddrVT.getScalarType(); 6101 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6102 if (IsA16 || IsG16) { 6103 if (IsA16) { 6104 if (!ST->hasA16()) { 6105 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6106 "support 16 bit addresses\n"); 6107 return Op; 6108 } 6109 if (!IsG16) { 6110 LLVM_DEBUG( 6111 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6112 "need 16 bit derivatives but got 32 bit derivatives\n"); 6113 return Op; 6114 } 6115 } else if (!ST->hasG16()) { 6116 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6117 "support 16 bit derivatives\n"); 6118 return Op; 6119 } 6120 6121 if (BaseOpcode->Gradients && !IsA16) { 6122 if (!ST->hasG16()) { 6123 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6124 "support 16 bit derivatives\n"); 6125 return Op; 6126 } 6127 // Activate g16 6128 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6129 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6130 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6131 } 6132 6133 // Don't compress addresses for G16 6134 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6135 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6136 ArgOffset + Intr->GradientStart, PackEndIdx, 6137 Intr->NumGradients); 6138 6139 if (!IsA16) { 6140 // Add uncompressed address 6141 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6142 VAddrs.push_back(Op.getOperand(I)); 6143 } 6144 } else { 6145 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6146 VAddrs.push_back(Op.getOperand(I)); 6147 } 6148 6149 // If the register allocator cannot place the address registers contiguously 6150 // without introducing moves, then using the non-sequential address encoding 6151 // is always preferable, since it saves VALU instructions and is usually a 6152 // wash in terms of code size or even better. 6153 // 6154 // However, we currently have no way of hinting to the register allocator that 6155 // MIMG addresses should be placed contiguously when it is possible to do so, 6156 // so force non-NSA for the common 2-address case as a heuristic. 6157 // 6158 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6159 // allocation when possible. 6160 bool UseNSA = 6161 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6162 SDValue VAddr; 6163 if (!UseNSA) 6164 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6165 6166 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6167 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6168 SDValue Unorm; 6169 if (!BaseOpcode->Sampler) { 6170 Unorm = True; 6171 } else { 6172 auto UnormConst = 6173 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6174 6175 Unorm = UnormConst->getZExtValue() ? True : False; 6176 } 6177 6178 SDValue TFE; 6179 SDValue LWE; 6180 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6181 bool IsTexFail = false; 6182 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6183 return Op; 6184 6185 if (IsTexFail) { 6186 if (!DMaskLanes) { 6187 // Expecting to get an error flag since TFC is on - and dmask is 0 6188 // Force dmask to be at least 1 otherwise the instruction will fail 6189 DMask = 0x1; 6190 DMaskLanes = 1; 6191 NumVDataDwords = 1; 6192 } 6193 NumVDataDwords += 1; 6194 AdjustRetType = true; 6195 } 6196 6197 // Has something earlier tagged that the return type needs adjusting 6198 // This happens if the instruction is a load or has set TexFailCtrl flags 6199 if (AdjustRetType) { 6200 // NumVDataDwords reflects the true number of dwords required in the return type 6201 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6202 // This is a no-op load. This can be eliminated 6203 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6204 if (isa<MemSDNode>(Op)) 6205 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6206 return Undef; 6207 } 6208 6209 EVT NewVT = NumVDataDwords > 1 ? 6210 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6211 : MVT::i32; 6212 6213 ResultTypes[0] = NewVT; 6214 if (ResultTypes.size() == 3) { 6215 // Original result was aggregate type used for TexFailCtrl results 6216 // The actual instruction returns as a vector type which has now been 6217 // created. Remove the aggregate result. 6218 ResultTypes.erase(&ResultTypes[1]); 6219 } 6220 } 6221 6222 SDValue GLC; 6223 SDValue SLC; 6224 SDValue DLC; 6225 if (BaseOpcode->Atomic) { 6226 GLC = True; // TODO no-return optimization 6227 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6228 DAG, nullptr, &SLC, IsGFX10 ? &DLC : nullptr)) 6229 return Op; 6230 } else { 6231 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6232 DAG, &GLC, &SLC, IsGFX10 ? &DLC : nullptr)) 6233 return Op; 6234 } 6235 6236 SmallVector<SDValue, 26> Ops; 6237 if (BaseOpcode->Store || BaseOpcode->Atomic) 6238 Ops.push_back(VData); // vdata 6239 if (UseNSA) { 6240 for (const SDValue &Addr : VAddrs) 6241 Ops.push_back(Addr); 6242 } else { 6243 Ops.push_back(VAddr); 6244 } 6245 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6246 if (BaseOpcode->Sampler) 6247 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6248 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6249 if (IsGFX10) 6250 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6251 Ops.push_back(Unorm); 6252 if (IsGFX10) 6253 Ops.push_back(DLC); 6254 Ops.push_back(GLC); 6255 Ops.push_back(SLC); 6256 Ops.push_back(IsA16 && // r128, a16 for gfx9 6257 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6258 if (IsGFX10) 6259 Ops.push_back(IsA16 ? True : False); 6260 Ops.push_back(TFE); 6261 Ops.push_back(LWE); 6262 if (!IsGFX10) 6263 Ops.push_back(DimInfo->DA ? True : False); 6264 if (BaseOpcode->HasD16) 6265 Ops.push_back(IsD16 ? True : False); 6266 if (isa<MemSDNode>(Op)) 6267 Ops.push_back(Op.getOperand(0)); // chain 6268 6269 int NumVAddrDwords = 6270 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6271 int Opcode = -1; 6272 6273 if (IsGFX10) { 6274 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6275 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6276 : AMDGPU::MIMGEncGfx10Default, 6277 NumVDataDwords, NumVAddrDwords); 6278 } else { 6279 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6280 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6281 NumVDataDwords, NumVAddrDwords); 6282 if (Opcode == -1) 6283 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6284 NumVDataDwords, NumVAddrDwords); 6285 } 6286 assert(Opcode != -1); 6287 6288 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6289 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6290 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6291 DAG.setNodeMemRefs(NewNode, {MemRef}); 6292 } 6293 6294 if (BaseOpcode->AtomicX2) { 6295 SmallVector<SDValue, 1> Elt; 6296 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6297 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6298 } else if (!BaseOpcode->Store) { 6299 return constructRetValue(DAG, NewNode, 6300 OrigResultTypes, IsTexFail, 6301 Subtarget->hasUnpackedD16VMem(), IsD16, 6302 DMaskLanes, NumVDataDwords, DL, 6303 *DAG.getContext()); 6304 } 6305 6306 return SDValue(NewNode, 0); 6307 } 6308 6309 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6310 SDValue Offset, SDValue CachePolicy, 6311 SelectionDAG &DAG) const { 6312 MachineFunction &MF = DAG.getMachineFunction(); 6313 6314 const DataLayout &DataLayout = DAG.getDataLayout(); 6315 Align Alignment = 6316 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6317 6318 MachineMemOperand *MMO = MF.getMachineMemOperand( 6319 MachinePointerInfo(), 6320 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6321 MachineMemOperand::MOInvariant, 6322 VT.getStoreSize(), Alignment); 6323 6324 if (!Offset->isDivergent()) { 6325 SDValue Ops[] = { 6326 Rsrc, 6327 Offset, // Offset 6328 CachePolicy 6329 }; 6330 6331 // Widen vec3 load to vec4. 6332 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6333 EVT WidenedVT = 6334 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6335 auto WidenedOp = DAG.getMemIntrinsicNode( 6336 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6337 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6338 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6339 DAG.getVectorIdxConstant(0, DL)); 6340 return Subvector; 6341 } 6342 6343 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6344 DAG.getVTList(VT), Ops, VT, MMO); 6345 } 6346 6347 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6348 // assume that the buffer is unswizzled. 6349 SmallVector<SDValue, 4> Loads; 6350 unsigned NumLoads = 1; 6351 MVT LoadVT = VT.getSimpleVT(); 6352 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6353 assert((LoadVT.getScalarType() == MVT::i32 || 6354 LoadVT.getScalarType() == MVT::f32)); 6355 6356 if (NumElts == 8 || NumElts == 16) { 6357 NumLoads = NumElts / 4; 6358 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6359 } 6360 6361 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6362 SDValue Ops[] = { 6363 DAG.getEntryNode(), // Chain 6364 Rsrc, // rsrc 6365 DAG.getConstant(0, DL, MVT::i32), // vindex 6366 {}, // voffset 6367 {}, // soffset 6368 {}, // offset 6369 CachePolicy, // cachepolicy 6370 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6371 }; 6372 6373 // Use the alignment to ensure that the required offsets will fit into the 6374 // immediate offsets. 6375 setBufferOffsets(Offset, DAG, &Ops[3], 6376 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6377 6378 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6379 for (unsigned i = 0; i < NumLoads; ++i) { 6380 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6381 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6382 LoadVT, MMO, DAG)); 6383 } 6384 6385 if (NumElts == 8 || NumElts == 16) 6386 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6387 6388 return Loads[0]; 6389 } 6390 6391 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6392 SelectionDAG &DAG) const { 6393 MachineFunction &MF = DAG.getMachineFunction(); 6394 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6395 6396 EVT VT = Op.getValueType(); 6397 SDLoc DL(Op); 6398 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6399 6400 // TODO: Should this propagate fast-math-flags? 6401 6402 switch (IntrinsicID) { 6403 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6404 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6405 return emitNonHSAIntrinsicError(DAG, DL, VT); 6406 return getPreloadedValue(DAG, *MFI, VT, 6407 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6408 } 6409 case Intrinsic::amdgcn_dispatch_ptr: 6410 case Intrinsic::amdgcn_queue_ptr: { 6411 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6412 DiagnosticInfoUnsupported BadIntrin( 6413 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6414 DL.getDebugLoc()); 6415 DAG.getContext()->diagnose(BadIntrin); 6416 return DAG.getUNDEF(VT); 6417 } 6418 6419 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6420 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6421 return getPreloadedValue(DAG, *MFI, VT, RegID); 6422 } 6423 case Intrinsic::amdgcn_implicitarg_ptr: { 6424 if (MFI->isEntryFunction()) 6425 return getImplicitArgPtr(DAG, DL); 6426 return getPreloadedValue(DAG, *MFI, VT, 6427 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6428 } 6429 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6430 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6431 // This only makes sense to call in a kernel, so just lower to null. 6432 return DAG.getConstant(0, DL, VT); 6433 } 6434 6435 return getPreloadedValue(DAG, *MFI, VT, 6436 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6437 } 6438 case Intrinsic::amdgcn_dispatch_id: { 6439 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6440 } 6441 case Intrinsic::amdgcn_rcp: 6442 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6443 case Intrinsic::amdgcn_rsq: 6444 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6445 case Intrinsic::amdgcn_rsq_legacy: 6446 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6447 return emitRemovedIntrinsicError(DAG, DL, VT); 6448 return SDValue(); 6449 case Intrinsic::amdgcn_rcp_legacy: 6450 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6451 return emitRemovedIntrinsicError(DAG, DL, VT); 6452 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6453 case Intrinsic::amdgcn_rsq_clamp: { 6454 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6455 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6456 6457 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6458 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6459 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6460 6461 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6462 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6463 DAG.getConstantFP(Max, DL, VT)); 6464 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6465 DAG.getConstantFP(Min, DL, VT)); 6466 } 6467 case Intrinsic::r600_read_ngroups_x: 6468 if (Subtarget->isAmdHsaOS()) 6469 return emitNonHSAIntrinsicError(DAG, DL, VT); 6470 6471 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6472 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6473 false); 6474 case Intrinsic::r600_read_ngroups_y: 6475 if (Subtarget->isAmdHsaOS()) 6476 return emitNonHSAIntrinsicError(DAG, DL, VT); 6477 6478 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6479 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6480 false); 6481 case Intrinsic::r600_read_ngroups_z: 6482 if (Subtarget->isAmdHsaOS()) 6483 return emitNonHSAIntrinsicError(DAG, DL, VT); 6484 6485 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6486 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6487 false); 6488 case Intrinsic::r600_read_global_size_x: 6489 if (Subtarget->isAmdHsaOS()) 6490 return emitNonHSAIntrinsicError(DAG, DL, VT); 6491 6492 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6493 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6494 Align(4), false); 6495 case Intrinsic::r600_read_global_size_y: 6496 if (Subtarget->isAmdHsaOS()) 6497 return emitNonHSAIntrinsicError(DAG, DL, VT); 6498 6499 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6500 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6501 Align(4), false); 6502 case Intrinsic::r600_read_global_size_z: 6503 if (Subtarget->isAmdHsaOS()) 6504 return emitNonHSAIntrinsicError(DAG, DL, VT); 6505 6506 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6507 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6508 Align(4), false); 6509 case Intrinsic::r600_read_local_size_x: 6510 if (Subtarget->isAmdHsaOS()) 6511 return emitNonHSAIntrinsicError(DAG, DL, VT); 6512 6513 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6514 SI::KernelInputOffsets::LOCAL_SIZE_X); 6515 case Intrinsic::r600_read_local_size_y: 6516 if (Subtarget->isAmdHsaOS()) 6517 return emitNonHSAIntrinsicError(DAG, DL, VT); 6518 6519 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6520 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6521 case Intrinsic::r600_read_local_size_z: 6522 if (Subtarget->isAmdHsaOS()) 6523 return emitNonHSAIntrinsicError(DAG, DL, VT); 6524 6525 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6526 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6527 case Intrinsic::amdgcn_workgroup_id_x: 6528 return getPreloadedValue(DAG, *MFI, VT, 6529 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6530 case Intrinsic::amdgcn_workgroup_id_y: 6531 return getPreloadedValue(DAG, *MFI, VT, 6532 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6533 case Intrinsic::amdgcn_workgroup_id_z: 6534 return getPreloadedValue(DAG, *MFI, VT, 6535 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6536 case Intrinsic::amdgcn_workitem_id_x: 6537 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6538 SDLoc(DAG.getEntryNode()), 6539 MFI->getArgInfo().WorkItemIDX); 6540 case Intrinsic::amdgcn_workitem_id_y: 6541 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6542 SDLoc(DAG.getEntryNode()), 6543 MFI->getArgInfo().WorkItemIDY); 6544 case Intrinsic::amdgcn_workitem_id_z: 6545 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6546 SDLoc(DAG.getEntryNode()), 6547 MFI->getArgInfo().WorkItemIDZ); 6548 case Intrinsic::amdgcn_wavefrontsize: 6549 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6550 SDLoc(Op), MVT::i32); 6551 case Intrinsic::amdgcn_s_buffer_load: { 6552 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6553 SDValue GLC; 6554 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6555 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6556 IsGFX10 ? &DLC : nullptr)) 6557 return Op; 6558 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6559 DAG); 6560 } 6561 case Intrinsic::amdgcn_fdiv_fast: 6562 return lowerFDIV_FAST(Op, DAG); 6563 case Intrinsic::amdgcn_sin: 6564 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6565 6566 case Intrinsic::amdgcn_cos: 6567 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6568 6569 case Intrinsic::amdgcn_mul_u24: 6570 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6571 case Intrinsic::amdgcn_mul_i24: 6572 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6573 6574 case Intrinsic::amdgcn_log_clamp: { 6575 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6576 return SDValue(); 6577 6578 DiagnosticInfoUnsupported BadIntrin( 6579 MF.getFunction(), "intrinsic not supported on subtarget", 6580 DL.getDebugLoc()); 6581 DAG.getContext()->diagnose(BadIntrin); 6582 return DAG.getUNDEF(VT); 6583 } 6584 case Intrinsic::amdgcn_ldexp: 6585 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6586 Op.getOperand(1), Op.getOperand(2)); 6587 6588 case Intrinsic::amdgcn_fract: 6589 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6590 6591 case Intrinsic::amdgcn_class: 6592 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6593 Op.getOperand(1), Op.getOperand(2)); 6594 case Intrinsic::amdgcn_div_fmas: 6595 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6596 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6597 Op.getOperand(4)); 6598 6599 case Intrinsic::amdgcn_div_fixup: 6600 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6601 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6602 6603 case Intrinsic::amdgcn_div_scale: { 6604 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6605 6606 // Translate to the operands expected by the machine instruction. The 6607 // first parameter must be the same as the first instruction. 6608 SDValue Numerator = Op.getOperand(1); 6609 SDValue Denominator = Op.getOperand(2); 6610 6611 // Note this order is opposite of the machine instruction's operations, 6612 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6613 // intrinsic has the numerator as the first operand to match a normal 6614 // division operation. 6615 6616 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6617 6618 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6619 Denominator, Numerator); 6620 } 6621 case Intrinsic::amdgcn_icmp: { 6622 // There is a Pat that handles this variant, so return it as-is. 6623 if (Op.getOperand(1).getValueType() == MVT::i1 && 6624 Op.getConstantOperandVal(2) == 0 && 6625 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6626 return Op; 6627 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6628 } 6629 case Intrinsic::amdgcn_fcmp: { 6630 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6631 } 6632 case Intrinsic::amdgcn_ballot: 6633 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6634 case Intrinsic::amdgcn_fmed3: 6635 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6636 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6637 case Intrinsic::amdgcn_fdot2: 6638 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6639 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6640 Op.getOperand(4)); 6641 case Intrinsic::amdgcn_fmul_legacy: 6642 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6643 Op.getOperand(1), Op.getOperand(2)); 6644 case Intrinsic::amdgcn_sffbh: 6645 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6646 case Intrinsic::amdgcn_sbfe: 6647 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6648 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6649 case Intrinsic::amdgcn_ubfe: 6650 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6651 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6652 case Intrinsic::amdgcn_cvt_pkrtz: 6653 case Intrinsic::amdgcn_cvt_pknorm_i16: 6654 case Intrinsic::amdgcn_cvt_pknorm_u16: 6655 case Intrinsic::amdgcn_cvt_pk_i16: 6656 case Intrinsic::amdgcn_cvt_pk_u16: { 6657 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6658 EVT VT = Op.getValueType(); 6659 unsigned Opcode; 6660 6661 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6662 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6663 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6664 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6665 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6666 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6667 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6668 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6669 else 6670 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6671 6672 if (isTypeLegal(VT)) 6673 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6674 6675 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6676 Op.getOperand(1), Op.getOperand(2)); 6677 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6678 } 6679 case Intrinsic::amdgcn_fmad_ftz: 6680 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6681 Op.getOperand(2), Op.getOperand(3)); 6682 6683 case Intrinsic::amdgcn_if_break: 6684 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6685 Op->getOperand(1), Op->getOperand(2)), 0); 6686 6687 case Intrinsic::amdgcn_groupstaticsize: { 6688 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6689 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6690 return Op; 6691 6692 const Module *M = MF.getFunction().getParent(); 6693 const GlobalValue *GV = 6694 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6695 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6696 SIInstrInfo::MO_ABS32_LO); 6697 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6698 } 6699 case Intrinsic::amdgcn_is_shared: 6700 case Intrinsic::amdgcn_is_private: { 6701 SDLoc SL(Op); 6702 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6703 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6704 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6705 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6706 Op.getOperand(1)); 6707 6708 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6709 DAG.getConstant(1, SL, MVT::i32)); 6710 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6711 } 6712 case Intrinsic::amdgcn_alignbit: 6713 return DAG.getNode(ISD::FSHR, DL, VT, 6714 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6715 case Intrinsic::amdgcn_reloc_constant: { 6716 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6717 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6718 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6719 auto RelocSymbol = cast<GlobalVariable>( 6720 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6721 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6722 SIInstrInfo::MO_ABS32_LO); 6723 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6724 } 6725 default: 6726 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6727 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6728 return lowerImage(Op, ImageDimIntr, DAG, false); 6729 6730 return Op; 6731 } 6732 } 6733 6734 // This function computes an appropriate offset to pass to 6735 // MachineMemOperand::setOffset() based on the offset inputs to 6736 // an intrinsic. If any of the offsets are non-contstant or 6737 // if VIndex is non-zero then this function returns 0. Otherwise, 6738 // it returns the sum of VOffset, SOffset, and Offset. 6739 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6740 SDValue SOffset, 6741 SDValue Offset, 6742 SDValue VIndex = SDValue()) { 6743 6744 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6745 !isa<ConstantSDNode>(Offset)) 6746 return 0; 6747 6748 if (VIndex) { 6749 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6750 return 0; 6751 } 6752 6753 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6754 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6755 cast<ConstantSDNode>(Offset)->getSExtValue(); 6756 } 6757 6758 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6759 SelectionDAG &DAG, 6760 unsigned NewOpcode) const { 6761 SDLoc DL(Op); 6762 6763 SDValue VData = Op.getOperand(2); 6764 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6765 SDValue Ops[] = { 6766 Op.getOperand(0), // Chain 6767 VData, // vdata 6768 Op.getOperand(3), // rsrc 6769 DAG.getConstant(0, DL, MVT::i32), // vindex 6770 Offsets.first, // voffset 6771 Op.getOperand(5), // soffset 6772 Offsets.second, // offset 6773 Op.getOperand(6), // cachepolicy 6774 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6775 }; 6776 6777 auto *M = cast<MemSDNode>(Op); 6778 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6779 6780 EVT MemVT = VData.getValueType(); 6781 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6782 M->getMemOperand()); 6783 } 6784 6785 SDValue 6786 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6787 unsigned NewOpcode) const { 6788 SDLoc DL(Op); 6789 6790 SDValue VData = Op.getOperand(2); 6791 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6792 SDValue Ops[] = { 6793 Op.getOperand(0), // Chain 6794 VData, // vdata 6795 Op.getOperand(3), // rsrc 6796 Op.getOperand(4), // vindex 6797 Offsets.first, // voffset 6798 Op.getOperand(6), // soffset 6799 Offsets.second, // offset 6800 Op.getOperand(7), // cachepolicy 6801 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6802 }; 6803 6804 auto *M = cast<MemSDNode>(Op); 6805 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6806 Ops[3])); 6807 6808 EVT MemVT = VData.getValueType(); 6809 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6810 M->getMemOperand()); 6811 } 6812 6813 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6814 SelectionDAG &DAG) const { 6815 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6816 SDLoc DL(Op); 6817 6818 switch (IntrID) { 6819 case Intrinsic::amdgcn_ds_ordered_add: 6820 case Intrinsic::amdgcn_ds_ordered_swap: { 6821 MemSDNode *M = cast<MemSDNode>(Op); 6822 SDValue Chain = M->getOperand(0); 6823 SDValue M0 = M->getOperand(2); 6824 SDValue Value = M->getOperand(3); 6825 unsigned IndexOperand = M->getConstantOperandVal(7); 6826 unsigned WaveRelease = M->getConstantOperandVal(8); 6827 unsigned WaveDone = M->getConstantOperandVal(9); 6828 6829 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6830 IndexOperand &= ~0x3f; 6831 unsigned CountDw = 0; 6832 6833 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6834 CountDw = (IndexOperand >> 24) & 0xf; 6835 IndexOperand &= ~(0xf << 24); 6836 6837 if (CountDw < 1 || CountDw > 4) { 6838 report_fatal_error( 6839 "ds_ordered_count: dword count must be between 1 and 4"); 6840 } 6841 } 6842 6843 if (IndexOperand) 6844 report_fatal_error("ds_ordered_count: bad index operand"); 6845 6846 if (WaveDone && !WaveRelease) 6847 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6848 6849 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6850 unsigned ShaderType = 6851 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6852 unsigned Offset0 = OrderedCountIndex << 2; 6853 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6854 (Instruction << 4); 6855 6856 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6857 Offset1 |= (CountDw - 1) << 6; 6858 6859 unsigned Offset = Offset0 | (Offset1 << 8); 6860 6861 SDValue Ops[] = { 6862 Chain, 6863 Value, 6864 DAG.getTargetConstant(Offset, DL, MVT::i16), 6865 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6866 }; 6867 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6868 M->getVTList(), Ops, M->getMemoryVT(), 6869 M->getMemOperand()); 6870 } 6871 case Intrinsic::amdgcn_ds_fadd: { 6872 MemSDNode *M = cast<MemSDNode>(Op); 6873 unsigned Opc; 6874 switch (IntrID) { 6875 case Intrinsic::amdgcn_ds_fadd: 6876 Opc = ISD::ATOMIC_LOAD_FADD; 6877 break; 6878 } 6879 6880 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6881 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6882 M->getMemOperand()); 6883 } 6884 case Intrinsic::amdgcn_atomic_inc: 6885 case Intrinsic::amdgcn_atomic_dec: 6886 case Intrinsic::amdgcn_ds_fmin: 6887 case Intrinsic::amdgcn_ds_fmax: { 6888 MemSDNode *M = cast<MemSDNode>(Op); 6889 unsigned Opc; 6890 switch (IntrID) { 6891 case Intrinsic::amdgcn_atomic_inc: 6892 Opc = AMDGPUISD::ATOMIC_INC; 6893 break; 6894 case Intrinsic::amdgcn_atomic_dec: 6895 Opc = AMDGPUISD::ATOMIC_DEC; 6896 break; 6897 case Intrinsic::amdgcn_ds_fmin: 6898 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6899 break; 6900 case Intrinsic::amdgcn_ds_fmax: 6901 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6902 break; 6903 default: 6904 llvm_unreachable("Unknown intrinsic!"); 6905 } 6906 SDValue Ops[] = { 6907 M->getOperand(0), // Chain 6908 M->getOperand(2), // Ptr 6909 M->getOperand(3) // Value 6910 }; 6911 6912 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6913 M->getMemoryVT(), M->getMemOperand()); 6914 } 6915 case Intrinsic::amdgcn_buffer_load: 6916 case Intrinsic::amdgcn_buffer_load_format: { 6917 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6918 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6919 unsigned IdxEn = 1; 6920 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6921 IdxEn = Idx->getZExtValue() != 0; 6922 SDValue Ops[] = { 6923 Op.getOperand(0), // Chain 6924 Op.getOperand(2), // rsrc 6925 Op.getOperand(3), // vindex 6926 SDValue(), // voffset -- will be set by setBufferOffsets 6927 SDValue(), // soffset -- will be set by setBufferOffsets 6928 SDValue(), // offset -- will be set by setBufferOffsets 6929 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6930 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6931 }; 6932 6933 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6934 // We don't know the offset if vindex is non-zero, so clear it. 6935 if (IdxEn) 6936 Offset = 0; 6937 6938 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6939 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6940 6941 EVT VT = Op.getValueType(); 6942 EVT IntVT = VT.changeTypeToInteger(); 6943 auto *M = cast<MemSDNode>(Op); 6944 M->getMemOperand()->setOffset(Offset); 6945 EVT LoadVT = Op.getValueType(); 6946 6947 if (LoadVT.getScalarType() == MVT::f16) 6948 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6949 M, DAG, Ops); 6950 6951 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6952 if (LoadVT.getScalarType() == MVT::i8 || 6953 LoadVT.getScalarType() == MVT::i16) 6954 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6955 6956 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6957 M->getMemOperand(), DAG); 6958 } 6959 case Intrinsic::amdgcn_raw_buffer_load: 6960 case Intrinsic::amdgcn_raw_buffer_load_format: { 6961 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6962 6963 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6964 SDValue Ops[] = { 6965 Op.getOperand(0), // Chain 6966 Op.getOperand(2), // rsrc 6967 DAG.getConstant(0, DL, MVT::i32), // vindex 6968 Offsets.first, // voffset 6969 Op.getOperand(4), // soffset 6970 Offsets.second, // offset 6971 Op.getOperand(5), // cachepolicy, swizzled buffer 6972 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6973 }; 6974 6975 auto *M = cast<MemSDNode>(Op); 6976 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6977 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6978 } 6979 case Intrinsic::amdgcn_struct_buffer_load: 6980 case Intrinsic::amdgcn_struct_buffer_load_format: { 6981 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6982 6983 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6984 SDValue Ops[] = { 6985 Op.getOperand(0), // Chain 6986 Op.getOperand(2), // rsrc 6987 Op.getOperand(3), // vindex 6988 Offsets.first, // voffset 6989 Op.getOperand(5), // soffset 6990 Offsets.second, // offset 6991 Op.getOperand(6), // cachepolicy, swizzled buffer 6992 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6993 }; 6994 6995 auto *M = cast<MemSDNode>(Op); 6996 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6997 Ops[2])); 6998 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6999 } 7000 case Intrinsic::amdgcn_tbuffer_load: { 7001 MemSDNode *M = cast<MemSDNode>(Op); 7002 EVT LoadVT = Op.getValueType(); 7003 7004 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7005 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7006 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7007 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7008 unsigned IdxEn = 1; 7009 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 7010 IdxEn = Idx->getZExtValue() != 0; 7011 SDValue Ops[] = { 7012 Op.getOperand(0), // Chain 7013 Op.getOperand(2), // rsrc 7014 Op.getOperand(3), // vindex 7015 Op.getOperand(4), // voffset 7016 Op.getOperand(5), // soffset 7017 Op.getOperand(6), // offset 7018 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7019 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7020 DAG.getTargetConstant(IdxEn, 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_raw_tbuffer_load: { 7031 MemSDNode *M = cast<MemSDNode>(Op); 7032 EVT LoadVT = Op.getValueType(); 7033 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7034 7035 SDValue Ops[] = { 7036 Op.getOperand(0), // Chain 7037 Op.getOperand(2), // rsrc 7038 DAG.getConstant(0, DL, MVT::i32), // vindex 7039 Offsets.first, // voffset 7040 Op.getOperand(4), // soffset 7041 Offsets.second, // offset 7042 Op.getOperand(5), // format 7043 Op.getOperand(6), // cachepolicy, swizzled buffer 7044 DAG.getTargetConstant(0, 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_struct_tbuffer_load: { 7055 MemSDNode *M = cast<MemSDNode>(Op); 7056 EVT LoadVT = Op.getValueType(); 7057 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7058 7059 SDValue Ops[] = { 7060 Op.getOperand(0), // Chain 7061 Op.getOperand(2), // rsrc 7062 Op.getOperand(3), // vindex 7063 Offsets.first, // voffset 7064 Op.getOperand(5), // soffset 7065 Offsets.second, // offset 7066 Op.getOperand(6), // format 7067 Op.getOperand(7), // cachepolicy, swizzled buffer 7068 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7069 }; 7070 7071 if (LoadVT.getScalarType() == MVT::f16) 7072 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7073 M, DAG, Ops); 7074 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7075 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7076 DAG); 7077 } 7078 case Intrinsic::amdgcn_buffer_atomic_swap: 7079 case Intrinsic::amdgcn_buffer_atomic_add: 7080 case Intrinsic::amdgcn_buffer_atomic_sub: 7081 case Intrinsic::amdgcn_buffer_atomic_csub: 7082 case Intrinsic::amdgcn_buffer_atomic_smin: 7083 case Intrinsic::amdgcn_buffer_atomic_umin: 7084 case Intrinsic::amdgcn_buffer_atomic_smax: 7085 case Intrinsic::amdgcn_buffer_atomic_umax: 7086 case Intrinsic::amdgcn_buffer_atomic_and: 7087 case Intrinsic::amdgcn_buffer_atomic_or: 7088 case Intrinsic::amdgcn_buffer_atomic_xor: 7089 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7090 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7091 unsigned IdxEn = 1; 7092 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7093 IdxEn = Idx->getZExtValue() != 0; 7094 SDValue Ops[] = { 7095 Op.getOperand(0), // Chain 7096 Op.getOperand(2), // vdata 7097 Op.getOperand(3), // rsrc 7098 Op.getOperand(4), // vindex 7099 SDValue(), // voffset -- will be set by setBufferOffsets 7100 SDValue(), // soffset -- will be set by setBufferOffsets 7101 SDValue(), // offset -- will be set by setBufferOffsets 7102 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7103 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7104 }; 7105 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7106 // We don't know the offset if vindex is non-zero, so clear it. 7107 if (IdxEn) 7108 Offset = 0; 7109 EVT VT = Op.getValueType(); 7110 7111 auto *M = cast<MemSDNode>(Op); 7112 M->getMemOperand()->setOffset(Offset); 7113 unsigned Opcode = 0; 7114 7115 switch (IntrID) { 7116 case Intrinsic::amdgcn_buffer_atomic_swap: 7117 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7118 break; 7119 case Intrinsic::amdgcn_buffer_atomic_add: 7120 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7121 break; 7122 case Intrinsic::amdgcn_buffer_atomic_sub: 7123 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7124 break; 7125 case Intrinsic::amdgcn_buffer_atomic_csub: 7126 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7127 break; 7128 case Intrinsic::amdgcn_buffer_atomic_smin: 7129 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7130 break; 7131 case Intrinsic::amdgcn_buffer_atomic_umin: 7132 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7133 break; 7134 case Intrinsic::amdgcn_buffer_atomic_smax: 7135 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7136 break; 7137 case Intrinsic::amdgcn_buffer_atomic_umax: 7138 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7139 break; 7140 case Intrinsic::amdgcn_buffer_atomic_and: 7141 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7142 break; 7143 case Intrinsic::amdgcn_buffer_atomic_or: 7144 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7145 break; 7146 case Intrinsic::amdgcn_buffer_atomic_xor: 7147 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7148 break; 7149 case Intrinsic::amdgcn_buffer_atomic_fadd: 7150 if (!Op.getValue(0).use_empty()) { 7151 DiagnosticInfoUnsupported 7152 NoFpRet(DAG.getMachineFunction().getFunction(), 7153 "return versions of fp atomics not supported", 7154 DL.getDebugLoc(), DS_Error); 7155 DAG.getContext()->diagnose(NoFpRet); 7156 return SDValue(); 7157 } 7158 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7159 break; 7160 default: 7161 llvm_unreachable("unhandled atomic opcode"); 7162 } 7163 7164 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7165 M->getMemOperand()); 7166 } 7167 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7168 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7169 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7170 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7171 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7172 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7173 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7174 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7175 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7176 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7177 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7178 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7179 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7180 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7181 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7182 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7183 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7184 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7185 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7186 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7187 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7188 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7189 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7190 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7191 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7192 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7193 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7194 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7195 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7196 return lowerStructBufferAtomicIntrin(Op, DAG, 7197 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7198 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7199 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7200 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7201 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7202 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7203 return lowerStructBufferAtomicIntrin(Op, DAG, 7204 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7205 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7206 return lowerStructBufferAtomicIntrin(Op, DAG, 7207 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7208 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7209 return lowerStructBufferAtomicIntrin(Op, DAG, 7210 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7211 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7212 return lowerStructBufferAtomicIntrin(Op, DAG, 7213 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7214 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7215 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7216 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7217 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7218 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7219 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7220 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7221 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7222 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7223 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7224 7225 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7226 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7227 unsigned IdxEn = 1; 7228 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7229 IdxEn = Idx->getZExtValue() != 0; 7230 SDValue Ops[] = { 7231 Op.getOperand(0), // Chain 7232 Op.getOperand(2), // src 7233 Op.getOperand(3), // cmp 7234 Op.getOperand(4), // rsrc 7235 Op.getOperand(5), // vindex 7236 SDValue(), // voffset -- will be set by setBufferOffsets 7237 SDValue(), // soffset -- will be set by setBufferOffsets 7238 SDValue(), // offset -- will be set by setBufferOffsets 7239 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7240 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7241 }; 7242 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7243 // We don't know the offset if vindex is non-zero, so clear it. 7244 if (IdxEn) 7245 Offset = 0; 7246 EVT VT = Op.getValueType(); 7247 auto *M = cast<MemSDNode>(Op); 7248 M->getMemOperand()->setOffset(Offset); 7249 7250 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7251 Op->getVTList(), Ops, VT, M->getMemOperand()); 7252 } 7253 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7254 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7255 SDValue Ops[] = { 7256 Op.getOperand(0), // Chain 7257 Op.getOperand(2), // src 7258 Op.getOperand(3), // cmp 7259 Op.getOperand(4), // rsrc 7260 DAG.getConstant(0, DL, MVT::i32), // vindex 7261 Offsets.first, // voffset 7262 Op.getOperand(6), // soffset 7263 Offsets.second, // offset 7264 Op.getOperand(7), // cachepolicy 7265 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7266 }; 7267 EVT VT = Op.getValueType(); 7268 auto *M = cast<MemSDNode>(Op); 7269 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7270 7271 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7272 Op->getVTList(), Ops, VT, M->getMemOperand()); 7273 } 7274 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7275 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7276 SDValue Ops[] = { 7277 Op.getOperand(0), // Chain 7278 Op.getOperand(2), // src 7279 Op.getOperand(3), // cmp 7280 Op.getOperand(4), // rsrc 7281 Op.getOperand(5), // vindex 7282 Offsets.first, // voffset 7283 Op.getOperand(7), // soffset 7284 Offsets.second, // offset 7285 Op.getOperand(8), // cachepolicy 7286 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7287 }; 7288 EVT VT = Op.getValueType(); 7289 auto *M = cast<MemSDNode>(Op); 7290 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7291 Ops[4])); 7292 7293 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7294 Op->getVTList(), Ops, VT, M->getMemOperand()); 7295 } 7296 case Intrinsic::amdgcn_global_atomic_fadd: { 7297 if (!Op.getValue(0).use_empty()) { 7298 DiagnosticInfoUnsupported 7299 NoFpRet(DAG.getMachineFunction().getFunction(), 7300 "return versions of fp atomics not supported", 7301 DL.getDebugLoc(), DS_Error); 7302 DAG.getContext()->diagnose(NoFpRet); 7303 return SDValue(); 7304 } 7305 MemSDNode *M = cast<MemSDNode>(Op); 7306 SDValue Ops[] = { 7307 M->getOperand(0), // Chain 7308 M->getOperand(2), // Ptr 7309 M->getOperand(3) // Value 7310 }; 7311 7312 EVT VT = Op.getOperand(3).getValueType(); 7313 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7314 DAG.getVTList(VT, MVT::Other), Ops, 7315 M->getMemOperand()); 7316 } 7317 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7318 SDLoc DL(Op); 7319 MemSDNode *M = cast<MemSDNode>(Op); 7320 SDValue NodePtr = M->getOperand(2); 7321 SDValue RayExtent = M->getOperand(3); 7322 SDValue RayOrigin = M->getOperand(4); 7323 SDValue RayDir = M->getOperand(5); 7324 SDValue RayInvDir = M->getOperand(6); 7325 SDValue TDescr = M->getOperand(7); 7326 7327 assert(NodePtr.getValueType() == MVT::i32 || 7328 NodePtr.getValueType() == MVT::i64); 7329 assert(RayDir.getValueType() == MVT::v4f16 || 7330 RayDir.getValueType() == MVT::v4f32); 7331 7332 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7333 bool Is64 = NodePtr.getValueType() == MVT::i64; 7334 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7335 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7336 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7337 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7338 7339 SmallVector<SDValue, 16> Ops; 7340 7341 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7342 SmallVector<SDValue, 3> Lanes; 7343 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7344 if (Lanes[0].getValueSizeInBits() == 32) { 7345 for (unsigned I = 0; I < 3; ++I) 7346 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7347 } else { 7348 if (IsAligned) { 7349 Ops.push_back( 7350 DAG.getBitcast(MVT::i32, 7351 DAG.getBuildVector(MVT::v2f16, DL, 7352 { Lanes[0], Lanes[1] }))); 7353 Ops.push_back(Lanes[2]); 7354 } else { 7355 SDValue Elt0 = Ops.pop_back_val(); 7356 Ops.push_back( 7357 DAG.getBitcast(MVT::i32, 7358 DAG.getBuildVector(MVT::v2f16, DL, 7359 { Elt0, Lanes[0] }))); 7360 Ops.push_back( 7361 DAG.getBitcast(MVT::i32, 7362 DAG.getBuildVector(MVT::v2f16, DL, 7363 { Lanes[1], Lanes[2] }))); 7364 } 7365 } 7366 }; 7367 7368 if (Is64) 7369 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7370 else 7371 Ops.push_back(NodePtr); 7372 7373 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7374 packLanes(RayOrigin, true); 7375 packLanes(RayDir, true); 7376 packLanes(RayInvDir, false); 7377 Ops.push_back(TDescr); 7378 if (IsA16) 7379 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7380 Ops.push_back(M->getChain()); 7381 7382 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7383 MachineMemOperand *MemRef = M->getMemOperand(); 7384 DAG.setNodeMemRefs(NewNode, {MemRef}); 7385 return SDValue(NewNode, 0); 7386 } 7387 default: 7388 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7389 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7390 return lowerImage(Op, ImageDimIntr, DAG, true); 7391 7392 return SDValue(); 7393 } 7394 } 7395 7396 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7397 // dwordx4 if on SI. 7398 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7399 SDVTList VTList, 7400 ArrayRef<SDValue> Ops, EVT MemVT, 7401 MachineMemOperand *MMO, 7402 SelectionDAG &DAG) const { 7403 EVT VT = VTList.VTs[0]; 7404 EVT WidenedVT = VT; 7405 EVT WidenedMemVT = MemVT; 7406 if (!Subtarget->hasDwordx3LoadStores() && 7407 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7408 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7409 WidenedVT.getVectorElementType(), 4); 7410 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7411 WidenedMemVT.getVectorElementType(), 4); 7412 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7413 } 7414 7415 assert(VTList.NumVTs == 2); 7416 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7417 7418 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7419 WidenedMemVT, MMO); 7420 if (WidenedVT != VT) { 7421 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7422 DAG.getVectorIdxConstant(0, DL)); 7423 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7424 } 7425 return NewOp; 7426 } 7427 7428 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7429 bool ImageStore) const { 7430 EVT StoreVT = VData.getValueType(); 7431 7432 // No change for f16 and legal vector D16 types. 7433 if (!StoreVT.isVector()) 7434 return VData; 7435 7436 SDLoc DL(VData); 7437 unsigned NumElements = StoreVT.getVectorNumElements(); 7438 7439 if (Subtarget->hasUnpackedD16VMem()) { 7440 // We need to unpack the packed data to store. 7441 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7442 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7443 7444 EVT EquivStoreVT = 7445 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7446 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7447 return DAG.UnrollVectorOp(ZExt.getNode()); 7448 } else if (NumElements == 3) { 7449 EVT IntStoreVT = 7450 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7451 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7452 7453 EVT WidenedStoreVT = EVT::getVectorVT( 7454 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7455 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7456 WidenedStoreVT.getStoreSizeInBits()); 7457 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7458 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7459 } 7460 7461 // The sq block of gfx8.1 does not estimate register use correctly for d16 7462 // image store instructions. The data operand is computed as if it were not a 7463 // d16 image instruction. 7464 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7465 // Bitcast to i16 7466 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7467 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7468 7469 // Decompose into scalars 7470 SmallVector<SDValue, 4> Elts; 7471 DAG.ExtractVectorElements(IntVData, Elts); 7472 7473 // Group pairs of i16 into v2i16 and bitcast to i32 7474 SmallVector<SDValue, 4> PackedElts; 7475 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7476 SDValue Pair = 7477 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7478 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7479 PackedElts.push_back(IntPair); 7480 } 7481 7482 // Pad using UNDEF 7483 PackedElts.resize(PackedElts.size() * 2, DAG.getUNDEF(MVT::i32)); 7484 7485 // Build final vector 7486 EVT VecVT = 7487 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7488 return DAG.getBuildVector(VecVT, DL, PackedElts); 7489 } 7490 7491 assert(isTypeLegal(StoreVT)); 7492 return VData; 7493 } 7494 7495 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7496 SelectionDAG &DAG) const { 7497 SDLoc DL(Op); 7498 SDValue Chain = Op.getOperand(0); 7499 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7500 MachineFunction &MF = DAG.getMachineFunction(); 7501 7502 switch (IntrinsicID) { 7503 case Intrinsic::amdgcn_exp_compr: { 7504 SDValue Src0 = Op.getOperand(4); 7505 SDValue Src1 = Op.getOperand(5); 7506 // Hack around illegal type on SI by directly selecting it. 7507 if (isTypeLegal(Src0.getValueType())) 7508 return SDValue(); 7509 7510 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7511 SDValue Undef = DAG.getUNDEF(MVT::f32); 7512 const SDValue Ops[] = { 7513 Op.getOperand(2), // tgt 7514 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7515 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7516 Undef, // src2 7517 Undef, // src3 7518 Op.getOperand(7), // vm 7519 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7520 Op.getOperand(3), // en 7521 Op.getOperand(0) // Chain 7522 }; 7523 7524 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7525 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7526 } 7527 case Intrinsic::amdgcn_s_barrier: { 7528 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7529 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7530 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7531 if (WGSize <= ST.getWavefrontSize()) 7532 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7533 Op.getOperand(0)), 0); 7534 } 7535 return SDValue(); 7536 }; 7537 case Intrinsic::amdgcn_tbuffer_store: { 7538 SDValue VData = Op.getOperand(2); 7539 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7540 if (IsD16) 7541 VData = handleD16VData(VData, DAG); 7542 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7543 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7544 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7545 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7546 unsigned IdxEn = 1; 7547 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7548 IdxEn = Idx->getZExtValue() != 0; 7549 SDValue Ops[] = { 7550 Chain, 7551 VData, // vdata 7552 Op.getOperand(3), // rsrc 7553 Op.getOperand(4), // vindex 7554 Op.getOperand(5), // voffset 7555 Op.getOperand(6), // soffset 7556 Op.getOperand(7), // offset 7557 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7558 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7559 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7560 }; 7561 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7562 AMDGPUISD::TBUFFER_STORE_FORMAT; 7563 MemSDNode *M = cast<MemSDNode>(Op); 7564 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7565 M->getMemoryVT(), M->getMemOperand()); 7566 } 7567 7568 case Intrinsic::amdgcn_struct_tbuffer_store: { 7569 SDValue VData = Op.getOperand(2); 7570 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7571 if (IsD16) 7572 VData = handleD16VData(VData, DAG); 7573 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7574 SDValue Ops[] = { 7575 Chain, 7576 VData, // vdata 7577 Op.getOperand(3), // rsrc 7578 Op.getOperand(4), // vindex 7579 Offsets.first, // voffset 7580 Op.getOperand(6), // soffset 7581 Offsets.second, // offset 7582 Op.getOperand(7), // format 7583 Op.getOperand(8), // cachepolicy, swizzled buffer 7584 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7585 }; 7586 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7587 AMDGPUISD::TBUFFER_STORE_FORMAT; 7588 MemSDNode *M = cast<MemSDNode>(Op); 7589 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7590 M->getMemoryVT(), M->getMemOperand()); 7591 } 7592 7593 case Intrinsic::amdgcn_raw_tbuffer_store: { 7594 SDValue VData = Op.getOperand(2); 7595 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7596 if (IsD16) 7597 VData = handleD16VData(VData, DAG); 7598 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7599 SDValue Ops[] = { 7600 Chain, 7601 VData, // vdata 7602 Op.getOperand(3), // rsrc 7603 DAG.getConstant(0, DL, MVT::i32), // vindex 7604 Offsets.first, // voffset 7605 Op.getOperand(5), // soffset 7606 Offsets.second, // offset 7607 Op.getOperand(6), // format 7608 Op.getOperand(7), // cachepolicy, swizzled buffer 7609 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7610 }; 7611 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7612 AMDGPUISD::TBUFFER_STORE_FORMAT; 7613 MemSDNode *M = cast<MemSDNode>(Op); 7614 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7615 M->getMemoryVT(), M->getMemOperand()); 7616 } 7617 7618 case Intrinsic::amdgcn_buffer_store: 7619 case Intrinsic::amdgcn_buffer_store_format: { 7620 SDValue VData = Op.getOperand(2); 7621 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7622 if (IsD16) 7623 VData = handleD16VData(VData, DAG); 7624 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7625 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7626 unsigned IdxEn = 1; 7627 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7628 IdxEn = Idx->getZExtValue() != 0; 7629 SDValue Ops[] = { 7630 Chain, 7631 VData, 7632 Op.getOperand(3), // rsrc 7633 Op.getOperand(4), // vindex 7634 SDValue(), // voffset -- will be set by setBufferOffsets 7635 SDValue(), // soffset -- will be set by setBufferOffsets 7636 SDValue(), // offset -- will be set by setBufferOffsets 7637 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7638 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7639 }; 7640 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7641 // We don't know the offset if vindex is non-zero, so clear it. 7642 if (IdxEn) 7643 Offset = 0; 7644 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7645 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7646 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7647 MemSDNode *M = cast<MemSDNode>(Op); 7648 M->getMemOperand()->setOffset(Offset); 7649 7650 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7651 EVT VDataType = VData.getValueType().getScalarType(); 7652 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7653 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7654 7655 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7656 M->getMemoryVT(), M->getMemOperand()); 7657 } 7658 7659 case Intrinsic::amdgcn_raw_buffer_store: 7660 case Intrinsic::amdgcn_raw_buffer_store_format: { 7661 const bool IsFormat = 7662 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7663 7664 SDValue VData = Op.getOperand(2); 7665 EVT VDataVT = VData.getValueType(); 7666 EVT EltType = VDataVT.getScalarType(); 7667 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7668 if (IsD16) { 7669 VData = handleD16VData(VData, DAG); 7670 VDataVT = VData.getValueType(); 7671 } 7672 7673 if (!isTypeLegal(VDataVT)) { 7674 VData = 7675 DAG.getNode(ISD::BITCAST, DL, 7676 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7677 } 7678 7679 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7680 SDValue Ops[] = { 7681 Chain, 7682 VData, 7683 Op.getOperand(3), // rsrc 7684 DAG.getConstant(0, DL, MVT::i32), // vindex 7685 Offsets.first, // voffset 7686 Op.getOperand(5), // soffset 7687 Offsets.second, // offset 7688 Op.getOperand(6), // cachepolicy, swizzled buffer 7689 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7690 }; 7691 unsigned Opc = 7692 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7693 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7694 MemSDNode *M = cast<MemSDNode>(Op); 7695 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7696 7697 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7698 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7699 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7700 7701 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7702 M->getMemoryVT(), M->getMemOperand()); 7703 } 7704 7705 case Intrinsic::amdgcn_struct_buffer_store: 7706 case Intrinsic::amdgcn_struct_buffer_store_format: { 7707 const bool IsFormat = 7708 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7709 7710 SDValue VData = Op.getOperand(2); 7711 EVT VDataVT = VData.getValueType(); 7712 EVT EltType = VDataVT.getScalarType(); 7713 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7714 7715 if (IsD16) { 7716 VData = handleD16VData(VData, DAG); 7717 VDataVT = VData.getValueType(); 7718 } 7719 7720 if (!isTypeLegal(VDataVT)) { 7721 VData = 7722 DAG.getNode(ISD::BITCAST, DL, 7723 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7724 } 7725 7726 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7727 SDValue Ops[] = { 7728 Chain, 7729 VData, 7730 Op.getOperand(3), // rsrc 7731 Op.getOperand(4), // vindex 7732 Offsets.first, // voffset 7733 Op.getOperand(6), // soffset 7734 Offsets.second, // offset 7735 Op.getOperand(7), // cachepolicy, swizzled buffer 7736 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7737 }; 7738 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7739 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7740 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7741 MemSDNode *M = cast<MemSDNode>(Op); 7742 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7743 Ops[3])); 7744 7745 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7746 EVT VDataType = VData.getValueType().getScalarType(); 7747 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7748 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7749 7750 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7751 M->getMemoryVT(), M->getMemOperand()); 7752 } 7753 case Intrinsic::amdgcn_end_cf: 7754 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7755 Op->getOperand(2), Chain), 0); 7756 7757 default: { 7758 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7759 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7760 return lowerImage(Op, ImageDimIntr, DAG, true); 7761 7762 return Op; 7763 } 7764 } 7765 } 7766 7767 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7768 // offset (the offset that is included in bounds checking and swizzling, to be 7769 // split between the instruction's voffset and immoffset fields) and soffset 7770 // (the offset that is excluded from bounds checking and swizzling, to go in 7771 // the instruction's soffset field). This function takes the first kind of 7772 // offset and figures out how to split it between voffset and immoffset. 7773 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7774 SDValue Offset, SelectionDAG &DAG) const { 7775 SDLoc DL(Offset); 7776 const unsigned MaxImm = 4095; 7777 SDValue N0 = Offset; 7778 ConstantSDNode *C1 = nullptr; 7779 7780 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7781 N0 = SDValue(); 7782 else if (DAG.isBaseWithConstantOffset(N0)) { 7783 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7784 N0 = N0.getOperand(0); 7785 } 7786 7787 if (C1) { 7788 unsigned ImmOffset = C1->getZExtValue(); 7789 // If the immediate value is too big for the immoffset field, put the value 7790 // and -4096 into the immoffset field so that the value that is copied/added 7791 // for the voffset field is a multiple of 4096, and it stands more chance 7792 // of being CSEd with the copy/add for another similar load/store. 7793 // However, do not do that rounding down to a multiple of 4096 if that is a 7794 // negative number, as it appears to be illegal to have a negative offset 7795 // in the vgpr, even if adding the immediate offset makes it positive. 7796 unsigned Overflow = ImmOffset & ~MaxImm; 7797 ImmOffset -= Overflow; 7798 if ((int32_t)Overflow < 0) { 7799 Overflow += ImmOffset; 7800 ImmOffset = 0; 7801 } 7802 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7803 if (Overflow) { 7804 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7805 if (!N0) 7806 N0 = OverflowVal; 7807 else { 7808 SDValue Ops[] = { N0, OverflowVal }; 7809 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7810 } 7811 } 7812 } 7813 if (!N0) 7814 N0 = DAG.getConstant(0, DL, MVT::i32); 7815 if (!C1) 7816 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7817 return {N0, SDValue(C1, 0)}; 7818 } 7819 7820 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7821 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7822 // pointed to by Offsets. 7823 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7824 SelectionDAG &DAG, SDValue *Offsets, 7825 Align Alignment) const { 7826 SDLoc DL(CombinedOffset); 7827 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7828 uint32_t Imm = C->getZExtValue(); 7829 uint32_t SOffset, ImmOffset; 7830 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7831 Alignment)) { 7832 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7833 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7834 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7835 return SOffset + ImmOffset; 7836 } 7837 } 7838 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7839 SDValue N0 = CombinedOffset.getOperand(0); 7840 SDValue N1 = CombinedOffset.getOperand(1); 7841 uint32_t SOffset, ImmOffset; 7842 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7843 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7844 Subtarget, Alignment)) { 7845 Offsets[0] = N0; 7846 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7847 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7848 return 0; 7849 } 7850 } 7851 Offsets[0] = CombinedOffset; 7852 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7853 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7854 return 0; 7855 } 7856 7857 // Handle 8 bit and 16 bit buffer loads 7858 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7859 EVT LoadVT, SDLoc DL, 7860 ArrayRef<SDValue> Ops, 7861 MemSDNode *M) const { 7862 EVT IntVT = LoadVT.changeTypeToInteger(); 7863 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7864 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7865 7866 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7867 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7868 Ops, IntVT, 7869 M->getMemOperand()); 7870 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7871 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7872 7873 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7874 } 7875 7876 // Handle 8 bit and 16 bit buffer stores 7877 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7878 EVT VDataType, SDLoc DL, 7879 SDValue Ops[], 7880 MemSDNode *M) const { 7881 if (VDataType == MVT::f16) 7882 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7883 7884 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7885 Ops[1] = BufferStoreExt; 7886 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7887 AMDGPUISD::BUFFER_STORE_SHORT; 7888 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7889 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7890 M->getMemOperand()); 7891 } 7892 7893 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7894 ISD::LoadExtType ExtType, SDValue Op, 7895 const SDLoc &SL, EVT VT) { 7896 if (VT.bitsLT(Op.getValueType())) 7897 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7898 7899 switch (ExtType) { 7900 case ISD::SEXTLOAD: 7901 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7902 case ISD::ZEXTLOAD: 7903 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7904 case ISD::EXTLOAD: 7905 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7906 case ISD::NON_EXTLOAD: 7907 return Op; 7908 } 7909 7910 llvm_unreachable("invalid ext type"); 7911 } 7912 7913 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7914 SelectionDAG &DAG = DCI.DAG; 7915 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7916 return SDValue(); 7917 7918 // FIXME: Constant loads should all be marked invariant. 7919 unsigned AS = Ld->getAddressSpace(); 7920 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7921 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7922 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7923 return SDValue(); 7924 7925 // Don't do this early, since it may interfere with adjacent load merging for 7926 // illegal types. We can avoid losing alignment information for exotic types 7927 // pre-legalize. 7928 EVT MemVT = Ld->getMemoryVT(); 7929 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7930 MemVT.getSizeInBits() >= 32) 7931 return SDValue(); 7932 7933 SDLoc SL(Ld); 7934 7935 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7936 "unexpected vector extload"); 7937 7938 // TODO: Drop only high part of range. 7939 SDValue Ptr = Ld->getBasePtr(); 7940 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7941 MVT::i32, SL, Ld->getChain(), Ptr, 7942 Ld->getOffset(), 7943 Ld->getPointerInfo(), MVT::i32, 7944 Ld->getAlignment(), 7945 Ld->getMemOperand()->getFlags(), 7946 Ld->getAAInfo(), 7947 nullptr); // Drop ranges 7948 7949 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7950 if (MemVT.isFloatingPoint()) { 7951 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7952 "unexpected fp extload"); 7953 TruncVT = MemVT.changeTypeToInteger(); 7954 } 7955 7956 SDValue Cvt = NewLoad; 7957 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7958 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7959 DAG.getValueType(TruncVT)); 7960 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7961 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7962 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7963 } else { 7964 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7965 } 7966 7967 EVT VT = Ld->getValueType(0); 7968 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7969 7970 DCI.AddToWorklist(Cvt.getNode()); 7971 7972 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7973 // the appropriate extension from the 32-bit load. 7974 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7975 DCI.AddToWorklist(Cvt.getNode()); 7976 7977 // Handle conversion back to floating point if necessary. 7978 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7979 7980 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7981 } 7982 7983 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7984 SDLoc DL(Op); 7985 LoadSDNode *Load = cast<LoadSDNode>(Op); 7986 ISD::LoadExtType ExtType = Load->getExtensionType(); 7987 EVT MemVT = Load->getMemoryVT(); 7988 7989 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7990 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7991 return SDValue(); 7992 7993 // FIXME: Copied from PPC 7994 // First, load into 32 bits, then truncate to 1 bit. 7995 7996 SDValue Chain = Load->getChain(); 7997 SDValue BasePtr = Load->getBasePtr(); 7998 MachineMemOperand *MMO = Load->getMemOperand(); 7999 8000 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8001 8002 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8003 BasePtr, RealMemVT, MMO); 8004 8005 if (!MemVT.isVector()) { 8006 SDValue Ops[] = { 8007 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8008 NewLD.getValue(1) 8009 }; 8010 8011 return DAG.getMergeValues(Ops, DL); 8012 } 8013 8014 SmallVector<SDValue, 3> Elts; 8015 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8016 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8017 DAG.getConstant(I, DL, MVT::i32)); 8018 8019 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8020 } 8021 8022 SDValue Ops[] = { 8023 DAG.getBuildVector(MemVT, DL, Elts), 8024 NewLD.getValue(1) 8025 }; 8026 8027 return DAG.getMergeValues(Ops, DL); 8028 } 8029 8030 if (!MemVT.isVector()) 8031 return SDValue(); 8032 8033 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8034 "Custom lowering for non-i32 vectors hasn't been implemented."); 8035 8036 unsigned Alignment = Load->getAlignment(); 8037 unsigned AS = Load->getAddressSpace(); 8038 if (Subtarget->hasLDSMisalignedBug() && 8039 AS == AMDGPUAS::FLAT_ADDRESS && 8040 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8041 return SplitVectorLoad(Op, DAG); 8042 } 8043 8044 MachineFunction &MF = DAG.getMachineFunction(); 8045 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8046 // If there is a possibilty that flat instruction access scratch memory 8047 // then we need to use the same legalization rules we use for private. 8048 if (AS == AMDGPUAS::FLAT_ADDRESS && 8049 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8050 AS = MFI->hasFlatScratchInit() ? 8051 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8052 8053 unsigned NumElements = MemVT.getVectorNumElements(); 8054 8055 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8056 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8057 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8058 if (MemVT.isPow2VectorType()) 8059 return SDValue(); 8060 if (NumElements == 3) 8061 return WidenVectorLoad(Op, DAG); 8062 return SplitVectorLoad(Op, DAG); 8063 } 8064 // Non-uniform loads will be selected to MUBUF instructions, so they 8065 // have the same legalization requirements as global and private 8066 // loads. 8067 // 8068 } 8069 8070 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8071 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8072 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8073 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8074 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8075 Alignment >= 4 && NumElements < 32) { 8076 if (MemVT.isPow2VectorType()) 8077 return SDValue(); 8078 if (NumElements == 3) 8079 return WidenVectorLoad(Op, DAG); 8080 return SplitVectorLoad(Op, DAG); 8081 } 8082 // Non-uniform loads will be selected to MUBUF instructions, so they 8083 // have the same legalization requirements as global and private 8084 // loads. 8085 // 8086 } 8087 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8088 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8089 AS == AMDGPUAS::GLOBAL_ADDRESS || 8090 AS == AMDGPUAS::FLAT_ADDRESS) { 8091 if (NumElements > 4) 8092 return SplitVectorLoad(Op, DAG); 8093 // v3 loads not supported on SI. 8094 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8095 return WidenVectorLoad(Op, DAG); 8096 // v3 and v4 loads are supported for private and global memory. 8097 return SDValue(); 8098 } 8099 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8100 // Depending on the setting of the private_element_size field in the 8101 // resource descriptor, we can only make private accesses up to a certain 8102 // size. 8103 switch (Subtarget->getMaxPrivateElementSize()) { 8104 case 4: { 8105 SDValue Ops[2]; 8106 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8107 return DAG.getMergeValues(Ops, DL); 8108 } 8109 case 8: 8110 if (NumElements > 2) 8111 return SplitVectorLoad(Op, DAG); 8112 return SDValue(); 8113 case 16: 8114 // Same as global/flat 8115 if (NumElements > 4) 8116 return SplitVectorLoad(Op, DAG); 8117 // v3 loads not supported on SI. 8118 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8119 return WidenVectorLoad(Op, DAG); 8120 return SDValue(); 8121 default: 8122 llvm_unreachable("unsupported private_element_size"); 8123 } 8124 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8125 // Use ds_read_b128 or ds_read_b96 when possible. 8126 if (Subtarget->hasDS96AndDS128() && 8127 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8128 MemVT.getStoreSize() == 12) && 8129 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8130 Load->getAlign())) 8131 return SDValue(); 8132 8133 if (NumElements > 2) 8134 return SplitVectorLoad(Op, DAG); 8135 8136 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8137 // address is negative, then the instruction is incorrectly treated as 8138 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8139 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8140 // load later in the SILoadStoreOptimizer. 8141 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8142 NumElements == 2 && MemVT.getStoreSize() == 8 && 8143 Load->getAlignment() < 8) { 8144 return SplitVectorLoad(Op, DAG); 8145 } 8146 } 8147 8148 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8149 MemVT, *Load->getMemOperand())) { 8150 SDValue Ops[2]; 8151 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8152 return DAG.getMergeValues(Ops, DL); 8153 } 8154 8155 return SDValue(); 8156 } 8157 8158 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8159 EVT VT = Op.getValueType(); 8160 assert(VT.getSizeInBits() == 64); 8161 8162 SDLoc DL(Op); 8163 SDValue Cond = Op.getOperand(0); 8164 8165 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8166 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8167 8168 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8169 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8170 8171 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8172 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8173 8174 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8175 8176 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8177 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8178 8179 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8180 8181 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8182 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8183 } 8184 8185 // Catch division cases where we can use shortcuts with rcp and rsq 8186 // instructions. 8187 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8188 SelectionDAG &DAG) const { 8189 SDLoc SL(Op); 8190 SDValue LHS = Op.getOperand(0); 8191 SDValue RHS = Op.getOperand(1); 8192 EVT VT = Op.getValueType(); 8193 const SDNodeFlags Flags = Op->getFlags(); 8194 8195 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8196 Flags.hasApproximateFuncs(); 8197 8198 // Without !fpmath accuracy information, we can't do more because we don't 8199 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8200 if (!AllowInaccurateRcp) 8201 return SDValue(); 8202 8203 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8204 if (CLHS->isExactlyValue(1.0)) { 8205 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8206 // the CI documentation has a worst case error of 1 ulp. 8207 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8208 // use it as long as we aren't trying to use denormals. 8209 // 8210 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8211 8212 // 1.0 / sqrt(x) -> rsq(x) 8213 8214 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8215 // error seems really high at 2^29 ULP. 8216 if (RHS.getOpcode() == ISD::FSQRT) 8217 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8218 8219 // 1.0 / x -> rcp(x) 8220 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8221 } 8222 8223 // Same as for 1.0, but expand the sign out of the constant. 8224 if (CLHS->isExactlyValue(-1.0)) { 8225 // -1.0 / x -> rcp (fneg x) 8226 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8227 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8228 } 8229 } 8230 8231 // Turn into multiply by the reciprocal. 8232 // x / y -> x * (1.0 / y) 8233 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8234 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8235 } 8236 8237 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8238 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8239 SDNodeFlags Flags) { 8240 if (GlueChain->getNumValues() <= 1) { 8241 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8242 } 8243 8244 assert(GlueChain->getNumValues() == 3); 8245 8246 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8247 switch (Opcode) { 8248 default: llvm_unreachable("no chain equivalent for opcode"); 8249 case ISD::FMUL: 8250 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8251 break; 8252 } 8253 8254 return DAG.getNode(Opcode, SL, VTList, 8255 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8256 Flags); 8257 } 8258 8259 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8260 EVT VT, SDValue A, SDValue B, SDValue C, 8261 SDValue GlueChain, SDNodeFlags Flags) { 8262 if (GlueChain->getNumValues() <= 1) { 8263 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8264 } 8265 8266 assert(GlueChain->getNumValues() == 3); 8267 8268 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8269 switch (Opcode) { 8270 default: llvm_unreachable("no chain equivalent for opcode"); 8271 case ISD::FMA: 8272 Opcode = AMDGPUISD::FMA_W_CHAIN; 8273 break; 8274 } 8275 8276 return DAG.getNode(Opcode, SL, VTList, 8277 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8278 Flags); 8279 } 8280 8281 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8282 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8283 return FastLowered; 8284 8285 SDLoc SL(Op); 8286 SDValue Src0 = Op.getOperand(0); 8287 SDValue Src1 = Op.getOperand(1); 8288 8289 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8290 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8291 8292 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8293 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8294 8295 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8296 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8297 8298 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8299 } 8300 8301 // Faster 2.5 ULP division that does not support denormals. 8302 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8303 SDLoc SL(Op); 8304 SDValue LHS = Op.getOperand(1); 8305 SDValue RHS = Op.getOperand(2); 8306 8307 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8308 8309 const APFloat K0Val(BitsToFloat(0x6f800000)); 8310 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8311 8312 const APFloat K1Val(BitsToFloat(0x2f800000)); 8313 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8314 8315 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8316 8317 EVT SetCCVT = 8318 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8319 8320 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8321 8322 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8323 8324 // TODO: Should this propagate fast-math-flags? 8325 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8326 8327 // rcp does not support denormals. 8328 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8329 8330 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8331 8332 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8333 } 8334 8335 // Returns immediate value for setting the F32 denorm mode when using the 8336 // S_DENORM_MODE instruction. 8337 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8338 const SDLoc &SL, const GCNSubtarget *ST) { 8339 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8340 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8341 ? FP_DENORM_FLUSH_NONE 8342 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8343 8344 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8345 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8346 } 8347 8348 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8349 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8350 return FastLowered; 8351 8352 // The selection matcher assumes anything with a chain selecting to a 8353 // mayRaiseFPException machine instruction. Since we're introducing a chain 8354 // here, we need to explicitly report nofpexcept for the regular fdiv 8355 // lowering. 8356 SDNodeFlags Flags = Op->getFlags(); 8357 Flags.setNoFPExcept(true); 8358 8359 SDLoc SL(Op); 8360 SDValue LHS = Op.getOperand(0); 8361 SDValue RHS = Op.getOperand(1); 8362 8363 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8364 8365 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8366 8367 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8368 {RHS, RHS, LHS}, Flags); 8369 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8370 {LHS, RHS, LHS}, Flags); 8371 8372 // Denominator is scaled to not be denormal, so using rcp is ok. 8373 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8374 DenominatorScaled, Flags); 8375 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8376 DenominatorScaled, Flags); 8377 8378 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8379 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8380 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8381 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8382 8383 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8384 8385 if (!HasFP32Denormals) { 8386 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8387 // lowering. The chain dependence is insufficient, and we need glue. We do 8388 // not need the glue variants in a strictfp function. 8389 8390 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8391 8392 SDNode *EnableDenorm; 8393 if (Subtarget->hasDenormModeInst()) { 8394 const SDValue EnableDenormValue = 8395 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8396 8397 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8398 DAG.getEntryNode(), EnableDenormValue).getNode(); 8399 } else { 8400 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8401 SL, MVT::i32); 8402 EnableDenorm = 8403 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8404 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8405 } 8406 8407 SDValue Ops[3] = { 8408 NegDivScale0, 8409 SDValue(EnableDenorm, 0), 8410 SDValue(EnableDenorm, 1) 8411 }; 8412 8413 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8414 } 8415 8416 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8417 ApproxRcp, One, NegDivScale0, Flags); 8418 8419 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8420 ApproxRcp, Fma0, Flags); 8421 8422 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8423 Fma1, Fma1, Flags); 8424 8425 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8426 NumeratorScaled, Mul, Flags); 8427 8428 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8429 Fma2, Fma1, Mul, Fma2, Flags); 8430 8431 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8432 NumeratorScaled, Fma3, Flags); 8433 8434 if (!HasFP32Denormals) { 8435 SDNode *DisableDenorm; 8436 if (Subtarget->hasDenormModeInst()) { 8437 const SDValue DisableDenormValue = 8438 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8439 8440 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8441 Fma4.getValue(1), DisableDenormValue, 8442 Fma4.getValue(2)).getNode(); 8443 } else { 8444 const SDValue DisableDenormValue = 8445 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8446 8447 DisableDenorm = DAG.getMachineNode( 8448 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8449 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8450 } 8451 8452 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8453 SDValue(DisableDenorm, 0), DAG.getRoot()); 8454 DAG.setRoot(OutputChain); 8455 } 8456 8457 SDValue Scale = NumeratorScaled.getValue(1); 8458 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8459 {Fma4, Fma1, Fma3, Scale}, Flags); 8460 8461 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8462 } 8463 8464 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8465 if (DAG.getTarget().Options.UnsafeFPMath) 8466 return lowerFastUnsafeFDIV(Op, DAG); 8467 8468 SDLoc SL(Op); 8469 SDValue X = Op.getOperand(0); 8470 SDValue Y = Op.getOperand(1); 8471 8472 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8473 8474 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8475 8476 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8477 8478 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8479 8480 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8481 8482 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8483 8484 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8485 8486 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8487 8488 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8489 8490 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8491 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8492 8493 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8494 NegDivScale0, Mul, DivScale1); 8495 8496 SDValue Scale; 8497 8498 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8499 // Workaround a hardware bug on SI where the condition output from div_scale 8500 // is not usable. 8501 8502 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8503 8504 // Figure out if the scale to use for div_fmas. 8505 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8506 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8507 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8508 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8509 8510 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8511 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8512 8513 SDValue Scale0Hi 8514 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8515 SDValue Scale1Hi 8516 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8517 8518 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8519 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8520 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8521 } else { 8522 Scale = DivScale1.getValue(1); 8523 } 8524 8525 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8526 Fma4, Fma3, Mul, Scale); 8527 8528 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8529 } 8530 8531 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8532 EVT VT = Op.getValueType(); 8533 8534 if (VT == MVT::f32) 8535 return LowerFDIV32(Op, DAG); 8536 8537 if (VT == MVT::f64) 8538 return LowerFDIV64(Op, DAG); 8539 8540 if (VT == MVT::f16) 8541 return LowerFDIV16(Op, DAG); 8542 8543 llvm_unreachable("Unexpected type for fdiv"); 8544 } 8545 8546 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8547 SDLoc DL(Op); 8548 StoreSDNode *Store = cast<StoreSDNode>(Op); 8549 EVT VT = Store->getMemoryVT(); 8550 8551 if (VT == MVT::i1) { 8552 return DAG.getTruncStore(Store->getChain(), DL, 8553 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8554 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8555 } 8556 8557 assert(VT.isVector() && 8558 Store->getValue().getValueType().getScalarType() == MVT::i32); 8559 8560 unsigned AS = Store->getAddressSpace(); 8561 if (Subtarget->hasLDSMisalignedBug() && 8562 AS == AMDGPUAS::FLAT_ADDRESS && 8563 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8564 return SplitVectorStore(Op, DAG); 8565 } 8566 8567 MachineFunction &MF = DAG.getMachineFunction(); 8568 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8569 // If there is a possibilty that flat instruction access scratch memory 8570 // then we need to use the same legalization rules we use for private. 8571 if (AS == AMDGPUAS::FLAT_ADDRESS && 8572 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8573 AS = MFI->hasFlatScratchInit() ? 8574 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8575 8576 unsigned NumElements = VT.getVectorNumElements(); 8577 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8578 AS == AMDGPUAS::FLAT_ADDRESS) { 8579 if (NumElements > 4) 8580 return SplitVectorStore(Op, DAG); 8581 // v3 stores not supported on SI. 8582 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8583 return SplitVectorStore(Op, DAG); 8584 8585 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8586 VT, *Store->getMemOperand())) 8587 return expandUnalignedStore(Store, DAG); 8588 8589 return SDValue(); 8590 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8591 switch (Subtarget->getMaxPrivateElementSize()) { 8592 case 4: 8593 return scalarizeVectorStore(Store, DAG); 8594 case 8: 8595 if (NumElements > 2) 8596 return SplitVectorStore(Op, DAG); 8597 return SDValue(); 8598 case 16: 8599 if (NumElements > 4 || NumElements == 3) 8600 return SplitVectorStore(Op, DAG); 8601 return SDValue(); 8602 default: 8603 llvm_unreachable("unsupported private_element_size"); 8604 } 8605 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8606 // Use ds_write_b128 or ds_write_b96 when possible. 8607 if (Subtarget->hasDS96AndDS128() && 8608 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8609 (VT.getStoreSize() == 12)) && 8610 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8611 Store->getAlign())) 8612 return SDValue(); 8613 8614 if (NumElements > 2) 8615 return SplitVectorStore(Op, DAG); 8616 8617 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8618 // address is negative, then the instruction is incorrectly treated as 8619 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8620 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8621 // store later in the SILoadStoreOptimizer. 8622 if (!Subtarget->hasUsableDSOffset() && 8623 NumElements == 2 && VT.getStoreSize() == 8 && 8624 Store->getAlignment() < 8) { 8625 return SplitVectorStore(Op, DAG); 8626 } 8627 8628 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8629 VT, *Store->getMemOperand())) { 8630 if (VT.isVector()) 8631 return SplitVectorStore(Op, DAG); 8632 return expandUnalignedStore(Store, DAG); 8633 } 8634 8635 return SDValue(); 8636 } else { 8637 llvm_unreachable("unhandled address space"); 8638 } 8639 } 8640 8641 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8642 SDLoc DL(Op); 8643 EVT VT = Op.getValueType(); 8644 SDValue Arg = Op.getOperand(0); 8645 SDValue TrigVal; 8646 8647 // Propagate fast-math flags so that the multiply we introduce can be folded 8648 // if Arg is already the result of a multiply by constant. 8649 auto Flags = Op->getFlags(); 8650 8651 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8652 8653 if (Subtarget->hasTrigReducedRange()) { 8654 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8655 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8656 } else { 8657 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8658 } 8659 8660 switch (Op.getOpcode()) { 8661 case ISD::FCOS: 8662 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8663 case ISD::FSIN: 8664 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8665 default: 8666 llvm_unreachable("Wrong trig opcode"); 8667 } 8668 } 8669 8670 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8671 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8672 assert(AtomicNode->isCompareAndSwap()); 8673 unsigned AS = AtomicNode->getAddressSpace(); 8674 8675 // No custom lowering required for local address space 8676 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8677 return Op; 8678 8679 // Non-local address space requires custom lowering for atomic compare 8680 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8681 SDLoc DL(Op); 8682 SDValue ChainIn = Op.getOperand(0); 8683 SDValue Addr = Op.getOperand(1); 8684 SDValue Old = Op.getOperand(2); 8685 SDValue New = Op.getOperand(3); 8686 EVT VT = Op.getValueType(); 8687 MVT SimpleVT = VT.getSimpleVT(); 8688 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8689 8690 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8691 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8692 8693 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8694 Ops, VT, AtomicNode->getMemOperand()); 8695 } 8696 8697 //===----------------------------------------------------------------------===// 8698 // Custom DAG optimizations 8699 //===----------------------------------------------------------------------===// 8700 8701 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8702 DAGCombinerInfo &DCI) const { 8703 EVT VT = N->getValueType(0); 8704 EVT ScalarVT = VT.getScalarType(); 8705 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8706 return SDValue(); 8707 8708 SelectionDAG &DAG = DCI.DAG; 8709 SDLoc DL(N); 8710 8711 SDValue Src = N->getOperand(0); 8712 EVT SrcVT = Src.getValueType(); 8713 8714 // TODO: We could try to match extracting the higher bytes, which would be 8715 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8716 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8717 // about in practice. 8718 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8719 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8720 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8721 DCI.AddToWorklist(Cvt.getNode()); 8722 8723 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8724 if (ScalarVT != MVT::f32) { 8725 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8726 DAG.getTargetConstant(0, DL, MVT::i32)); 8727 } 8728 return Cvt; 8729 } 8730 } 8731 8732 return SDValue(); 8733 } 8734 8735 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8736 8737 // This is a variant of 8738 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8739 // 8740 // The normal DAG combiner will do this, but only if the add has one use since 8741 // that would increase the number of instructions. 8742 // 8743 // This prevents us from seeing a constant offset that can be folded into a 8744 // memory instruction's addressing mode. If we know the resulting add offset of 8745 // a pointer can be folded into an addressing offset, we can replace the pointer 8746 // operand with the add of new constant offset. This eliminates one of the uses, 8747 // and may allow the remaining use to also be simplified. 8748 // 8749 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8750 unsigned AddrSpace, 8751 EVT MemVT, 8752 DAGCombinerInfo &DCI) const { 8753 SDValue N0 = N->getOperand(0); 8754 SDValue N1 = N->getOperand(1); 8755 8756 // We only do this to handle cases where it's profitable when there are 8757 // multiple uses of the add, so defer to the standard combine. 8758 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8759 N0->hasOneUse()) 8760 return SDValue(); 8761 8762 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8763 if (!CN1) 8764 return SDValue(); 8765 8766 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8767 if (!CAdd) 8768 return SDValue(); 8769 8770 // If the resulting offset is too large, we can't fold it into the addressing 8771 // mode offset. 8772 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8773 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8774 8775 AddrMode AM; 8776 AM.HasBaseReg = true; 8777 AM.BaseOffs = Offset.getSExtValue(); 8778 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8779 return SDValue(); 8780 8781 SelectionDAG &DAG = DCI.DAG; 8782 SDLoc SL(N); 8783 EVT VT = N->getValueType(0); 8784 8785 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8786 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8787 8788 SDNodeFlags Flags; 8789 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8790 (N0.getOpcode() == ISD::OR || 8791 N0->getFlags().hasNoUnsignedWrap())); 8792 8793 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8794 } 8795 8796 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8797 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8798 /// specific intrinsic, but they all place the pointer operand first. 8799 static unsigned getBasePtrIndex(const MemSDNode *N) { 8800 switch (N->getOpcode()) { 8801 case ISD::STORE: 8802 case ISD::INTRINSIC_W_CHAIN: 8803 case ISD::INTRINSIC_VOID: 8804 return 2; 8805 default: 8806 return 1; 8807 } 8808 } 8809 8810 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8811 DAGCombinerInfo &DCI) const { 8812 SelectionDAG &DAG = DCI.DAG; 8813 SDLoc SL(N); 8814 8815 unsigned PtrIdx = getBasePtrIndex(N); 8816 SDValue Ptr = N->getOperand(PtrIdx); 8817 8818 // TODO: We could also do this for multiplies. 8819 if (Ptr.getOpcode() == ISD::SHL) { 8820 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8821 N->getMemoryVT(), DCI); 8822 if (NewPtr) { 8823 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8824 8825 NewOps[PtrIdx] = NewPtr; 8826 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8827 } 8828 } 8829 8830 return SDValue(); 8831 } 8832 8833 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8834 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8835 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8836 (Opc == ISD::XOR && Val == 0); 8837 } 8838 8839 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8840 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8841 // integer combine opportunities since most 64-bit operations are decomposed 8842 // this way. TODO: We won't want this for SALU especially if it is an inline 8843 // immediate. 8844 SDValue SITargetLowering::splitBinaryBitConstantOp( 8845 DAGCombinerInfo &DCI, 8846 const SDLoc &SL, 8847 unsigned Opc, SDValue LHS, 8848 const ConstantSDNode *CRHS) const { 8849 uint64_t Val = CRHS->getZExtValue(); 8850 uint32_t ValLo = Lo_32(Val); 8851 uint32_t ValHi = Hi_32(Val); 8852 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8853 8854 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8855 bitOpWithConstantIsReducible(Opc, ValHi)) || 8856 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8857 // If we need to materialize a 64-bit immediate, it will be split up later 8858 // anyway. Avoid creating the harder to understand 64-bit immediate 8859 // materialization. 8860 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8861 } 8862 8863 return SDValue(); 8864 } 8865 8866 // Returns true if argument is a boolean value which is not serialized into 8867 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8868 static bool isBoolSGPR(SDValue V) { 8869 if (V.getValueType() != MVT::i1) 8870 return false; 8871 switch (V.getOpcode()) { 8872 default: break; 8873 case ISD::SETCC: 8874 case ISD::AND: 8875 case ISD::OR: 8876 case ISD::XOR: 8877 case AMDGPUISD::FP_CLASS: 8878 return true; 8879 } 8880 return false; 8881 } 8882 8883 // If a constant has all zeroes or all ones within each byte return it. 8884 // Otherwise return 0. 8885 static uint32_t getConstantPermuteMask(uint32_t C) { 8886 // 0xff for any zero byte in the mask 8887 uint32_t ZeroByteMask = 0; 8888 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8889 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8890 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8891 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8892 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8893 if ((NonZeroByteMask & C) != NonZeroByteMask) 8894 return 0; // Partial bytes selected. 8895 return C; 8896 } 8897 8898 // Check if a node selects whole bytes from its operand 0 starting at a byte 8899 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8900 // or -1 if not succeeded. 8901 // Note byte select encoding: 8902 // value 0-3 selects corresponding source byte; 8903 // value 0xc selects zero; 8904 // value 0xff selects 0xff. 8905 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8906 assert(V.getValueSizeInBits() == 32); 8907 8908 if (V.getNumOperands() != 2) 8909 return ~0; 8910 8911 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8912 if (!N1) 8913 return ~0; 8914 8915 uint32_t C = N1->getZExtValue(); 8916 8917 switch (V.getOpcode()) { 8918 default: 8919 break; 8920 case ISD::AND: 8921 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8922 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8923 } 8924 break; 8925 8926 case ISD::OR: 8927 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8928 return (0x03020100 & ~ConstMask) | ConstMask; 8929 } 8930 break; 8931 8932 case ISD::SHL: 8933 if (C % 8) 8934 return ~0; 8935 8936 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8937 8938 case ISD::SRL: 8939 if (C % 8) 8940 return ~0; 8941 8942 return uint32_t(0x0c0c0c0c03020100ull >> C); 8943 } 8944 8945 return ~0; 8946 } 8947 8948 SDValue SITargetLowering::performAndCombine(SDNode *N, 8949 DAGCombinerInfo &DCI) const { 8950 if (DCI.isBeforeLegalize()) 8951 return SDValue(); 8952 8953 SelectionDAG &DAG = DCI.DAG; 8954 EVT VT = N->getValueType(0); 8955 SDValue LHS = N->getOperand(0); 8956 SDValue RHS = N->getOperand(1); 8957 8958 8959 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8960 if (VT == MVT::i64 && CRHS) { 8961 if (SDValue Split 8962 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8963 return Split; 8964 } 8965 8966 if (CRHS && VT == MVT::i32) { 8967 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8968 // nb = number of trailing zeroes in mask 8969 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8970 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8971 uint64_t Mask = CRHS->getZExtValue(); 8972 unsigned Bits = countPopulation(Mask); 8973 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8974 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8975 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8976 unsigned Shift = CShift->getZExtValue(); 8977 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8978 unsigned Offset = NB + Shift; 8979 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8980 SDLoc SL(N); 8981 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8982 LHS->getOperand(0), 8983 DAG.getConstant(Offset, SL, MVT::i32), 8984 DAG.getConstant(Bits, SL, MVT::i32)); 8985 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8986 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8987 DAG.getValueType(NarrowVT)); 8988 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8989 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8990 return Shl; 8991 } 8992 } 8993 } 8994 8995 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8996 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8997 isa<ConstantSDNode>(LHS.getOperand(2))) { 8998 uint32_t Sel = getConstantPermuteMask(Mask); 8999 if (!Sel) 9000 return SDValue(); 9001 9002 // Select 0xc for all zero bytes 9003 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9004 SDLoc DL(N); 9005 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9006 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9007 } 9008 } 9009 9010 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9011 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9012 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9013 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9014 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9015 9016 SDValue X = LHS.getOperand(0); 9017 SDValue Y = RHS.getOperand(0); 9018 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9019 return SDValue(); 9020 9021 if (LCC == ISD::SETO) { 9022 if (X != LHS.getOperand(1)) 9023 return SDValue(); 9024 9025 if (RCC == ISD::SETUNE) { 9026 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9027 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9028 return SDValue(); 9029 9030 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9031 SIInstrFlags::N_SUBNORMAL | 9032 SIInstrFlags::N_ZERO | 9033 SIInstrFlags::P_ZERO | 9034 SIInstrFlags::P_SUBNORMAL | 9035 SIInstrFlags::P_NORMAL; 9036 9037 static_assert(((~(SIInstrFlags::S_NAN | 9038 SIInstrFlags::Q_NAN | 9039 SIInstrFlags::N_INFINITY | 9040 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9041 "mask not equal"); 9042 9043 SDLoc DL(N); 9044 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9045 X, DAG.getConstant(Mask, DL, MVT::i32)); 9046 } 9047 } 9048 } 9049 9050 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9051 std::swap(LHS, RHS); 9052 9053 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9054 RHS.hasOneUse()) { 9055 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9056 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9057 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9058 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9059 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9060 (RHS.getOperand(0) == LHS.getOperand(0) && 9061 LHS.getOperand(0) == LHS.getOperand(1))) { 9062 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9063 unsigned NewMask = LCC == ISD::SETO ? 9064 Mask->getZExtValue() & ~OrdMask : 9065 Mask->getZExtValue() & OrdMask; 9066 9067 SDLoc DL(N); 9068 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9069 DAG.getConstant(NewMask, DL, MVT::i32)); 9070 } 9071 } 9072 9073 if (VT == MVT::i32 && 9074 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9075 // and x, (sext cc from i1) => select cc, x, 0 9076 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9077 std::swap(LHS, RHS); 9078 if (isBoolSGPR(RHS.getOperand(0))) 9079 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9080 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9081 } 9082 9083 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9084 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9085 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9086 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9087 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9088 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9089 if (LHSMask != ~0u && RHSMask != ~0u) { 9090 // Canonicalize the expression in an attempt to have fewer unique masks 9091 // and therefore fewer registers used to hold the masks. 9092 if (LHSMask > RHSMask) { 9093 std::swap(LHSMask, RHSMask); 9094 std::swap(LHS, RHS); 9095 } 9096 9097 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9098 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9099 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9100 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9101 9102 // Check of we need to combine values from two sources within a byte. 9103 if (!(LHSUsedLanes & RHSUsedLanes) && 9104 // If we select high and lower word keep it for SDWA. 9105 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9106 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9107 // Each byte in each mask is either selector mask 0-3, or has higher 9108 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9109 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9110 // mask which is not 0xff wins. By anding both masks we have a correct 9111 // result except that 0x0c shall be corrected to give 0x0c only. 9112 uint32_t Mask = LHSMask & RHSMask; 9113 for (unsigned I = 0; I < 32; I += 8) { 9114 uint32_t ByteSel = 0xff << I; 9115 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9116 Mask &= (0x0c << I) & 0xffffffff; 9117 } 9118 9119 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9120 // or 0x0c. 9121 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9122 SDLoc DL(N); 9123 9124 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9125 LHS.getOperand(0), RHS.getOperand(0), 9126 DAG.getConstant(Sel, DL, MVT::i32)); 9127 } 9128 } 9129 } 9130 9131 return SDValue(); 9132 } 9133 9134 SDValue SITargetLowering::performOrCombine(SDNode *N, 9135 DAGCombinerInfo &DCI) const { 9136 SelectionDAG &DAG = DCI.DAG; 9137 SDValue LHS = N->getOperand(0); 9138 SDValue RHS = N->getOperand(1); 9139 9140 EVT VT = N->getValueType(0); 9141 if (VT == MVT::i1) { 9142 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9143 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9144 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9145 SDValue Src = LHS.getOperand(0); 9146 if (Src != RHS.getOperand(0)) 9147 return SDValue(); 9148 9149 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9150 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9151 if (!CLHS || !CRHS) 9152 return SDValue(); 9153 9154 // Only 10 bits are used. 9155 static const uint32_t MaxMask = 0x3ff; 9156 9157 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9158 SDLoc DL(N); 9159 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9160 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9161 } 9162 9163 return SDValue(); 9164 } 9165 9166 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9167 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9168 LHS.getOpcode() == AMDGPUISD::PERM && 9169 isa<ConstantSDNode>(LHS.getOperand(2))) { 9170 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9171 if (!Sel) 9172 return SDValue(); 9173 9174 Sel |= LHS.getConstantOperandVal(2); 9175 SDLoc DL(N); 9176 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9177 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9178 } 9179 9180 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9181 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9182 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9183 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9184 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9185 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9186 if (LHSMask != ~0u && RHSMask != ~0u) { 9187 // Canonicalize the expression in an attempt to have fewer unique masks 9188 // and therefore fewer registers used to hold the masks. 9189 if (LHSMask > RHSMask) { 9190 std::swap(LHSMask, RHSMask); 9191 std::swap(LHS, RHS); 9192 } 9193 9194 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9195 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9196 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9197 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9198 9199 // Check of we need to combine values from two sources within a byte. 9200 if (!(LHSUsedLanes & RHSUsedLanes) && 9201 // If we select high and lower word keep it for SDWA. 9202 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9203 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9204 // Kill zero bytes selected by other mask. Zero value is 0xc. 9205 LHSMask &= ~RHSUsedLanes; 9206 RHSMask &= ~LHSUsedLanes; 9207 // Add 4 to each active LHS lane 9208 LHSMask |= LHSUsedLanes & 0x04040404; 9209 // Combine masks 9210 uint32_t Sel = LHSMask | RHSMask; 9211 SDLoc DL(N); 9212 9213 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9214 LHS.getOperand(0), RHS.getOperand(0), 9215 DAG.getConstant(Sel, DL, MVT::i32)); 9216 } 9217 } 9218 } 9219 9220 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9221 return SDValue(); 9222 9223 // TODO: This could be a generic combine with a predicate for extracting the 9224 // high half of an integer being free. 9225 9226 // (or i64:x, (zero_extend i32:y)) -> 9227 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9228 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9229 RHS.getOpcode() != ISD::ZERO_EXTEND) 9230 std::swap(LHS, RHS); 9231 9232 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9233 SDValue ExtSrc = RHS.getOperand(0); 9234 EVT SrcVT = ExtSrc.getValueType(); 9235 if (SrcVT == MVT::i32) { 9236 SDLoc SL(N); 9237 SDValue LowLHS, HiBits; 9238 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9239 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9240 9241 DCI.AddToWorklist(LowOr.getNode()); 9242 DCI.AddToWorklist(HiBits.getNode()); 9243 9244 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9245 LowOr, HiBits); 9246 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9247 } 9248 } 9249 9250 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9251 if (CRHS) { 9252 if (SDValue Split 9253 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9254 return Split; 9255 } 9256 9257 return SDValue(); 9258 } 9259 9260 SDValue SITargetLowering::performXorCombine(SDNode *N, 9261 DAGCombinerInfo &DCI) const { 9262 EVT VT = N->getValueType(0); 9263 if (VT != MVT::i64) 9264 return SDValue(); 9265 9266 SDValue LHS = N->getOperand(0); 9267 SDValue RHS = N->getOperand(1); 9268 9269 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9270 if (CRHS) { 9271 if (SDValue Split 9272 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9273 return Split; 9274 } 9275 9276 return SDValue(); 9277 } 9278 9279 // Instructions that will be lowered with a final instruction that zeros the 9280 // high result bits. 9281 // XXX - probably only need to list legal operations. 9282 static bool fp16SrcZerosHighBits(unsigned Opc) { 9283 switch (Opc) { 9284 case ISD::FADD: 9285 case ISD::FSUB: 9286 case ISD::FMUL: 9287 case ISD::FDIV: 9288 case ISD::FREM: 9289 case ISD::FMA: 9290 case ISD::FMAD: 9291 case ISD::FCANONICALIZE: 9292 case ISD::FP_ROUND: 9293 case ISD::UINT_TO_FP: 9294 case ISD::SINT_TO_FP: 9295 case ISD::FABS: 9296 // Fabs is lowered to a bit operation, but it's an and which will clear the 9297 // high bits anyway. 9298 case ISD::FSQRT: 9299 case ISD::FSIN: 9300 case ISD::FCOS: 9301 case ISD::FPOWI: 9302 case ISD::FPOW: 9303 case ISD::FLOG: 9304 case ISD::FLOG2: 9305 case ISD::FLOG10: 9306 case ISD::FEXP: 9307 case ISD::FEXP2: 9308 case ISD::FCEIL: 9309 case ISD::FTRUNC: 9310 case ISD::FRINT: 9311 case ISD::FNEARBYINT: 9312 case ISD::FROUND: 9313 case ISD::FFLOOR: 9314 case ISD::FMINNUM: 9315 case ISD::FMAXNUM: 9316 case AMDGPUISD::FRACT: 9317 case AMDGPUISD::CLAMP: 9318 case AMDGPUISD::COS_HW: 9319 case AMDGPUISD::SIN_HW: 9320 case AMDGPUISD::FMIN3: 9321 case AMDGPUISD::FMAX3: 9322 case AMDGPUISD::FMED3: 9323 case AMDGPUISD::FMAD_FTZ: 9324 case AMDGPUISD::RCP: 9325 case AMDGPUISD::RSQ: 9326 case AMDGPUISD::RCP_IFLAG: 9327 case AMDGPUISD::LDEXP: 9328 return true; 9329 default: 9330 // fcopysign, select and others may be lowered to 32-bit bit operations 9331 // which don't zero the high bits. 9332 return false; 9333 } 9334 } 9335 9336 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9337 DAGCombinerInfo &DCI) const { 9338 if (!Subtarget->has16BitInsts() || 9339 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9340 return SDValue(); 9341 9342 EVT VT = N->getValueType(0); 9343 if (VT != MVT::i32) 9344 return SDValue(); 9345 9346 SDValue Src = N->getOperand(0); 9347 if (Src.getValueType() != MVT::i16) 9348 return SDValue(); 9349 9350 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9351 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9352 if (Src.getOpcode() == ISD::BITCAST) { 9353 SDValue BCSrc = Src.getOperand(0); 9354 if (BCSrc.getValueType() == MVT::f16 && 9355 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9356 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9357 } 9358 9359 return SDValue(); 9360 } 9361 9362 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9363 DAGCombinerInfo &DCI) 9364 const { 9365 SDValue Src = N->getOperand(0); 9366 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9367 9368 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9369 VTSign->getVT() == MVT::i8) || 9370 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9371 VTSign->getVT() == MVT::i16)) && 9372 Src.hasOneUse()) { 9373 auto *M = cast<MemSDNode>(Src); 9374 SDValue Ops[] = { 9375 Src.getOperand(0), // Chain 9376 Src.getOperand(1), // rsrc 9377 Src.getOperand(2), // vindex 9378 Src.getOperand(3), // voffset 9379 Src.getOperand(4), // soffset 9380 Src.getOperand(5), // offset 9381 Src.getOperand(6), 9382 Src.getOperand(7) 9383 }; 9384 // replace with BUFFER_LOAD_BYTE/SHORT 9385 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9386 Src.getOperand(0).getValueType()); 9387 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9388 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9389 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9390 ResList, 9391 Ops, M->getMemoryVT(), 9392 M->getMemOperand()); 9393 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9394 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9395 } 9396 return SDValue(); 9397 } 9398 9399 SDValue SITargetLowering::performClassCombine(SDNode *N, 9400 DAGCombinerInfo &DCI) const { 9401 SelectionDAG &DAG = DCI.DAG; 9402 SDValue Mask = N->getOperand(1); 9403 9404 // fp_class x, 0 -> false 9405 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9406 if (CMask->isNullValue()) 9407 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9408 } 9409 9410 if (N->getOperand(0).isUndef()) 9411 return DAG.getUNDEF(MVT::i1); 9412 9413 return SDValue(); 9414 } 9415 9416 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9417 DAGCombinerInfo &DCI) const { 9418 EVT VT = N->getValueType(0); 9419 SDValue N0 = N->getOperand(0); 9420 9421 if (N0.isUndef()) 9422 return N0; 9423 9424 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9425 N0.getOpcode() == ISD::SINT_TO_FP)) { 9426 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9427 N->getFlags()); 9428 } 9429 9430 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9431 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9432 N0.getOperand(0), N->getFlags()); 9433 } 9434 9435 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9436 } 9437 9438 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9439 unsigned MaxDepth) const { 9440 unsigned Opcode = Op.getOpcode(); 9441 if (Opcode == ISD::FCANONICALIZE) 9442 return true; 9443 9444 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9445 auto F = CFP->getValueAPF(); 9446 if (F.isNaN() && F.isSignaling()) 9447 return false; 9448 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9449 } 9450 9451 // If source is a result of another standard FP operation it is already in 9452 // canonical form. 9453 if (MaxDepth == 0) 9454 return false; 9455 9456 switch (Opcode) { 9457 // These will flush denorms if required. 9458 case ISD::FADD: 9459 case ISD::FSUB: 9460 case ISD::FMUL: 9461 case ISD::FCEIL: 9462 case ISD::FFLOOR: 9463 case ISD::FMA: 9464 case ISD::FMAD: 9465 case ISD::FSQRT: 9466 case ISD::FDIV: 9467 case ISD::FREM: 9468 case ISD::FP_ROUND: 9469 case ISD::FP_EXTEND: 9470 case AMDGPUISD::FMUL_LEGACY: 9471 case AMDGPUISD::FMAD_FTZ: 9472 case AMDGPUISD::RCP: 9473 case AMDGPUISD::RSQ: 9474 case AMDGPUISD::RSQ_CLAMP: 9475 case AMDGPUISD::RCP_LEGACY: 9476 case AMDGPUISD::RCP_IFLAG: 9477 case AMDGPUISD::DIV_SCALE: 9478 case AMDGPUISD::DIV_FMAS: 9479 case AMDGPUISD::DIV_FIXUP: 9480 case AMDGPUISD::FRACT: 9481 case AMDGPUISD::LDEXP: 9482 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9483 case AMDGPUISD::CVT_F32_UBYTE0: 9484 case AMDGPUISD::CVT_F32_UBYTE1: 9485 case AMDGPUISD::CVT_F32_UBYTE2: 9486 case AMDGPUISD::CVT_F32_UBYTE3: 9487 return true; 9488 9489 // It can/will be lowered or combined as a bit operation. 9490 // Need to check their input recursively to handle. 9491 case ISD::FNEG: 9492 case ISD::FABS: 9493 case ISD::FCOPYSIGN: 9494 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9495 9496 case ISD::FSIN: 9497 case ISD::FCOS: 9498 case ISD::FSINCOS: 9499 return Op.getValueType().getScalarType() != MVT::f16; 9500 9501 case ISD::FMINNUM: 9502 case ISD::FMAXNUM: 9503 case ISD::FMINNUM_IEEE: 9504 case ISD::FMAXNUM_IEEE: 9505 case AMDGPUISD::CLAMP: 9506 case AMDGPUISD::FMED3: 9507 case AMDGPUISD::FMAX3: 9508 case AMDGPUISD::FMIN3: { 9509 // FIXME: Shouldn't treat the generic operations different based these. 9510 // However, we aren't really required to flush the result from 9511 // minnum/maxnum.. 9512 9513 // snans will be quieted, so we only need to worry about denormals. 9514 if (Subtarget->supportsMinMaxDenormModes() || 9515 denormalsEnabledForType(DAG, Op.getValueType())) 9516 return true; 9517 9518 // Flushing may be required. 9519 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9520 // targets need to check their input recursively. 9521 9522 // FIXME: Does this apply with clamp? It's implemented with max. 9523 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9524 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9525 return false; 9526 } 9527 9528 return true; 9529 } 9530 case ISD::SELECT: { 9531 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9532 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9533 } 9534 case ISD::BUILD_VECTOR: { 9535 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9536 SDValue SrcOp = Op.getOperand(i); 9537 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9538 return false; 9539 } 9540 9541 return true; 9542 } 9543 case ISD::EXTRACT_VECTOR_ELT: 9544 case ISD::EXTRACT_SUBVECTOR: { 9545 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9546 } 9547 case ISD::INSERT_VECTOR_ELT: { 9548 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9549 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9550 } 9551 case ISD::UNDEF: 9552 // Could be anything. 9553 return false; 9554 9555 case ISD::BITCAST: { 9556 // Hack round the mess we make when legalizing extract_vector_elt 9557 SDValue Src = Op.getOperand(0); 9558 if (Src.getValueType() == MVT::i16 && 9559 Src.getOpcode() == ISD::TRUNCATE) { 9560 SDValue TruncSrc = Src.getOperand(0); 9561 if (TruncSrc.getValueType() == MVT::i32 && 9562 TruncSrc.getOpcode() == ISD::BITCAST && 9563 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9564 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9565 } 9566 } 9567 9568 return false; 9569 } 9570 case ISD::INTRINSIC_WO_CHAIN: { 9571 unsigned IntrinsicID 9572 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9573 // TODO: Handle more intrinsics 9574 switch (IntrinsicID) { 9575 case Intrinsic::amdgcn_cvt_pkrtz: 9576 case Intrinsic::amdgcn_cubeid: 9577 case Intrinsic::amdgcn_frexp_mant: 9578 case Intrinsic::amdgcn_fdot2: 9579 case Intrinsic::amdgcn_rcp: 9580 case Intrinsic::amdgcn_rsq: 9581 case Intrinsic::amdgcn_rsq_clamp: 9582 case Intrinsic::amdgcn_rcp_legacy: 9583 case Intrinsic::amdgcn_rsq_legacy: 9584 case Intrinsic::amdgcn_trig_preop: 9585 return true; 9586 default: 9587 break; 9588 } 9589 9590 LLVM_FALLTHROUGH; 9591 } 9592 default: 9593 return denormalsEnabledForType(DAG, Op.getValueType()) && 9594 DAG.isKnownNeverSNaN(Op); 9595 } 9596 9597 llvm_unreachable("invalid operation"); 9598 } 9599 9600 // Constant fold canonicalize. 9601 SDValue SITargetLowering::getCanonicalConstantFP( 9602 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9603 // Flush denormals to 0 if not enabled. 9604 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9605 return DAG.getConstantFP(0.0, SL, VT); 9606 9607 if (C.isNaN()) { 9608 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9609 if (C.isSignaling()) { 9610 // Quiet a signaling NaN. 9611 // FIXME: Is this supposed to preserve payload bits? 9612 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9613 } 9614 9615 // Make sure it is the canonical NaN bitpattern. 9616 // 9617 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9618 // immediate? 9619 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9620 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9621 } 9622 9623 // Already canonical. 9624 return DAG.getConstantFP(C, SL, VT); 9625 } 9626 9627 static bool vectorEltWillFoldAway(SDValue Op) { 9628 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9629 } 9630 9631 SDValue SITargetLowering::performFCanonicalizeCombine( 9632 SDNode *N, 9633 DAGCombinerInfo &DCI) const { 9634 SelectionDAG &DAG = DCI.DAG; 9635 SDValue N0 = N->getOperand(0); 9636 EVT VT = N->getValueType(0); 9637 9638 // fcanonicalize undef -> qnan 9639 if (N0.isUndef()) { 9640 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9641 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9642 } 9643 9644 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9645 EVT VT = N->getValueType(0); 9646 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9647 } 9648 9649 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9650 // (fcanonicalize k) 9651 // 9652 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9653 9654 // TODO: This could be better with wider vectors that will be split to v2f16, 9655 // and to consider uses since there aren't that many packed operations. 9656 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9657 isTypeLegal(MVT::v2f16)) { 9658 SDLoc SL(N); 9659 SDValue NewElts[2]; 9660 SDValue Lo = N0.getOperand(0); 9661 SDValue Hi = N0.getOperand(1); 9662 EVT EltVT = Lo.getValueType(); 9663 9664 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9665 for (unsigned I = 0; I != 2; ++I) { 9666 SDValue Op = N0.getOperand(I); 9667 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9668 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9669 CFP->getValueAPF()); 9670 } else if (Op.isUndef()) { 9671 // Handled below based on what the other operand is. 9672 NewElts[I] = Op; 9673 } else { 9674 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9675 } 9676 } 9677 9678 // If one half is undef, and one is constant, perfer a splat vector rather 9679 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9680 // cheaper to use and may be free with a packed operation. 9681 if (NewElts[0].isUndef()) { 9682 if (isa<ConstantFPSDNode>(NewElts[1])) 9683 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9684 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9685 } 9686 9687 if (NewElts[1].isUndef()) { 9688 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9689 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9690 } 9691 9692 return DAG.getBuildVector(VT, SL, NewElts); 9693 } 9694 } 9695 9696 unsigned SrcOpc = N0.getOpcode(); 9697 9698 // If it's free to do so, push canonicalizes further up the source, which may 9699 // find a canonical source. 9700 // 9701 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9702 // sNaNs. 9703 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9704 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9705 if (CRHS && N0.hasOneUse()) { 9706 SDLoc SL(N); 9707 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9708 N0.getOperand(0)); 9709 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9710 DCI.AddToWorklist(Canon0.getNode()); 9711 9712 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9713 } 9714 } 9715 9716 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9717 } 9718 9719 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9720 switch (Opc) { 9721 case ISD::FMAXNUM: 9722 case ISD::FMAXNUM_IEEE: 9723 return AMDGPUISD::FMAX3; 9724 case ISD::SMAX: 9725 return AMDGPUISD::SMAX3; 9726 case ISD::UMAX: 9727 return AMDGPUISD::UMAX3; 9728 case ISD::FMINNUM: 9729 case ISD::FMINNUM_IEEE: 9730 return AMDGPUISD::FMIN3; 9731 case ISD::SMIN: 9732 return AMDGPUISD::SMIN3; 9733 case ISD::UMIN: 9734 return AMDGPUISD::UMIN3; 9735 default: 9736 llvm_unreachable("Not a min/max opcode"); 9737 } 9738 } 9739 9740 SDValue SITargetLowering::performIntMed3ImmCombine( 9741 SelectionDAG &DAG, const SDLoc &SL, 9742 SDValue Op0, SDValue Op1, bool Signed) const { 9743 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9744 if (!K1) 9745 return SDValue(); 9746 9747 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9748 if (!K0) 9749 return SDValue(); 9750 9751 if (Signed) { 9752 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9753 return SDValue(); 9754 } else { 9755 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9756 return SDValue(); 9757 } 9758 9759 EVT VT = K0->getValueType(0); 9760 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9761 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9762 return DAG.getNode(Med3Opc, SL, VT, 9763 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9764 } 9765 9766 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9767 MVT NVT = MVT::i32; 9768 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9769 9770 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9771 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9772 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9773 9774 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9775 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9776 } 9777 9778 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9779 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9780 return C; 9781 9782 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9783 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9784 return C; 9785 } 9786 9787 return nullptr; 9788 } 9789 9790 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9791 const SDLoc &SL, 9792 SDValue Op0, 9793 SDValue Op1) const { 9794 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9795 if (!K1) 9796 return SDValue(); 9797 9798 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9799 if (!K0) 9800 return SDValue(); 9801 9802 // Ordered >= (although NaN inputs should have folded away by now). 9803 if (K0->getValueAPF() > K1->getValueAPF()) 9804 return SDValue(); 9805 9806 const MachineFunction &MF = DAG.getMachineFunction(); 9807 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9808 9809 // TODO: Check IEEE bit enabled? 9810 EVT VT = Op0.getValueType(); 9811 if (Info->getMode().DX10Clamp) { 9812 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9813 // hardware fmed3 behavior converting to a min. 9814 // FIXME: Should this be allowing -0.0? 9815 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9816 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9817 } 9818 9819 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9820 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9821 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9822 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9823 // then give the other result, which is different from med3 with a NaN 9824 // input. 9825 SDValue Var = Op0.getOperand(0); 9826 if (!DAG.isKnownNeverSNaN(Var)) 9827 return SDValue(); 9828 9829 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9830 9831 if ((!K0->hasOneUse() || 9832 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9833 (!K1->hasOneUse() || 9834 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9835 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9836 Var, SDValue(K0, 0), SDValue(K1, 0)); 9837 } 9838 } 9839 9840 return SDValue(); 9841 } 9842 9843 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9844 DAGCombinerInfo &DCI) const { 9845 SelectionDAG &DAG = DCI.DAG; 9846 9847 EVT VT = N->getValueType(0); 9848 unsigned Opc = N->getOpcode(); 9849 SDValue Op0 = N->getOperand(0); 9850 SDValue Op1 = N->getOperand(1); 9851 9852 // Only do this if the inner op has one use since this will just increases 9853 // register pressure for no benefit. 9854 9855 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9856 !VT.isVector() && 9857 (VT == MVT::i32 || VT == MVT::f32 || 9858 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9859 // max(max(a, b), c) -> max3(a, b, c) 9860 // min(min(a, b), c) -> min3(a, b, c) 9861 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9862 SDLoc DL(N); 9863 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9864 DL, 9865 N->getValueType(0), 9866 Op0.getOperand(0), 9867 Op0.getOperand(1), 9868 Op1); 9869 } 9870 9871 // Try commuted. 9872 // max(a, max(b, c)) -> max3(a, b, c) 9873 // min(a, min(b, c)) -> min3(a, b, c) 9874 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9875 SDLoc DL(N); 9876 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9877 DL, 9878 N->getValueType(0), 9879 Op0, 9880 Op1.getOperand(0), 9881 Op1.getOperand(1)); 9882 } 9883 } 9884 9885 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9886 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9887 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9888 return Med3; 9889 } 9890 9891 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9892 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9893 return Med3; 9894 } 9895 9896 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9897 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9898 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9899 (Opc == AMDGPUISD::FMIN_LEGACY && 9900 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9901 (VT == MVT::f32 || VT == MVT::f64 || 9902 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9903 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9904 Op0.hasOneUse()) { 9905 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9906 return Res; 9907 } 9908 9909 return SDValue(); 9910 } 9911 9912 static bool isClampZeroToOne(SDValue A, SDValue B) { 9913 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9914 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9915 // FIXME: Should this be allowing -0.0? 9916 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9917 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9918 } 9919 } 9920 9921 return false; 9922 } 9923 9924 // FIXME: Should only worry about snans for version with chain. 9925 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9926 DAGCombinerInfo &DCI) const { 9927 EVT VT = N->getValueType(0); 9928 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9929 // NaNs. With a NaN input, the order of the operands may change the result. 9930 9931 SelectionDAG &DAG = DCI.DAG; 9932 SDLoc SL(N); 9933 9934 SDValue Src0 = N->getOperand(0); 9935 SDValue Src1 = N->getOperand(1); 9936 SDValue Src2 = N->getOperand(2); 9937 9938 if (isClampZeroToOne(Src0, Src1)) { 9939 // const_a, const_b, x -> clamp is safe in all cases including signaling 9940 // nans. 9941 // FIXME: Should this be allowing -0.0? 9942 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9943 } 9944 9945 const MachineFunction &MF = DAG.getMachineFunction(); 9946 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9947 9948 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9949 // handling no dx10-clamp? 9950 if (Info->getMode().DX10Clamp) { 9951 // If NaNs is clamped to 0, we are free to reorder the inputs. 9952 9953 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9954 std::swap(Src0, Src1); 9955 9956 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9957 std::swap(Src1, Src2); 9958 9959 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9960 std::swap(Src0, Src1); 9961 9962 if (isClampZeroToOne(Src1, Src2)) 9963 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9964 } 9965 9966 return SDValue(); 9967 } 9968 9969 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9970 DAGCombinerInfo &DCI) const { 9971 SDValue Src0 = N->getOperand(0); 9972 SDValue Src1 = N->getOperand(1); 9973 if (Src0.isUndef() && Src1.isUndef()) 9974 return DCI.DAG.getUNDEF(N->getValueType(0)); 9975 return SDValue(); 9976 } 9977 9978 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9979 // expanded into a set of cmp/select instructions. 9980 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9981 unsigned NumElem, 9982 bool IsDivergentIdx) { 9983 if (UseDivergentRegisterIndexing) 9984 return false; 9985 9986 unsigned VecSize = EltSize * NumElem; 9987 9988 // Sub-dword vectors of size 2 dword or less have better implementation. 9989 if (VecSize <= 64 && EltSize < 32) 9990 return false; 9991 9992 // Always expand the rest of sub-dword instructions, otherwise it will be 9993 // lowered via memory. 9994 if (EltSize < 32) 9995 return true; 9996 9997 // Always do this if var-idx is divergent, otherwise it will become a loop. 9998 if (IsDivergentIdx) 9999 return true; 10000 10001 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10002 unsigned NumInsts = NumElem /* Number of compares */ + 10003 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10004 return NumInsts <= 16; 10005 } 10006 10007 static bool shouldExpandVectorDynExt(SDNode *N) { 10008 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10009 if (isa<ConstantSDNode>(Idx)) 10010 return false; 10011 10012 SDValue Vec = N->getOperand(0); 10013 EVT VecVT = Vec.getValueType(); 10014 EVT EltVT = VecVT.getVectorElementType(); 10015 unsigned EltSize = EltVT.getSizeInBits(); 10016 unsigned NumElem = VecVT.getVectorNumElements(); 10017 10018 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10019 Idx->isDivergent()); 10020 } 10021 10022 SDValue SITargetLowering::performExtractVectorEltCombine( 10023 SDNode *N, DAGCombinerInfo &DCI) const { 10024 SDValue Vec = N->getOperand(0); 10025 SelectionDAG &DAG = DCI.DAG; 10026 10027 EVT VecVT = Vec.getValueType(); 10028 EVT EltVT = VecVT.getVectorElementType(); 10029 10030 if ((Vec.getOpcode() == ISD::FNEG || 10031 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10032 SDLoc SL(N); 10033 EVT EltVT = N->getValueType(0); 10034 SDValue Idx = N->getOperand(1); 10035 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10036 Vec.getOperand(0), Idx); 10037 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10038 } 10039 10040 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10041 // => 10042 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10043 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10044 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10045 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10046 SDLoc SL(N); 10047 EVT EltVT = N->getValueType(0); 10048 SDValue Idx = N->getOperand(1); 10049 unsigned Opc = Vec.getOpcode(); 10050 10051 switch(Opc) { 10052 default: 10053 break; 10054 // TODO: Support other binary operations. 10055 case ISD::FADD: 10056 case ISD::FSUB: 10057 case ISD::FMUL: 10058 case ISD::ADD: 10059 case ISD::UMIN: 10060 case ISD::UMAX: 10061 case ISD::SMIN: 10062 case ISD::SMAX: 10063 case ISD::FMAXNUM: 10064 case ISD::FMINNUM: 10065 case ISD::FMAXNUM_IEEE: 10066 case ISD::FMINNUM_IEEE: { 10067 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10068 Vec.getOperand(0), Idx); 10069 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10070 Vec.getOperand(1), Idx); 10071 10072 DCI.AddToWorklist(Elt0.getNode()); 10073 DCI.AddToWorklist(Elt1.getNode()); 10074 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10075 } 10076 } 10077 } 10078 10079 unsigned VecSize = VecVT.getSizeInBits(); 10080 unsigned EltSize = EltVT.getSizeInBits(); 10081 10082 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10083 if (::shouldExpandVectorDynExt(N)) { 10084 SDLoc SL(N); 10085 SDValue Idx = N->getOperand(1); 10086 SDValue V; 10087 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10088 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10089 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10090 if (I == 0) 10091 V = Elt; 10092 else 10093 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10094 } 10095 return V; 10096 } 10097 10098 if (!DCI.isBeforeLegalize()) 10099 return SDValue(); 10100 10101 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10102 // elements. This exposes more load reduction opportunities by replacing 10103 // multiple small extract_vector_elements with a single 32-bit extract. 10104 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10105 if (isa<MemSDNode>(Vec) && 10106 EltSize <= 16 && 10107 EltVT.isByteSized() && 10108 VecSize > 32 && 10109 VecSize % 32 == 0 && 10110 Idx) { 10111 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10112 10113 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10114 unsigned EltIdx = BitIndex / 32; 10115 unsigned LeftoverBitIdx = BitIndex % 32; 10116 SDLoc SL(N); 10117 10118 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10119 DCI.AddToWorklist(Cast.getNode()); 10120 10121 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10122 DAG.getConstant(EltIdx, SL, MVT::i32)); 10123 DCI.AddToWorklist(Elt.getNode()); 10124 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10125 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10126 DCI.AddToWorklist(Srl.getNode()); 10127 10128 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10129 DCI.AddToWorklist(Trunc.getNode()); 10130 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10131 } 10132 10133 return SDValue(); 10134 } 10135 10136 SDValue 10137 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10138 DAGCombinerInfo &DCI) const { 10139 SDValue Vec = N->getOperand(0); 10140 SDValue Idx = N->getOperand(2); 10141 EVT VecVT = Vec.getValueType(); 10142 EVT EltVT = VecVT.getVectorElementType(); 10143 10144 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10145 // => BUILD_VECTOR n x select (e, const-idx) 10146 if (!::shouldExpandVectorDynExt(N)) 10147 return SDValue(); 10148 10149 SelectionDAG &DAG = DCI.DAG; 10150 SDLoc SL(N); 10151 SDValue Ins = N->getOperand(1); 10152 EVT IdxVT = Idx.getValueType(); 10153 10154 SmallVector<SDValue, 16> Ops; 10155 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10156 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10157 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10158 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10159 Ops.push_back(V); 10160 } 10161 10162 return DAG.getBuildVector(VecVT, SL, Ops); 10163 } 10164 10165 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10166 const SDNode *N0, 10167 const SDNode *N1) const { 10168 EVT VT = N0->getValueType(0); 10169 10170 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10171 // support denormals ever. 10172 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10173 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10174 getSubtarget()->hasMadF16())) && 10175 isOperationLegal(ISD::FMAD, VT)) 10176 return ISD::FMAD; 10177 10178 const TargetOptions &Options = DAG.getTarget().Options; 10179 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10180 (N0->getFlags().hasAllowContract() && 10181 N1->getFlags().hasAllowContract())) && 10182 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10183 return ISD::FMA; 10184 } 10185 10186 return 0; 10187 } 10188 10189 // For a reassociatable opcode perform: 10190 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10191 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10192 SelectionDAG &DAG) const { 10193 EVT VT = N->getValueType(0); 10194 if (VT != MVT::i32 && VT != MVT::i64) 10195 return SDValue(); 10196 10197 unsigned Opc = N->getOpcode(); 10198 SDValue Op0 = N->getOperand(0); 10199 SDValue Op1 = N->getOperand(1); 10200 10201 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10202 return SDValue(); 10203 10204 if (Op0->isDivergent()) 10205 std::swap(Op0, Op1); 10206 10207 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10208 return SDValue(); 10209 10210 SDValue Op2 = Op1.getOperand(1); 10211 Op1 = Op1.getOperand(0); 10212 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10213 return SDValue(); 10214 10215 if (Op1->isDivergent()) 10216 std::swap(Op1, Op2); 10217 10218 // If either operand is constant this will conflict with 10219 // DAGCombiner::ReassociateOps(). 10220 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10221 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10222 return SDValue(); 10223 10224 SDLoc SL(N); 10225 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10226 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10227 } 10228 10229 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10230 EVT VT, 10231 SDValue N0, SDValue N1, SDValue N2, 10232 bool Signed) { 10233 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10234 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10235 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10236 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10237 } 10238 10239 SDValue SITargetLowering::performAddCombine(SDNode *N, 10240 DAGCombinerInfo &DCI) const { 10241 SelectionDAG &DAG = DCI.DAG; 10242 EVT VT = N->getValueType(0); 10243 SDLoc SL(N); 10244 SDValue LHS = N->getOperand(0); 10245 SDValue RHS = N->getOperand(1); 10246 10247 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10248 && Subtarget->hasMad64_32() && 10249 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10250 VT.getScalarSizeInBits() <= 64) { 10251 if (LHS.getOpcode() != ISD::MUL) 10252 std::swap(LHS, RHS); 10253 10254 SDValue MulLHS = LHS.getOperand(0); 10255 SDValue MulRHS = LHS.getOperand(1); 10256 SDValue AddRHS = RHS; 10257 10258 // TODO: Maybe restrict if SGPR inputs. 10259 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10260 numBitsUnsigned(MulRHS, DAG) <= 32) { 10261 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10262 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10263 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10264 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10265 } 10266 10267 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10268 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10269 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10270 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10271 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10272 } 10273 10274 return SDValue(); 10275 } 10276 10277 if (SDValue V = reassociateScalarOps(N, DAG)) { 10278 return V; 10279 } 10280 10281 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10282 return SDValue(); 10283 10284 // add x, zext (setcc) => addcarry x, 0, setcc 10285 // add x, sext (setcc) => subcarry x, 0, setcc 10286 unsigned Opc = LHS.getOpcode(); 10287 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10288 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10289 std::swap(RHS, LHS); 10290 10291 Opc = RHS.getOpcode(); 10292 switch (Opc) { 10293 default: break; 10294 case ISD::ZERO_EXTEND: 10295 case ISD::SIGN_EXTEND: 10296 case ISD::ANY_EXTEND: { 10297 auto Cond = RHS.getOperand(0); 10298 // If this won't be a real VOPC output, we would still need to insert an 10299 // extra instruction anyway. 10300 if (!isBoolSGPR(Cond)) 10301 break; 10302 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10303 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10304 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10305 return DAG.getNode(Opc, SL, VTList, Args); 10306 } 10307 case ISD::ADDCARRY: { 10308 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10309 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10310 if (!C || C->getZExtValue() != 0) break; 10311 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10312 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10313 } 10314 } 10315 return SDValue(); 10316 } 10317 10318 SDValue SITargetLowering::performSubCombine(SDNode *N, 10319 DAGCombinerInfo &DCI) const { 10320 SelectionDAG &DAG = DCI.DAG; 10321 EVT VT = N->getValueType(0); 10322 10323 if (VT != MVT::i32) 10324 return SDValue(); 10325 10326 SDLoc SL(N); 10327 SDValue LHS = N->getOperand(0); 10328 SDValue RHS = N->getOperand(1); 10329 10330 // sub x, zext (setcc) => subcarry x, 0, setcc 10331 // sub x, sext (setcc) => addcarry x, 0, setcc 10332 unsigned Opc = RHS.getOpcode(); 10333 switch (Opc) { 10334 default: break; 10335 case ISD::ZERO_EXTEND: 10336 case ISD::SIGN_EXTEND: 10337 case ISD::ANY_EXTEND: { 10338 auto Cond = RHS.getOperand(0); 10339 // If this won't be a real VOPC output, we would still need to insert an 10340 // extra instruction anyway. 10341 if (!isBoolSGPR(Cond)) 10342 break; 10343 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10344 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10345 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10346 return DAG.getNode(Opc, SL, VTList, Args); 10347 } 10348 } 10349 10350 if (LHS.getOpcode() == ISD::SUBCARRY) { 10351 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10352 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10353 if (!C || !C->isNullValue()) 10354 return SDValue(); 10355 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10356 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10357 } 10358 return SDValue(); 10359 } 10360 10361 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10362 DAGCombinerInfo &DCI) const { 10363 10364 if (N->getValueType(0) != MVT::i32) 10365 return SDValue(); 10366 10367 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10368 if (!C || C->getZExtValue() != 0) 10369 return SDValue(); 10370 10371 SelectionDAG &DAG = DCI.DAG; 10372 SDValue LHS = N->getOperand(0); 10373 10374 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10375 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10376 unsigned LHSOpc = LHS.getOpcode(); 10377 unsigned Opc = N->getOpcode(); 10378 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10379 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10380 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10381 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10382 } 10383 return SDValue(); 10384 } 10385 10386 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10387 DAGCombinerInfo &DCI) const { 10388 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10389 return SDValue(); 10390 10391 SelectionDAG &DAG = DCI.DAG; 10392 EVT VT = N->getValueType(0); 10393 10394 SDLoc SL(N); 10395 SDValue LHS = N->getOperand(0); 10396 SDValue RHS = N->getOperand(1); 10397 10398 // These should really be instruction patterns, but writing patterns with 10399 // source modiifiers is a pain. 10400 10401 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10402 if (LHS.getOpcode() == ISD::FADD) { 10403 SDValue A = LHS.getOperand(0); 10404 if (A == LHS.getOperand(1)) { 10405 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10406 if (FusedOp != 0) { 10407 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10408 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10409 } 10410 } 10411 } 10412 10413 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10414 if (RHS.getOpcode() == ISD::FADD) { 10415 SDValue A = RHS.getOperand(0); 10416 if (A == RHS.getOperand(1)) { 10417 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10418 if (FusedOp != 0) { 10419 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10420 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10421 } 10422 } 10423 } 10424 10425 return SDValue(); 10426 } 10427 10428 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10429 DAGCombinerInfo &DCI) const { 10430 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10431 return SDValue(); 10432 10433 SelectionDAG &DAG = DCI.DAG; 10434 SDLoc SL(N); 10435 EVT VT = N->getValueType(0); 10436 assert(!VT.isVector()); 10437 10438 // Try to get the fneg to fold into the source modifier. This undoes generic 10439 // DAG combines and folds them into the mad. 10440 // 10441 // Only do this if we are not trying to support denormals. v_mad_f32 does 10442 // not support denormals ever. 10443 SDValue LHS = N->getOperand(0); 10444 SDValue RHS = N->getOperand(1); 10445 if (LHS.getOpcode() == ISD::FADD) { 10446 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10447 SDValue A = LHS.getOperand(0); 10448 if (A == LHS.getOperand(1)) { 10449 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10450 if (FusedOp != 0){ 10451 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10452 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10453 10454 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10455 } 10456 } 10457 } 10458 10459 if (RHS.getOpcode() == ISD::FADD) { 10460 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10461 10462 SDValue A = RHS.getOperand(0); 10463 if (A == RHS.getOperand(1)) { 10464 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10465 if (FusedOp != 0){ 10466 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10467 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10468 } 10469 } 10470 } 10471 10472 return SDValue(); 10473 } 10474 10475 SDValue SITargetLowering::performFMACombine(SDNode *N, 10476 DAGCombinerInfo &DCI) const { 10477 SelectionDAG &DAG = DCI.DAG; 10478 EVT VT = N->getValueType(0); 10479 SDLoc SL(N); 10480 10481 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10482 return SDValue(); 10483 10484 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10485 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10486 SDValue Op1 = N->getOperand(0); 10487 SDValue Op2 = N->getOperand(1); 10488 SDValue FMA = N->getOperand(2); 10489 10490 if (FMA.getOpcode() != ISD::FMA || 10491 Op1.getOpcode() != ISD::FP_EXTEND || 10492 Op2.getOpcode() != ISD::FP_EXTEND) 10493 return SDValue(); 10494 10495 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10496 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10497 // is sufficient to allow generaing fdot2. 10498 const TargetOptions &Options = DAG.getTarget().Options; 10499 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10500 (N->getFlags().hasAllowContract() && 10501 FMA->getFlags().hasAllowContract())) { 10502 Op1 = Op1.getOperand(0); 10503 Op2 = Op2.getOperand(0); 10504 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10505 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10506 return SDValue(); 10507 10508 SDValue Vec1 = Op1.getOperand(0); 10509 SDValue Idx1 = Op1.getOperand(1); 10510 SDValue Vec2 = Op2.getOperand(0); 10511 10512 SDValue FMAOp1 = FMA.getOperand(0); 10513 SDValue FMAOp2 = FMA.getOperand(1); 10514 SDValue FMAAcc = FMA.getOperand(2); 10515 10516 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10517 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10518 return SDValue(); 10519 10520 FMAOp1 = FMAOp1.getOperand(0); 10521 FMAOp2 = FMAOp2.getOperand(0); 10522 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10523 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10524 return SDValue(); 10525 10526 SDValue Vec3 = FMAOp1.getOperand(0); 10527 SDValue Vec4 = FMAOp2.getOperand(0); 10528 SDValue Idx2 = FMAOp1.getOperand(1); 10529 10530 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10531 // Idx1 and Idx2 cannot be the same. 10532 Idx1 == Idx2) 10533 return SDValue(); 10534 10535 if (Vec1 == Vec2 || Vec3 == Vec4) 10536 return SDValue(); 10537 10538 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10539 return SDValue(); 10540 10541 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10542 (Vec1 == Vec4 && Vec2 == Vec3)) { 10543 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10544 DAG.getTargetConstant(0, SL, MVT::i1)); 10545 } 10546 } 10547 return SDValue(); 10548 } 10549 10550 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10551 DAGCombinerInfo &DCI) const { 10552 SelectionDAG &DAG = DCI.DAG; 10553 SDLoc SL(N); 10554 10555 SDValue LHS = N->getOperand(0); 10556 SDValue RHS = N->getOperand(1); 10557 EVT VT = LHS.getValueType(); 10558 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10559 10560 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10561 if (!CRHS) { 10562 CRHS = dyn_cast<ConstantSDNode>(LHS); 10563 if (CRHS) { 10564 std::swap(LHS, RHS); 10565 CC = getSetCCSwappedOperands(CC); 10566 } 10567 } 10568 10569 if (CRHS) { 10570 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10571 isBoolSGPR(LHS.getOperand(0))) { 10572 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10573 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10574 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10575 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10576 if ((CRHS->isAllOnesValue() && 10577 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10578 (CRHS->isNullValue() && 10579 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10580 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10581 DAG.getConstant(-1, SL, MVT::i1)); 10582 if ((CRHS->isAllOnesValue() && 10583 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10584 (CRHS->isNullValue() && 10585 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10586 return LHS.getOperand(0); 10587 } 10588 10589 uint64_t CRHSVal = CRHS->getZExtValue(); 10590 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10591 LHS.getOpcode() == ISD::SELECT && 10592 isa<ConstantSDNode>(LHS.getOperand(1)) && 10593 isa<ConstantSDNode>(LHS.getOperand(2)) && 10594 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10595 isBoolSGPR(LHS.getOperand(0))) { 10596 // Given CT != FT: 10597 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10598 // setcc (select cc, CT, CF), CF, ne => cc 10599 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10600 // setcc (select cc, CT, CF), CT, eq => cc 10601 uint64_t CT = LHS.getConstantOperandVal(1); 10602 uint64_t CF = LHS.getConstantOperandVal(2); 10603 10604 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10605 (CT == CRHSVal && CC == ISD::SETNE)) 10606 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10607 DAG.getConstant(-1, SL, MVT::i1)); 10608 if ((CF == CRHSVal && CC == ISD::SETNE) || 10609 (CT == CRHSVal && CC == ISD::SETEQ)) 10610 return LHS.getOperand(0); 10611 } 10612 } 10613 10614 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10615 VT != MVT::f16)) 10616 return SDValue(); 10617 10618 // Match isinf/isfinite pattern 10619 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10620 // (fcmp one (fabs x), inf) -> (fp_class x, 10621 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10622 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10623 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10624 if (!CRHS) 10625 return SDValue(); 10626 10627 const APFloat &APF = CRHS->getValueAPF(); 10628 if (APF.isInfinity() && !APF.isNegative()) { 10629 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10630 SIInstrFlags::N_INFINITY; 10631 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10632 SIInstrFlags::P_ZERO | 10633 SIInstrFlags::N_NORMAL | 10634 SIInstrFlags::P_NORMAL | 10635 SIInstrFlags::N_SUBNORMAL | 10636 SIInstrFlags::P_SUBNORMAL; 10637 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10638 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10639 DAG.getConstant(Mask, SL, MVT::i32)); 10640 } 10641 } 10642 10643 return SDValue(); 10644 } 10645 10646 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10647 DAGCombinerInfo &DCI) const { 10648 SelectionDAG &DAG = DCI.DAG; 10649 SDLoc SL(N); 10650 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10651 10652 SDValue Src = N->getOperand(0); 10653 SDValue Shift = N->getOperand(0); 10654 10655 // TODO: Extend type shouldn't matter (assuming legal types). 10656 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10657 Shift = Shift.getOperand(0); 10658 10659 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10660 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10661 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10662 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10663 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10664 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10665 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10666 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10667 SDLoc(Shift.getOperand(0)), MVT::i32); 10668 10669 unsigned ShiftOffset = 8 * Offset; 10670 if (Shift.getOpcode() == ISD::SHL) 10671 ShiftOffset -= C->getZExtValue(); 10672 else 10673 ShiftOffset += C->getZExtValue(); 10674 10675 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10676 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10677 MVT::f32, Shift); 10678 } 10679 } 10680 } 10681 10682 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10683 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10684 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10685 // We simplified Src. If this node is not dead, visit it again so it is 10686 // folded properly. 10687 if (N->getOpcode() != ISD::DELETED_NODE) 10688 DCI.AddToWorklist(N); 10689 return SDValue(N, 0); 10690 } 10691 10692 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10693 if (SDValue DemandedSrc = 10694 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10695 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10696 10697 return SDValue(); 10698 } 10699 10700 SDValue SITargetLowering::performClampCombine(SDNode *N, 10701 DAGCombinerInfo &DCI) const { 10702 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10703 if (!CSrc) 10704 return SDValue(); 10705 10706 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10707 const APFloat &F = CSrc->getValueAPF(); 10708 APFloat Zero = APFloat::getZero(F.getSemantics()); 10709 if (F < Zero || 10710 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10711 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10712 } 10713 10714 APFloat One(F.getSemantics(), "1.0"); 10715 if (F > One) 10716 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10717 10718 return SDValue(CSrc, 0); 10719 } 10720 10721 10722 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10723 DAGCombinerInfo &DCI) const { 10724 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10725 return SDValue(); 10726 switch (N->getOpcode()) { 10727 case ISD::ADD: 10728 return performAddCombine(N, DCI); 10729 case ISD::SUB: 10730 return performSubCombine(N, DCI); 10731 case ISD::ADDCARRY: 10732 case ISD::SUBCARRY: 10733 return performAddCarrySubCarryCombine(N, DCI); 10734 case ISD::FADD: 10735 return performFAddCombine(N, DCI); 10736 case ISD::FSUB: 10737 return performFSubCombine(N, DCI); 10738 case ISD::SETCC: 10739 return performSetCCCombine(N, DCI); 10740 case ISD::FMAXNUM: 10741 case ISD::FMINNUM: 10742 case ISD::FMAXNUM_IEEE: 10743 case ISD::FMINNUM_IEEE: 10744 case ISD::SMAX: 10745 case ISD::SMIN: 10746 case ISD::UMAX: 10747 case ISD::UMIN: 10748 case AMDGPUISD::FMIN_LEGACY: 10749 case AMDGPUISD::FMAX_LEGACY: 10750 return performMinMaxCombine(N, DCI); 10751 case ISD::FMA: 10752 return performFMACombine(N, DCI); 10753 case ISD::AND: 10754 return performAndCombine(N, DCI); 10755 case ISD::OR: 10756 return performOrCombine(N, DCI); 10757 case ISD::XOR: 10758 return performXorCombine(N, DCI); 10759 case ISD::ZERO_EXTEND: 10760 return performZeroExtendCombine(N, DCI); 10761 case ISD::SIGN_EXTEND_INREG: 10762 return performSignExtendInRegCombine(N , DCI); 10763 case AMDGPUISD::FP_CLASS: 10764 return performClassCombine(N, DCI); 10765 case ISD::FCANONICALIZE: 10766 return performFCanonicalizeCombine(N, DCI); 10767 case AMDGPUISD::RCP: 10768 return performRcpCombine(N, DCI); 10769 case AMDGPUISD::FRACT: 10770 case AMDGPUISD::RSQ: 10771 case AMDGPUISD::RCP_LEGACY: 10772 case AMDGPUISD::RCP_IFLAG: 10773 case AMDGPUISD::RSQ_CLAMP: 10774 case AMDGPUISD::LDEXP: { 10775 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10776 SDValue Src = N->getOperand(0); 10777 if (Src.isUndef()) 10778 return Src; 10779 break; 10780 } 10781 case ISD::SINT_TO_FP: 10782 case ISD::UINT_TO_FP: 10783 return performUCharToFloatCombine(N, DCI); 10784 case AMDGPUISD::CVT_F32_UBYTE0: 10785 case AMDGPUISD::CVT_F32_UBYTE1: 10786 case AMDGPUISD::CVT_F32_UBYTE2: 10787 case AMDGPUISD::CVT_F32_UBYTE3: 10788 return performCvtF32UByteNCombine(N, DCI); 10789 case AMDGPUISD::FMED3: 10790 return performFMed3Combine(N, DCI); 10791 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10792 return performCvtPkRTZCombine(N, DCI); 10793 case AMDGPUISD::CLAMP: 10794 return performClampCombine(N, DCI); 10795 case ISD::SCALAR_TO_VECTOR: { 10796 SelectionDAG &DAG = DCI.DAG; 10797 EVT VT = N->getValueType(0); 10798 10799 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10800 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10801 SDLoc SL(N); 10802 SDValue Src = N->getOperand(0); 10803 EVT EltVT = Src.getValueType(); 10804 if (EltVT == MVT::f16) 10805 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10806 10807 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10808 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10809 } 10810 10811 break; 10812 } 10813 case ISD::EXTRACT_VECTOR_ELT: 10814 return performExtractVectorEltCombine(N, DCI); 10815 case ISD::INSERT_VECTOR_ELT: 10816 return performInsertVectorEltCombine(N, DCI); 10817 case ISD::LOAD: { 10818 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10819 return Widended; 10820 LLVM_FALLTHROUGH; 10821 } 10822 default: { 10823 if (!DCI.isBeforeLegalize()) { 10824 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10825 return performMemSDNodeCombine(MemNode, DCI); 10826 } 10827 10828 break; 10829 } 10830 } 10831 10832 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10833 } 10834 10835 /// Helper function for adjustWritemask 10836 static unsigned SubIdx2Lane(unsigned Idx) { 10837 switch (Idx) { 10838 default: return 0; 10839 case AMDGPU::sub0: return 0; 10840 case AMDGPU::sub1: return 1; 10841 case AMDGPU::sub2: return 2; 10842 case AMDGPU::sub3: return 3; 10843 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10844 } 10845 } 10846 10847 /// Adjust the writemask of MIMG instructions 10848 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10849 SelectionDAG &DAG) const { 10850 unsigned Opcode = Node->getMachineOpcode(); 10851 10852 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10853 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10854 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10855 return Node; // not implemented for D16 10856 10857 SDNode *Users[5] = { nullptr }; 10858 unsigned Lane = 0; 10859 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10860 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10861 unsigned NewDmask = 0; 10862 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10863 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10864 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10865 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10866 unsigned TFCLane = 0; 10867 bool HasChain = Node->getNumValues() > 1; 10868 10869 if (OldDmask == 0) { 10870 // These are folded out, but on the chance it happens don't assert. 10871 return Node; 10872 } 10873 10874 unsigned OldBitsSet = countPopulation(OldDmask); 10875 // Work out which is the TFE/LWE lane if that is enabled. 10876 if (UsesTFC) { 10877 TFCLane = OldBitsSet; 10878 } 10879 10880 // Try to figure out the used register components 10881 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10882 I != E; ++I) { 10883 10884 // Don't look at users of the chain. 10885 if (I.getUse().getResNo() != 0) 10886 continue; 10887 10888 // Abort if we can't understand the usage 10889 if (!I->isMachineOpcode() || 10890 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10891 return Node; 10892 10893 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10894 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10895 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10896 // set, etc. 10897 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10898 10899 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10900 if (UsesTFC && Lane == TFCLane) { 10901 Users[Lane] = *I; 10902 } else { 10903 // Set which texture component corresponds to the lane. 10904 unsigned Comp; 10905 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10906 Comp = countTrailingZeros(Dmask); 10907 Dmask &= ~(1 << Comp); 10908 } 10909 10910 // Abort if we have more than one user per component. 10911 if (Users[Lane]) 10912 return Node; 10913 10914 Users[Lane] = *I; 10915 NewDmask |= 1 << Comp; 10916 } 10917 } 10918 10919 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10920 bool NoChannels = !NewDmask; 10921 if (NoChannels) { 10922 if (!UsesTFC) { 10923 // No uses of the result and not using TFC. Then do nothing. 10924 return Node; 10925 } 10926 // If the original dmask has one channel - then nothing to do 10927 if (OldBitsSet == 1) 10928 return Node; 10929 // Use an arbitrary dmask - required for the instruction to work 10930 NewDmask = 1; 10931 } 10932 // Abort if there's no change 10933 if (NewDmask == OldDmask) 10934 return Node; 10935 10936 unsigned BitsSet = countPopulation(NewDmask); 10937 10938 // Check for TFE or LWE - increase the number of channels by one to account 10939 // for the extra return value 10940 // This will need adjustment for D16 if this is also included in 10941 // adjustWriteMask (this function) but at present D16 are excluded. 10942 unsigned NewChannels = BitsSet + UsesTFC; 10943 10944 int NewOpcode = 10945 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10946 assert(NewOpcode != -1 && 10947 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10948 "failed to find equivalent MIMG op"); 10949 10950 // Adjust the writemask in the node 10951 SmallVector<SDValue, 12> Ops; 10952 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10953 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10954 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10955 10956 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10957 10958 MVT ResultVT = NewChannels == 1 ? 10959 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10960 NewChannels == 5 ? 8 : NewChannels); 10961 SDVTList NewVTList = HasChain ? 10962 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10963 10964 10965 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10966 NewVTList, Ops); 10967 10968 if (HasChain) { 10969 // Update chain. 10970 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10971 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10972 } 10973 10974 if (NewChannels == 1) { 10975 assert(Node->hasNUsesOfValue(1, 0)); 10976 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10977 SDLoc(Node), Users[Lane]->getValueType(0), 10978 SDValue(NewNode, 0)); 10979 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10980 return nullptr; 10981 } 10982 10983 // Update the users of the node with the new indices 10984 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10985 SDNode *User = Users[i]; 10986 if (!User) { 10987 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10988 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10989 if (i || !NoChannels) 10990 continue; 10991 } else { 10992 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10993 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10994 } 10995 10996 switch (Idx) { 10997 default: break; 10998 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10999 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11000 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11001 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11002 } 11003 } 11004 11005 DAG.RemoveDeadNode(Node); 11006 return nullptr; 11007 } 11008 11009 static bool isFrameIndexOp(SDValue Op) { 11010 if (Op.getOpcode() == ISD::AssertZext) 11011 Op = Op.getOperand(0); 11012 11013 return isa<FrameIndexSDNode>(Op); 11014 } 11015 11016 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11017 /// with frame index operands. 11018 /// LLVM assumes that inputs are to these instructions are registers. 11019 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11020 SelectionDAG &DAG) const { 11021 if (Node->getOpcode() == ISD::CopyToReg) { 11022 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11023 SDValue SrcVal = Node->getOperand(2); 11024 11025 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11026 // to try understanding copies to physical registers. 11027 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11028 SDLoc SL(Node); 11029 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11030 SDValue VReg = DAG.getRegister( 11031 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11032 11033 SDNode *Glued = Node->getGluedNode(); 11034 SDValue ToVReg 11035 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11036 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11037 SDValue ToResultReg 11038 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11039 VReg, ToVReg.getValue(1)); 11040 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11041 DAG.RemoveDeadNode(Node); 11042 return ToResultReg.getNode(); 11043 } 11044 } 11045 11046 SmallVector<SDValue, 8> Ops; 11047 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11048 if (!isFrameIndexOp(Node->getOperand(i))) { 11049 Ops.push_back(Node->getOperand(i)); 11050 continue; 11051 } 11052 11053 SDLoc DL(Node); 11054 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11055 Node->getOperand(i).getValueType(), 11056 Node->getOperand(i)), 0)); 11057 } 11058 11059 return DAG.UpdateNodeOperands(Node, Ops); 11060 } 11061 11062 /// Fold the instructions after selecting them. 11063 /// Returns null if users were already updated. 11064 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11065 SelectionDAG &DAG) const { 11066 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11067 unsigned Opcode = Node->getMachineOpcode(); 11068 11069 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11070 !TII->isGather4(Opcode) && 11071 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11072 return adjustWritemask(Node, DAG); 11073 } 11074 11075 if (Opcode == AMDGPU::INSERT_SUBREG || 11076 Opcode == AMDGPU::REG_SEQUENCE) { 11077 legalizeTargetIndependentNode(Node, DAG); 11078 return Node; 11079 } 11080 11081 switch (Opcode) { 11082 case AMDGPU::V_DIV_SCALE_F32: 11083 case AMDGPU::V_DIV_SCALE_F64: { 11084 // Satisfy the operand register constraint when one of the inputs is 11085 // undefined. Ordinarily each undef value will have its own implicit_def of 11086 // a vreg, so force these to use a single register. 11087 SDValue Src0 = Node->getOperand(0); 11088 SDValue Src1 = Node->getOperand(1); 11089 SDValue Src2 = Node->getOperand(2); 11090 11091 if ((Src0.isMachineOpcode() && 11092 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11093 (Src0 == Src1 || Src0 == Src2)) 11094 break; 11095 11096 MVT VT = Src0.getValueType().getSimpleVT(); 11097 const TargetRegisterClass *RC = 11098 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11099 11100 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11101 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11102 11103 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11104 UndefReg, Src0, SDValue()); 11105 11106 // src0 must be the same register as src1 or src2, even if the value is 11107 // undefined, so make sure we don't violate this constraint. 11108 if (Src0.isMachineOpcode() && 11109 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11110 if (Src1.isMachineOpcode() && 11111 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11112 Src0 = Src1; 11113 else if (Src2.isMachineOpcode() && 11114 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11115 Src0 = Src2; 11116 else { 11117 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11118 Src0 = UndefReg; 11119 Src1 = UndefReg; 11120 } 11121 } else 11122 break; 11123 11124 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 11125 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 11126 Ops.push_back(Node->getOperand(I)); 11127 11128 Ops.push_back(ImpDef.getValue(1)); 11129 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11130 } 11131 default: 11132 break; 11133 } 11134 11135 return Node; 11136 } 11137 11138 /// Assign the register class depending on the number of 11139 /// bits set in the writemask 11140 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11141 SDNode *Node) const { 11142 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11143 11144 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11145 11146 if (TII->isVOP3(MI.getOpcode())) { 11147 // Make sure constant bus requirements are respected. 11148 TII->legalizeOperandsVOP3(MRI, MI); 11149 11150 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11151 // This saves a chain-copy of registers and better ballance register 11152 // use between vgpr and agpr as agpr tuples tend to be big. 11153 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11154 unsigned Opc = MI.getOpcode(); 11155 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11156 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11157 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11158 if (I == -1) 11159 break; 11160 MachineOperand &Op = MI.getOperand(I); 11161 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11162 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11163 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11164 continue; 11165 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11166 if (!Src || !Src->isCopy() || 11167 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11168 continue; 11169 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11170 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11171 // All uses of agpr64 and agpr32 can also accept vgpr except for 11172 // v_accvgpr_read, but we do not produce agpr reads during selection, 11173 // so no use checks are needed. 11174 MRI.setRegClass(Op.getReg(), NewRC); 11175 } 11176 } 11177 11178 return; 11179 } 11180 11181 // Replace unused atomics with the no return version. 11182 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11183 if (NoRetAtomicOp != -1) { 11184 if (!Node->hasAnyUseOfValue(0)) { 11185 MI.setDesc(TII->get(NoRetAtomicOp)); 11186 MI.RemoveOperand(0); 11187 return; 11188 } 11189 11190 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11191 // instruction, because the return type of these instructions is a vec2 of 11192 // the memory type, so it can be tied to the input operand. 11193 // This means these instructions always have a use, so we need to add a 11194 // special case to check if the atomic has only one extract_subreg use, 11195 // which itself has no uses. 11196 if ((Node->hasNUsesOfValue(1, 0) && 11197 Node->use_begin()->isMachineOpcode() && 11198 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11199 !Node->use_begin()->hasAnyUseOfValue(0))) { 11200 Register Def = MI.getOperand(0).getReg(); 11201 11202 // Change this into a noret atomic. 11203 MI.setDesc(TII->get(NoRetAtomicOp)); 11204 MI.RemoveOperand(0); 11205 11206 // If we only remove the def operand from the atomic instruction, the 11207 // extract_subreg will be left with a use of a vreg without a def. 11208 // So we need to insert an implicit_def to avoid machine verifier 11209 // errors. 11210 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11211 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11212 } 11213 return; 11214 } 11215 } 11216 11217 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11218 uint64_t Val) { 11219 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11220 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11221 } 11222 11223 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11224 const SDLoc &DL, 11225 SDValue Ptr) const { 11226 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11227 11228 // Build the half of the subregister with the constants before building the 11229 // full 128-bit register. If we are building multiple resource descriptors, 11230 // this will allow CSEing of the 2-component register. 11231 const SDValue Ops0[] = { 11232 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11233 buildSMovImm32(DAG, DL, 0), 11234 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11235 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11236 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11237 }; 11238 11239 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11240 MVT::v2i32, Ops0), 0); 11241 11242 // Combine the constants and the pointer. 11243 const SDValue Ops1[] = { 11244 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11245 Ptr, 11246 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11247 SubRegHi, 11248 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11249 }; 11250 11251 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11252 } 11253 11254 /// Return a resource descriptor with the 'Add TID' bit enabled 11255 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11256 /// of the resource descriptor) to create an offset, which is added to 11257 /// the resource pointer. 11258 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11259 SDValue Ptr, uint32_t RsrcDword1, 11260 uint64_t RsrcDword2And3) const { 11261 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11262 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11263 if (RsrcDword1) { 11264 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11265 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11266 0); 11267 } 11268 11269 SDValue DataLo = buildSMovImm32(DAG, DL, 11270 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11271 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11272 11273 const SDValue Ops[] = { 11274 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11275 PtrLo, 11276 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11277 PtrHi, 11278 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11279 DataLo, 11280 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11281 DataHi, 11282 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11283 }; 11284 11285 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11286 } 11287 11288 //===----------------------------------------------------------------------===// 11289 // SI Inline Assembly Support 11290 //===----------------------------------------------------------------------===// 11291 11292 std::pair<unsigned, const TargetRegisterClass *> 11293 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11294 StringRef Constraint, 11295 MVT VT) const { 11296 const TargetRegisterClass *RC = nullptr; 11297 if (Constraint.size() == 1) { 11298 const unsigned BitWidth = VT.getSizeInBits(); 11299 switch (Constraint[0]) { 11300 default: 11301 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11302 case 's': 11303 case 'r': 11304 switch (BitWidth) { 11305 case 16: 11306 RC = &AMDGPU::SReg_32RegClass; 11307 break; 11308 case 64: 11309 RC = &AMDGPU::SGPR_64RegClass; 11310 break; 11311 default: 11312 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11313 if (!RC) 11314 return std::make_pair(0U, nullptr); 11315 break; 11316 } 11317 break; 11318 case 'v': 11319 switch (BitWidth) { 11320 case 16: 11321 RC = &AMDGPU::VGPR_32RegClass; 11322 break; 11323 default: 11324 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11325 if (!RC) 11326 return std::make_pair(0U, nullptr); 11327 break; 11328 } 11329 break; 11330 case 'a': 11331 if (!Subtarget->hasMAIInsts()) 11332 break; 11333 switch (BitWidth) { 11334 case 16: 11335 RC = &AMDGPU::AGPR_32RegClass; 11336 break; 11337 default: 11338 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11339 if (!RC) 11340 return std::make_pair(0U, nullptr); 11341 break; 11342 } 11343 break; 11344 } 11345 // We actually support i128, i16 and f16 as inline parameters 11346 // even if they are not reported as legal 11347 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11348 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11349 return std::make_pair(0U, RC); 11350 } 11351 11352 if (Constraint.size() > 1) { 11353 if (Constraint[1] == 'v') { 11354 RC = &AMDGPU::VGPR_32RegClass; 11355 } else if (Constraint[1] == 's') { 11356 RC = &AMDGPU::SGPR_32RegClass; 11357 } else if (Constraint[1] == 'a') { 11358 RC = &AMDGPU::AGPR_32RegClass; 11359 } 11360 11361 if (RC) { 11362 uint32_t Idx; 11363 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11364 if (!Failed && Idx < RC->getNumRegs()) 11365 return std::make_pair(RC->getRegister(Idx), RC); 11366 } 11367 } 11368 11369 // FIXME: Returns VS_32 for physical SGPR constraints 11370 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11371 } 11372 11373 static bool isImmConstraint(StringRef Constraint) { 11374 if (Constraint.size() == 1) { 11375 switch (Constraint[0]) { 11376 default: break; 11377 case 'I': 11378 case 'J': 11379 case 'A': 11380 case 'B': 11381 case 'C': 11382 return true; 11383 } 11384 } else if (Constraint == "DA" || 11385 Constraint == "DB") { 11386 return true; 11387 } 11388 return false; 11389 } 11390 11391 SITargetLowering::ConstraintType 11392 SITargetLowering::getConstraintType(StringRef Constraint) const { 11393 if (Constraint.size() == 1) { 11394 switch (Constraint[0]) { 11395 default: break; 11396 case 's': 11397 case 'v': 11398 case 'a': 11399 return C_RegisterClass; 11400 } 11401 } 11402 if (isImmConstraint(Constraint)) { 11403 return C_Other; 11404 } 11405 return TargetLowering::getConstraintType(Constraint); 11406 } 11407 11408 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11409 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11410 Val = Val & maskTrailingOnes<uint64_t>(Size); 11411 } 11412 return Val; 11413 } 11414 11415 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11416 std::string &Constraint, 11417 std::vector<SDValue> &Ops, 11418 SelectionDAG &DAG) const { 11419 if (isImmConstraint(Constraint)) { 11420 uint64_t Val; 11421 if (getAsmOperandConstVal(Op, Val) && 11422 checkAsmConstraintVal(Op, Constraint, Val)) { 11423 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11424 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11425 } 11426 } else { 11427 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11428 } 11429 } 11430 11431 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11432 unsigned Size = Op.getScalarValueSizeInBits(); 11433 if (Size > 64) 11434 return false; 11435 11436 if (Size == 16 && !Subtarget->has16BitInsts()) 11437 return false; 11438 11439 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11440 Val = C->getSExtValue(); 11441 return true; 11442 } 11443 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11444 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11445 return true; 11446 } 11447 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11448 if (Size != 16 || Op.getNumOperands() != 2) 11449 return false; 11450 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11451 return false; 11452 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11453 Val = C->getSExtValue(); 11454 return true; 11455 } 11456 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11457 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11458 return true; 11459 } 11460 } 11461 11462 return false; 11463 } 11464 11465 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11466 const std::string &Constraint, 11467 uint64_t Val) const { 11468 if (Constraint.size() == 1) { 11469 switch (Constraint[0]) { 11470 case 'I': 11471 return AMDGPU::isInlinableIntLiteral(Val); 11472 case 'J': 11473 return isInt<16>(Val); 11474 case 'A': 11475 return checkAsmConstraintValA(Op, Val); 11476 case 'B': 11477 return isInt<32>(Val); 11478 case 'C': 11479 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11480 AMDGPU::isInlinableIntLiteral(Val); 11481 default: 11482 break; 11483 } 11484 } else if (Constraint.size() == 2) { 11485 if (Constraint == "DA") { 11486 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11487 int64_t LoBits = static_cast<int32_t>(Val); 11488 return checkAsmConstraintValA(Op, HiBits, 32) && 11489 checkAsmConstraintValA(Op, LoBits, 32); 11490 } 11491 if (Constraint == "DB") { 11492 return true; 11493 } 11494 } 11495 llvm_unreachable("Invalid asm constraint"); 11496 } 11497 11498 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11499 uint64_t Val, 11500 unsigned MaxSize) const { 11501 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11502 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11503 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11504 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11505 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11506 return true; 11507 } 11508 return false; 11509 } 11510 11511 // Figure out which registers should be reserved for stack access. Only after 11512 // the function is legalized do we know all of the non-spill stack objects or if 11513 // calls are present. 11514 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11515 MachineRegisterInfo &MRI = MF.getRegInfo(); 11516 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11517 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11518 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11519 11520 if (Info->isEntryFunction()) { 11521 // Callable functions have fixed registers used for stack access. 11522 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11523 } 11524 11525 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11526 Info->getStackPtrOffsetReg())); 11527 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11528 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11529 11530 // We need to worry about replacing the default register with itself in case 11531 // of MIR testcases missing the MFI. 11532 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11533 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11534 11535 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11536 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11537 11538 Info->limitOccupancy(MF); 11539 11540 if (ST.isWave32() && !MF.empty()) { 11541 // Add VCC_HI def because many instructions marked as imp-use VCC where 11542 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11543 // having a use of undef. 11544 11545 const SIInstrInfo *TII = ST.getInstrInfo(); 11546 DebugLoc DL; 11547 11548 MachineBasicBlock &MBB = MF.front(); 11549 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11550 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11551 11552 for (auto &MBB : MF) { 11553 for (auto &MI : MBB) { 11554 TII->fixImplicitOperands(MI); 11555 } 11556 } 11557 } 11558 11559 TargetLoweringBase::finalizeLowering(MF); 11560 11561 // Allocate a VGPR for future SGPR Spill if 11562 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11563 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11564 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11565 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11566 Info->reserveVGPRforSGPRSpills(MF); 11567 } 11568 11569 void SITargetLowering::computeKnownBitsForFrameIndex( 11570 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11571 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11572 11573 // Set the high bits to zero based on the maximum allowed scratch size per 11574 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11575 // calculation won't overflow, so assume the sign bit is never set. 11576 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11577 } 11578 11579 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11580 KnownBits &Known, unsigned Dim) { 11581 unsigned MaxValue = 11582 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11583 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11584 } 11585 11586 void SITargetLowering::computeKnownBitsForTargetInstr( 11587 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11588 const MachineRegisterInfo &MRI, unsigned Depth) const { 11589 const MachineInstr *MI = MRI.getVRegDef(R); 11590 switch (MI->getOpcode()) { 11591 case AMDGPU::G_INTRINSIC: { 11592 switch (MI->getIntrinsicID()) { 11593 case Intrinsic::amdgcn_workitem_id_x: 11594 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11595 break; 11596 case Intrinsic::amdgcn_workitem_id_y: 11597 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11598 break; 11599 case Intrinsic::amdgcn_workitem_id_z: 11600 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11601 break; 11602 case Intrinsic::amdgcn_mbcnt_lo: 11603 case Intrinsic::amdgcn_mbcnt_hi: { 11604 // These return at most the wavefront size - 1. 11605 unsigned Size = MRI.getType(R).getSizeInBits(); 11606 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11607 break; 11608 } 11609 case Intrinsic::amdgcn_groupstaticsize: { 11610 // We can report everything over the maximum size as 0. We can't report 11611 // based on the actual size because we don't know if it's accurate or not 11612 // at any given point. 11613 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11614 break; 11615 } 11616 } 11617 break; 11618 } 11619 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11620 Known.Zero.setHighBits(24); 11621 break; 11622 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11623 Known.Zero.setHighBits(16); 11624 break; 11625 } 11626 } 11627 11628 Align SITargetLowering::computeKnownAlignForTargetInstr( 11629 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11630 unsigned Depth) const { 11631 const MachineInstr *MI = MRI.getVRegDef(R); 11632 switch (MI->getOpcode()) { 11633 case AMDGPU::G_INTRINSIC: 11634 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11635 // FIXME: Can this move to generic code? What about the case where the call 11636 // site specifies a lower alignment? 11637 Intrinsic::ID IID = MI->getIntrinsicID(); 11638 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11639 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11640 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11641 return *RetAlign; 11642 return Align(1); 11643 } 11644 default: 11645 return Align(1); 11646 } 11647 } 11648 11649 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11650 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11651 const Align CacheLineAlign = Align(64); 11652 11653 // Pre-GFX10 target did not benefit from loop alignment 11654 if (!ML || DisableLoopAlignment || 11655 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11656 getSubtarget()->hasInstFwdPrefetchBug()) 11657 return PrefAlign; 11658 11659 // On GFX10 I$ is 4 x 64 bytes cache lines. 11660 // By default prefetcher keeps one cache line behind and reads two ahead. 11661 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11662 // behind and one ahead. 11663 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11664 // If loop fits 64 bytes it always spans no more than two cache lines and 11665 // does not need an alignment. 11666 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11667 // Else if loop is less or equal 192 bytes we need two lines behind. 11668 11669 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11670 const MachineBasicBlock *Header = ML->getHeader(); 11671 if (Header->getAlignment() != PrefAlign) 11672 return Header->getAlignment(); // Already processed. 11673 11674 unsigned LoopSize = 0; 11675 for (const MachineBasicBlock *MBB : ML->blocks()) { 11676 // If inner loop block is aligned assume in average half of the alignment 11677 // size to be added as nops. 11678 if (MBB != Header) 11679 LoopSize += MBB->getAlignment().value() / 2; 11680 11681 for (const MachineInstr &MI : *MBB) { 11682 LoopSize += TII->getInstSizeInBytes(MI); 11683 if (LoopSize > 192) 11684 return PrefAlign; 11685 } 11686 } 11687 11688 if (LoopSize <= 64) 11689 return PrefAlign; 11690 11691 if (LoopSize <= 128) 11692 return CacheLineAlign; 11693 11694 // If any of parent loops is surrounded by prefetch instructions do not 11695 // insert new for inner loop, which would reset parent's settings. 11696 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11697 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11698 auto I = Exit->getFirstNonDebugInstr(); 11699 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11700 return CacheLineAlign; 11701 } 11702 } 11703 11704 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11705 MachineBasicBlock *Exit = ML->getExitBlock(); 11706 11707 if (Pre && Exit) { 11708 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11709 TII->get(AMDGPU::S_INST_PREFETCH)) 11710 .addImm(1); // prefetch 2 lines behind PC 11711 11712 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11713 TII->get(AMDGPU::S_INST_PREFETCH)) 11714 .addImm(2); // prefetch 1 line behind PC 11715 } 11716 11717 return CacheLineAlign; 11718 } 11719 11720 LLVM_ATTRIBUTE_UNUSED 11721 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11722 assert(N->getOpcode() == ISD::CopyFromReg); 11723 do { 11724 // Follow the chain until we find an INLINEASM node. 11725 N = N->getOperand(0).getNode(); 11726 if (N->getOpcode() == ISD::INLINEASM || 11727 N->getOpcode() == ISD::INLINEASM_BR) 11728 return true; 11729 } while (N->getOpcode() == ISD::CopyFromReg); 11730 return false; 11731 } 11732 11733 bool SITargetLowering::isSDNodeSourceOfDivergence( 11734 const SDNode *N, FunctionLoweringInfo *FLI, 11735 LegacyDivergenceAnalysis *KDA) const { 11736 switch (N->getOpcode()) { 11737 case ISD::CopyFromReg: { 11738 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11739 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11740 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11741 Register Reg = R->getReg(); 11742 11743 // FIXME: Why does this need to consider isLiveIn? 11744 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11745 return !TRI->isSGPRReg(MRI, Reg); 11746 11747 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11748 return KDA->isDivergent(V); 11749 11750 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11751 return !TRI->isSGPRReg(MRI, Reg); 11752 } 11753 case ISD::LOAD: { 11754 const LoadSDNode *L = cast<LoadSDNode>(N); 11755 unsigned AS = L->getAddressSpace(); 11756 // A flat load may access private memory. 11757 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11758 } 11759 case ISD::CALLSEQ_END: 11760 return true; 11761 case ISD::INTRINSIC_WO_CHAIN: 11762 return AMDGPU::isIntrinsicSourceOfDivergence( 11763 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11764 case ISD::INTRINSIC_W_CHAIN: 11765 return AMDGPU::isIntrinsicSourceOfDivergence( 11766 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11767 } 11768 return false; 11769 } 11770 11771 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11772 EVT VT) const { 11773 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11774 case MVT::f32: 11775 return hasFP32Denormals(DAG.getMachineFunction()); 11776 case MVT::f64: 11777 case MVT::f16: 11778 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11779 default: 11780 return false; 11781 } 11782 } 11783 11784 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11785 const SelectionDAG &DAG, 11786 bool SNaN, 11787 unsigned Depth) const { 11788 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11789 const MachineFunction &MF = DAG.getMachineFunction(); 11790 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11791 11792 if (Info->getMode().DX10Clamp) 11793 return true; // Clamped to 0. 11794 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11795 } 11796 11797 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11798 SNaN, Depth); 11799 } 11800 11801 // Global FP atomic instructions have a hardcoded FP mode and do not support 11802 // FP32 denormals, and only support v2f16 denormals. 11803 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11804 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11805 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11806 if (&Flt == &APFloat::IEEEsingle()) 11807 return DenormMode == DenormalMode::getPreserveSign(); 11808 return DenormMode == DenormalMode::getIEEE(); 11809 } 11810 11811 TargetLowering::AtomicExpansionKind 11812 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11813 switch (RMW->getOperation()) { 11814 case AtomicRMWInst::FAdd: { 11815 Type *Ty = RMW->getType(); 11816 11817 // We don't have a way to support 16-bit atomics now, so just leave them 11818 // as-is. 11819 if (Ty->isHalfTy()) 11820 return AtomicExpansionKind::None; 11821 11822 if (!Ty->isFloatTy()) 11823 return AtomicExpansionKind::CmpXChg; 11824 11825 // TODO: Do have these for flat. Older targets also had them for buffers. 11826 unsigned AS = RMW->getPointerAddressSpace(); 11827 11828 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11829 if (!fpModeMatchesGlobalFPAtomicMode(RMW)) 11830 return AtomicExpansionKind::CmpXChg; 11831 11832 return RMW->use_empty() ? AtomicExpansionKind::None : 11833 AtomicExpansionKind::CmpXChg; 11834 } 11835 11836 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11837 // to round-to-nearest-even. 11838 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11839 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11840 } 11841 default: 11842 break; 11843 } 11844 11845 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11846 } 11847 11848 const TargetRegisterClass * 11849 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11850 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11851 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11852 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11853 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11854 : &AMDGPU::SReg_32RegClass; 11855 if (!TRI->isSGPRClass(RC) && !isDivergent) 11856 return TRI->getEquivalentSGPRClass(RC); 11857 else if (TRI->isSGPRClass(RC) && isDivergent) 11858 return TRI->getEquivalentVGPRClass(RC); 11859 11860 return RC; 11861 } 11862 11863 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11864 // uniform values (as produced by the mask results of control flow intrinsics) 11865 // used outside of divergent blocks. The phi users need to also be treated as 11866 // always uniform. 11867 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11868 unsigned WaveSize) { 11869 // FIXME: We asssume we never cast the mask results of a control flow 11870 // intrinsic. 11871 // Early exit if the type won't be consistent as a compile time hack. 11872 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11873 if (!IT || IT->getBitWidth() != WaveSize) 11874 return false; 11875 11876 if (!isa<Instruction>(V)) 11877 return false; 11878 if (!Visited.insert(V).second) 11879 return false; 11880 bool Result = false; 11881 for (auto U : V->users()) { 11882 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11883 if (V == U->getOperand(1)) { 11884 switch (Intrinsic->getIntrinsicID()) { 11885 default: 11886 Result = false; 11887 break; 11888 case Intrinsic::amdgcn_if_break: 11889 case Intrinsic::amdgcn_if: 11890 case Intrinsic::amdgcn_else: 11891 Result = true; 11892 break; 11893 } 11894 } 11895 if (V == U->getOperand(0)) { 11896 switch (Intrinsic->getIntrinsicID()) { 11897 default: 11898 Result = false; 11899 break; 11900 case Intrinsic::amdgcn_end_cf: 11901 case Intrinsic::amdgcn_loop: 11902 Result = true; 11903 break; 11904 } 11905 } 11906 } else { 11907 Result = hasCFUser(U, Visited, WaveSize); 11908 } 11909 if (Result) 11910 break; 11911 } 11912 return Result; 11913 } 11914 11915 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11916 const Value *V) const { 11917 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11918 if (CI->isInlineAsm()) { 11919 // FIXME: This cannot give a correct answer. This should only trigger in 11920 // the case where inline asm returns mixed SGPR and VGPR results, used 11921 // outside the defining block. We don't have a specific result to 11922 // consider, so this assumes if any value is SGPR, the overall register 11923 // also needs to be SGPR. 11924 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11925 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11926 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11927 for (auto &TC : TargetConstraints) { 11928 if (TC.Type == InlineAsm::isOutput) { 11929 ComputeConstraintToUse(TC, SDValue()); 11930 unsigned AssignedReg; 11931 const TargetRegisterClass *RC; 11932 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11933 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11934 if (RC) { 11935 MachineRegisterInfo &MRI = MF.getRegInfo(); 11936 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11937 return true; 11938 else if (SIRI->isSGPRClass(RC)) 11939 return true; 11940 } 11941 } 11942 } 11943 } 11944 } 11945 SmallPtrSet<const Value *, 16> Visited; 11946 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11947 } 11948 11949 std::pair<int, MVT> 11950 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11951 Type *Ty) const { 11952 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11953 auto Size = DL.getTypeSizeInBits(Ty); 11954 // Maximum load or store can handle 8 dwords for scalar and 4 for 11955 // vector ALU. Let's assume anything above 8 dwords is expensive 11956 // even if legal. 11957 if (Size <= 256) 11958 return Cost; 11959 11960 Cost.first = (Size + 255) / 256; 11961 return Cost; 11962 } 11963