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, Promote); 550 setOperationAction(ISD::ROTL, MVT::i16, Promote); 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::v4f16, Custom); 810 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 811 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 812 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 813 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 815 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 816 817 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 818 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 819 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 820 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 821 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 822 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 823 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 824 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 825 826 setTargetDAGCombine(ISD::ADD); 827 setTargetDAGCombine(ISD::ADDCARRY); 828 setTargetDAGCombine(ISD::SUB); 829 setTargetDAGCombine(ISD::SUBCARRY); 830 setTargetDAGCombine(ISD::FADD); 831 setTargetDAGCombine(ISD::FSUB); 832 setTargetDAGCombine(ISD::FMINNUM); 833 setTargetDAGCombine(ISD::FMAXNUM); 834 setTargetDAGCombine(ISD::FMINNUM_IEEE); 835 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 836 setTargetDAGCombine(ISD::FMA); 837 setTargetDAGCombine(ISD::SMIN); 838 setTargetDAGCombine(ISD::SMAX); 839 setTargetDAGCombine(ISD::UMIN); 840 setTargetDAGCombine(ISD::UMAX); 841 setTargetDAGCombine(ISD::SETCC); 842 setTargetDAGCombine(ISD::AND); 843 setTargetDAGCombine(ISD::OR); 844 setTargetDAGCombine(ISD::XOR); 845 setTargetDAGCombine(ISD::SINT_TO_FP); 846 setTargetDAGCombine(ISD::UINT_TO_FP); 847 setTargetDAGCombine(ISD::FCANONICALIZE); 848 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 849 setTargetDAGCombine(ISD::ZERO_EXTEND); 850 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 851 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 852 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 853 854 // All memory operations. Some folding on the pointer operand is done to help 855 // matching the constant offsets in the addressing modes. 856 setTargetDAGCombine(ISD::LOAD); 857 setTargetDAGCombine(ISD::STORE); 858 setTargetDAGCombine(ISD::ATOMIC_LOAD); 859 setTargetDAGCombine(ISD::ATOMIC_STORE); 860 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 861 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 862 setTargetDAGCombine(ISD::ATOMIC_SWAP); 863 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 864 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 865 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 866 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 867 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 868 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 870 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 871 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 872 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 873 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 874 setTargetDAGCombine(ISD::INTRINSIC_VOID); 875 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 876 877 // FIXME: In other contexts we pretend this is a per-function property. 878 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 879 880 setSchedulingPreference(Sched::RegPressure); 881 } 882 883 const GCNSubtarget *SITargetLowering::getSubtarget() const { 884 return Subtarget; 885 } 886 887 //===----------------------------------------------------------------------===// 888 // TargetLowering queries 889 //===----------------------------------------------------------------------===// 890 891 // v_mad_mix* support a conversion from f16 to f32. 892 // 893 // There is only one special case when denormals are enabled we don't currently, 894 // where this is OK to use. 895 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 896 EVT DestVT, EVT SrcVT) const { 897 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 898 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 899 DestVT.getScalarType() == MVT::f32 && 900 SrcVT.getScalarType() == MVT::f16 && 901 // TODO: This probably only requires no input flushing? 902 !hasFP32Denormals(DAG.getMachineFunction()); 903 } 904 905 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 906 // SI has some legal vector types, but no legal vector operations. Say no 907 // shuffles are legal in order to prefer scalarizing some vector operations. 908 return false; 909 } 910 911 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 912 CallingConv::ID CC, 913 EVT VT) const { 914 if (CC == CallingConv::AMDGPU_KERNEL) 915 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 916 917 if (VT.isVector()) { 918 EVT ScalarVT = VT.getScalarType(); 919 unsigned Size = ScalarVT.getSizeInBits(); 920 if (Size == 32) 921 return ScalarVT.getSimpleVT(); 922 923 if (Size > 32) 924 return MVT::i32; 925 926 if (Size == 16 && Subtarget->has16BitInsts()) 927 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 928 } else if (VT.getSizeInBits() > 32) 929 return MVT::i32; 930 931 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 932 } 933 934 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 935 CallingConv::ID CC, 936 EVT VT) const { 937 if (CC == CallingConv::AMDGPU_KERNEL) 938 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 939 940 if (VT.isVector()) { 941 unsigned NumElts = VT.getVectorNumElements(); 942 EVT ScalarVT = VT.getScalarType(); 943 unsigned Size = ScalarVT.getSizeInBits(); 944 945 if (Size == 32) 946 return NumElts; 947 948 if (Size > 32) 949 return NumElts * ((Size + 31) / 32); 950 951 if (Size == 16 && Subtarget->has16BitInsts()) 952 return (NumElts + 1) / 2; 953 } else if (VT.getSizeInBits() > 32) 954 return (VT.getSizeInBits() + 31) / 32; 955 956 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 957 } 958 959 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 960 LLVMContext &Context, CallingConv::ID CC, 961 EVT VT, EVT &IntermediateVT, 962 unsigned &NumIntermediates, MVT &RegisterVT) const { 963 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 964 unsigned NumElts = VT.getVectorNumElements(); 965 EVT ScalarVT = VT.getScalarType(); 966 unsigned Size = ScalarVT.getSizeInBits(); 967 if (Size == 32) { 968 RegisterVT = ScalarVT.getSimpleVT(); 969 IntermediateVT = RegisterVT; 970 NumIntermediates = NumElts; 971 return NumIntermediates; 972 } 973 974 if (Size > 32) { 975 RegisterVT = MVT::i32; 976 IntermediateVT = RegisterVT; 977 NumIntermediates = NumElts * ((Size + 31) / 32); 978 return NumIntermediates; 979 } 980 981 // FIXME: We should fix the ABI to be the same on targets without 16-bit 982 // support, but unless we can properly handle 3-vectors, it will be still be 983 // inconsistent. 984 if (Size == 16 && Subtarget->has16BitInsts()) { 985 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 986 IntermediateVT = RegisterVT; 987 NumIntermediates = (NumElts + 1) / 2; 988 return NumIntermediates; 989 } 990 } 991 992 return TargetLowering::getVectorTypeBreakdownForCallingConv( 993 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 994 } 995 996 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 997 assert(DMaskLanes != 0); 998 999 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1000 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1001 return EVT::getVectorVT(Ty->getContext(), 1002 EVT::getEVT(VT->getElementType()), 1003 NumElts); 1004 } 1005 1006 return EVT::getEVT(Ty); 1007 } 1008 1009 // Peek through TFE struct returns to only use the data size. 1010 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1011 auto *ST = dyn_cast<StructType>(Ty); 1012 if (!ST) 1013 return memVTFromImageData(Ty, DMaskLanes); 1014 1015 // Some intrinsics return an aggregate type - special case to work out the 1016 // correct memVT. 1017 // 1018 // Only limited forms of aggregate type currently expected. 1019 if (ST->getNumContainedTypes() != 2 || 1020 !ST->getContainedType(1)->isIntegerTy(32)) 1021 return EVT(); 1022 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1023 } 1024 1025 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1026 const CallInst &CI, 1027 MachineFunction &MF, 1028 unsigned IntrID) const { 1029 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1030 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1031 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1032 (Intrinsic::ID)IntrID); 1033 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1034 return false; 1035 1036 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1037 1038 if (RsrcIntr->IsImage) { 1039 Info.ptrVal = MFI->getImagePSV( 1040 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1041 CI.getArgOperand(RsrcIntr->RsrcArg)); 1042 Info.align.reset(); 1043 } else { 1044 Info.ptrVal = MFI->getBufferPSV( 1045 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1046 CI.getArgOperand(RsrcIntr->RsrcArg)); 1047 } 1048 1049 Info.flags = MachineMemOperand::MODereferenceable; 1050 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1051 unsigned DMaskLanes = 4; 1052 1053 if (RsrcIntr->IsImage) { 1054 const AMDGPU::ImageDimIntrinsicInfo *Intr 1055 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1056 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1057 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1058 1059 if (!BaseOpcode->Gather4) { 1060 // If this isn't a gather, we may have excess loaded elements in the 1061 // IR type. Check the dmask for the real number of elements loaded. 1062 unsigned DMask 1063 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1064 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1065 } 1066 1067 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1068 } else 1069 Info.memVT = EVT::getEVT(CI.getType()); 1070 1071 // FIXME: What does alignment mean for an image? 1072 Info.opc = ISD::INTRINSIC_W_CHAIN; 1073 Info.flags |= MachineMemOperand::MOLoad; 1074 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1075 Info.opc = ISD::INTRINSIC_VOID; 1076 1077 Type *DataTy = CI.getArgOperand(0)->getType(); 1078 if (RsrcIntr->IsImage) { 1079 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1080 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1081 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1082 } else 1083 Info.memVT = EVT::getEVT(DataTy); 1084 1085 Info.flags |= MachineMemOperand::MOStore; 1086 } else { 1087 // Atomic 1088 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1089 ISD::INTRINSIC_W_CHAIN; 1090 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1091 Info.flags = MachineMemOperand::MOLoad | 1092 MachineMemOperand::MOStore | 1093 MachineMemOperand::MODereferenceable; 1094 1095 // XXX - Should this be volatile without known ordering? 1096 Info.flags |= MachineMemOperand::MOVolatile; 1097 } 1098 return true; 1099 } 1100 1101 switch (IntrID) { 1102 case Intrinsic::amdgcn_atomic_inc: 1103 case Intrinsic::amdgcn_atomic_dec: 1104 case Intrinsic::amdgcn_ds_ordered_add: 1105 case Intrinsic::amdgcn_ds_ordered_swap: 1106 case Intrinsic::amdgcn_ds_fadd: 1107 case Intrinsic::amdgcn_ds_fmin: 1108 case Intrinsic::amdgcn_ds_fmax: { 1109 Info.opc = ISD::INTRINSIC_W_CHAIN; 1110 Info.memVT = MVT::getVT(CI.getType()); 1111 Info.ptrVal = CI.getOperand(0); 1112 Info.align.reset(); 1113 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1114 1115 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1116 if (!Vol->isZero()) 1117 Info.flags |= MachineMemOperand::MOVolatile; 1118 1119 return true; 1120 } 1121 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1122 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1123 1124 Info.opc = ISD::INTRINSIC_VOID; 1125 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1126 Info.ptrVal = MFI->getBufferPSV( 1127 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1128 CI.getArgOperand(1)); 1129 Info.align.reset(); 1130 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1131 1132 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1133 if (!Vol || !Vol->isZero()) 1134 Info.flags |= MachineMemOperand::MOVolatile; 1135 1136 return true; 1137 } 1138 case Intrinsic::amdgcn_global_atomic_fadd: { 1139 Info.opc = ISD::INTRINSIC_VOID; 1140 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1141 ->getPointerElementType()); 1142 Info.ptrVal = CI.getOperand(0); 1143 Info.align.reset(); 1144 1145 // FIXME: Should report an atomic ordering here. 1146 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1147 1148 return true; 1149 } 1150 case Intrinsic::amdgcn_ds_append: 1151 case Intrinsic::amdgcn_ds_consume: { 1152 Info.opc = ISD::INTRINSIC_W_CHAIN; 1153 Info.memVT = MVT::getVT(CI.getType()); 1154 Info.ptrVal = CI.getOperand(0); 1155 Info.align.reset(); 1156 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1157 1158 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1159 if (!Vol->isZero()) 1160 Info.flags |= MachineMemOperand::MOVolatile; 1161 1162 return true; 1163 } 1164 case Intrinsic::amdgcn_global_atomic_csub: { 1165 Info.opc = ISD::INTRINSIC_W_CHAIN; 1166 Info.memVT = MVT::getVT(CI.getType()); 1167 Info.ptrVal = CI.getOperand(0); 1168 Info.align.reset(); 1169 Info.flags = MachineMemOperand::MOLoad | 1170 MachineMemOperand::MOStore | 1171 MachineMemOperand::MOVolatile; 1172 return true; 1173 } 1174 case Intrinsic::amdgcn_ds_gws_init: 1175 case Intrinsic::amdgcn_ds_gws_barrier: 1176 case Intrinsic::amdgcn_ds_gws_sema_v: 1177 case Intrinsic::amdgcn_ds_gws_sema_br: 1178 case Intrinsic::amdgcn_ds_gws_sema_p: 1179 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1180 Info.opc = ISD::INTRINSIC_VOID; 1181 1182 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1183 Info.ptrVal = 1184 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1185 1186 // This is an abstract access, but we need to specify a type and size. 1187 Info.memVT = MVT::i32; 1188 Info.size = 4; 1189 Info.align = Align(4); 1190 1191 Info.flags = MachineMemOperand::MOStore; 1192 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1193 Info.flags = MachineMemOperand::MOLoad; 1194 return true; 1195 } 1196 default: 1197 return false; 1198 } 1199 } 1200 1201 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1202 SmallVectorImpl<Value*> &Ops, 1203 Type *&AccessTy) const { 1204 switch (II->getIntrinsicID()) { 1205 case Intrinsic::amdgcn_atomic_inc: 1206 case Intrinsic::amdgcn_atomic_dec: 1207 case Intrinsic::amdgcn_ds_ordered_add: 1208 case Intrinsic::amdgcn_ds_ordered_swap: 1209 case Intrinsic::amdgcn_ds_append: 1210 case Intrinsic::amdgcn_ds_consume: 1211 case Intrinsic::amdgcn_ds_fadd: 1212 case Intrinsic::amdgcn_ds_fmin: 1213 case Intrinsic::amdgcn_ds_fmax: 1214 case Intrinsic::amdgcn_global_atomic_fadd: 1215 case Intrinsic::amdgcn_global_atomic_csub: { 1216 Value *Ptr = II->getArgOperand(0); 1217 AccessTy = II->getType(); 1218 Ops.push_back(Ptr); 1219 return true; 1220 } 1221 default: 1222 return false; 1223 } 1224 } 1225 1226 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1227 if (!Subtarget->hasFlatInstOffsets()) { 1228 // Flat instructions do not have offsets, and only have the register 1229 // address. 1230 return AM.BaseOffs == 0 && AM.Scale == 0; 1231 } 1232 1233 return AM.Scale == 0 && 1234 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1235 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1236 /*Signed=*/false)); 1237 } 1238 1239 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1240 if (Subtarget->hasFlatGlobalInsts()) 1241 return AM.Scale == 0 && 1242 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1243 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1244 /*Signed=*/true)); 1245 1246 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1247 // Assume the we will use FLAT for all global memory accesses 1248 // on VI. 1249 // FIXME: This assumption is currently wrong. On VI we still use 1250 // MUBUF instructions for the r + i addressing mode. As currently 1251 // implemented, the MUBUF instructions only work on buffer < 4GB. 1252 // It may be possible to support > 4GB buffers with MUBUF instructions, 1253 // by setting the stride value in the resource descriptor which would 1254 // increase the size limit to (stride * 4GB). However, this is risky, 1255 // because it has never been validated. 1256 return isLegalFlatAddressingMode(AM); 1257 } 1258 1259 return isLegalMUBUFAddressingMode(AM); 1260 } 1261 1262 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1263 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1264 // additionally can do r + r + i with addr64. 32-bit has more addressing 1265 // mode options. Depending on the resource constant, it can also do 1266 // (i64 r0) + (i32 r1) * (i14 i). 1267 // 1268 // Private arrays end up using a scratch buffer most of the time, so also 1269 // assume those use MUBUF instructions. Scratch loads / stores are currently 1270 // implemented as mubuf instructions with offen bit set, so slightly 1271 // different than the normal addr64. 1272 if (!isUInt<12>(AM.BaseOffs)) 1273 return false; 1274 1275 // FIXME: Since we can split immediate into soffset and immediate offset, 1276 // would it make sense to allow any immediate? 1277 1278 switch (AM.Scale) { 1279 case 0: // r + i or just i, depending on HasBaseReg. 1280 return true; 1281 case 1: 1282 return true; // We have r + r or r + i. 1283 case 2: 1284 if (AM.HasBaseReg) { 1285 // Reject 2 * r + r. 1286 return false; 1287 } 1288 1289 // Allow 2 * r as r + r 1290 // Or 2 * r + i is allowed as r + r + i. 1291 return true; 1292 default: // Don't allow n * r 1293 return false; 1294 } 1295 } 1296 1297 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1298 const AddrMode &AM, Type *Ty, 1299 unsigned AS, Instruction *I) const { 1300 // No global is ever allowed as a base. 1301 if (AM.BaseGV) 1302 return false; 1303 1304 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1305 return isLegalGlobalAddressingMode(AM); 1306 1307 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1308 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1309 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1310 // If the offset isn't a multiple of 4, it probably isn't going to be 1311 // correctly aligned. 1312 // FIXME: Can we get the real alignment here? 1313 if (AM.BaseOffs % 4 != 0) 1314 return isLegalMUBUFAddressingMode(AM); 1315 1316 // There are no SMRD extloads, so if we have to do a small type access we 1317 // will use a MUBUF load. 1318 // FIXME?: We also need to do this if unaligned, but we don't know the 1319 // alignment here. 1320 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1321 return isLegalGlobalAddressingMode(AM); 1322 1323 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1324 // SMRD instructions have an 8-bit, dword offset on SI. 1325 if (!isUInt<8>(AM.BaseOffs / 4)) 1326 return false; 1327 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1328 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1329 // in 8-bits, it can use a smaller encoding. 1330 if (!isUInt<32>(AM.BaseOffs / 4)) 1331 return false; 1332 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1333 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1334 if (!isUInt<20>(AM.BaseOffs)) 1335 return false; 1336 } else 1337 llvm_unreachable("unhandled generation"); 1338 1339 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1340 return true; 1341 1342 if (AM.Scale == 1 && AM.HasBaseReg) 1343 return true; 1344 1345 return false; 1346 1347 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1348 return isLegalMUBUFAddressingMode(AM); 1349 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1350 AS == AMDGPUAS::REGION_ADDRESS) { 1351 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1352 // field. 1353 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1354 // an 8-bit dword offset but we don't know the alignment here. 1355 if (!isUInt<16>(AM.BaseOffs)) 1356 return false; 1357 1358 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1359 return true; 1360 1361 if (AM.Scale == 1 && AM.HasBaseReg) 1362 return true; 1363 1364 return false; 1365 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1366 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1367 // For an unknown address space, this usually means that this is for some 1368 // reason being used for pure arithmetic, and not based on some addressing 1369 // computation. We don't have instructions that compute pointers with any 1370 // addressing modes, so treat them as having no offset like flat 1371 // instructions. 1372 return isLegalFlatAddressingMode(AM); 1373 } 1374 1375 // Assume a user alias of global for unknown address spaces. 1376 return isLegalGlobalAddressingMode(AM); 1377 } 1378 1379 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1380 const SelectionDAG &DAG) const { 1381 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1382 return (MemVT.getSizeInBits() <= 4 * 32); 1383 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1384 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1385 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1386 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1387 return (MemVT.getSizeInBits() <= 2 * 32); 1388 } 1389 return true; 1390 } 1391 1392 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1393 unsigned Size, unsigned AddrSpace, Align Alignment, 1394 MachineMemOperand::Flags Flags, bool *IsFast) const { 1395 if (IsFast) 1396 *IsFast = false; 1397 1398 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1399 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1400 // Check if alignment requirements for ds_read/write instructions are 1401 // disabled. 1402 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1403 if (IsFast) 1404 *IsFast = true; 1405 return true; 1406 } 1407 1408 if (Size == 64) { 1409 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1410 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1411 // with adjacent offsets. 1412 bool AlignedBy4 = Alignment >= Align(4); 1413 if (IsFast) 1414 *IsFast = AlignedBy4; 1415 1416 return AlignedBy4; 1417 } 1418 if (Size == 96) { 1419 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1420 bool Aligned = Alignment >= Align((Subtarget->hasUnalignedDSAccess() && 1421 !Subtarget->hasLDSMisalignedBug()) 1422 ? 4 1423 : 16); 1424 if (IsFast) 1425 *IsFast = Aligned; 1426 1427 return Aligned; 1428 } 1429 if (Size == 128) { 1430 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1431 // can do a 8 byte aligned, 16 byte access in a single operation using 1432 // ds_read2/write2_b64. 1433 bool Aligned = Alignment >= Align((Subtarget->hasUnalignedDSAccess() && 1434 !Subtarget->hasLDSMisalignedBug()) 1435 ? 4 1436 : 8); 1437 if (IsFast) 1438 *IsFast = Aligned; 1439 1440 return Aligned; 1441 } 1442 } 1443 1444 // FIXME: We have to be conservative here and assume that flat operations 1445 // will access scratch. If we had access to the IR function, then we 1446 // could determine if any private memory was used in the function. 1447 if (!Subtarget->hasUnalignedScratchAccess() && 1448 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1449 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1450 bool AlignedBy4 = Alignment >= Align(4); 1451 if (IsFast) 1452 *IsFast = AlignedBy4; 1453 1454 return AlignedBy4; 1455 } 1456 1457 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1458 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1459 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1460 // If we have an uniform constant load, it still requires using a slow 1461 // buffer instruction if unaligned. 1462 if (IsFast) { 1463 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1464 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1465 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1466 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1467 Alignment >= Align(4) : Alignment != Align(2); 1468 } 1469 1470 return true; 1471 } 1472 1473 // Smaller than dword value must be aligned. 1474 if (Size < 32) 1475 return false; 1476 1477 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1478 // byte-address are ignored, thus forcing Dword alignment. 1479 // This applies to private, global, and constant memory. 1480 if (IsFast) 1481 *IsFast = true; 1482 1483 return Size >= 32 && Alignment >= Align(4); 1484 } 1485 1486 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1487 EVT VT, unsigned AddrSpace, unsigned Alignment, 1488 MachineMemOperand::Flags Flags, bool *IsFast) const { 1489 if (IsFast) 1490 *IsFast = false; 1491 1492 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1493 // which isn't a simple VT. 1494 // Until MVT is extended to handle this, simply check for the size and 1495 // rely on the condition below: allow accesses if the size is a multiple of 4. 1496 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1497 VT.getStoreSize() > 16)) { 1498 return false; 1499 } 1500 1501 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1502 Align(Alignment), Flags, IsFast); 1503 } 1504 1505 EVT SITargetLowering::getOptimalMemOpType( 1506 const MemOp &Op, const AttributeList &FuncAttributes) const { 1507 // FIXME: Should account for address space here. 1508 1509 // The default fallback uses the private pointer size as a guess for a type to 1510 // use. Make sure we switch these to 64-bit accesses. 1511 1512 if (Op.size() >= 16 && 1513 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1514 return MVT::v4i32; 1515 1516 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1517 return MVT::v2i32; 1518 1519 // Use the default. 1520 return MVT::Other; 1521 } 1522 1523 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1524 const MemSDNode *MemNode = cast<MemSDNode>(N); 1525 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1526 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1527 return I && I->getMetadata("amdgpu.noclobber"); 1528 } 1529 1530 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1531 unsigned DestAS) const { 1532 // Flat -> private/local is a simple truncate. 1533 // Flat -> global is no-op 1534 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1535 return true; 1536 1537 const GCNTargetMachine &TM = 1538 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1539 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1540 } 1541 1542 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1543 const MemSDNode *MemNode = cast<MemSDNode>(N); 1544 1545 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1546 } 1547 1548 TargetLoweringBase::LegalizeTypeAction 1549 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1550 int NumElts = VT.getVectorNumElements(); 1551 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1552 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1553 return TargetLoweringBase::getPreferredVectorAction(VT); 1554 } 1555 1556 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1557 Type *Ty) const { 1558 // FIXME: Could be smarter if called for vector constants. 1559 return true; 1560 } 1561 1562 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1563 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1564 switch (Op) { 1565 case ISD::LOAD: 1566 case ISD::STORE: 1567 1568 // These operations are done with 32-bit instructions anyway. 1569 case ISD::AND: 1570 case ISD::OR: 1571 case ISD::XOR: 1572 case ISD::SELECT: 1573 // TODO: Extensions? 1574 return true; 1575 default: 1576 return false; 1577 } 1578 } 1579 1580 // SimplifySetCC uses this function to determine whether or not it should 1581 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1582 if (VT == MVT::i1 && Op == ISD::SETCC) 1583 return false; 1584 1585 return TargetLowering::isTypeDesirableForOp(Op, VT); 1586 } 1587 1588 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1589 const SDLoc &SL, 1590 SDValue Chain, 1591 uint64_t Offset) const { 1592 const DataLayout &DL = DAG.getDataLayout(); 1593 MachineFunction &MF = DAG.getMachineFunction(); 1594 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1595 1596 const ArgDescriptor *InputPtrReg; 1597 const TargetRegisterClass *RC; 1598 LLT ArgTy; 1599 1600 std::tie(InputPtrReg, RC, ArgTy) = 1601 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1602 1603 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1604 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1605 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1606 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1607 1608 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1609 } 1610 1611 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1612 const SDLoc &SL) const { 1613 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1614 FIRST_IMPLICIT); 1615 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1616 } 1617 1618 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1619 const SDLoc &SL, SDValue Val, 1620 bool Signed, 1621 const ISD::InputArg *Arg) const { 1622 // First, if it is a widened vector, narrow it. 1623 if (VT.isVector() && 1624 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1625 EVT NarrowedVT = 1626 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1627 VT.getVectorNumElements()); 1628 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1629 DAG.getConstant(0, SL, MVT::i32)); 1630 } 1631 1632 // Then convert the vector elements or scalar value. 1633 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1634 VT.bitsLT(MemVT)) { 1635 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1636 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1637 } 1638 1639 if (MemVT.isFloatingPoint()) 1640 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1641 else if (Signed) 1642 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1643 else 1644 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1645 1646 return Val; 1647 } 1648 1649 SDValue SITargetLowering::lowerKernargMemParameter( 1650 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1651 uint64_t Offset, Align Alignment, bool Signed, 1652 const ISD::InputArg *Arg) const { 1653 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1654 1655 // Try to avoid using an extload by loading earlier than the argument address, 1656 // and extracting the relevant bits. The load should hopefully be merged with 1657 // the previous argument. 1658 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1659 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1660 int64_t AlignDownOffset = alignDown(Offset, 4); 1661 int64_t OffsetDiff = Offset - AlignDownOffset; 1662 1663 EVT IntVT = MemVT.changeTypeToInteger(); 1664 1665 // TODO: If we passed in the base kernel offset we could have a better 1666 // alignment than 4, but we don't really need it. 1667 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1668 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1669 MachineMemOperand::MODereferenceable | 1670 MachineMemOperand::MOInvariant); 1671 1672 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1673 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1674 1675 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1676 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1677 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1678 1679 1680 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1681 } 1682 1683 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1684 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1685 MachineMemOperand::MODereferenceable | 1686 MachineMemOperand::MOInvariant); 1687 1688 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1689 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1690 } 1691 1692 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1693 const SDLoc &SL, SDValue Chain, 1694 const ISD::InputArg &Arg) const { 1695 MachineFunction &MF = DAG.getMachineFunction(); 1696 MachineFrameInfo &MFI = MF.getFrameInfo(); 1697 1698 if (Arg.Flags.isByVal()) { 1699 unsigned Size = Arg.Flags.getByValSize(); 1700 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1701 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1702 } 1703 1704 unsigned ArgOffset = VA.getLocMemOffset(); 1705 unsigned ArgSize = VA.getValVT().getStoreSize(); 1706 1707 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1708 1709 // Create load nodes to retrieve arguments from the stack. 1710 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1711 SDValue ArgValue; 1712 1713 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1714 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1715 MVT MemVT = VA.getValVT(); 1716 1717 switch (VA.getLocInfo()) { 1718 default: 1719 break; 1720 case CCValAssign::BCvt: 1721 MemVT = VA.getLocVT(); 1722 break; 1723 case CCValAssign::SExt: 1724 ExtType = ISD::SEXTLOAD; 1725 break; 1726 case CCValAssign::ZExt: 1727 ExtType = ISD::ZEXTLOAD; 1728 break; 1729 case CCValAssign::AExt: 1730 ExtType = ISD::EXTLOAD; 1731 break; 1732 } 1733 1734 ArgValue = DAG.getExtLoad( 1735 ExtType, SL, VA.getLocVT(), Chain, FIN, 1736 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1737 MemVT); 1738 return ArgValue; 1739 } 1740 1741 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1742 const SIMachineFunctionInfo &MFI, 1743 EVT VT, 1744 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1745 const ArgDescriptor *Reg; 1746 const TargetRegisterClass *RC; 1747 LLT Ty; 1748 1749 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1750 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1751 } 1752 1753 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1754 CallingConv::ID CallConv, 1755 ArrayRef<ISD::InputArg> Ins, 1756 BitVector &Skipped, 1757 FunctionType *FType, 1758 SIMachineFunctionInfo *Info) { 1759 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1760 const ISD::InputArg *Arg = &Ins[I]; 1761 1762 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1763 "vector type argument should have been split"); 1764 1765 // First check if it's a PS input addr. 1766 if (CallConv == CallingConv::AMDGPU_PS && 1767 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1768 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1769 1770 // Inconveniently only the first part of the split is marked as isSplit, 1771 // so skip to the end. We only want to increment PSInputNum once for the 1772 // entire split argument. 1773 if (Arg->Flags.isSplit()) { 1774 while (!Arg->Flags.isSplitEnd()) { 1775 assert((!Arg->VT.isVector() || 1776 Arg->VT.getScalarSizeInBits() == 16) && 1777 "unexpected vector split in ps argument type"); 1778 if (!SkipArg) 1779 Splits.push_back(*Arg); 1780 Arg = &Ins[++I]; 1781 } 1782 } 1783 1784 if (SkipArg) { 1785 // We can safely skip PS inputs. 1786 Skipped.set(Arg->getOrigArgIndex()); 1787 ++PSInputNum; 1788 continue; 1789 } 1790 1791 Info->markPSInputAllocated(PSInputNum); 1792 if (Arg->Used) 1793 Info->markPSInputEnabled(PSInputNum); 1794 1795 ++PSInputNum; 1796 } 1797 1798 Splits.push_back(*Arg); 1799 } 1800 } 1801 1802 // Allocate special inputs passed in VGPRs. 1803 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1804 MachineFunction &MF, 1805 const SIRegisterInfo &TRI, 1806 SIMachineFunctionInfo &Info) const { 1807 const LLT S32 = LLT::scalar(32); 1808 MachineRegisterInfo &MRI = MF.getRegInfo(); 1809 1810 if (Info.hasWorkItemIDX()) { 1811 Register Reg = AMDGPU::VGPR0; 1812 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1813 1814 CCInfo.AllocateReg(Reg); 1815 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1816 } 1817 1818 if (Info.hasWorkItemIDY()) { 1819 Register Reg = AMDGPU::VGPR1; 1820 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1821 1822 CCInfo.AllocateReg(Reg); 1823 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1824 } 1825 1826 if (Info.hasWorkItemIDZ()) { 1827 Register Reg = AMDGPU::VGPR2; 1828 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1829 1830 CCInfo.AllocateReg(Reg); 1831 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1832 } 1833 } 1834 1835 // Try to allocate a VGPR at the end of the argument list, or if no argument 1836 // VGPRs are left allocating a stack slot. 1837 // If \p Mask is is given it indicates bitfield position in the register. 1838 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1839 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1840 ArgDescriptor Arg = ArgDescriptor()) { 1841 if (Arg.isSet()) 1842 return ArgDescriptor::createArg(Arg, Mask); 1843 1844 ArrayRef<MCPhysReg> ArgVGPRs 1845 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1846 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1847 if (RegIdx == ArgVGPRs.size()) { 1848 // Spill to stack required. 1849 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1850 1851 return ArgDescriptor::createStack(Offset, Mask); 1852 } 1853 1854 unsigned Reg = ArgVGPRs[RegIdx]; 1855 Reg = CCInfo.AllocateReg(Reg); 1856 assert(Reg != AMDGPU::NoRegister); 1857 1858 MachineFunction &MF = CCInfo.getMachineFunction(); 1859 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1860 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1861 return ArgDescriptor::createRegister(Reg, Mask); 1862 } 1863 1864 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1865 const TargetRegisterClass *RC, 1866 unsigned NumArgRegs) { 1867 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1868 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1869 if (RegIdx == ArgSGPRs.size()) 1870 report_fatal_error("ran out of SGPRs for arguments"); 1871 1872 unsigned Reg = ArgSGPRs[RegIdx]; 1873 Reg = CCInfo.AllocateReg(Reg); 1874 assert(Reg != AMDGPU::NoRegister); 1875 1876 MachineFunction &MF = CCInfo.getMachineFunction(); 1877 MF.addLiveIn(Reg, RC); 1878 return ArgDescriptor::createRegister(Reg); 1879 } 1880 1881 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1882 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1883 } 1884 1885 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1886 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1887 } 1888 1889 /// Allocate implicit function VGPR arguments at the end of allocated user 1890 /// arguments. 1891 void SITargetLowering::allocateSpecialInputVGPRs( 1892 CCState &CCInfo, MachineFunction &MF, 1893 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1894 const unsigned Mask = 0x3ff; 1895 ArgDescriptor Arg; 1896 1897 if (Info.hasWorkItemIDX()) { 1898 Arg = allocateVGPR32Input(CCInfo, Mask); 1899 Info.setWorkItemIDX(Arg); 1900 } 1901 1902 if (Info.hasWorkItemIDY()) { 1903 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1904 Info.setWorkItemIDY(Arg); 1905 } 1906 1907 if (Info.hasWorkItemIDZ()) 1908 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1909 } 1910 1911 /// Allocate implicit function VGPR arguments in fixed registers. 1912 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1913 CCState &CCInfo, MachineFunction &MF, 1914 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1915 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1916 if (!Reg) 1917 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1918 1919 const unsigned Mask = 0x3ff; 1920 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1921 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1922 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1923 } 1924 1925 void SITargetLowering::allocateSpecialInputSGPRs( 1926 CCState &CCInfo, 1927 MachineFunction &MF, 1928 const SIRegisterInfo &TRI, 1929 SIMachineFunctionInfo &Info) const { 1930 auto &ArgInfo = Info.getArgInfo(); 1931 1932 // TODO: Unify handling with private memory pointers. 1933 1934 if (Info.hasDispatchPtr()) 1935 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1936 1937 if (Info.hasQueuePtr()) 1938 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1939 1940 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1941 // constant offset from the kernarg segment. 1942 if (Info.hasImplicitArgPtr()) 1943 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1944 1945 if (Info.hasDispatchID()) 1946 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1947 1948 // flat_scratch_init is not applicable for non-kernel functions. 1949 1950 if (Info.hasWorkGroupIDX()) 1951 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1952 1953 if (Info.hasWorkGroupIDY()) 1954 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1955 1956 if (Info.hasWorkGroupIDZ()) 1957 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1958 } 1959 1960 // Allocate special inputs passed in user SGPRs. 1961 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1962 MachineFunction &MF, 1963 const SIRegisterInfo &TRI, 1964 SIMachineFunctionInfo &Info) const { 1965 if (Info.hasImplicitBufferPtr()) { 1966 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1967 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1968 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1969 } 1970 1971 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1972 if (Info.hasPrivateSegmentBuffer()) { 1973 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1974 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1975 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1976 } 1977 1978 if (Info.hasDispatchPtr()) { 1979 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 1980 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1981 CCInfo.AllocateReg(DispatchPtrReg); 1982 } 1983 1984 if (Info.hasQueuePtr()) { 1985 Register QueuePtrReg = Info.addQueuePtr(TRI); 1986 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1987 CCInfo.AllocateReg(QueuePtrReg); 1988 } 1989 1990 if (Info.hasKernargSegmentPtr()) { 1991 MachineRegisterInfo &MRI = MF.getRegInfo(); 1992 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1993 CCInfo.AllocateReg(InputPtrReg); 1994 1995 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1996 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1997 } 1998 1999 if (Info.hasDispatchID()) { 2000 Register DispatchIDReg = Info.addDispatchID(TRI); 2001 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2002 CCInfo.AllocateReg(DispatchIDReg); 2003 } 2004 2005 if (Info.hasFlatScratchInit()) { 2006 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2007 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2008 CCInfo.AllocateReg(FlatScratchInitReg); 2009 } 2010 2011 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2012 // these from the dispatch pointer. 2013 } 2014 2015 // Allocate special input registers that are initialized per-wave. 2016 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2017 MachineFunction &MF, 2018 SIMachineFunctionInfo &Info, 2019 CallingConv::ID CallConv, 2020 bool IsShader) const { 2021 if (Info.hasWorkGroupIDX()) { 2022 Register Reg = Info.addWorkGroupIDX(); 2023 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2024 CCInfo.AllocateReg(Reg); 2025 } 2026 2027 if (Info.hasWorkGroupIDY()) { 2028 Register Reg = Info.addWorkGroupIDY(); 2029 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2030 CCInfo.AllocateReg(Reg); 2031 } 2032 2033 if (Info.hasWorkGroupIDZ()) { 2034 Register Reg = Info.addWorkGroupIDZ(); 2035 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2036 CCInfo.AllocateReg(Reg); 2037 } 2038 2039 if (Info.hasWorkGroupInfo()) { 2040 Register Reg = Info.addWorkGroupInfo(); 2041 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2042 CCInfo.AllocateReg(Reg); 2043 } 2044 2045 if (Info.hasPrivateSegmentWaveByteOffset()) { 2046 // Scratch wave offset passed in system SGPR. 2047 unsigned PrivateSegmentWaveByteOffsetReg; 2048 2049 if (IsShader) { 2050 PrivateSegmentWaveByteOffsetReg = 2051 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2052 2053 // This is true if the scratch wave byte offset doesn't have a fixed 2054 // location. 2055 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2056 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2057 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2058 } 2059 } else 2060 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2061 2062 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2063 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2064 } 2065 } 2066 2067 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2068 MachineFunction &MF, 2069 const SIRegisterInfo &TRI, 2070 SIMachineFunctionInfo &Info) { 2071 // Now that we've figured out where the scratch register inputs are, see if 2072 // should reserve the arguments and use them directly. 2073 MachineFrameInfo &MFI = MF.getFrameInfo(); 2074 bool HasStackObjects = MFI.hasStackObjects(); 2075 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2076 2077 // Record that we know we have non-spill stack objects so we don't need to 2078 // check all stack objects later. 2079 if (HasStackObjects) 2080 Info.setHasNonSpillStackObjects(true); 2081 2082 // Everything live out of a block is spilled with fast regalloc, so it's 2083 // almost certain that spilling will be required. 2084 if (TM.getOptLevel() == CodeGenOpt::None) 2085 HasStackObjects = true; 2086 2087 // For now assume stack access is needed in any callee functions, so we need 2088 // the scratch registers to pass in. 2089 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2090 2091 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2092 // If we have stack objects, we unquestionably need the private buffer 2093 // resource. For the Code Object V2 ABI, this will be the first 4 user 2094 // SGPR inputs. We can reserve those and use them directly. 2095 2096 Register PrivateSegmentBufferReg = 2097 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2098 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2099 } else { 2100 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2101 // We tentatively reserve the last registers (skipping the last registers 2102 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2103 // we'll replace these with the ones immediately after those which were 2104 // really allocated. In the prologue copies will be inserted from the 2105 // argument to these reserved registers. 2106 2107 // Without HSA, relocations are used for the scratch pointer and the 2108 // buffer resource setup is always inserted in the prologue. Scratch wave 2109 // offset is still in an input SGPR. 2110 Info.setScratchRSrcReg(ReservedBufferReg); 2111 } 2112 2113 MachineRegisterInfo &MRI = MF.getRegInfo(); 2114 2115 // For entry functions we have to set up the stack pointer if we use it, 2116 // whereas non-entry functions get this "for free". This means there is no 2117 // intrinsic advantage to using S32 over S34 in cases where we do not have 2118 // calls but do need a frame pointer (i.e. if we are requested to have one 2119 // because frame pointer elimination is disabled). To keep things simple we 2120 // only ever use S32 as the call ABI stack pointer, and so using it does not 2121 // imply we need a separate frame pointer. 2122 // 2123 // Try to use s32 as the SP, but move it if it would interfere with input 2124 // arguments. This won't work with calls though. 2125 // 2126 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2127 // registers. 2128 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2129 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2130 } else { 2131 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2132 2133 if (MFI.hasCalls()) 2134 report_fatal_error("call in graphics shader with too many input SGPRs"); 2135 2136 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2137 if (!MRI.isLiveIn(Reg)) { 2138 Info.setStackPtrOffsetReg(Reg); 2139 break; 2140 } 2141 } 2142 2143 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2144 report_fatal_error("failed to find register for SP"); 2145 } 2146 2147 // hasFP should be accurate for entry functions even before the frame is 2148 // finalized, because it does not rely on the known stack size, only 2149 // properties like whether variable sized objects are present. 2150 if (ST.getFrameLowering()->hasFP(MF)) { 2151 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2152 } 2153 } 2154 2155 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2156 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2157 return !Info->isEntryFunction(); 2158 } 2159 2160 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2161 2162 } 2163 2164 void SITargetLowering::insertCopiesSplitCSR( 2165 MachineBasicBlock *Entry, 2166 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2167 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2168 2169 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2170 if (!IStart) 2171 return; 2172 2173 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2174 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2175 MachineBasicBlock::iterator MBBI = Entry->begin(); 2176 for (const MCPhysReg *I = IStart; *I; ++I) { 2177 const TargetRegisterClass *RC = nullptr; 2178 if (AMDGPU::SReg_64RegClass.contains(*I)) 2179 RC = &AMDGPU::SGPR_64RegClass; 2180 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2181 RC = &AMDGPU::SGPR_32RegClass; 2182 else 2183 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2184 2185 Register NewVR = MRI->createVirtualRegister(RC); 2186 // Create copy from CSR to a virtual register. 2187 Entry->addLiveIn(*I); 2188 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2189 .addReg(*I); 2190 2191 // Insert the copy-back instructions right before the terminator. 2192 for (auto *Exit : Exits) 2193 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2194 TII->get(TargetOpcode::COPY), *I) 2195 .addReg(NewVR); 2196 } 2197 } 2198 2199 SDValue SITargetLowering::LowerFormalArguments( 2200 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2201 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2202 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2203 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2204 2205 MachineFunction &MF = DAG.getMachineFunction(); 2206 const Function &Fn = MF.getFunction(); 2207 FunctionType *FType = MF.getFunction().getFunctionType(); 2208 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2209 2210 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2211 DiagnosticInfoUnsupported NoGraphicsHSA( 2212 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2213 DAG.getContext()->diagnose(NoGraphicsHSA); 2214 return DAG.getEntryNode(); 2215 } 2216 2217 SmallVector<ISD::InputArg, 16> Splits; 2218 SmallVector<CCValAssign, 16> ArgLocs; 2219 BitVector Skipped(Ins.size()); 2220 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2221 *DAG.getContext()); 2222 2223 bool IsShader = AMDGPU::isShader(CallConv); 2224 bool IsKernel = AMDGPU::isKernel(CallConv); 2225 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2226 2227 if (IsShader) { 2228 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2229 2230 // At least one interpolation mode must be enabled or else the GPU will 2231 // hang. 2232 // 2233 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2234 // set PSInputAddr, the user wants to enable some bits after the compilation 2235 // based on run-time states. Since we can't know what the final PSInputEna 2236 // will look like, so we shouldn't do anything here and the user should take 2237 // responsibility for the correct programming. 2238 // 2239 // Otherwise, the following restrictions apply: 2240 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2241 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2242 // enabled too. 2243 if (CallConv == CallingConv::AMDGPU_PS) { 2244 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2245 ((Info->getPSInputAddr() & 0xF) == 0 && 2246 Info->isPSInputAllocated(11))) { 2247 CCInfo.AllocateReg(AMDGPU::VGPR0); 2248 CCInfo.AllocateReg(AMDGPU::VGPR1); 2249 Info->markPSInputAllocated(0); 2250 Info->markPSInputEnabled(0); 2251 } 2252 if (Subtarget->isAmdPalOS()) { 2253 // For isAmdPalOS, the user does not enable some bits after compilation 2254 // based on run-time states; the register values being generated here are 2255 // the final ones set in hardware. Therefore we need to apply the 2256 // workaround to PSInputAddr and PSInputEnable together. (The case where 2257 // a bit is set in PSInputAddr but not PSInputEnable is where the 2258 // frontend set up an input arg for a particular interpolation mode, but 2259 // nothing uses that input arg. Really we should have an earlier pass 2260 // that removes such an arg.) 2261 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2262 if ((PsInputBits & 0x7F) == 0 || 2263 ((PsInputBits & 0xF) == 0 && 2264 (PsInputBits >> 11 & 1))) 2265 Info->markPSInputEnabled( 2266 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2267 } 2268 } 2269 2270 assert(!Info->hasDispatchPtr() && 2271 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2272 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2273 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2274 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2275 !Info->hasWorkItemIDZ()); 2276 } else if (IsKernel) { 2277 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2278 } else { 2279 Splits.append(Ins.begin(), Ins.end()); 2280 } 2281 2282 if (IsEntryFunc) { 2283 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2284 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2285 } else { 2286 // For the fixed ABI, pass workitem IDs in the last argument register. 2287 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2288 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2289 } 2290 2291 if (IsKernel) { 2292 analyzeFormalArgumentsCompute(CCInfo, Ins); 2293 } else { 2294 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2295 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2296 } 2297 2298 SmallVector<SDValue, 16> Chains; 2299 2300 // FIXME: This is the minimum kernel argument alignment. We should improve 2301 // this to the maximum alignment of the arguments. 2302 // 2303 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2304 // kern arg offset. 2305 const Align KernelArgBaseAlign = Align(16); 2306 2307 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2308 const ISD::InputArg &Arg = Ins[i]; 2309 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2310 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2311 continue; 2312 } 2313 2314 CCValAssign &VA = ArgLocs[ArgIdx++]; 2315 MVT VT = VA.getLocVT(); 2316 2317 if (IsEntryFunc && VA.isMemLoc()) { 2318 VT = Ins[i].VT; 2319 EVT MemVT = VA.getLocVT(); 2320 2321 const uint64_t Offset = VA.getLocMemOffset(); 2322 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2323 2324 if (Arg.Flags.isByRef()) { 2325 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2326 2327 const GCNTargetMachine &TM = 2328 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2329 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2330 Arg.Flags.getPointerAddrSpace())) { 2331 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2332 Arg.Flags.getPointerAddrSpace()); 2333 } 2334 2335 InVals.push_back(Ptr); 2336 continue; 2337 } 2338 2339 SDValue Arg = lowerKernargMemParameter( 2340 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2341 Chains.push_back(Arg.getValue(1)); 2342 2343 auto *ParamTy = 2344 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2345 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2346 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2347 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2348 // On SI local pointers are just offsets into LDS, so they are always 2349 // less than 16-bits. On CI and newer they could potentially be 2350 // real pointers, so we can't guarantee their size. 2351 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2352 DAG.getValueType(MVT::i16)); 2353 } 2354 2355 InVals.push_back(Arg); 2356 continue; 2357 } else if (!IsEntryFunc && VA.isMemLoc()) { 2358 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2359 InVals.push_back(Val); 2360 if (!Arg.Flags.isByVal()) 2361 Chains.push_back(Val.getValue(1)); 2362 continue; 2363 } 2364 2365 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2366 2367 Register Reg = VA.getLocReg(); 2368 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2369 EVT ValVT = VA.getValVT(); 2370 2371 Reg = MF.addLiveIn(Reg, RC); 2372 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2373 2374 if (Arg.Flags.isSRet()) { 2375 // The return object should be reasonably addressable. 2376 2377 // FIXME: This helps when the return is a real sret. If it is a 2378 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2379 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2380 unsigned NumBits 2381 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2382 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2383 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2384 } 2385 2386 // If this is an 8 or 16-bit value, it is really passed promoted 2387 // to 32 bits. Insert an assert[sz]ext to capture this, then 2388 // truncate to the right size. 2389 switch (VA.getLocInfo()) { 2390 case CCValAssign::Full: 2391 break; 2392 case CCValAssign::BCvt: 2393 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2394 break; 2395 case CCValAssign::SExt: 2396 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2397 DAG.getValueType(ValVT)); 2398 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2399 break; 2400 case CCValAssign::ZExt: 2401 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2402 DAG.getValueType(ValVT)); 2403 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2404 break; 2405 case CCValAssign::AExt: 2406 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2407 break; 2408 default: 2409 llvm_unreachable("Unknown loc info!"); 2410 } 2411 2412 InVals.push_back(Val); 2413 } 2414 2415 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2416 // Special inputs come after user arguments. 2417 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2418 } 2419 2420 // Start adding system SGPRs. 2421 if (IsEntryFunc) { 2422 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2423 } else { 2424 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2425 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2426 } 2427 2428 auto &ArgUsageInfo = 2429 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2430 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2431 2432 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2433 Info->setBytesInStackArgArea(StackArgSize); 2434 2435 return Chains.empty() ? Chain : 2436 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2437 } 2438 2439 // TODO: If return values can't fit in registers, we should return as many as 2440 // possible in registers before passing on stack. 2441 bool SITargetLowering::CanLowerReturn( 2442 CallingConv::ID CallConv, 2443 MachineFunction &MF, bool IsVarArg, 2444 const SmallVectorImpl<ISD::OutputArg> &Outs, 2445 LLVMContext &Context) const { 2446 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2447 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2448 // for shaders. Vector types should be explicitly handled by CC. 2449 if (AMDGPU::isEntryFunctionCC(CallConv)) 2450 return true; 2451 2452 SmallVector<CCValAssign, 16> RVLocs; 2453 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2454 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2455 } 2456 2457 SDValue 2458 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2459 bool isVarArg, 2460 const SmallVectorImpl<ISD::OutputArg> &Outs, 2461 const SmallVectorImpl<SDValue> &OutVals, 2462 const SDLoc &DL, SelectionDAG &DAG) const { 2463 MachineFunction &MF = DAG.getMachineFunction(); 2464 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2465 2466 if (AMDGPU::isKernel(CallConv)) { 2467 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2468 OutVals, DL, DAG); 2469 } 2470 2471 bool IsShader = AMDGPU::isShader(CallConv); 2472 2473 Info->setIfReturnsVoid(Outs.empty()); 2474 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2475 2476 // CCValAssign - represent the assignment of the return value to a location. 2477 SmallVector<CCValAssign, 48> RVLocs; 2478 SmallVector<ISD::OutputArg, 48> Splits; 2479 2480 // CCState - Info about the registers and stack slots. 2481 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2482 *DAG.getContext()); 2483 2484 // Analyze outgoing return values. 2485 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2486 2487 SDValue Flag; 2488 SmallVector<SDValue, 48> RetOps; 2489 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2490 2491 // Add return address for callable functions. 2492 if (!Info->isEntryFunction()) { 2493 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2494 SDValue ReturnAddrReg = CreateLiveInRegister( 2495 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2496 2497 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2498 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2499 MVT::i64); 2500 Chain = 2501 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2502 Flag = Chain.getValue(1); 2503 RetOps.push_back(ReturnAddrVirtualReg); 2504 } 2505 2506 // Copy the result values into the output registers. 2507 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2508 ++I, ++RealRVLocIdx) { 2509 CCValAssign &VA = RVLocs[I]; 2510 assert(VA.isRegLoc() && "Can only return in registers!"); 2511 // TODO: Partially return in registers if return values don't fit. 2512 SDValue Arg = OutVals[RealRVLocIdx]; 2513 2514 // Copied from other backends. 2515 switch (VA.getLocInfo()) { 2516 case CCValAssign::Full: 2517 break; 2518 case CCValAssign::BCvt: 2519 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2520 break; 2521 case CCValAssign::SExt: 2522 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2523 break; 2524 case CCValAssign::ZExt: 2525 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2526 break; 2527 case CCValAssign::AExt: 2528 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2529 break; 2530 default: 2531 llvm_unreachable("Unknown loc info!"); 2532 } 2533 2534 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2535 Flag = Chain.getValue(1); 2536 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2537 } 2538 2539 // FIXME: Does sret work properly? 2540 if (!Info->isEntryFunction()) { 2541 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2542 const MCPhysReg *I = 2543 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2544 if (I) { 2545 for (; *I; ++I) { 2546 if (AMDGPU::SReg_64RegClass.contains(*I)) 2547 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2548 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2549 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2550 else 2551 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2552 } 2553 } 2554 } 2555 2556 // Update chain and glue. 2557 RetOps[0] = Chain; 2558 if (Flag.getNode()) 2559 RetOps.push_back(Flag); 2560 2561 unsigned Opc = AMDGPUISD::ENDPGM; 2562 if (!IsWaveEnd) 2563 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2564 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2565 } 2566 2567 SDValue SITargetLowering::LowerCallResult( 2568 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2569 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2570 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2571 SDValue ThisVal) const { 2572 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2573 2574 // Assign locations to each value returned by this call. 2575 SmallVector<CCValAssign, 16> RVLocs; 2576 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2577 *DAG.getContext()); 2578 CCInfo.AnalyzeCallResult(Ins, RetCC); 2579 2580 // Copy all of the result registers out of their specified physreg. 2581 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2582 CCValAssign VA = RVLocs[i]; 2583 SDValue Val; 2584 2585 if (VA.isRegLoc()) { 2586 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2587 Chain = Val.getValue(1); 2588 InFlag = Val.getValue(2); 2589 } else if (VA.isMemLoc()) { 2590 report_fatal_error("TODO: return values in memory"); 2591 } else 2592 llvm_unreachable("unknown argument location type"); 2593 2594 switch (VA.getLocInfo()) { 2595 case CCValAssign::Full: 2596 break; 2597 case CCValAssign::BCvt: 2598 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2599 break; 2600 case CCValAssign::ZExt: 2601 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2602 DAG.getValueType(VA.getValVT())); 2603 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2604 break; 2605 case CCValAssign::SExt: 2606 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2607 DAG.getValueType(VA.getValVT())); 2608 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2609 break; 2610 case CCValAssign::AExt: 2611 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2612 break; 2613 default: 2614 llvm_unreachable("Unknown loc info!"); 2615 } 2616 2617 InVals.push_back(Val); 2618 } 2619 2620 return Chain; 2621 } 2622 2623 // Add code to pass special inputs required depending on used features separate 2624 // from the explicit user arguments present in the IR. 2625 void SITargetLowering::passSpecialInputs( 2626 CallLoweringInfo &CLI, 2627 CCState &CCInfo, 2628 const SIMachineFunctionInfo &Info, 2629 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2630 SmallVectorImpl<SDValue> &MemOpChains, 2631 SDValue Chain) const { 2632 // If we don't have a call site, this was a call inserted by 2633 // legalization. These can never use special inputs. 2634 if (!CLI.CB) 2635 return; 2636 2637 SelectionDAG &DAG = CLI.DAG; 2638 const SDLoc &DL = CLI.DL; 2639 2640 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2641 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2642 2643 const AMDGPUFunctionArgInfo *CalleeArgInfo 2644 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2645 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2646 auto &ArgUsageInfo = 2647 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2648 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2649 } 2650 2651 // TODO: Unify with private memory register handling. This is complicated by 2652 // the fact that at least in kernels, the input argument is not necessarily 2653 // in the same location as the input. 2654 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2655 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2656 AMDGPUFunctionArgInfo::QUEUE_PTR, 2657 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2658 AMDGPUFunctionArgInfo::DISPATCH_ID, 2659 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2660 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2661 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2662 }; 2663 2664 for (auto InputID : InputRegs) { 2665 const ArgDescriptor *OutgoingArg; 2666 const TargetRegisterClass *ArgRC; 2667 LLT ArgTy; 2668 2669 std::tie(OutgoingArg, ArgRC, ArgTy) = 2670 CalleeArgInfo->getPreloadedValue(InputID); 2671 if (!OutgoingArg) 2672 continue; 2673 2674 const ArgDescriptor *IncomingArg; 2675 const TargetRegisterClass *IncomingArgRC; 2676 LLT Ty; 2677 std::tie(IncomingArg, IncomingArgRC, Ty) = 2678 CallerArgInfo.getPreloadedValue(InputID); 2679 assert(IncomingArgRC == ArgRC); 2680 2681 // All special arguments are ints for now. 2682 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2683 SDValue InputReg; 2684 2685 if (IncomingArg) { 2686 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2687 } else { 2688 // The implicit arg ptr is special because it doesn't have a corresponding 2689 // input for kernels, and is computed from the kernarg segment pointer. 2690 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2691 InputReg = getImplicitArgPtr(DAG, DL); 2692 } 2693 2694 if (OutgoingArg->isRegister()) { 2695 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2696 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2697 report_fatal_error("failed to allocate implicit input argument"); 2698 } else { 2699 unsigned SpecialArgOffset = 2700 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2701 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2702 SpecialArgOffset); 2703 MemOpChains.push_back(ArgStore); 2704 } 2705 } 2706 2707 // Pack workitem IDs into a single register or pass it as is if already 2708 // packed. 2709 const ArgDescriptor *OutgoingArg; 2710 const TargetRegisterClass *ArgRC; 2711 LLT Ty; 2712 2713 std::tie(OutgoingArg, ArgRC, Ty) = 2714 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2715 if (!OutgoingArg) 2716 std::tie(OutgoingArg, ArgRC, Ty) = 2717 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2718 if (!OutgoingArg) 2719 std::tie(OutgoingArg, ArgRC, Ty) = 2720 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2721 if (!OutgoingArg) 2722 return; 2723 2724 const ArgDescriptor *IncomingArgX = std::get<0>( 2725 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2726 const ArgDescriptor *IncomingArgY = std::get<0>( 2727 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2728 const ArgDescriptor *IncomingArgZ = std::get<0>( 2729 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2730 2731 SDValue InputReg; 2732 SDLoc SL; 2733 2734 // If incoming ids are not packed we need to pack them. 2735 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2736 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2737 2738 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2739 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2740 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2741 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2742 InputReg = InputReg.getNode() ? 2743 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2744 } 2745 2746 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2747 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2748 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2749 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2750 InputReg = InputReg.getNode() ? 2751 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2752 } 2753 2754 if (!InputReg.getNode()) { 2755 // Workitem ids are already packed, any of present incoming arguments 2756 // will carry all required fields. 2757 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2758 IncomingArgX ? *IncomingArgX : 2759 IncomingArgY ? *IncomingArgY : 2760 *IncomingArgZ, ~0u); 2761 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2762 } 2763 2764 if (OutgoingArg->isRegister()) { 2765 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2766 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2767 } else { 2768 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2769 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2770 SpecialArgOffset); 2771 MemOpChains.push_back(ArgStore); 2772 } 2773 } 2774 2775 static bool canGuaranteeTCO(CallingConv::ID CC) { 2776 return CC == CallingConv::Fast; 2777 } 2778 2779 /// Return true if we might ever do TCO for calls with this calling convention. 2780 static bool mayTailCallThisCC(CallingConv::ID CC) { 2781 switch (CC) { 2782 case CallingConv::C: 2783 return true; 2784 default: 2785 return canGuaranteeTCO(CC); 2786 } 2787 } 2788 2789 bool SITargetLowering::isEligibleForTailCallOptimization( 2790 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2791 const SmallVectorImpl<ISD::OutputArg> &Outs, 2792 const SmallVectorImpl<SDValue> &OutVals, 2793 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2794 if (!mayTailCallThisCC(CalleeCC)) 2795 return false; 2796 2797 MachineFunction &MF = DAG.getMachineFunction(); 2798 const Function &CallerF = MF.getFunction(); 2799 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2800 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2801 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2802 2803 // Kernels aren't callable, and don't have a live in return address so it 2804 // doesn't make sense to do a tail call with entry functions. 2805 if (!CallerPreserved) 2806 return false; 2807 2808 bool CCMatch = CallerCC == CalleeCC; 2809 2810 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2811 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2812 return true; 2813 return false; 2814 } 2815 2816 // TODO: Can we handle var args? 2817 if (IsVarArg) 2818 return false; 2819 2820 for (const Argument &Arg : CallerF.args()) { 2821 if (Arg.hasByValAttr()) 2822 return false; 2823 } 2824 2825 LLVMContext &Ctx = *DAG.getContext(); 2826 2827 // Check that the call results are passed in the same way. 2828 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2829 CCAssignFnForCall(CalleeCC, IsVarArg), 2830 CCAssignFnForCall(CallerCC, IsVarArg))) 2831 return false; 2832 2833 // The callee has to preserve all registers the caller needs to preserve. 2834 if (!CCMatch) { 2835 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2836 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2837 return false; 2838 } 2839 2840 // Nothing more to check if the callee is taking no arguments. 2841 if (Outs.empty()) 2842 return true; 2843 2844 SmallVector<CCValAssign, 16> ArgLocs; 2845 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2846 2847 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2848 2849 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2850 // If the stack arguments for this call do not fit into our own save area then 2851 // the call cannot be made tail. 2852 // TODO: Is this really necessary? 2853 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2854 return false; 2855 2856 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2857 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2858 } 2859 2860 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2861 if (!CI->isTailCall()) 2862 return false; 2863 2864 const Function *ParentFn = CI->getParent()->getParent(); 2865 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2866 return false; 2867 return true; 2868 } 2869 2870 // The wave scratch offset register is used as the global base pointer. 2871 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2872 SmallVectorImpl<SDValue> &InVals) const { 2873 SelectionDAG &DAG = CLI.DAG; 2874 const SDLoc &DL = CLI.DL; 2875 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2876 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2877 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2878 SDValue Chain = CLI.Chain; 2879 SDValue Callee = CLI.Callee; 2880 bool &IsTailCall = CLI.IsTailCall; 2881 CallingConv::ID CallConv = CLI.CallConv; 2882 bool IsVarArg = CLI.IsVarArg; 2883 bool IsSibCall = false; 2884 bool IsThisReturn = false; 2885 MachineFunction &MF = DAG.getMachineFunction(); 2886 2887 if (Callee.isUndef() || isNullConstant(Callee)) { 2888 if (!CLI.IsTailCall) { 2889 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2890 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2891 } 2892 2893 return Chain; 2894 } 2895 2896 if (IsVarArg) { 2897 return lowerUnhandledCall(CLI, InVals, 2898 "unsupported call to variadic function "); 2899 } 2900 2901 if (!CLI.CB) 2902 report_fatal_error("unsupported libcall legalization"); 2903 2904 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2905 !CLI.CB->getCalledFunction()) { 2906 return lowerUnhandledCall(CLI, InVals, 2907 "unsupported indirect call to function "); 2908 } 2909 2910 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2911 return lowerUnhandledCall(CLI, InVals, 2912 "unsupported required tail call to function "); 2913 } 2914 2915 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2916 // Note the issue is with the CC of the calling function, not of the call 2917 // itself. 2918 return lowerUnhandledCall(CLI, InVals, 2919 "unsupported call from graphics shader of function "); 2920 } 2921 2922 if (IsTailCall) { 2923 IsTailCall = isEligibleForTailCallOptimization( 2924 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2925 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2926 report_fatal_error("failed to perform tail call elimination on a call " 2927 "site marked musttail"); 2928 } 2929 2930 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2931 2932 // A sibling call is one where we're under the usual C ABI and not planning 2933 // to change that but can still do a tail call: 2934 if (!TailCallOpt && IsTailCall) 2935 IsSibCall = true; 2936 2937 if (IsTailCall) 2938 ++NumTailCalls; 2939 } 2940 2941 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2942 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2943 SmallVector<SDValue, 8> MemOpChains; 2944 2945 // Analyze operands of the call, assigning locations to each operand. 2946 SmallVector<CCValAssign, 16> ArgLocs; 2947 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2948 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2949 2950 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2951 // With a fixed ABI, allocate fixed registers before user arguments. 2952 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2953 } 2954 2955 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2956 2957 // Get a count of how many bytes are to be pushed on the stack. 2958 unsigned NumBytes = CCInfo.getNextStackOffset(); 2959 2960 if (IsSibCall) { 2961 // Since we're not changing the ABI to make this a tail call, the memory 2962 // operands are already available in the caller's incoming argument space. 2963 NumBytes = 0; 2964 } 2965 2966 // FPDiff is the byte offset of the call's argument area from the callee's. 2967 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2968 // by this amount for a tail call. In a sibling call it must be 0 because the 2969 // caller will deallocate the entire stack and the callee still expects its 2970 // arguments to begin at SP+0. Completely unused for non-tail calls. 2971 int32_t FPDiff = 0; 2972 MachineFrameInfo &MFI = MF.getFrameInfo(); 2973 2974 // Adjust the stack pointer for the new arguments... 2975 // These operations are automatically eliminated by the prolog/epilog pass 2976 if (!IsSibCall) { 2977 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2978 2979 SmallVector<SDValue, 4> CopyFromChains; 2980 2981 // In the HSA case, this should be an identity copy. 2982 SDValue ScratchRSrcReg 2983 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2984 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2985 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2986 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2987 } 2988 2989 MVT PtrVT = MVT::i32; 2990 2991 // Walk the register/memloc assignments, inserting copies/loads. 2992 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2993 CCValAssign &VA = ArgLocs[i]; 2994 SDValue Arg = OutVals[i]; 2995 2996 // Promote the value if needed. 2997 switch (VA.getLocInfo()) { 2998 case CCValAssign::Full: 2999 break; 3000 case CCValAssign::BCvt: 3001 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3002 break; 3003 case CCValAssign::ZExt: 3004 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3005 break; 3006 case CCValAssign::SExt: 3007 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3008 break; 3009 case CCValAssign::AExt: 3010 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3011 break; 3012 case CCValAssign::FPExt: 3013 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3014 break; 3015 default: 3016 llvm_unreachable("Unknown loc info!"); 3017 } 3018 3019 if (VA.isRegLoc()) { 3020 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3021 } else { 3022 assert(VA.isMemLoc()); 3023 3024 SDValue DstAddr; 3025 MachinePointerInfo DstInfo; 3026 3027 unsigned LocMemOffset = VA.getLocMemOffset(); 3028 int32_t Offset = LocMemOffset; 3029 3030 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3031 MaybeAlign Alignment; 3032 3033 if (IsTailCall) { 3034 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3035 unsigned OpSize = Flags.isByVal() ? 3036 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3037 3038 // FIXME: We can have better than the minimum byval required alignment. 3039 Alignment = 3040 Flags.isByVal() 3041 ? Flags.getNonZeroByValAlign() 3042 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3043 3044 Offset = Offset + FPDiff; 3045 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3046 3047 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3048 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3049 3050 // Make sure any stack arguments overlapping with where we're storing 3051 // are loaded before this eventual operation. Otherwise they'll be 3052 // clobbered. 3053 3054 // FIXME: Why is this really necessary? This seems to just result in a 3055 // lot of code to copy the stack and write them back to the same 3056 // locations, which are supposed to be immutable? 3057 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3058 } else { 3059 DstAddr = PtrOff; 3060 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3061 Alignment = 3062 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3063 } 3064 3065 if (Outs[i].Flags.isByVal()) { 3066 SDValue SizeNode = 3067 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3068 SDValue Cpy = 3069 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3070 Outs[i].Flags.getNonZeroByValAlign(), 3071 /*isVol = */ false, /*AlwaysInline = */ true, 3072 /*isTailCall = */ false, DstInfo, 3073 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3074 3075 MemOpChains.push_back(Cpy); 3076 } else { 3077 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 3078 Alignment ? Alignment->value() : 0); 3079 MemOpChains.push_back(Store); 3080 } 3081 } 3082 } 3083 3084 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3085 // Copy special input registers after user input arguments. 3086 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3087 } 3088 3089 if (!MemOpChains.empty()) 3090 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3091 3092 // Build a sequence of copy-to-reg nodes chained together with token chain 3093 // and flag operands which copy the outgoing args into the appropriate regs. 3094 SDValue InFlag; 3095 for (auto &RegToPass : RegsToPass) { 3096 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3097 RegToPass.second, InFlag); 3098 InFlag = Chain.getValue(1); 3099 } 3100 3101 3102 SDValue PhysReturnAddrReg; 3103 if (IsTailCall) { 3104 // Since the return is being combined with the call, we need to pass on the 3105 // return address. 3106 3107 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3108 SDValue ReturnAddrReg = CreateLiveInRegister( 3109 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3110 3111 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3112 MVT::i64); 3113 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3114 InFlag = Chain.getValue(1); 3115 } 3116 3117 // We don't usually want to end the call-sequence here because we would tidy 3118 // the frame up *after* the call, however in the ABI-changing tail-call case 3119 // we've carefully laid out the parameters so that when sp is reset they'll be 3120 // in the correct location. 3121 if (IsTailCall && !IsSibCall) { 3122 Chain = DAG.getCALLSEQ_END(Chain, 3123 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3124 DAG.getTargetConstant(0, DL, MVT::i32), 3125 InFlag, DL); 3126 InFlag = Chain.getValue(1); 3127 } 3128 3129 std::vector<SDValue> Ops; 3130 Ops.push_back(Chain); 3131 Ops.push_back(Callee); 3132 // Add a redundant copy of the callee global which will not be legalized, as 3133 // we need direct access to the callee later. 3134 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3135 const GlobalValue *GV = GSD->getGlobal(); 3136 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3137 } else { 3138 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3139 } 3140 3141 if (IsTailCall) { 3142 // Each tail call may have to adjust the stack by a different amount, so 3143 // this information must travel along with the operation for eventual 3144 // consumption by emitEpilogue. 3145 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3146 3147 Ops.push_back(PhysReturnAddrReg); 3148 } 3149 3150 // Add argument registers to the end of the list so that they are known live 3151 // into the call. 3152 for (auto &RegToPass : RegsToPass) { 3153 Ops.push_back(DAG.getRegister(RegToPass.first, 3154 RegToPass.second.getValueType())); 3155 } 3156 3157 // Add a register mask operand representing the call-preserved registers. 3158 3159 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3160 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3161 assert(Mask && "Missing call preserved mask for calling convention"); 3162 Ops.push_back(DAG.getRegisterMask(Mask)); 3163 3164 if (InFlag.getNode()) 3165 Ops.push_back(InFlag); 3166 3167 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3168 3169 // If we're doing a tall call, use a TC_RETURN here rather than an 3170 // actual call instruction. 3171 if (IsTailCall) { 3172 MFI.setHasTailCall(); 3173 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3174 } 3175 3176 // Returns a chain and a flag for retval copy to use. 3177 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3178 Chain = Call.getValue(0); 3179 InFlag = Call.getValue(1); 3180 3181 uint64_t CalleePopBytes = NumBytes; 3182 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3183 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3184 InFlag, DL); 3185 if (!Ins.empty()) 3186 InFlag = Chain.getValue(1); 3187 3188 // Handle result values, copying them out of physregs into vregs that we 3189 // return. 3190 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3191 InVals, IsThisReturn, 3192 IsThisReturn ? OutVals[0] : SDValue()); 3193 } 3194 3195 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3196 // except for applying the wave size scale to the increment amount. 3197 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3198 SDValue Op, SelectionDAG &DAG) const { 3199 const MachineFunction &MF = DAG.getMachineFunction(); 3200 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3201 3202 SDLoc dl(Op); 3203 EVT VT = Op.getValueType(); 3204 SDValue Tmp1 = Op; 3205 SDValue Tmp2 = Op.getValue(1); 3206 SDValue Tmp3 = Op.getOperand(2); 3207 SDValue Chain = Tmp1.getOperand(0); 3208 3209 Register SPReg = Info->getStackPtrOffsetReg(); 3210 3211 // Chain the dynamic stack allocation so that it doesn't modify the stack 3212 // pointer when other instructions are using the stack. 3213 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3214 3215 SDValue Size = Tmp2.getOperand(1); 3216 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3217 Chain = SP.getValue(1); 3218 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3219 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3220 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3221 unsigned Opc = 3222 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3223 ISD::ADD : ISD::SUB; 3224 3225 SDValue ScaledSize = DAG.getNode( 3226 ISD::SHL, dl, VT, Size, 3227 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3228 3229 Align StackAlign = TFL->getStackAlign(); 3230 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3231 if (Alignment && *Alignment > StackAlign) { 3232 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3233 DAG.getConstant(-(uint64_t)Alignment->value() 3234 << ST.getWavefrontSizeLog2(), 3235 dl, VT)); 3236 } 3237 3238 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3239 Tmp2 = DAG.getCALLSEQ_END( 3240 Chain, DAG.getIntPtrConstant(0, dl, true), 3241 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3242 3243 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3244 } 3245 3246 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3247 SelectionDAG &DAG) const { 3248 // We only handle constant sizes here to allow non-entry block, static sized 3249 // allocas. A truly dynamic value is more difficult to support because we 3250 // don't know if the size value is uniform or not. If the size isn't uniform, 3251 // we would need to do a wave reduction to get the maximum size to know how 3252 // much to increment the uniform stack pointer. 3253 SDValue Size = Op.getOperand(1); 3254 if (isa<ConstantSDNode>(Size)) 3255 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3256 3257 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3258 } 3259 3260 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3261 const MachineFunction &MF) const { 3262 Register Reg = StringSwitch<Register>(RegName) 3263 .Case("m0", AMDGPU::M0) 3264 .Case("exec", AMDGPU::EXEC) 3265 .Case("exec_lo", AMDGPU::EXEC_LO) 3266 .Case("exec_hi", AMDGPU::EXEC_HI) 3267 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3268 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3269 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3270 .Default(Register()); 3271 3272 if (Reg == AMDGPU::NoRegister) { 3273 report_fatal_error(Twine("invalid register name \"" 3274 + StringRef(RegName) + "\".")); 3275 3276 } 3277 3278 if (!Subtarget->hasFlatScrRegister() && 3279 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3280 report_fatal_error(Twine("invalid register \"" 3281 + StringRef(RegName) + "\" for subtarget.")); 3282 } 3283 3284 switch (Reg) { 3285 case AMDGPU::M0: 3286 case AMDGPU::EXEC_LO: 3287 case AMDGPU::EXEC_HI: 3288 case AMDGPU::FLAT_SCR_LO: 3289 case AMDGPU::FLAT_SCR_HI: 3290 if (VT.getSizeInBits() == 32) 3291 return Reg; 3292 break; 3293 case AMDGPU::EXEC: 3294 case AMDGPU::FLAT_SCR: 3295 if (VT.getSizeInBits() == 64) 3296 return Reg; 3297 break; 3298 default: 3299 llvm_unreachable("missing register type checking"); 3300 } 3301 3302 report_fatal_error(Twine("invalid type for register \"" 3303 + StringRef(RegName) + "\".")); 3304 } 3305 3306 // If kill is not the last instruction, split the block so kill is always a 3307 // proper terminator. 3308 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3309 MachineBasicBlock *BB) const { 3310 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3311 3312 MachineBasicBlock::iterator SplitPoint(&MI); 3313 ++SplitPoint; 3314 3315 if (SplitPoint == BB->end()) { 3316 // Don't bother with a new block. 3317 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3318 return BB; 3319 } 3320 3321 MachineFunction *MF = BB->getParent(); 3322 MachineBasicBlock *SplitBB 3323 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3324 3325 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3326 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3327 3328 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3329 BB->addSuccessor(SplitBB); 3330 3331 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3332 return SplitBB; 3333 } 3334 3335 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3336 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3337 // be the first instruction in the remainder block. 3338 // 3339 /// \returns { LoopBody, Remainder } 3340 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3341 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3342 MachineFunction *MF = MBB.getParent(); 3343 MachineBasicBlock::iterator I(&MI); 3344 3345 // To insert the loop we need to split the block. Move everything after this 3346 // point to a new block, and insert a new empty block between the two. 3347 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3348 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3349 MachineFunction::iterator MBBI(MBB); 3350 ++MBBI; 3351 3352 MF->insert(MBBI, LoopBB); 3353 MF->insert(MBBI, RemainderBB); 3354 3355 LoopBB->addSuccessor(LoopBB); 3356 LoopBB->addSuccessor(RemainderBB); 3357 3358 // Move the rest of the block into a new block. 3359 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3360 3361 if (InstInLoop) { 3362 auto Next = std::next(I); 3363 3364 // Move instruction to loop body. 3365 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3366 3367 // Move the rest of the block. 3368 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3369 } else { 3370 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3371 } 3372 3373 MBB.addSuccessor(LoopBB); 3374 3375 return std::make_pair(LoopBB, RemainderBB); 3376 } 3377 3378 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3379 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3380 MachineBasicBlock *MBB = MI.getParent(); 3381 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3382 auto I = MI.getIterator(); 3383 auto E = std::next(I); 3384 3385 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3386 .addImm(0); 3387 3388 MIBundleBuilder Bundler(*MBB, I, E); 3389 finalizeBundle(*MBB, Bundler.begin()); 3390 } 3391 3392 MachineBasicBlock * 3393 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3394 MachineBasicBlock *BB) const { 3395 const DebugLoc &DL = MI.getDebugLoc(); 3396 3397 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3398 3399 MachineBasicBlock *LoopBB; 3400 MachineBasicBlock *RemainderBB; 3401 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3402 3403 // Apparently kill flags are only valid if the def is in the same block? 3404 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3405 Src->setIsKill(false); 3406 3407 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3408 3409 MachineBasicBlock::iterator I = LoopBB->end(); 3410 3411 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3412 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3413 3414 // Clear TRAP_STS.MEM_VIOL 3415 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3416 .addImm(0) 3417 .addImm(EncodedReg); 3418 3419 bundleInstWithWaitcnt(MI); 3420 3421 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3422 3423 // Load and check TRAP_STS.MEM_VIOL 3424 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3425 .addImm(EncodedReg); 3426 3427 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3428 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3429 .addReg(Reg, RegState::Kill) 3430 .addImm(0); 3431 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3432 .addMBB(LoopBB); 3433 3434 return RemainderBB; 3435 } 3436 3437 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3438 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3439 // will only do one iteration. In the worst case, this will loop 64 times. 3440 // 3441 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3442 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3443 const SIInstrInfo *TII, 3444 MachineRegisterInfo &MRI, 3445 MachineBasicBlock &OrigBB, 3446 MachineBasicBlock &LoopBB, 3447 const DebugLoc &DL, 3448 const MachineOperand &IdxReg, 3449 unsigned InitReg, 3450 unsigned ResultReg, 3451 unsigned PhiReg, 3452 unsigned InitSaveExecReg, 3453 int Offset, 3454 bool UseGPRIdxMode, 3455 bool IsIndirectSrc) { 3456 MachineFunction *MF = OrigBB.getParent(); 3457 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3458 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3459 MachineBasicBlock::iterator I = LoopBB.begin(); 3460 3461 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3462 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3463 Register NewExec = MRI.createVirtualRegister(BoolRC); 3464 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3465 Register CondReg = MRI.createVirtualRegister(BoolRC); 3466 3467 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3468 .addReg(InitReg) 3469 .addMBB(&OrigBB) 3470 .addReg(ResultReg) 3471 .addMBB(&LoopBB); 3472 3473 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3474 .addReg(InitSaveExecReg) 3475 .addMBB(&OrigBB) 3476 .addReg(NewExec) 3477 .addMBB(&LoopBB); 3478 3479 // Read the next variant <- also loop target. 3480 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3481 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3482 3483 // Compare the just read M0 value to all possible Idx values. 3484 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3485 .addReg(CurrentIdxReg) 3486 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3487 3488 // Update EXEC, save the original EXEC value to VCC. 3489 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3490 : AMDGPU::S_AND_SAVEEXEC_B64), 3491 NewExec) 3492 .addReg(CondReg, RegState::Kill); 3493 3494 MRI.setSimpleHint(NewExec, CondReg); 3495 3496 if (UseGPRIdxMode) { 3497 unsigned IdxReg; 3498 if (Offset == 0) { 3499 IdxReg = CurrentIdxReg; 3500 } else { 3501 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3502 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3503 .addReg(CurrentIdxReg, RegState::Kill) 3504 .addImm(Offset); 3505 } 3506 unsigned IdxMode = IsIndirectSrc ? 3507 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3508 MachineInstr *SetOn = 3509 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3510 .addReg(IdxReg, RegState::Kill) 3511 .addImm(IdxMode); 3512 SetOn->getOperand(3).setIsUndef(); 3513 } else { 3514 // Move index from VCC into M0 3515 if (Offset == 0) { 3516 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3517 .addReg(CurrentIdxReg, RegState::Kill); 3518 } else { 3519 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3520 .addReg(CurrentIdxReg, RegState::Kill) 3521 .addImm(Offset); 3522 } 3523 } 3524 3525 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3526 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3527 MachineInstr *InsertPt = 3528 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3529 : AMDGPU::S_XOR_B64_term), Exec) 3530 .addReg(Exec) 3531 .addReg(NewExec); 3532 3533 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3534 // s_cbranch_scc0? 3535 3536 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3537 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3538 .addMBB(&LoopBB); 3539 3540 return InsertPt->getIterator(); 3541 } 3542 3543 // This has slightly sub-optimal regalloc when the source vector is killed by 3544 // the read. The register allocator does not understand that the kill is 3545 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3546 // subregister from it, using 1 more VGPR than necessary. This was saved when 3547 // this was expanded after register allocation. 3548 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3549 MachineBasicBlock &MBB, 3550 MachineInstr &MI, 3551 unsigned InitResultReg, 3552 unsigned PhiReg, 3553 int Offset, 3554 bool UseGPRIdxMode, 3555 bool IsIndirectSrc) { 3556 MachineFunction *MF = MBB.getParent(); 3557 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3558 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3559 MachineRegisterInfo &MRI = MF->getRegInfo(); 3560 const DebugLoc &DL = MI.getDebugLoc(); 3561 MachineBasicBlock::iterator I(&MI); 3562 3563 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3564 Register DstReg = MI.getOperand(0).getReg(); 3565 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3566 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3567 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3568 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3569 3570 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3571 3572 // Save the EXEC mask 3573 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3574 .addReg(Exec); 3575 3576 MachineBasicBlock *LoopBB; 3577 MachineBasicBlock *RemainderBB; 3578 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3579 3580 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3581 3582 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3583 InitResultReg, DstReg, PhiReg, TmpExec, 3584 Offset, UseGPRIdxMode, IsIndirectSrc); 3585 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3586 MachineFunction::iterator MBBI(LoopBB); 3587 ++MBBI; 3588 MF->insert(MBBI, LandingPad); 3589 LoopBB->removeSuccessor(RemainderBB); 3590 LandingPad->addSuccessor(RemainderBB); 3591 LoopBB->addSuccessor(LandingPad); 3592 MachineBasicBlock::iterator First = LandingPad->begin(); 3593 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3594 .addReg(SaveExec); 3595 3596 return InsPt; 3597 } 3598 3599 // Returns subreg index, offset 3600 static std::pair<unsigned, int> 3601 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3602 const TargetRegisterClass *SuperRC, 3603 unsigned VecReg, 3604 int Offset) { 3605 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3606 3607 // Skip out of bounds offsets, or else we would end up using an undefined 3608 // register. 3609 if (Offset >= NumElts || Offset < 0) 3610 return std::make_pair(AMDGPU::sub0, Offset); 3611 3612 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3613 } 3614 3615 // Return true if the index is an SGPR and was set. 3616 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3617 MachineRegisterInfo &MRI, 3618 MachineInstr &MI, 3619 int Offset, 3620 bool UseGPRIdxMode, 3621 bool IsIndirectSrc) { 3622 MachineBasicBlock *MBB = MI.getParent(); 3623 const DebugLoc &DL = MI.getDebugLoc(); 3624 MachineBasicBlock::iterator I(&MI); 3625 3626 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3627 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3628 3629 assert(Idx->getReg() != AMDGPU::NoRegister); 3630 3631 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3632 return false; 3633 3634 if (UseGPRIdxMode) { 3635 unsigned IdxMode = IsIndirectSrc ? 3636 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3637 if (Offset == 0) { 3638 MachineInstr *SetOn = 3639 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3640 .add(*Idx) 3641 .addImm(IdxMode); 3642 3643 SetOn->getOperand(3).setIsUndef(); 3644 } else { 3645 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3646 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3647 .add(*Idx) 3648 .addImm(Offset); 3649 MachineInstr *SetOn = 3650 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3651 .addReg(Tmp, RegState::Kill) 3652 .addImm(IdxMode); 3653 3654 SetOn->getOperand(3).setIsUndef(); 3655 } 3656 3657 return true; 3658 } 3659 3660 if (Offset == 0) { 3661 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3662 .add(*Idx); 3663 } else { 3664 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3665 .add(*Idx) 3666 .addImm(Offset); 3667 } 3668 3669 return true; 3670 } 3671 3672 // Control flow needs to be inserted if indexing with a VGPR. 3673 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3674 MachineBasicBlock &MBB, 3675 const GCNSubtarget &ST) { 3676 const SIInstrInfo *TII = ST.getInstrInfo(); 3677 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3678 MachineFunction *MF = MBB.getParent(); 3679 MachineRegisterInfo &MRI = MF->getRegInfo(); 3680 3681 Register Dst = MI.getOperand(0).getReg(); 3682 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3683 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3684 3685 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3686 3687 unsigned SubReg; 3688 std::tie(SubReg, Offset) 3689 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3690 3691 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3692 3693 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3694 MachineBasicBlock::iterator I(&MI); 3695 const DebugLoc &DL = MI.getDebugLoc(); 3696 3697 if (UseGPRIdxMode) { 3698 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3699 // to avoid interfering with other uses, so probably requires a new 3700 // optimization pass. 3701 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3702 .addReg(SrcReg, 0, SubReg) 3703 .addReg(SrcReg, RegState::Implicit) 3704 .addReg(AMDGPU::M0, RegState::Implicit); 3705 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3706 } else { 3707 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3708 .addReg(SrcReg, 0, SubReg) 3709 .addReg(SrcReg, RegState::Implicit); 3710 } 3711 3712 MI.eraseFromParent(); 3713 3714 return &MBB; 3715 } 3716 3717 const DebugLoc &DL = MI.getDebugLoc(); 3718 MachineBasicBlock::iterator I(&MI); 3719 3720 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3721 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3722 3723 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3724 3725 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3726 Offset, UseGPRIdxMode, true); 3727 MachineBasicBlock *LoopBB = InsPt->getParent(); 3728 3729 if (UseGPRIdxMode) { 3730 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3731 .addReg(SrcReg, 0, SubReg) 3732 .addReg(SrcReg, RegState::Implicit) 3733 .addReg(AMDGPU::M0, RegState::Implicit); 3734 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3735 } else { 3736 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3737 .addReg(SrcReg, 0, SubReg) 3738 .addReg(SrcReg, RegState::Implicit); 3739 } 3740 3741 MI.eraseFromParent(); 3742 3743 return LoopBB; 3744 } 3745 3746 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3747 MachineBasicBlock &MBB, 3748 const GCNSubtarget &ST) { 3749 const SIInstrInfo *TII = ST.getInstrInfo(); 3750 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3751 MachineFunction *MF = MBB.getParent(); 3752 MachineRegisterInfo &MRI = MF->getRegInfo(); 3753 3754 Register Dst = MI.getOperand(0).getReg(); 3755 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3756 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3757 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3758 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3759 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3760 3761 // This can be an immediate, but will be folded later. 3762 assert(Val->getReg()); 3763 3764 unsigned SubReg; 3765 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3766 SrcVec->getReg(), 3767 Offset); 3768 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3769 3770 if (Idx->getReg() == AMDGPU::NoRegister) { 3771 MachineBasicBlock::iterator I(&MI); 3772 const DebugLoc &DL = MI.getDebugLoc(); 3773 3774 assert(Offset == 0); 3775 3776 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3777 .add(*SrcVec) 3778 .add(*Val) 3779 .addImm(SubReg); 3780 3781 MI.eraseFromParent(); 3782 return &MBB; 3783 } 3784 3785 const MCInstrDesc &MovRelDesc 3786 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3787 3788 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3789 MachineBasicBlock::iterator I(&MI); 3790 const DebugLoc &DL = MI.getDebugLoc(); 3791 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3792 .addReg(SrcVec->getReg()) 3793 .add(*Val) 3794 .addImm(SubReg); 3795 if (UseGPRIdxMode) 3796 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3797 3798 MI.eraseFromParent(); 3799 return &MBB; 3800 } 3801 3802 if (Val->isReg()) 3803 MRI.clearKillFlags(Val->getReg()); 3804 3805 const DebugLoc &DL = MI.getDebugLoc(); 3806 3807 Register PhiReg = MRI.createVirtualRegister(VecRC); 3808 3809 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3810 Offset, UseGPRIdxMode, false); 3811 MachineBasicBlock *LoopBB = InsPt->getParent(); 3812 3813 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3814 .addReg(PhiReg) 3815 .add(*Val) 3816 .addImm(AMDGPU::sub0); 3817 if (UseGPRIdxMode) 3818 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3819 3820 MI.eraseFromParent(); 3821 return LoopBB; 3822 } 3823 3824 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3825 MachineInstr &MI, MachineBasicBlock *BB) const { 3826 3827 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3828 MachineFunction *MF = BB->getParent(); 3829 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3830 3831 switch (MI.getOpcode()) { 3832 case AMDGPU::S_UADDO_PSEUDO: 3833 case AMDGPU::S_USUBO_PSEUDO: { 3834 const DebugLoc &DL = MI.getDebugLoc(); 3835 MachineOperand &Dest0 = MI.getOperand(0); 3836 MachineOperand &Dest1 = MI.getOperand(1); 3837 MachineOperand &Src0 = MI.getOperand(2); 3838 MachineOperand &Src1 = MI.getOperand(3); 3839 3840 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3841 ? AMDGPU::S_ADD_I32 3842 : AMDGPU::S_SUB_I32; 3843 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3844 3845 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3846 .addImm(1) 3847 .addImm(0); 3848 3849 MI.eraseFromParent(); 3850 return BB; 3851 } 3852 case AMDGPU::S_ADD_U64_PSEUDO: 3853 case AMDGPU::S_SUB_U64_PSEUDO: { 3854 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3855 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3856 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3857 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3858 const DebugLoc &DL = MI.getDebugLoc(); 3859 3860 MachineOperand &Dest = MI.getOperand(0); 3861 MachineOperand &Src0 = MI.getOperand(1); 3862 MachineOperand &Src1 = MI.getOperand(2); 3863 3864 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3865 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3866 3867 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3868 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3869 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3870 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3871 3872 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3873 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3874 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3875 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3876 3877 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3878 3879 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3880 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3881 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3882 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3883 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3884 .addReg(DestSub0) 3885 .addImm(AMDGPU::sub0) 3886 .addReg(DestSub1) 3887 .addImm(AMDGPU::sub1); 3888 MI.eraseFromParent(); 3889 return BB; 3890 } 3891 case AMDGPU::V_ADD_U64_PSEUDO: 3892 case AMDGPU::V_SUB_U64_PSEUDO: { 3893 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3894 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3895 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3896 const DebugLoc &DL = MI.getDebugLoc(); 3897 3898 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3899 3900 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3901 3902 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3903 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3904 3905 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3906 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3907 3908 MachineOperand &Dest = MI.getOperand(0); 3909 MachineOperand &Src0 = MI.getOperand(1); 3910 MachineOperand &Src1 = MI.getOperand(2); 3911 3912 const TargetRegisterClass *Src0RC = Src0.isReg() 3913 ? MRI.getRegClass(Src0.getReg()) 3914 : &AMDGPU::VReg_64RegClass; 3915 const TargetRegisterClass *Src1RC = Src1.isReg() 3916 ? MRI.getRegClass(Src1.getReg()) 3917 : &AMDGPU::VReg_64RegClass; 3918 3919 const TargetRegisterClass *Src0SubRC = 3920 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3921 const TargetRegisterClass *Src1SubRC = 3922 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3923 3924 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3925 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3926 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3927 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3928 3929 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3930 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3931 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3932 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3933 3934 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3935 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3936 .addReg(CarryReg, RegState::Define) 3937 .add(SrcReg0Sub0) 3938 .add(SrcReg1Sub0) 3939 .addImm(0); // clamp bit 3940 3941 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3942 MachineInstr *HiHalf = 3943 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3944 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3945 .add(SrcReg0Sub1) 3946 .add(SrcReg1Sub1) 3947 .addReg(CarryReg, RegState::Kill) 3948 .addImm(0); // clamp bit 3949 3950 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3951 .addReg(DestSub0) 3952 .addImm(AMDGPU::sub0) 3953 .addReg(DestSub1) 3954 .addImm(AMDGPU::sub1); 3955 TII->legalizeOperands(*LoHalf); 3956 TII->legalizeOperands(*HiHalf); 3957 MI.eraseFromParent(); 3958 return BB; 3959 } 3960 case AMDGPU::S_ADD_CO_PSEUDO: 3961 case AMDGPU::S_SUB_CO_PSEUDO: { 3962 // This pseudo has a chance to be selected 3963 // only from uniform add/subcarry node. All the VGPR operands 3964 // therefore assumed to be splat vectors. 3965 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3966 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3967 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3968 MachineBasicBlock::iterator MII = MI; 3969 const DebugLoc &DL = MI.getDebugLoc(); 3970 MachineOperand &Dest = MI.getOperand(0); 3971 MachineOperand &CarryDest = MI.getOperand(1); 3972 MachineOperand &Src0 = MI.getOperand(2); 3973 MachineOperand &Src1 = MI.getOperand(3); 3974 MachineOperand &Src2 = MI.getOperand(4); 3975 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3976 ? AMDGPU::S_ADDC_U32 3977 : AMDGPU::S_SUBB_U32; 3978 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3979 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3980 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3981 .addReg(Src0.getReg()); 3982 Src0.setReg(RegOp0); 3983 } 3984 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3985 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3986 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3987 .addReg(Src1.getReg()); 3988 Src1.setReg(RegOp1); 3989 } 3990 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3991 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3992 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3993 .addReg(Src2.getReg()); 3994 Src2.setReg(RegOp2); 3995 } 3996 3997 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3998 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3999 .addReg(Src2.getReg()) 4000 .addImm(0); 4001 } else { 4002 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4003 .addReg(Src2.getReg()) 4004 .addImm(0); 4005 } 4006 4007 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4008 4009 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4010 .addReg(AMDGPU::SCC); 4011 MI.eraseFromParent(); 4012 return BB; 4013 } 4014 case AMDGPU::SI_INIT_M0: { 4015 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4016 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4017 .add(MI.getOperand(0)); 4018 MI.eraseFromParent(); 4019 return BB; 4020 } 4021 case AMDGPU::SI_INIT_EXEC: 4022 // This should be before all vector instructions. 4023 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4024 AMDGPU::EXEC) 4025 .addImm(MI.getOperand(0).getImm()); 4026 MI.eraseFromParent(); 4027 return BB; 4028 4029 case AMDGPU::SI_INIT_EXEC_LO: 4030 // This should be before all vector instructions. 4031 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4032 AMDGPU::EXEC_LO) 4033 .addImm(MI.getOperand(0).getImm()); 4034 MI.eraseFromParent(); 4035 return BB; 4036 4037 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4038 // Extract the thread count from an SGPR input and set EXEC accordingly. 4039 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4040 // 4041 // S_BFE_U32 count, input, {shift, 7} 4042 // S_BFM_B64 exec, count, 0 4043 // S_CMP_EQ_U32 count, 64 4044 // S_CMOV_B64 exec, -1 4045 MachineInstr *FirstMI = &*BB->begin(); 4046 MachineRegisterInfo &MRI = MF->getRegInfo(); 4047 Register InputReg = MI.getOperand(0).getReg(); 4048 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4049 bool Found = false; 4050 4051 // Move the COPY of the input reg to the beginning, so that we can use it. 4052 for (auto I = BB->begin(); I != &MI; I++) { 4053 if (I->getOpcode() != TargetOpcode::COPY || 4054 I->getOperand(0).getReg() != InputReg) 4055 continue; 4056 4057 if (I == FirstMI) { 4058 FirstMI = &*++BB->begin(); 4059 } else { 4060 I->removeFromParent(); 4061 BB->insert(FirstMI, &*I); 4062 } 4063 Found = true; 4064 break; 4065 } 4066 assert(Found); 4067 (void)Found; 4068 4069 // This should be before all vector instructions. 4070 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4071 bool isWave32 = getSubtarget()->isWave32(); 4072 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4073 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4074 .addReg(InputReg) 4075 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4076 BuildMI(*BB, FirstMI, DebugLoc(), 4077 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4078 Exec) 4079 .addReg(CountReg) 4080 .addImm(0); 4081 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4082 .addReg(CountReg, RegState::Kill) 4083 .addImm(getSubtarget()->getWavefrontSize()); 4084 BuildMI(*BB, FirstMI, DebugLoc(), 4085 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4086 Exec) 4087 .addImm(-1); 4088 MI.eraseFromParent(); 4089 return BB; 4090 } 4091 4092 case AMDGPU::GET_GROUPSTATICSIZE: { 4093 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4094 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4095 DebugLoc DL = MI.getDebugLoc(); 4096 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4097 .add(MI.getOperand(0)) 4098 .addImm(MFI->getLDSSize()); 4099 MI.eraseFromParent(); 4100 return BB; 4101 } 4102 case AMDGPU::SI_INDIRECT_SRC_V1: 4103 case AMDGPU::SI_INDIRECT_SRC_V2: 4104 case AMDGPU::SI_INDIRECT_SRC_V4: 4105 case AMDGPU::SI_INDIRECT_SRC_V8: 4106 case AMDGPU::SI_INDIRECT_SRC_V16: 4107 case AMDGPU::SI_INDIRECT_SRC_V32: 4108 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4109 case AMDGPU::SI_INDIRECT_DST_V1: 4110 case AMDGPU::SI_INDIRECT_DST_V2: 4111 case AMDGPU::SI_INDIRECT_DST_V4: 4112 case AMDGPU::SI_INDIRECT_DST_V8: 4113 case AMDGPU::SI_INDIRECT_DST_V16: 4114 case AMDGPU::SI_INDIRECT_DST_V32: 4115 return emitIndirectDst(MI, *BB, *getSubtarget()); 4116 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4117 case AMDGPU::SI_KILL_I1_PSEUDO: 4118 return splitKillBlock(MI, BB); 4119 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4120 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4121 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4122 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4123 4124 Register Dst = MI.getOperand(0).getReg(); 4125 Register Src0 = MI.getOperand(1).getReg(); 4126 Register Src1 = MI.getOperand(2).getReg(); 4127 const DebugLoc &DL = MI.getDebugLoc(); 4128 Register SrcCond = MI.getOperand(3).getReg(); 4129 4130 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4131 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4132 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4133 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4134 4135 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4136 .addReg(SrcCond); 4137 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4138 .addImm(0) 4139 .addReg(Src0, 0, AMDGPU::sub0) 4140 .addImm(0) 4141 .addReg(Src1, 0, AMDGPU::sub0) 4142 .addReg(SrcCondCopy); 4143 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4144 .addImm(0) 4145 .addReg(Src0, 0, AMDGPU::sub1) 4146 .addImm(0) 4147 .addReg(Src1, 0, AMDGPU::sub1) 4148 .addReg(SrcCondCopy); 4149 4150 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4151 .addReg(DstLo) 4152 .addImm(AMDGPU::sub0) 4153 .addReg(DstHi) 4154 .addImm(AMDGPU::sub1); 4155 MI.eraseFromParent(); 4156 return BB; 4157 } 4158 case AMDGPU::SI_BR_UNDEF: { 4159 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4160 const DebugLoc &DL = MI.getDebugLoc(); 4161 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4162 .add(MI.getOperand(0)); 4163 Br->getOperand(1).setIsUndef(true); // read undef SCC 4164 MI.eraseFromParent(); 4165 return BB; 4166 } 4167 case AMDGPU::ADJCALLSTACKUP: 4168 case AMDGPU::ADJCALLSTACKDOWN: { 4169 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4170 MachineInstrBuilder MIB(*MF, &MI); 4171 4172 // Add an implicit use of the frame offset reg to prevent the restore copy 4173 // inserted after the call from being reorderd after stack operations in the 4174 // the caller's frame. 4175 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4176 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4177 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4178 return BB; 4179 } 4180 case AMDGPU::SI_CALL_ISEL: { 4181 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4182 const DebugLoc &DL = MI.getDebugLoc(); 4183 4184 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4185 4186 MachineInstrBuilder MIB; 4187 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4188 4189 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4190 MIB.add(MI.getOperand(I)); 4191 4192 MIB.cloneMemRefs(MI); 4193 MI.eraseFromParent(); 4194 return BB; 4195 } 4196 case AMDGPU::V_ADD_CO_U32_e32: 4197 case AMDGPU::V_SUB_CO_U32_e32: 4198 case AMDGPU::V_SUBREV_CO_U32_e32: { 4199 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4200 const DebugLoc &DL = MI.getDebugLoc(); 4201 unsigned Opc = MI.getOpcode(); 4202 4203 bool NeedClampOperand = false; 4204 if (TII->pseudoToMCOpcode(Opc) == -1) { 4205 Opc = AMDGPU::getVOPe64(Opc); 4206 NeedClampOperand = true; 4207 } 4208 4209 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4210 if (TII->isVOP3(*I)) { 4211 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4212 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4213 I.addReg(TRI->getVCC(), RegState::Define); 4214 } 4215 I.add(MI.getOperand(1)) 4216 .add(MI.getOperand(2)); 4217 if (NeedClampOperand) 4218 I.addImm(0); // clamp bit for e64 encoding 4219 4220 TII->legalizeOperands(*I); 4221 4222 MI.eraseFromParent(); 4223 return BB; 4224 } 4225 case AMDGPU::DS_GWS_INIT: 4226 case AMDGPU::DS_GWS_SEMA_V: 4227 case AMDGPU::DS_GWS_SEMA_BR: 4228 case AMDGPU::DS_GWS_SEMA_P: 4229 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4230 case AMDGPU::DS_GWS_BARRIER: 4231 // A s_waitcnt 0 is required to be the instruction immediately following. 4232 if (getSubtarget()->hasGWSAutoReplay()) { 4233 bundleInstWithWaitcnt(MI); 4234 return BB; 4235 } 4236 4237 return emitGWSMemViolTestLoop(MI, BB); 4238 case AMDGPU::S_SETREG_B32: { 4239 if (!getSubtarget()->hasDenormModeInst()) 4240 return BB; 4241 4242 // Try to optimize cases that only set the denormal mode or rounding mode. 4243 // 4244 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4245 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4246 // instead. 4247 // 4248 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4249 // allow you to have a no side effect instruction in the output of a 4250 // sideeffecting pattern. 4251 4252 // TODO: Should also emit a no side effects pseudo if only FP bits are 4253 // touched, even if not all of them or to a variable. 4254 unsigned ID, Offset, Width; 4255 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4256 if (ID != AMDGPU::Hwreg::ID_MODE) 4257 return BB; 4258 4259 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4260 const unsigned SetMask = WidthMask << Offset; 4261 unsigned SetDenormOp = 0; 4262 unsigned SetRoundOp = 0; 4263 4264 // The dedicated instructions can only set the whole denorm or round mode at 4265 // once, not a subset of bits in either. 4266 if (SetMask == 4267 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4268 // If this fully sets both the round and denorm mode, emit the two 4269 // dedicated instructions for these. 4270 SetRoundOp = AMDGPU::S_ROUND_MODE; 4271 SetDenormOp = AMDGPU::S_DENORM_MODE; 4272 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4273 SetRoundOp = AMDGPU::S_ROUND_MODE; 4274 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4275 SetDenormOp = AMDGPU::S_DENORM_MODE; 4276 } 4277 4278 if (SetRoundOp || SetDenormOp) { 4279 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4280 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4281 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4282 unsigned ImmVal = Def->getOperand(1).getImm(); 4283 if (SetRoundOp) { 4284 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4285 .addImm(ImmVal & 0xf); 4286 4287 // If we also have the denorm mode, get just the denorm mode bits. 4288 ImmVal >>= 4; 4289 } 4290 4291 if (SetDenormOp) { 4292 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4293 .addImm(ImmVal & 0xf); 4294 } 4295 4296 MI.eraseFromParent(); 4297 } 4298 } 4299 4300 return BB; 4301 } 4302 default: 4303 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4304 } 4305 } 4306 4307 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4308 return isTypeLegal(VT.getScalarType()); 4309 } 4310 4311 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4312 // This currently forces unfolding various combinations of fsub into fma with 4313 // free fneg'd operands. As long as we have fast FMA (controlled by 4314 // isFMAFasterThanFMulAndFAdd), we should perform these. 4315 4316 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4317 // most of these combines appear to be cycle neutral but save on instruction 4318 // count / code size. 4319 return true; 4320 } 4321 4322 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4323 EVT VT) const { 4324 if (!VT.isVector()) { 4325 return MVT::i1; 4326 } 4327 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4328 } 4329 4330 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4331 // TODO: Should i16 be used always if legal? For now it would force VALU 4332 // shifts. 4333 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4334 } 4335 4336 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4337 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4338 ? Ty.changeElementSize(16) 4339 : Ty.changeElementSize(32); 4340 } 4341 4342 // Answering this is somewhat tricky and depends on the specific device which 4343 // have different rates for fma or all f64 operations. 4344 // 4345 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4346 // regardless of which device (although the number of cycles differs between 4347 // devices), so it is always profitable for f64. 4348 // 4349 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4350 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4351 // which we can always do even without fused FP ops since it returns the same 4352 // result as the separate operations and since it is always full 4353 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4354 // however does not support denormals, so we do report fma as faster if we have 4355 // a fast fma device and require denormals. 4356 // 4357 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4358 EVT VT) const { 4359 VT = VT.getScalarType(); 4360 4361 switch (VT.getSimpleVT().SimpleTy) { 4362 case MVT::f32: { 4363 // If mad is not available this depends only on if f32 fma is full rate. 4364 if (!Subtarget->hasMadMacF32Insts()) 4365 return Subtarget->hasFastFMAF32(); 4366 4367 // Otherwise f32 mad is always full rate and returns the same result as 4368 // the separate operations so should be preferred over fma. 4369 // However does not support denomals. 4370 if (hasFP32Denormals(MF)) 4371 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4372 4373 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4374 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4375 } 4376 case MVT::f64: 4377 return true; 4378 case MVT::f16: 4379 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4380 default: 4381 break; 4382 } 4383 4384 return false; 4385 } 4386 4387 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4388 const SDNode *N) const { 4389 // TODO: Check future ftz flag 4390 // v_mad_f32/v_mac_f32 do not support denormals. 4391 EVT VT = N->getValueType(0); 4392 if (VT == MVT::f32) 4393 return Subtarget->hasMadMacF32Insts() && 4394 !hasFP32Denormals(DAG.getMachineFunction()); 4395 if (VT == MVT::f16) { 4396 return Subtarget->hasMadF16() && 4397 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4398 } 4399 4400 return false; 4401 } 4402 4403 //===----------------------------------------------------------------------===// 4404 // Custom DAG Lowering Operations 4405 //===----------------------------------------------------------------------===// 4406 4407 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4408 // wider vector type is legal. 4409 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4410 SelectionDAG &DAG) const { 4411 unsigned Opc = Op.getOpcode(); 4412 EVT VT = Op.getValueType(); 4413 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4414 4415 SDValue Lo, Hi; 4416 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4417 4418 SDLoc SL(Op); 4419 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4420 Op->getFlags()); 4421 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4422 Op->getFlags()); 4423 4424 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4425 } 4426 4427 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4428 // wider vector type is legal. 4429 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4430 SelectionDAG &DAG) const { 4431 unsigned Opc = Op.getOpcode(); 4432 EVT VT = Op.getValueType(); 4433 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4434 4435 SDValue Lo0, Hi0; 4436 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4437 SDValue Lo1, Hi1; 4438 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4439 4440 SDLoc SL(Op); 4441 4442 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4443 Op->getFlags()); 4444 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4445 Op->getFlags()); 4446 4447 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4448 } 4449 4450 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4451 SelectionDAG &DAG) const { 4452 unsigned Opc = Op.getOpcode(); 4453 EVT VT = Op.getValueType(); 4454 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4455 4456 SDValue Lo0, Hi0; 4457 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4458 SDValue Lo1, Hi1; 4459 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4460 SDValue Lo2, Hi2; 4461 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4462 4463 SDLoc SL(Op); 4464 4465 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4466 Op->getFlags()); 4467 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4468 Op->getFlags()); 4469 4470 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4471 } 4472 4473 4474 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4475 switch (Op.getOpcode()) { 4476 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4477 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4478 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4479 case ISD::LOAD: { 4480 SDValue Result = LowerLOAD(Op, DAG); 4481 assert((!Result.getNode() || 4482 Result.getNode()->getNumValues() == 2) && 4483 "Load should return a value and a chain"); 4484 return Result; 4485 } 4486 4487 case ISD::FSIN: 4488 case ISD::FCOS: 4489 return LowerTrig(Op, DAG); 4490 case ISD::SELECT: return LowerSELECT(Op, DAG); 4491 case ISD::FDIV: return LowerFDIV(Op, DAG); 4492 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4493 case ISD::STORE: return LowerSTORE(Op, DAG); 4494 case ISD::GlobalAddress: { 4495 MachineFunction &MF = DAG.getMachineFunction(); 4496 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4497 return LowerGlobalAddress(MFI, Op, DAG); 4498 } 4499 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4500 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4501 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4502 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4503 case ISD::INSERT_SUBVECTOR: 4504 return lowerINSERT_SUBVECTOR(Op, DAG); 4505 case ISD::INSERT_VECTOR_ELT: 4506 return lowerINSERT_VECTOR_ELT(Op, DAG); 4507 case ISD::EXTRACT_VECTOR_ELT: 4508 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4509 case ISD::VECTOR_SHUFFLE: 4510 return lowerVECTOR_SHUFFLE(Op, DAG); 4511 case ISD::BUILD_VECTOR: 4512 return lowerBUILD_VECTOR(Op, DAG); 4513 case ISD::FP_ROUND: 4514 return lowerFP_ROUND(Op, DAG); 4515 case ISD::TRAP: 4516 return lowerTRAP(Op, DAG); 4517 case ISD::DEBUGTRAP: 4518 return lowerDEBUGTRAP(Op, DAG); 4519 case ISD::FABS: 4520 case ISD::FNEG: 4521 case ISD::FCANONICALIZE: 4522 case ISD::BSWAP: 4523 return splitUnaryVectorOp(Op, DAG); 4524 case ISD::FMINNUM: 4525 case ISD::FMAXNUM: 4526 return lowerFMINNUM_FMAXNUM(Op, DAG); 4527 case ISD::FMA: 4528 return splitTernaryVectorOp(Op, DAG); 4529 case ISD::SHL: 4530 case ISD::SRA: 4531 case ISD::SRL: 4532 case ISD::ADD: 4533 case ISD::SUB: 4534 case ISD::MUL: 4535 case ISD::SMIN: 4536 case ISD::SMAX: 4537 case ISD::UMIN: 4538 case ISD::UMAX: 4539 case ISD::FADD: 4540 case ISD::FMUL: 4541 case ISD::FMINNUM_IEEE: 4542 case ISD::FMAXNUM_IEEE: 4543 case ISD::UADDSAT: 4544 case ISD::USUBSAT: 4545 case ISD::SADDSAT: 4546 case ISD::SSUBSAT: 4547 return splitBinaryVectorOp(Op, DAG); 4548 case ISD::SMULO: 4549 case ISD::UMULO: 4550 return lowerXMULO(Op, DAG); 4551 case ISD::DYNAMIC_STACKALLOC: 4552 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4553 } 4554 return SDValue(); 4555 } 4556 4557 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4558 const SDLoc &DL, 4559 SelectionDAG &DAG, bool Unpacked) { 4560 if (!LoadVT.isVector()) 4561 return Result; 4562 4563 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4564 // Truncate to v2i16/v4i16. 4565 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4566 4567 // Workaround legalizer not scalarizing truncate after vector op 4568 // legalization but not creating intermediate vector trunc. 4569 SmallVector<SDValue, 4> Elts; 4570 DAG.ExtractVectorElements(Result, Elts); 4571 for (SDValue &Elt : Elts) 4572 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4573 4574 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4575 4576 // Bitcast to original type (v2f16/v4f16). 4577 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4578 } 4579 4580 // Cast back to the original packed type. 4581 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4582 } 4583 4584 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4585 MemSDNode *M, 4586 SelectionDAG &DAG, 4587 ArrayRef<SDValue> Ops, 4588 bool IsIntrinsic) const { 4589 SDLoc DL(M); 4590 4591 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4592 EVT LoadVT = M->getValueType(0); 4593 4594 EVT EquivLoadVT = LoadVT; 4595 if (Unpacked && LoadVT.isVector()) { 4596 EquivLoadVT = LoadVT.isVector() ? 4597 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4598 LoadVT.getVectorNumElements()) : LoadVT; 4599 } 4600 4601 // Change from v4f16/v2f16 to EquivLoadVT. 4602 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4603 4604 SDValue Load 4605 = DAG.getMemIntrinsicNode( 4606 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4607 VTList, Ops, M->getMemoryVT(), 4608 M->getMemOperand()); 4609 if (!Unpacked) // Just adjusted the opcode. 4610 return Load; 4611 4612 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4613 4614 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4615 } 4616 4617 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4618 SelectionDAG &DAG, 4619 ArrayRef<SDValue> Ops) const { 4620 SDLoc DL(M); 4621 EVT LoadVT = M->getValueType(0); 4622 EVT EltType = LoadVT.getScalarType(); 4623 EVT IntVT = LoadVT.changeTypeToInteger(); 4624 4625 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4626 4627 unsigned Opc = 4628 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4629 4630 if (IsD16) { 4631 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4632 } 4633 4634 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4635 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4636 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4637 4638 if (isTypeLegal(LoadVT)) { 4639 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4640 M->getMemOperand(), DAG); 4641 } 4642 4643 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4644 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4645 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4646 M->getMemOperand(), DAG); 4647 return DAG.getMergeValues( 4648 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4649 DL); 4650 } 4651 4652 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4653 SDNode *N, SelectionDAG &DAG) { 4654 EVT VT = N->getValueType(0); 4655 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4656 unsigned CondCode = CD->getZExtValue(); 4657 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4658 return DAG.getUNDEF(VT); 4659 4660 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4661 4662 SDValue LHS = N->getOperand(1); 4663 SDValue RHS = N->getOperand(2); 4664 4665 SDLoc DL(N); 4666 4667 EVT CmpVT = LHS.getValueType(); 4668 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4669 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4670 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4671 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4672 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4673 } 4674 4675 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4676 4677 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4678 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4679 4680 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4681 DAG.getCondCode(CCOpcode)); 4682 if (VT.bitsEq(CCVT)) 4683 return SetCC; 4684 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4685 } 4686 4687 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4688 SDNode *N, SelectionDAG &DAG) { 4689 EVT VT = N->getValueType(0); 4690 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4691 4692 unsigned CondCode = CD->getZExtValue(); 4693 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4694 return DAG.getUNDEF(VT); 4695 4696 SDValue Src0 = N->getOperand(1); 4697 SDValue Src1 = N->getOperand(2); 4698 EVT CmpVT = Src0.getValueType(); 4699 SDLoc SL(N); 4700 4701 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4702 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4703 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4704 } 4705 4706 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4707 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4708 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4709 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4710 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4711 Src1, DAG.getCondCode(CCOpcode)); 4712 if (VT.bitsEq(CCVT)) 4713 return SetCC; 4714 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4715 } 4716 4717 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4718 SelectionDAG &DAG) { 4719 EVT VT = N->getValueType(0); 4720 SDValue Src = N->getOperand(1); 4721 SDLoc SL(N); 4722 4723 if (Src.getOpcode() == ISD::SETCC) { 4724 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4725 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4726 Src.getOperand(1), Src.getOperand(2)); 4727 } 4728 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4729 // (ballot 0) -> 0 4730 if (Arg->isNullValue()) 4731 return DAG.getConstant(0, SL, VT); 4732 4733 // (ballot 1) -> EXEC/EXEC_LO 4734 if (Arg->isOne()) { 4735 Register Exec; 4736 if (VT.getScalarSizeInBits() == 32) 4737 Exec = AMDGPU::EXEC_LO; 4738 else if (VT.getScalarSizeInBits() == 64) 4739 Exec = AMDGPU::EXEC; 4740 else 4741 return SDValue(); 4742 4743 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4744 } 4745 } 4746 4747 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4748 // ISD::SETNE) 4749 return DAG.getNode( 4750 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4751 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4752 } 4753 4754 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4755 SmallVectorImpl<SDValue> &Results, 4756 SelectionDAG &DAG) const { 4757 switch (N->getOpcode()) { 4758 case ISD::INSERT_VECTOR_ELT: { 4759 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4760 Results.push_back(Res); 4761 return; 4762 } 4763 case ISD::EXTRACT_VECTOR_ELT: { 4764 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4765 Results.push_back(Res); 4766 return; 4767 } 4768 case ISD::INTRINSIC_WO_CHAIN: { 4769 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4770 switch (IID) { 4771 case Intrinsic::amdgcn_cvt_pkrtz: { 4772 SDValue Src0 = N->getOperand(1); 4773 SDValue Src1 = N->getOperand(2); 4774 SDLoc SL(N); 4775 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4776 Src0, Src1); 4777 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4778 return; 4779 } 4780 case Intrinsic::amdgcn_cvt_pknorm_i16: 4781 case Intrinsic::amdgcn_cvt_pknorm_u16: 4782 case Intrinsic::amdgcn_cvt_pk_i16: 4783 case Intrinsic::amdgcn_cvt_pk_u16: { 4784 SDValue Src0 = N->getOperand(1); 4785 SDValue Src1 = N->getOperand(2); 4786 SDLoc SL(N); 4787 unsigned Opcode; 4788 4789 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4790 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4791 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4792 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4793 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4794 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4795 else 4796 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4797 4798 EVT VT = N->getValueType(0); 4799 if (isTypeLegal(VT)) 4800 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4801 else { 4802 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4803 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4804 } 4805 return; 4806 } 4807 } 4808 break; 4809 } 4810 case ISD::INTRINSIC_W_CHAIN: { 4811 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4812 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4813 // FIXME: Hacky 4814 Results.push_back(Res.getOperand(0)); 4815 Results.push_back(Res.getOperand(1)); 4816 } else { 4817 Results.push_back(Res); 4818 Results.push_back(Res.getValue(1)); 4819 } 4820 return; 4821 } 4822 4823 break; 4824 } 4825 case ISD::SELECT: { 4826 SDLoc SL(N); 4827 EVT VT = N->getValueType(0); 4828 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4829 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4830 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4831 4832 EVT SelectVT = NewVT; 4833 if (NewVT.bitsLT(MVT::i32)) { 4834 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4835 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4836 SelectVT = MVT::i32; 4837 } 4838 4839 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4840 N->getOperand(0), LHS, RHS); 4841 4842 if (NewVT != SelectVT) 4843 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4844 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4845 return; 4846 } 4847 case ISD::FNEG: { 4848 if (N->getValueType(0) != MVT::v2f16) 4849 break; 4850 4851 SDLoc SL(N); 4852 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4853 4854 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4855 BC, 4856 DAG.getConstant(0x80008000, SL, MVT::i32)); 4857 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4858 return; 4859 } 4860 case ISD::FABS: { 4861 if (N->getValueType(0) != MVT::v2f16) 4862 break; 4863 4864 SDLoc SL(N); 4865 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4866 4867 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4868 BC, 4869 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4870 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4871 return; 4872 } 4873 default: 4874 break; 4875 } 4876 } 4877 4878 /// Helper function for LowerBRCOND 4879 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4880 4881 SDNode *Parent = Value.getNode(); 4882 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4883 I != E; ++I) { 4884 4885 if (I.getUse().get() != Value) 4886 continue; 4887 4888 if (I->getOpcode() == Opcode) 4889 return *I; 4890 } 4891 return nullptr; 4892 } 4893 4894 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4895 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4896 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4897 case Intrinsic::amdgcn_if: 4898 return AMDGPUISD::IF; 4899 case Intrinsic::amdgcn_else: 4900 return AMDGPUISD::ELSE; 4901 case Intrinsic::amdgcn_loop: 4902 return AMDGPUISD::LOOP; 4903 case Intrinsic::amdgcn_end_cf: 4904 llvm_unreachable("should not occur"); 4905 default: 4906 return 0; 4907 } 4908 } 4909 4910 // break, if_break, else_break are all only used as inputs to loop, not 4911 // directly as branch conditions. 4912 return 0; 4913 } 4914 4915 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4916 const Triple &TT = getTargetMachine().getTargetTriple(); 4917 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4918 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4919 AMDGPU::shouldEmitConstantsToTextSection(TT); 4920 } 4921 4922 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4923 // FIXME: Either avoid relying on address space here or change the default 4924 // address space for functions to avoid the explicit check. 4925 return (GV->getValueType()->isFunctionTy() || 4926 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4927 !shouldEmitFixup(GV) && 4928 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4929 } 4930 4931 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4932 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4933 } 4934 4935 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4936 if (!GV->hasExternalLinkage()) 4937 return true; 4938 4939 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4940 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4941 } 4942 4943 /// This transforms the control flow intrinsics to get the branch destination as 4944 /// last parameter, also switches branch target with BR if the need arise 4945 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4946 SelectionDAG &DAG) const { 4947 SDLoc DL(BRCOND); 4948 4949 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4950 SDValue Target = BRCOND.getOperand(2); 4951 SDNode *BR = nullptr; 4952 SDNode *SetCC = nullptr; 4953 4954 if (Intr->getOpcode() == ISD::SETCC) { 4955 // As long as we negate the condition everything is fine 4956 SetCC = Intr; 4957 Intr = SetCC->getOperand(0).getNode(); 4958 4959 } else { 4960 // Get the target from BR if we don't negate the condition 4961 BR = findUser(BRCOND, ISD::BR); 4962 assert(BR && "brcond missing unconditional branch user"); 4963 Target = BR->getOperand(1); 4964 } 4965 4966 unsigned CFNode = isCFIntrinsic(Intr); 4967 if (CFNode == 0) { 4968 // This is a uniform branch so we don't need to legalize. 4969 return BRCOND; 4970 } 4971 4972 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4973 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4974 4975 assert(!SetCC || 4976 (SetCC->getConstantOperandVal(1) == 1 && 4977 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4978 ISD::SETNE)); 4979 4980 // operands of the new intrinsic call 4981 SmallVector<SDValue, 4> Ops; 4982 if (HaveChain) 4983 Ops.push_back(BRCOND.getOperand(0)); 4984 4985 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4986 Ops.push_back(Target); 4987 4988 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4989 4990 // build the new intrinsic call 4991 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4992 4993 if (!HaveChain) { 4994 SDValue Ops[] = { 4995 SDValue(Result, 0), 4996 BRCOND.getOperand(0) 4997 }; 4998 4999 Result = DAG.getMergeValues(Ops, DL).getNode(); 5000 } 5001 5002 if (BR) { 5003 // Give the branch instruction our target 5004 SDValue Ops[] = { 5005 BR->getOperand(0), 5006 BRCOND.getOperand(2) 5007 }; 5008 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5009 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5010 } 5011 5012 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5013 5014 // Copy the intrinsic results to registers 5015 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5016 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5017 if (!CopyToReg) 5018 continue; 5019 5020 Chain = DAG.getCopyToReg( 5021 Chain, DL, 5022 CopyToReg->getOperand(1), 5023 SDValue(Result, i - 1), 5024 SDValue()); 5025 5026 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5027 } 5028 5029 // Remove the old intrinsic from the chain 5030 DAG.ReplaceAllUsesOfValueWith( 5031 SDValue(Intr, Intr->getNumValues() - 1), 5032 Intr->getOperand(0)); 5033 5034 return Chain; 5035 } 5036 5037 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5038 SelectionDAG &DAG) const { 5039 MVT VT = Op.getSimpleValueType(); 5040 SDLoc DL(Op); 5041 // Checking the depth 5042 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5043 return DAG.getConstant(0, DL, VT); 5044 5045 MachineFunction &MF = DAG.getMachineFunction(); 5046 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5047 // Check for kernel and shader functions 5048 if (Info->isEntryFunction()) 5049 return DAG.getConstant(0, DL, VT); 5050 5051 MachineFrameInfo &MFI = MF.getFrameInfo(); 5052 // There is a call to @llvm.returnaddress in this function 5053 MFI.setReturnAddressIsTaken(true); 5054 5055 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5056 // Get the return address reg and mark it as an implicit live-in 5057 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5058 5059 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5060 } 5061 5062 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5063 SDValue Op, 5064 const SDLoc &DL, 5065 EVT VT) const { 5066 return Op.getValueType().bitsLE(VT) ? 5067 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5068 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5069 DAG.getTargetConstant(0, DL, MVT::i32)); 5070 } 5071 5072 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5073 assert(Op.getValueType() == MVT::f16 && 5074 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5075 5076 SDValue Src = Op.getOperand(0); 5077 EVT SrcVT = Src.getValueType(); 5078 if (SrcVT != MVT::f64) 5079 return Op; 5080 5081 SDLoc DL(Op); 5082 5083 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5084 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5085 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5086 } 5087 5088 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5089 SelectionDAG &DAG) const { 5090 EVT VT = Op.getValueType(); 5091 const MachineFunction &MF = DAG.getMachineFunction(); 5092 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5093 bool IsIEEEMode = Info->getMode().IEEE; 5094 5095 // FIXME: Assert during selection that this is only selected for 5096 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5097 // mode functions, but this happens to be OK since it's only done in cases 5098 // where there is known no sNaN. 5099 if (IsIEEEMode) 5100 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5101 5102 if (VT == MVT::v4f16) 5103 return splitBinaryVectorOp(Op, DAG); 5104 return Op; 5105 } 5106 5107 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5108 EVT VT = Op.getValueType(); 5109 SDLoc SL(Op); 5110 SDValue LHS = Op.getOperand(0); 5111 SDValue RHS = Op.getOperand(1); 5112 bool isSigned = Op.getOpcode() == ISD::SMULO; 5113 5114 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5115 const APInt &C = RHSC->getAPIntValue(); 5116 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5117 if (C.isPowerOf2()) { 5118 // smulo(x, signed_min) is same as umulo(x, signed_min). 5119 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5120 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5121 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5122 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5123 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5124 SL, VT, Result, ShiftAmt), 5125 LHS, ISD::SETNE); 5126 return DAG.getMergeValues({ Result, Overflow }, SL); 5127 } 5128 } 5129 5130 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5131 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5132 SL, VT, LHS, RHS); 5133 5134 SDValue Sign = isSigned 5135 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5136 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5137 : DAG.getConstant(0, SL, VT); 5138 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5139 5140 return DAG.getMergeValues({ Result, Overflow }, SL); 5141 } 5142 5143 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5144 SDLoc SL(Op); 5145 SDValue Chain = Op.getOperand(0); 5146 5147 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5148 !Subtarget->isTrapHandlerEnabled()) 5149 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5150 5151 MachineFunction &MF = DAG.getMachineFunction(); 5152 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5153 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5154 assert(UserSGPR != AMDGPU::NoRegister); 5155 SDValue QueuePtr = CreateLiveInRegister( 5156 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5157 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5158 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5159 QueuePtr, SDValue()); 5160 SDValue Ops[] = { 5161 ToReg, 5162 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5163 SGPR01, 5164 ToReg.getValue(1) 5165 }; 5166 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5167 } 5168 5169 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5170 SDLoc SL(Op); 5171 SDValue Chain = Op.getOperand(0); 5172 MachineFunction &MF = DAG.getMachineFunction(); 5173 5174 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5175 !Subtarget->isTrapHandlerEnabled()) { 5176 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5177 "debugtrap handler not supported", 5178 Op.getDebugLoc(), 5179 DS_Warning); 5180 LLVMContext &Ctx = MF.getFunction().getContext(); 5181 Ctx.diagnose(NoTrap); 5182 return Chain; 5183 } 5184 5185 SDValue Ops[] = { 5186 Chain, 5187 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5188 }; 5189 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5190 } 5191 5192 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5193 SelectionDAG &DAG) const { 5194 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5195 if (Subtarget->hasApertureRegs()) { 5196 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5197 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5198 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5199 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5200 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5201 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5202 unsigned Encoding = 5203 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5204 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5205 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5206 5207 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5208 SDValue ApertureReg = SDValue( 5209 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5210 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5211 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5212 } 5213 5214 MachineFunction &MF = DAG.getMachineFunction(); 5215 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5216 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5217 assert(UserSGPR != AMDGPU::NoRegister); 5218 5219 SDValue QueuePtr = CreateLiveInRegister( 5220 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5221 5222 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5223 // private_segment_aperture_base_hi. 5224 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5225 5226 SDValue Ptr = 5227 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5228 5229 // TODO: Use custom target PseudoSourceValue. 5230 // TODO: We should use the value from the IR intrinsic call, but it might not 5231 // be available and how do we get it? 5232 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5233 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5234 MinAlign(64, StructOffset), 5235 MachineMemOperand::MODereferenceable | 5236 MachineMemOperand::MOInvariant); 5237 } 5238 5239 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5240 SelectionDAG &DAG) const { 5241 SDLoc SL(Op); 5242 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5243 5244 SDValue Src = ASC->getOperand(0); 5245 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5246 5247 const AMDGPUTargetMachine &TM = 5248 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5249 5250 // flat -> local/private 5251 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5252 unsigned DestAS = ASC->getDestAddressSpace(); 5253 5254 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5255 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5256 unsigned NullVal = TM.getNullPointerValue(DestAS); 5257 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5258 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5259 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5260 5261 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5262 NonNull, Ptr, SegmentNullPtr); 5263 } 5264 } 5265 5266 // local/private -> flat 5267 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5268 unsigned SrcAS = ASC->getSrcAddressSpace(); 5269 5270 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5271 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5272 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5273 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5274 5275 SDValue NonNull 5276 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5277 5278 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5279 SDValue CvtPtr 5280 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5281 5282 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5283 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5284 FlatNullPtr); 5285 } 5286 } 5287 5288 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5289 Src.getValueType() == MVT::i64) 5290 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5291 5292 // global <-> flat are no-ops and never emitted. 5293 5294 const MachineFunction &MF = DAG.getMachineFunction(); 5295 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5296 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5297 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5298 5299 return DAG.getUNDEF(ASC->getValueType(0)); 5300 } 5301 5302 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5303 // the small vector and inserting them into the big vector. That is better than 5304 // the default expansion of doing it via a stack slot. Even though the use of 5305 // the stack slot would be optimized away afterwards, the stack slot itself 5306 // remains. 5307 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5308 SelectionDAG &DAG) const { 5309 SDValue Vec = Op.getOperand(0); 5310 SDValue Ins = Op.getOperand(1); 5311 SDValue Idx = Op.getOperand(2); 5312 EVT VecVT = Vec.getValueType(); 5313 EVT InsVT = Ins.getValueType(); 5314 EVT EltVT = VecVT.getVectorElementType(); 5315 unsigned InsNumElts = InsVT.getVectorNumElements(); 5316 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5317 SDLoc SL(Op); 5318 5319 for (unsigned I = 0; I != InsNumElts; ++I) { 5320 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5321 DAG.getConstant(I, SL, MVT::i32)); 5322 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5323 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5324 } 5325 return Vec; 5326 } 5327 5328 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5329 SelectionDAG &DAG) const { 5330 SDValue Vec = Op.getOperand(0); 5331 SDValue InsVal = Op.getOperand(1); 5332 SDValue Idx = Op.getOperand(2); 5333 EVT VecVT = Vec.getValueType(); 5334 EVT EltVT = VecVT.getVectorElementType(); 5335 unsigned VecSize = VecVT.getSizeInBits(); 5336 unsigned EltSize = EltVT.getSizeInBits(); 5337 5338 5339 assert(VecSize <= 64); 5340 5341 unsigned NumElts = VecVT.getVectorNumElements(); 5342 SDLoc SL(Op); 5343 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5344 5345 if (NumElts == 4 && EltSize == 16 && KIdx) { 5346 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5347 5348 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5349 DAG.getConstant(0, SL, MVT::i32)); 5350 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5351 DAG.getConstant(1, SL, MVT::i32)); 5352 5353 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5354 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5355 5356 unsigned Idx = KIdx->getZExtValue(); 5357 bool InsertLo = Idx < 2; 5358 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5359 InsertLo ? LoVec : HiVec, 5360 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5361 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5362 5363 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5364 5365 SDValue Concat = InsertLo ? 5366 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5367 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5368 5369 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5370 } 5371 5372 if (isa<ConstantSDNode>(Idx)) 5373 return SDValue(); 5374 5375 MVT IntVT = MVT::getIntegerVT(VecSize); 5376 5377 // Avoid stack access for dynamic indexing. 5378 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5379 5380 // Create a congruent vector with the target value in each element so that 5381 // the required element can be masked and ORed into the target vector. 5382 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5383 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5384 5385 assert(isPowerOf2_32(EltSize)); 5386 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5387 5388 // Convert vector index to bit-index. 5389 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5390 5391 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5392 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5393 DAG.getConstant(0xffff, SL, IntVT), 5394 ScaledIdx); 5395 5396 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5397 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5398 DAG.getNOT(SL, BFM, IntVT), BCVec); 5399 5400 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5401 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5402 } 5403 5404 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5405 SelectionDAG &DAG) const { 5406 SDLoc SL(Op); 5407 5408 EVT ResultVT = Op.getValueType(); 5409 SDValue Vec = Op.getOperand(0); 5410 SDValue Idx = Op.getOperand(1); 5411 EVT VecVT = Vec.getValueType(); 5412 unsigned VecSize = VecVT.getSizeInBits(); 5413 EVT EltVT = VecVT.getVectorElementType(); 5414 assert(VecSize <= 64); 5415 5416 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5417 5418 // Make sure we do any optimizations that will make it easier to fold 5419 // source modifiers before obscuring it with bit operations. 5420 5421 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5422 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5423 return Combined; 5424 5425 unsigned EltSize = EltVT.getSizeInBits(); 5426 assert(isPowerOf2_32(EltSize)); 5427 5428 MVT IntVT = MVT::getIntegerVT(VecSize); 5429 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5430 5431 // Convert vector index to bit-index (* EltSize) 5432 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5433 5434 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5435 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5436 5437 if (ResultVT == MVT::f16) { 5438 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5439 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5440 } 5441 5442 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5443 } 5444 5445 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5446 assert(Elt % 2 == 0); 5447 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5448 } 5449 5450 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5451 SelectionDAG &DAG) const { 5452 SDLoc SL(Op); 5453 EVT ResultVT = Op.getValueType(); 5454 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5455 5456 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5457 EVT EltVT = PackVT.getVectorElementType(); 5458 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5459 5460 // vector_shuffle <0,1,6,7> lhs, rhs 5461 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5462 // 5463 // vector_shuffle <6,7,2,3> lhs, rhs 5464 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5465 // 5466 // vector_shuffle <6,7,0,1> lhs, rhs 5467 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5468 5469 // Avoid scalarizing when both halves are reading from consecutive elements. 5470 SmallVector<SDValue, 4> Pieces; 5471 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5472 if (elementPairIsContiguous(SVN->getMask(), I)) { 5473 const int Idx = SVN->getMaskElt(I); 5474 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5475 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5476 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5477 PackVT, SVN->getOperand(VecIdx), 5478 DAG.getConstant(EltIdx, SL, MVT::i32)); 5479 Pieces.push_back(SubVec); 5480 } else { 5481 const int Idx0 = SVN->getMaskElt(I); 5482 const int Idx1 = SVN->getMaskElt(I + 1); 5483 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5484 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5485 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5486 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5487 5488 SDValue Vec0 = SVN->getOperand(VecIdx0); 5489 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5490 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5491 5492 SDValue Vec1 = SVN->getOperand(VecIdx1); 5493 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5494 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5495 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5496 } 5497 } 5498 5499 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5500 } 5501 5502 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5503 SelectionDAG &DAG) const { 5504 SDLoc SL(Op); 5505 EVT VT = Op.getValueType(); 5506 5507 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5508 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5509 5510 // Turn into pair of packed build_vectors. 5511 // TODO: Special case for constants that can be materialized with s_mov_b64. 5512 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5513 { Op.getOperand(0), Op.getOperand(1) }); 5514 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5515 { Op.getOperand(2), Op.getOperand(3) }); 5516 5517 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5518 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5519 5520 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5521 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5522 } 5523 5524 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5525 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5526 5527 SDValue Lo = Op.getOperand(0); 5528 SDValue Hi = Op.getOperand(1); 5529 5530 // Avoid adding defined bits with the zero_extend. 5531 if (Hi.isUndef()) { 5532 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5533 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5534 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5535 } 5536 5537 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5538 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5539 5540 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5541 DAG.getConstant(16, SL, MVT::i32)); 5542 if (Lo.isUndef()) 5543 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5544 5545 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5546 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5547 5548 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5549 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5550 } 5551 5552 bool 5553 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5554 // We can fold offsets for anything that doesn't require a GOT relocation. 5555 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5556 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5557 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5558 !shouldEmitGOTReloc(GA->getGlobal()); 5559 } 5560 5561 static SDValue 5562 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5563 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5564 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5565 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5566 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5567 // lowered to the following code sequence: 5568 // 5569 // For constant address space: 5570 // s_getpc_b64 s[0:1] 5571 // s_add_u32 s0, s0, $symbol 5572 // s_addc_u32 s1, s1, 0 5573 // 5574 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5575 // a fixup or relocation is emitted to replace $symbol with a literal 5576 // constant, which is a pc-relative offset from the encoding of the $symbol 5577 // operand to the global variable. 5578 // 5579 // For global address space: 5580 // s_getpc_b64 s[0:1] 5581 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5582 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5583 // 5584 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5585 // fixups or relocations are emitted to replace $symbol@*@lo and 5586 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5587 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5588 // operand to the global variable. 5589 // 5590 // What we want here is an offset from the value returned by s_getpc 5591 // (which is the address of the s_add_u32 instruction) to the global 5592 // variable, but since the encoding of $symbol starts 4 bytes after the start 5593 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5594 // small. This requires us to add 4 to the global variable offset in order to 5595 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5596 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5597 // instruction. 5598 SDValue PtrLo = 5599 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5600 SDValue PtrHi; 5601 if (GAFlags == SIInstrInfo::MO_NONE) { 5602 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5603 } else { 5604 PtrHi = 5605 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5606 } 5607 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5608 } 5609 5610 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5611 SDValue Op, 5612 SelectionDAG &DAG) const { 5613 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5614 SDLoc DL(GSD); 5615 EVT PtrVT = Op.getValueType(); 5616 5617 const GlobalValue *GV = GSD->getGlobal(); 5618 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5619 shouldUseLDSConstAddress(GV)) || 5620 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5621 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5622 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5623 GV->hasExternalLinkage()) { 5624 Type *Ty = GV->getValueType(); 5625 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5626 // zero-sized type in other languages to declare the dynamic shared 5627 // memory which size is not known at the compile time. They will be 5628 // allocated by the runtime and placed directly after the static 5629 // allocated ones. They all share the same offset. 5630 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5631 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5632 // Adjust alignment for that dynamic shared memory array. 5633 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5634 return SDValue( 5635 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5636 } 5637 } 5638 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5639 } 5640 5641 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5642 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5643 SIInstrInfo::MO_ABS32_LO); 5644 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5645 } 5646 5647 if (shouldEmitFixup(GV)) 5648 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5649 else if (shouldEmitPCReloc(GV)) 5650 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5651 SIInstrInfo::MO_REL32); 5652 5653 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5654 SIInstrInfo::MO_GOTPCREL32); 5655 5656 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5657 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5658 const DataLayout &DataLayout = DAG.getDataLayout(); 5659 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5660 MachinePointerInfo PtrInfo 5661 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5662 5663 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5664 MachineMemOperand::MODereferenceable | 5665 MachineMemOperand::MOInvariant); 5666 } 5667 5668 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5669 const SDLoc &DL, SDValue V) const { 5670 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5671 // the destination register. 5672 // 5673 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5674 // so we will end up with redundant moves to m0. 5675 // 5676 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5677 5678 // A Null SDValue creates a glue result. 5679 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5680 V, Chain); 5681 return SDValue(M0, 0); 5682 } 5683 5684 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5685 SDValue Op, 5686 MVT VT, 5687 unsigned Offset) const { 5688 SDLoc SL(Op); 5689 SDValue Param = lowerKernargMemParameter( 5690 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5691 // The local size values will have the hi 16-bits as zero. 5692 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5693 DAG.getValueType(VT)); 5694 } 5695 5696 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5697 EVT VT) { 5698 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5699 "non-hsa intrinsic with hsa target", 5700 DL.getDebugLoc()); 5701 DAG.getContext()->diagnose(BadIntrin); 5702 return DAG.getUNDEF(VT); 5703 } 5704 5705 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5706 EVT VT) { 5707 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5708 "intrinsic not supported on subtarget", 5709 DL.getDebugLoc()); 5710 DAG.getContext()->diagnose(BadIntrin); 5711 return DAG.getUNDEF(VT); 5712 } 5713 5714 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5715 ArrayRef<SDValue> Elts) { 5716 assert(!Elts.empty()); 5717 MVT Type; 5718 unsigned NumElts; 5719 5720 if (Elts.size() == 1) { 5721 Type = MVT::f32; 5722 NumElts = 1; 5723 } else if (Elts.size() == 2) { 5724 Type = MVT::v2f32; 5725 NumElts = 2; 5726 } else if (Elts.size() == 3) { 5727 Type = MVT::v3f32; 5728 NumElts = 3; 5729 } else if (Elts.size() <= 4) { 5730 Type = MVT::v4f32; 5731 NumElts = 4; 5732 } else if (Elts.size() <= 8) { 5733 Type = MVT::v8f32; 5734 NumElts = 8; 5735 } else { 5736 assert(Elts.size() <= 16); 5737 Type = MVT::v16f32; 5738 NumElts = 16; 5739 } 5740 5741 SmallVector<SDValue, 16> VecElts(NumElts); 5742 for (unsigned i = 0; i < Elts.size(); ++i) { 5743 SDValue Elt = Elts[i]; 5744 if (Elt.getValueType() != MVT::f32) 5745 Elt = DAG.getBitcast(MVT::f32, Elt); 5746 VecElts[i] = Elt; 5747 } 5748 for (unsigned i = Elts.size(); i < NumElts; ++i) 5749 VecElts[i] = DAG.getUNDEF(MVT::f32); 5750 5751 if (NumElts == 1) 5752 return VecElts[0]; 5753 return DAG.getBuildVector(Type, DL, VecElts); 5754 } 5755 5756 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5757 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5758 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5759 5760 uint64_t Value = CachePolicyConst->getZExtValue(); 5761 SDLoc DL(CachePolicy); 5762 if (GLC) { 5763 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5764 Value &= ~(uint64_t)0x1; 5765 } 5766 if (SLC) { 5767 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5768 Value &= ~(uint64_t)0x2; 5769 } 5770 if (DLC) { 5771 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5772 Value &= ~(uint64_t)0x4; 5773 } 5774 5775 return Value == 0; 5776 } 5777 5778 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5779 SDValue Src, int ExtraElts) { 5780 EVT SrcVT = Src.getValueType(); 5781 5782 SmallVector<SDValue, 8> Elts; 5783 5784 if (SrcVT.isVector()) 5785 DAG.ExtractVectorElements(Src, Elts); 5786 else 5787 Elts.push_back(Src); 5788 5789 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5790 while (ExtraElts--) 5791 Elts.push_back(Undef); 5792 5793 return DAG.getBuildVector(CastVT, DL, Elts); 5794 } 5795 5796 // Re-construct the required return value for a image load intrinsic. 5797 // This is more complicated due to the optional use TexFailCtrl which means the required 5798 // return type is an aggregate 5799 static SDValue constructRetValue(SelectionDAG &DAG, 5800 MachineSDNode *Result, 5801 ArrayRef<EVT> ResultTypes, 5802 bool IsTexFail, bool Unpacked, bool IsD16, 5803 int DMaskPop, int NumVDataDwords, 5804 const SDLoc &DL, LLVMContext &Context) { 5805 // Determine the required return type. This is the same regardless of IsTexFail flag 5806 EVT ReqRetVT = ResultTypes[0]; 5807 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5808 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5809 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5810 5811 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5812 DMaskPop : (DMaskPop + 1) / 2; 5813 5814 MVT DataDwordVT = NumDataDwords == 1 ? 5815 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5816 5817 MVT MaskPopVT = MaskPopDwords == 1 ? 5818 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5819 5820 SDValue Data(Result, 0); 5821 SDValue TexFail; 5822 5823 if (IsTexFail) { 5824 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5825 if (MaskPopVT.isVector()) { 5826 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5827 SDValue(Result, 0), ZeroIdx); 5828 } else { 5829 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5830 SDValue(Result, 0), ZeroIdx); 5831 } 5832 5833 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5834 SDValue(Result, 0), 5835 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5836 } 5837 5838 if (DataDwordVT.isVector()) 5839 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5840 NumDataDwords - MaskPopDwords); 5841 5842 if (IsD16) 5843 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5844 5845 if (!ReqRetVT.isVector()) 5846 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5847 5848 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5849 5850 if (TexFail) 5851 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5852 5853 if (Result->getNumValues() == 1) 5854 return Data; 5855 5856 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5857 } 5858 5859 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5860 SDValue *LWE, bool &IsTexFail) { 5861 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5862 5863 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5864 if (Value) { 5865 IsTexFail = true; 5866 } 5867 5868 SDLoc DL(TexFailCtrlConst); 5869 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5870 Value &= ~(uint64_t)0x1; 5871 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5872 Value &= ~(uint64_t)0x2; 5873 5874 return Value == 0; 5875 } 5876 5877 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5878 MVT PackVectorVT, 5879 SmallVectorImpl<SDValue> &PackedAddrs, 5880 unsigned DimIdx, unsigned EndIdx, 5881 unsigned NumGradients) { 5882 SDLoc DL(Op); 5883 for (unsigned I = DimIdx; I < EndIdx; I++) { 5884 SDValue Addr = Op.getOperand(I); 5885 5886 // Gradients are packed with undef for each coordinate. 5887 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5888 // 1D: undef,dx/dh; undef,dx/dv 5889 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5890 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5891 if (((I + 1) >= EndIdx) || 5892 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5893 I == DimIdx + NumGradients - 1))) { 5894 if (Addr.getValueType() != MVT::i16) 5895 Addr = DAG.getBitcast(MVT::i16, Addr); 5896 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5897 } else { 5898 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5899 I++; 5900 } 5901 Addr = DAG.getBitcast(MVT::f32, Addr); 5902 PackedAddrs.push_back(Addr); 5903 } 5904 } 5905 5906 SDValue SITargetLowering::lowerImage(SDValue Op, 5907 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5908 SelectionDAG &DAG) const { 5909 SDLoc DL(Op); 5910 MachineFunction &MF = DAG.getMachineFunction(); 5911 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5912 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5913 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5914 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5915 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5916 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5917 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5918 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5919 unsigned IntrOpcode = Intr->BaseOpcode; 5920 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5921 5922 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5923 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5924 bool IsD16 = false; 5925 bool IsG16 = false; 5926 bool IsA16 = false; 5927 SDValue VData; 5928 int NumVDataDwords; 5929 bool AdjustRetType = false; 5930 5931 unsigned AddrIdx; // Index of first address argument 5932 unsigned DMask; 5933 unsigned DMaskLanes = 0; 5934 5935 if (BaseOpcode->Atomic) { 5936 VData = Op.getOperand(2); 5937 5938 bool Is64Bit = VData.getValueType() == MVT::i64; 5939 if (BaseOpcode->AtomicX2) { 5940 SDValue VData2 = Op.getOperand(3); 5941 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5942 {VData, VData2}); 5943 if (Is64Bit) 5944 VData = DAG.getBitcast(MVT::v4i32, VData); 5945 5946 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5947 DMask = Is64Bit ? 0xf : 0x3; 5948 NumVDataDwords = Is64Bit ? 4 : 2; 5949 AddrIdx = 4; 5950 } else { 5951 DMask = Is64Bit ? 0x3 : 0x1; 5952 NumVDataDwords = Is64Bit ? 2 : 1; 5953 AddrIdx = 3; 5954 } 5955 } else { 5956 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5957 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5958 DMask = DMaskConst->getZExtValue(); 5959 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5960 5961 if (BaseOpcode->Store) { 5962 VData = Op.getOperand(2); 5963 5964 MVT StoreVT = VData.getSimpleValueType(); 5965 if (StoreVT.getScalarType() == MVT::f16) { 5966 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5967 return Op; // D16 is unsupported for this instruction 5968 5969 IsD16 = true; 5970 VData = handleD16VData(VData, DAG); 5971 } 5972 5973 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5974 } else { 5975 // Work out the num dwords based on the dmask popcount and underlying type 5976 // and whether packing is supported. 5977 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5978 if (LoadVT.getScalarType() == MVT::f16) { 5979 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5980 return Op; // D16 is unsupported for this instruction 5981 5982 IsD16 = true; 5983 } 5984 5985 // Confirm that the return type is large enough for the dmask specified 5986 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5987 (!LoadVT.isVector() && DMaskLanes > 1)) 5988 return Op; 5989 5990 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5991 NumVDataDwords = (DMaskLanes + 1) / 2; 5992 else 5993 NumVDataDwords = DMaskLanes; 5994 5995 AdjustRetType = true; 5996 } 5997 5998 AddrIdx = DMaskIdx + 1; 5999 } 6000 6001 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 6002 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 6003 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 6004 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 6005 NumCoords + NumLCM; 6006 unsigned NumMIVAddrs = NumVAddrs; 6007 6008 SmallVector<SDValue, 4> VAddrs; 6009 6010 // Optimize _L to _LZ when _L is zero 6011 if (LZMappingInfo) { 6012 if (auto ConstantLod = 6013 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 6014 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6015 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6016 NumMIVAddrs--; // remove 'lod' 6017 } 6018 } 6019 } 6020 6021 // Optimize _mip away, when 'lod' is zero 6022 if (MIPMappingInfo) { 6023 if (auto ConstantLod = 6024 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 6025 if (ConstantLod->isNullValue()) { 6026 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6027 NumMIVAddrs--; // remove 'lod' 6028 } 6029 } 6030 } 6031 6032 // Push back extra arguments. 6033 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 6034 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 6035 6036 // Check for 16 bit addresses or derivatives and pack if true. 6037 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 6038 unsigned CoordIdx = DimIdx + NumGradients; 6039 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 6040 6041 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 6042 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6043 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6044 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6045 6046 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 6047 VAddrScalarVT = VAddrVT.getScalarType(); 6048 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6049 if (IsA16 || IsG16) { 6050 if (IsA16) { 6051 if (!ST->hasA16()) { 6052 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6053 "support 16 bit addresses\n"); 6054 return Op; 6055 } 6056 if (!IsG16) { 6057 LLVM_DEBUG( 6058 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6059 "need 16 bit derivatives but got 32 bit derivatives\n"); 6060 return Op; 6061 } 6062 } else if (!ST->hasG16()) { 6063 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6064 "support 16 bit derivatives\n"); 6065 return Op; 6066 } 6067 6068 if (BaseOpcode->Gradients && !IsA16) { 6069 if (!ST->hasG16()) { 6070 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6071 "support 16 bit derivatives\n"); 6072 return Op; 6073 } 6074 // Activate g16 6075 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6076 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6077 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6078 } 6079 6080 // Don't compress addresses for G16 6081 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 6082 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 6083 PackEndIdx, NumGradients); 6084 6085 if (!IsA16) { 6086 // Add uncompressed address 6087 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 6088 VAddrs.push_back(Op.getOperand(I)); 6089 } 6090 } else { 6091 for (unsigned I = DimIdx; I < CoordsEnd; I++) 6092 VAddrs.push_back(Op.getOperand(I)); 6093 } 6094 6095 // If the register allocator cannot place the address registers contiguously 6096 // without introducing moves, then using the non-sequential address encoding 6097 // is always preferable, since it saves VALU instructions and is usually a 6098 // wash in terms of code size or even better. 6099 // 6100 // However, we currently have no way of hinting to the register allocator that 6101 // MIMG addresses should be placed contiguously when it is possible to do so, 6102 // so force non-NSA for the common 2-address case as a heuristic. 6103 // 6104 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6105 // allocation when possible. 6106 bool UseNSA = 6107 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6108 SDValue VAddr; 6109 if (!UseNSA) 6110 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6111 6112 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6113 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6114 unsigned CtrlIdx; // Index of texfailctrl argument 6115 SDValue Unorm; 6116 if (!BaseOpcode->Sampler) { 6117 Unorm = True; 6118 CtrlIdx = AddrIdx + NumVAddrs + 1; 6119 } else { 6120 auto UnormConst = 6121 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6122 6123 Unorm = UnormConst->getZExtValue() ? True : False; 6124 CtrlIdx = AddrIdx + NumVAddrs + 3; 6125 } 6126 6127 SDValue TFE; 6128 SDValue LWE; 6129 SDValue TexFail = Op.getOperand(CtrlIdx); 6130 bool IsTexFail = false; 6131 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6132 return Op; 6133 6134 if (IsTexFail) { 6135 if (!DMaskLanes) { 6136 // Expecting to get an error flag since TFC is on - and dmask is 0 6137 // Force dmask to be at least 1 otherwise the instruction will fail 6138 DMask = 0x1; 6139 DMaskLanes = 1; 6140 NumVDataDwords = 1; 6141 } 6142 NumVDataDwords += 1; 6143 AdjustRetType = true; 6144 } 6145 6146 // Has something earlier tagged that the return type needs adjusting 6147 // This happens if the instruction is a load or has set TexFailCtrl flags 6148 if (AdjustRetType) { 6149 // NumVDataDwords reflects the true number of dwords required in the return type 6150 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6151 // This is a no-op load. This can be eliminated 6152 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6153 if (isa<MemSDNode>(Op)) 6154 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6155 return Undef; 6156 } 6157 6158 EVT NewVT = NumVDataDwords > 1 ? 6159 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6160 : MVT::i32; 6161 6162 ResultTypes[0] = NewVT; 6163 if (ResultTypes.size() == 3) { 6164 // Original result was aggregate type used for TexFailCtrl results 6165 // The actual instruction returns as a vector type which has now been 6166 // created. Remove the aggregate result. 6167 ResultTypes.erase(&ResultTypes[1]); 6168 } 6169 } 6170 6171 SDValue GLC; 6172 SDValue SLC; 6173 SDValue DLC; 6174 if (BaseOpcode->Atomic) { 6175 GLC = True; // TODO no-return optimization 6176 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6177 IsGFX10 ? &DLC : nullptr)) 6178 return Op; 6179 } else { 6180 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6181 IsGFX10 ? &DLC : nullptr)) 6182 return Op; 6183 } 6184 6185 SmallVector<SDValue, 26> Ops; 6186 if (BaseOpcode->Store || BaseOpcode->Atomic) 6187 Ops.push_back(VData); // vdata 6188 if (UseNSA) { 6189 for (const SDValue &Addr : VAddrs) 6190 Ops.push_back(Addr); 6191 } else { 6192 Ops.push_back(VAddr); 6193 } 6194 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6195 if (BaseOpcode->Sampler) 6196 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6197 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6198 if (IsGFX10) 6199 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6200 Ops.push_back(Unorm); 6201 if (IsGFX10) 6202 Ops.push_back(DLC); 6203 Ops.push_back(GLC); 6204 Ops.push_back(SLC); 6205 Ops.push_back(IsA16 && // r128, a16 for gfx9 6206 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6207 if (IsGFX10) 6208 Ops.push_back(IsA16 ? True : False); 6209 Ops.push_back(TFE); 6210 Ops.push_back(LWE); 6211 if (!IsGFX10) 6212 Ops.push_back(DimInfo->DA ? True : False); 6213 if (BaseOpcode->HasD16) 6214 Ops.push_back(IsD16 ? True : False); 6215 if (isa<MemSDNode>(Op)) 6216 Ops.push_back(Op.getOperand(0)); // chain 6217 6218 int NumVAddrDwords = 6219 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6220 int Opcode = -1; 6221 6222 if (IsGFX10) { 6223 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6224 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6225 : AMDGPU::MIMGEncGfx10Default, 6226 NumVDataDwords, NumVAddrDwords); 6227 } else { 6228 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6229 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6230 NumVDataDwords, NumVAddrDwords); 6231 if (Opcode == -1) 6232 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6233 NumVDataDwords, NumVAddrDwords); 6234 } 6235 assert(Opcode != -1); 6236 6237 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6238 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6239 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6240 DAG.setNodeMemRefs(NewNode, {MemRef}); 6241 } 6242 6243 if (BaseOpcode->AtomicX2) { 6244 SmallVector<SDValue, 1> Elt; 6245 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6246 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6247 } else if (!BaseOpcode->Store) { 6248 return constructRetValue(DAG, NewNode, 6249 OrigResultTypes, IsTexFail, 6250 Subtarget->hasUnpackedD16VMem(), IsD16, 6251 DMaskLanes, NumVDataDwords, DL, 6252 *DAG.getContext()); 6253 } 6254 6255 return SDValue(NewNode, 0); 6256 } 6257 6258 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6259 SDValue Offset, SDValue CachePolicy, 6260 SelectionDAG &DAG) const { 6261 MachineFunction &MF = DAG.getMachineFunction(); 6262 6263 const DataLayout &DataLayout = DAG.getDataLayout(); 6264 Align Alignment = 6265 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6266 6267 MachineMemOperand *MMO = MF.getMachineMemOperand( 6268 MachinePointerInfo(), 6269 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6270 MachineMemOperand::MOInvariant, 6271 VT.getStoreSize(), Alignment); 6272 6273 if (!Offset->isDivergent()) { 6274 SDValue Ops[] = { 6275 Rsrc, 6276 Offset, // Offset 6277 CachePolicy 6278 }; 6279 6280 // Widen vec3 load to vec4. 6281 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6282 EVT WidenedVT = 6283 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6284 auto WidenedOp = DAG.getMemIntrinsicNode( 6285 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6286 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6287 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6288 DAG.getVectorIdxConstant(0, DL)); 6289 return Subvector; 6290 } 6291 6292 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6293 DAG.getVTList(VT), Ops, VT, MMO); 6294 } 6295 6296 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6297 // assume that the buffer is unswizzled. 6298 SmallVector<SDValue, 4> Loads; 6299 unsigned NumLoads = 1; 6300 MVT LoadVT = VT.getSimpleVT(); 6301 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6302 assert((LoadVT.getScalarType() == MVT::i32 || 6303 LoadVT.getScalarType() == MVT::f32)); 6304 6305 if (NumElts == 8 || NumElts == 16) { 6306 NumLoads = NumElts / 4; 6307 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6308 } 6309 6310 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6311 SDValue Ops[] = { 6312 DAG.getEntryNode(), // Chain 6313 Rsrc, // rsrc 6314 DAG.getConstant(0, DL, MVT::i32), // vindex 6315 {}, // voffset 6316 {}, // soffset 6317 {}, // offset 6318 CachePolicy, // cachepolicy 6319 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6320 }; 6321 6322 // Use the alignment to ensure that the required offsets will fit into the 6323 // immediate offsets. 6324 setBufferOffsets(Offset, DAG, &Ops[3], 6325 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6326 6327 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6328 for (unsigned i = 0; i < NumLoads; ++i) { 6329 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6330 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6331 LoadVT, MMO, DAG)); 6332 } 6333 6334 if (NumElts == 8 || NumElts == 16) 6335 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6336 6337 return Loads[0]; 6338 } 6339 6340 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6341 SelectionDAG &DAG) const { 6342 MachineFunction &MF = DAG.getMachineFunction(); 6343 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6344 6345 EVT VT = Op.getValueType(); 6346 SDLoc DL(Op); 6347 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6348 6349 // TODO: Should this propagate fast-math-flags? 6350 6351 switch (IntrinsicID) { 6352 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6353 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6354 return emitNonHSAIntrinsicError(DAG, DL, VT); 6355 return getPreloadedValue(DAG, *MFI, VT, 6356 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6357 } 6358 case Intrinsic::amdgcn_dispatch_ptr: 6359 case Intrinsic::amdgcn_queue_ptr: { 6360 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6361 DiagnosticInfoUnsupported BadIntrin( 6362 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6363 DL.getDebugLoc()); 6364 DAG.getContext()->diagnose(BadIntrin); 6365 return DAG.getUNDEF(VT); 6366 } 6367 6368 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6369 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6370 return getPreloadedValue(DAG, *MFI, VT, RegID); 6371 } 6372 case Intrinsic::amdgcn_implicitarg_ptr: { 6373 if (MFI->isEntryFunction()) 6374 return getImplicitArgPtr(DAG, DL); 6375 return getPreloadedValue(DAG, *MFI, VT, 6376 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6377 } 6378 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6379 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6380 // This only makes sense to call in a kernel, so just lower to null. 6381 return DAG.getConstant(0, DL, VT); 6382 } 6383 6384 return getPreloadedValue(DAG, *MFI, VT, 6385 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6386 } 6387 case Intrinsic::amdgcn_dispatch_id: { 6388 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6389 } 6390 case Intrinsic::amdgcn_rcp: 6391 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6392 case Intrinsic::amdgcn_rsq: 6393 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6394 case Intrinsic::amdgcn_rsq_legacy: 6395 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6396 return emitRemovedIntrinsicError(DAG, DL, VT); 6397 return SDValue(); 6398 case Intrinsic::amdgcn_rcp_legacy: 6399 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6400 return emitRemovedIntrinsicError(DAG, DL, VT); 6401 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6402 case Intrinsic::amdgcn_rsq_clamp: { 6403 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6404 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6405 6406 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6407 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6408 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6409 6410 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6411 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6412 DAG.getConstantFP(Max, DL, VT)); 6413 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6414 DAG.getConstantFP(Min, DL, VT)); 6415 } 6416 case Intrinsic::r600_read_ngroups_x: 6417 if (Subtarget->isAmdHsaOS()) 6418 return emitNonHSAIntrinsicError(DAG, DL, VT); 6419 6420 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6421 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6422 false); 6423 case Intrinsic::r600_read_ngroups_y: 6424 if (Subtarget->isAmdHsaOS()) 6425 return emitNonHSAIntrinsicError(DAG, DL, VT); 6426 6427 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6428 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6429 false); 6430 case Intrinsic::r600_read_ngroups_z: 6431 if (Subtarget->isAmdHsaOS()) 6432 return emitNonHSAIntrinsicError(DAG, DL, VT); 6433 6434 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6435 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6436 false); 6437 case Intrinsic::r600_read_global_size_x: 6438 if (Subtarget->isAmdHsaOS()) 6439 return emitNonHSAIntrinsicError(DAG, DL, VT); 6440 6441 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6442 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6443 Align(4), false); 6444 case Intrinsic::r600_read_global_size_y: 6445 if (Subtarget->isAmdHsaOS()) 6446 return emitNonHSAIntrinsicError(DAG, DL, VT); 6447 6448 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6449 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6450 Align(4), false); 6451 case Intrinsic::r600_read_global_size_z: 6452 if (Subtarget->isAmdHsaOS()) 6453 return emitNonHSAIntrinsicError(DAG, DL, VT); 6454 6455 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6456 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6457 Align(4), false); 6458 case Intrinsic::r600_read_local_size_x: 6459 if (Subtarget->isAmdHsaOS()) 6460 return emitNonHSAIntrinsicError(DAG, DL, VT); 6461 6462 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6463 SI::KernelInputOffsets::LOCAL_SIZE_X); 6464 case Intrinsic::r600_read_local_size_y: 6465 if (Subtarget->isAmdHsaOS()) 6466 return emitNonHSAIntrinsicError(DAG, DL, VT); 6467 6468 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6469 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6470 case Intrinsic::r600_read_local_size_z: 6471 if (Subtarget->isAmdHsaOS()) 6472 return emitNonHSAIntrinsicError(DAG, DL, VT); 6473 6474 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6475 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6476 case Intrinsic::amdgcn_workgroup_id_x: 6477 return getPreloadedValue(DAG, *MFI, VT, 6478 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6479 case Intrinsic::amdgcn_workgroup_id_y: 6480 return getPreloadedValue(DAG, *MFI, VT, 6481 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6482 case Intrinsic::amdgcn_workgroup_id_z: 6483 return getPreloadedValue(DAG, *MFI, VT, 6484 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6485 case Intrinsic::amdgcn_workitem_id_x: 6486 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6487 SDLoc(DAG.getEntryNode()), 6488 MFI->getArgInfo().WorkItemIDX); 6489 case Intrinsic::amdgcn_workitem_id_y: 6490 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6491 SDLoc(DAG.getEntryNode()), 6492 MFI->getArgInfo().WorkItemIDY); 6493 case Intrinsic::amdgcn_workitem_id_z: 6494 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6495 SDLoc(DAG.getEntryNode()), 6496 MFI->getArgInfo().WorkItemIDZ); 6497 case Intrinsic::amdgcn_wavefrontsize: 6498 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6499 SDLoc(Op), MVT::i32); 6500 case Intrinsic::amdgcn_s_buffer_load: { 6501 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6502 SDValue GLC; 6503 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6504 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6505 IsGFX10 ? &DLC : nullptr)) 6506 return Op; 6507 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6508 DAG); 6509 } 6510 case Intrinsic::amdgcn_fdiv_fast: 6511 return lowerFDIV_FAST(Op, DAG); 6512 case Intrinsic::amdgcn_sin: 6513 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6514 6515 case Intrinsic::amdgcn_cos: 6516 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6517 6518 case Intrinsic::amdgcn_mul_u24: 6519 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6520 case Intrinsic::amdgcn_mul_i24: 6521 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6522 6523 case Intrinsic::amdgcn_log_clamp: { 6524 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6525 return SDValue(); 6526 6527 DiagnosticInfoUnsupported BadIntrin( 6528 MF.getFunction(), "intrinsic not supported on subtarget", 6529 DL.getDebugLoc()); 6530 DAG.getContext()->diagnose(BadIntrin); 6531 return DAG.getUNDEF(VT); 6532 } 6533 case Intrinsic::amdgcn_ldexp: 6534 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6535 Op.getOperand(1), Op.getOperand(2)); 6536 6537 case Intrinsic::amdgcn_fract: 6538 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6539 6540 case Intrinsic::amdgcn_class: 6541 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6542 Op.getOperand(1), Op.getOperand(2)); 6543 case Intrinsic::amdgcn_div_fmas: 6544 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6545 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6546 Op.getOperand(4)); 6547 6548 case Intrinsic::amdgcn_div_fixup: 6549 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6550 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6551 6552 case Intrinsic::amdgcn_div_scale: { 6553 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6554 6555 // Translate to the operands expected by the machine instruction. The 6556 // first parameter must be the same as the first instruction. 6557 SDValue Numerator = Op.getOperand(1); 6558 SDValue Denominator = Op.getOperand(2); 6559 6560 // Note this order is opposite of the machine instruction's operations, 6561 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6562 // intrinsic has the numerator as the first operand to match a normal 6563 // division operation. 6564 6565 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6566 6567 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6568 Denominator, Numerator); 6569 } 6570 case Intrinsic::amdgcn_icmp: { 6571 // There is a Pat that handles this variant, so return it as-is. 6572 if (Op.getOperand(1).getValueType() == MVT::i1 && 6573 Op.getConstantOperandVal(2) == 0 && 6574 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6575 return Op; 6576 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6577 } 6578 case Intrinsic::amdgcn_fcmp: { 6579 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6580 } 6581 case Intrinsic::amdgcn_ballot: 6582 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6583 case Intrinsic::amdgcn_fmed3: 6584 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6585 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6586 case Intrinsic::amdgcn_fdot2: 6587 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6588 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6589 Op.getOperand(4)); 6590 case Intrinsic::amdgcn_fmul_legacy: 6591 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6592 Op.getOperand(1), Op.getOperand(2)); 6593 case Intrinsic::amdgcn_sffbh: 6594 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6595 case Intrinsic::amdgcn_sbfe: 6596 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6597 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6598 case Intrinsic::amdgcn_ubfe: 6599 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6600 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6601 case Intrinsic::amdgcn_cvt_pkrtz: 6602 case Intrinsic::amdgcn_cvt_pknorm_i16: 6603 case Intrinsic::amdgcn_cvt_pknorm_u16: 6604 case Intrinsic::amdgcn_cvt_pk_i16: 6605 case Intrinsic::amdgcn_cvt_pk_u16: { 6606 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6607 EVT VT = Op.getValueType(); 6608 unsigned Opcode; 6609 6610 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6611 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6612 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6613 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6614 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6615 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6616 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6617 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6618 else 6619 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6620 6621 if (isTypeLegal(VT)) 6622 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6623 6624 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6625 Op.getOperand(1), Op.getOperand(2)); 6626 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6627 } 6628 case Intrinsic::amdgcn_fmad_ftz: 6629 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6630 Op.getOperand(2), Op.getOperand(3)); 6631 6632 case Intrinsic::amdgcn_if_break: 6633 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6634 Op->getOperand(1), Op->getOperand(2)), 0); 6635 6636 case Intrinsic::amdgcn_groupstaticsize: { 6637 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6638 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6639 return Op; 6640 6641 const Module *M = MF.getFunction().getParent(); 6642 const GlobalValue *GV = 6643 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6644 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6645 SIInstrInfo::MO_ABS32_LO); 6646 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6647 } 6648 case Intrinsic::amdgcn_is_shared: 6649 case Intrinsic::amdgcn_is_private: { 6650 SDLoc SL(Op); 6651 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6652 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6653 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6654 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6655 Op.getOperand(1)); 6656 6657 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6658 DAG.getConstant(1, SL, MVT::i32)); 6659 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6660 } 6661 case Intrinsic::amdgcn_alignbit: 6662 return DAG.getNode(ISD::FSHR, DL, VT, 6663 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6664 case Intrinsic::amdgcn_reloc_constant: { 6665 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6666 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6667 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6668 auto RelocSymbol = cast<GlobalVariable>( 6669 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6670 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6671 SIInstrInfo::MO_ABS32_LO); 6672 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6673 } 6674 default: 6675 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6676 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6677 return lowerImage(Op, ImageDimIntr, DAG); 6678 6679 return Op; 6680 } 6681 } 6682 6683 // This function computes an appropriate offset to pass to 6684 // MachineMemOperand::setOffset() based on the offset inputs to 6685 // an intrinsic. If any of the offsets are non-contstant or 6686 // if VIndex is non-zero then this function returns 0. Otherwise, 6687 // it returns the sum of VOffset, SOffset, and Offset. 6688 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6689 SDValue SOffset, 6690 SDValue Offset, 6691 SDValue VIndex = SDValue()) { 6692 6693 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6694 !isa<ConstantSDNode>(Offset)) 6695 return 0; 6696 6697 if (VIndex) { 6698 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6699 return 0; 6700 } 6701 6702 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6703 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6704 cast<ConstantSDNode>(Offset)->getSExtValue(); 6705 } 6706 6707 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6708 SelectionDAG &DAG, 6709 unsigned NewOpcode) const { 6710 SDLoc DL(Op); 6711 6712 SDValue VData = Op.getOperand(2); 6713 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6714 SDValue Ops[] = { 6715 Op.getOperand(0), // Chain 6716 VData, // vdata 6717 Op.getOperand(3), // rsrc 6718 DAG.getConstant(0, DL, MVT::i32), // vindex 6719 Offsets.first, // voffset 6720 Op.getOperand(5), // soffset 6721 Offsets.second, // offset 6722 Op.getOperand(6), // cachepolicy 6723 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6724 }; 6725 6726 auto *M = cast<MemSDNode>(Op); 6727 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6728 6729 EVT MemVT = VData.getValueType(); 6730 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6731 M->getMemOperand()); 6732 } 6733 6734 SDValue 6735 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6736 unsigned NewOpcode) const { 6737 SDLoc DL(Op); 6738 6739 SDValue VData = Op.getOperand(2); 6740 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6741 SDValue Ops[] = { 6742 Op.getOperand(0), // Chain 6743 VData, // vdata 6744 Op.getOperand(3), // rsrc 6745 Op.getOperand(4), // vindex 6746 Offsets.first, // voffset 6747 Op.getOperand(6), // soffset 6748 Offsets.second, // offset 6749 Op.getOperand(7), // cachepolicy 6750 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6751 }; 6752 6753 auto *M = cast<MemSDNode>(Op); 6754 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6755 Ops[3])); 6756 6757 EVT MemVT = VData.getValueType(); 6758 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6759 M->getMemOperand()); 6760 } 6761 6762 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6763 SelectionDAG &DAG) const { 6764 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6765 SDLoc DL(Op); 6766 6767 switch (IntrID) { 6768 case Intrinsic::amdgcn_ds_ordered_add: 6769 case Intrinsic::amdgcn_ds_ordered_swap: { 6770 MemSDNode *M = cast<MemSDNode>(Op); 6771 SDValue Chain = M->getOperand(0); 6772 SDValue M0 = M->getOperand(2); 6773 SDValue Value = M->getOperand(3); 6774 unsigned IndexOperand = M->getConstantOperandVal(7); 6775 unsigned WaveRelease = M->getConstantOperandVal(8); 6776 unsigned WaveDone = M->getConstantOperandVal(9); 6777 6778 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6779 IndexOperand &= ~0x3f; 6780 unsigned CountDw = 0; 6781 6782 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6783 CountDw = (IndexOperand >> 24) & 0xf; 6784 IndexOperand &= ~(0xf << 24); 6785 6786 if (CountDw < 1 || CountDw > 4) { 6787 report_fatal_error( 6788 "ds_ordered_count: dword count must be between 1 and 4"); 6789 } 6790 } 6791 6792 if (IndexOperand) 6793 report_fatal_error("ds_ordered_count: bad index operand"); 6794 6795 if (WaveDone && !WaveRelease) 6796 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6797 6798 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6799 unsigned ShaderType = 6800 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6801 unsigned Offset0 = OrderedCountIndex << 2; 6802 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6803 (Instruction << 4); 6804 6805 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6806 Offset1 |= (CountDw - 1) << 6; 6807 6808 unsigned Offset = Offset0 | (Offset1 << 8); 6809 6810 SDValue Ops[] = { 6811 Chain, 6812 Value, 6813 DAG.getTargetConstant(Offset, DL, MVT::i16), 6814 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6815 }; 6816 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6817 M->getVTList(), Ops, M->getMemoryVT(), 6818 M->getMemOperand()); 6819 } 6820 case Intrinsic::amdgcn_ds_fadd: { 6821 MemSDNode *M = cast<MemSDNode>(Op); 6822 unsigned Opc; 6823 switch (IntrID) { 6824 case Intrinsic::amdgcn_ds_fadd: 6825 Opc = ISD::ATOMIC_LOAD_FADD; 6826 break; 6827 } 6828 6829 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6830 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6831 M->getMemOperand()); 6832 } 6833 case Intrinsic::amdgcn_atomic_inc: 6834 case Intrinsic::amdgcn_atomic_dec: 6835 case Intrinsic::amdgcn_ds_fmin: 6836 case Intrinsic::amdgcn_ds_fmax: { 6837 MemSDNode *M = cast<MemSDNode>(Op); 6838 unsigned Opc; 6839 switch (IntrID) { 6840 case Intrinsic::amdgcn_atomic_inc: 6841 Opc = AMDGPUISD::ATOMIC_INC; 6842 break; 6843 case Intrinsic::amdgcn_atomic_dec: 6844 Opc = AMDGPUISD::ATOMIC_DEC; 6845 break; 6846 case Intrinsic::amdgcn_ds_fmin: 6847 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6848 break; 6849 case Intrinsic::amdgcn_ds_fmax: 6850 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6851 break; 6852 default: 6853 llvm_unreachable("Unknown intrinsic!"); 6854 } 6855 SDValue Ops[] = { 6856 M->getOperand(0), // Chain 6857 M->getOperand(2), // Ptr 6858 M->getOperand(3) // Value 6859 }; 6860 6861 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6862 M->getMemoryVT(), M->getMemOperand()); 6863 } 6864 case Intrinsic::amdgcn_buffer_load: 6865 case Intrinsic::amdgcn_buffer_load_format: { 6866 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6867 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6868 unsigned IdxEn = 1; 6869 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6870 IdxEn = Idx->getZExtValue() != 0; 6871 SDValue Ops[] = { 6872 Op.getOperand(0), // Chain 6873 Op.getOperand(2), // rsrc 6874 Op.getOperand(3), // vindex 6875 SDValue(), // voffset -- will be set by setBufferOffsets 6876 SDValue(), // soffset -- will be set by setBufferOffsets 6877 SDValue(), // offset -- will be set by setBufferOffsets 6878 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6879 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6880 }; 6881 6882 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6883 // We don't know the offset if vindex is non-zero, so clear it. 6884 if (IdxEn) 6885 Offset = 0; 6886 6887 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6888 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6889 6890 EVT VT = Op.getValueType(); 6891 EVT IntVT = VT.changeTypeToInteger(); 6892 auto *M = cast<MemSDNode>(Op); 6893 M->getMemOperand()->setOffset(Offset); 6894 EVT LoadVT = Op.getValueType(); 6895 6896 if (LoadVT.getScalarType() == MVT::f16) 6897 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6898 M, DAG, Ops); 6899 6900 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6901 if (LoadVT.getScalarType() == MVT::i8 || 6902 LoadVT.getScalarType() == MVT::i16) 6903 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6904 6905 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6906 M->getMemOperand(), DAG); 6907 } 6908 case Intrinsic::amdgcn_raw_buffer_load: 6909 case Intrinsic::amdgcn_raw_buffer_load_format: { 6910 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6911 6912 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6913 SDValue Ops[] = { 6914 Op.getOperand(0), // Chain 6915 Op.getOperand(2), // rsrc 6916 DAG.getConstant(0, DL, MVT::i32), // vindex 6917 Offsets.first, // voffset 6918 Op.getOperand(4), // soffset 6919 Offsets.second, // offset 6920 Op.getOperand(5), // cachepolicy, swizzled buffer 6921 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6922 }; 6923 6924 auto *M = cast<MemSDNode>(Op); 6925 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6926 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6927 } 6928 case Intrinsic::amdgcn_struct_buffer_load: 6929 case Intrinsic::amdgcn_struct_buffer_load_format: { 6930 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6931 6932 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6933 SDValue Ops[] = { 6934 Op.getOperand(0), // Chain 6935 Op.getOperand(2), // rsrc 6936 Op.getOperand(3), // vindex 6937 Offsets.first, // voffset 6938 Op.getOperand(5), // soffset 6939 Offsets.second, // offset 6940 Op.getOperand(6), // cachepolicy, swizzled buffer 6941 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6942 }; 6943 6944 auto *M = cast<MemSDNode>(Op); 6945 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6946 Ops[2])); 6947 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6948 } 6949 case Intrinsic::amdgcn_tbuffer_load: { 6950 MemSDNode *M = cast<MemSDNode>(Op); 6951 EVT LoadVT = Op.getValueType(); 6952 6953 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6954 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6955 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6956 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6957 unsigned IdxEn = 1; 6958 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6959 IdxEn = Idx->getZExtValue() != 0; 6960 SDValue Ops[] = { 6961 Op.getOperand(0), // Chain 6962 Op.getOperand(2), // rsrc 6963 Op.getOperand(3), // vindex 6964 Op.getOperand(4), // voffset 6965 Op.getOperand(5), // soffset 6966 Op.getOperand(6), // offset 6967 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6968 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6969 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6970 }; 6971 6972 if (LoadVT.getScalarType() == MVT::f16) 6973 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6974 M, DAG, Ops); 6975 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6976 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6977 DAG); 6978 } 6979 case Intrinsic::amdgcn_raw_tbuffer_load: { 6980 MemSDNode *M = cast<MemSDNode>(Op); 6981 EVT LoadVT = Op.getValueType(); 6982 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6983 6984 SDValue Ops[] = { 6985 Op.getOperand(0), // Chain 6986 Op.getOperand(2), // rsrc 6987 DAG.getConstant(0, DL, MVT::i32), // vindex 6988 Offsets.first, // voffset 6989 Op.getOperand(4), // soffset 6990 Offsets.second, // offset 6991 Op.getOperand(5), // format 6992 Op.getOperand(6), // cachepolicy, swizzled buffer 6993 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6994 }; 6995 6996 if (LoadVT.getScalarType() == MVT::f16) 6997 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6998 M, DAG, Ops); 6999 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7000 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7001 DAG); 7002 } 7003 case Intrinsic::amdgcn_struct_tbuffer_load: { 7004 MemSDNode *M = cast<MemSDNode>(Op); 7005 EVT LoadVT = Op.getValueType(); 7006 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7007 7008 SDValue Ops[] = { 7009 Op.getOperand(0), // Chain 7010 Op.getOperand(2), // rsrc 7011 Op.getOperand(3), // vindex 7012 Offsets.first, // voffset 7013 Op.getOperand(5), // soffset 7014 Offsets.second, // offset 7015 Op.getOperand(6), // format 7016 Op.getOperand(7), // cachepolicy, swizzled buffer 7017 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7018 }; 7019 7020 if (LoadVT.getScalarType() == MVT::f16) 7021 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7022 M, DAG, Ops); 7023 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7024 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7025 DAG); 7026 } 7027 case Intrinsic::amdgcn_buffer_atomic_swap: 7028 case Intrinsic::amdgcn_buffer_atomic_add: 7029 case Intrinsic::amdgcn_buffer_atomic_sub: 7030 case Intrinsic::amdgcn_buffer_atomic_csub: 7031 case Intrinsic::amdgcn_buffer_atomic_smin: 7032 case Intrinsic::amdgcn_buffer_atomic_umin: 7033 case Intrinsic::amdgcn_buffer_atomic_smax: 7034 case Intrinsic::amdgcn_buffer_atomic_umax: 7035 case Intrinsic::amdgcn_buffer_atomic_and: 7036 case Intrinsic::amdgcn_buffer_atomic_or: 7037 case Intrinsic::amdgcn_buffer_atomic_xor: { 7038 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7039 unsigned IdxEn = 1; 7040 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7041 IdxEn = Idx->getZExtValue() != 0; 7042 SDValue Ops[] = { 7043 Op.getOperand(0), // Chain 7044 Op.getOperand(2), // vdata 7045 Op.getOperand(3), // rsrc 7046 Op.getOperand(4), // vindex 7047 SDValue(), // voffset -- will be set by setBufferOffsets 7048 SDValue(), // soffset -- will be set by setBufferOffsets 7049 SDValue(), // offset -- will be set by setBufferOffsets 7050 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7051 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7052 }; 7053 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7054 // We don't know the offset if vindex is non-zero, so clear it. 7055 if (IdxEn) 7056 Offset = 0; 7057 EVT VT = Op.getValueType(); 7058 7059 auto *M = cast<MemSDNode>(Op); 7060 M->getMemOperand()->setOffset(Offset); 7061 unsigned Opcode = 0; 7062 7063 switch (IntrID) { 7064 case Intrinsic::amdgcn_buffer_atomic_swap: 7065 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7066 break; 7067 case Intrinsic::amdgcn_buffer_atomic_add: 7068 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7069 break; 7070 case Intrinsic::amdgcn_buffer_atomic_sub: 7071 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7072 break; 7073 case Intrinsic::amdgcn_buffer_atomic_csub: 7074 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7075 break; 7076 case Intrinsic::amdgcn_buffer_atomic_smin: 7077 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7078 break; 7079 case Intrinsic::amdgcn_buffer_atomic_umin: 7080 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7081 break; 7082 case Intrinsic::amdgcn_buffer_atomic_smax: 7083 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7084 break; 7085 case Intrinsic::amdgcn_buffer_atomic_umax: 7086 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7087 break; 7088 case Intrinsic::amdgcn_buffer_atomic_and: 7089 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7090 break; 7091 case Intrinsic::amdgcn_buffer_atomic_or: 7092 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7093 break; 7094 case Intrinsic::amdgcn_buffer_atomic_xor: 7095 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7096 break; 7097 default: 7098 llvm_unreachable("unhandled atomic opcode"); 7099 } 7100 7101 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7102 M->getMemOperand()); 7103 } 7104 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7105 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7106 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7107 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7108 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7109 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7110 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7111 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7112 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7113 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7114 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7115 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7116 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7117 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7118 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7119 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7120 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7121 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7122 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7123 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7124 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7125 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7126 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7127 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7128 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7129 return lowerStructBufferAtomicIntrin(Op, DAG, 7130 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7131 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7132 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7133 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7134 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7135 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7136 return lowerStructBufferAtomicIntrin(Op, DAG, 7137 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7138 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7139 return lowerStructBufferAtomicIntrin(Op, DAG, 7140 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7141 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7142 return lowerStructBufferAtomicIntrin(Op, DAG, 7143 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7144 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7145 return lowerStructBufferAtomicIntrin(Op, DAG, 7146 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7147 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7148 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7149 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7150 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7151 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7152 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7153 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7154 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7155 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7156 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7157 7158 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7159 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7160 unsigned IdxEn = 1; 7161 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7162 IdxEn = Idx->getZExtValue() != 0; 7163 SDValue Ops[] = { 7164 Op.getOperand(0), // Chain 7165 Op.getOperand(2), // src 7166 Op.getOperand(3), // cmp 7167 Op.getOperand(4), // rsrc 7168 Op.getOperand(5), // vindex 7169 SDValue(), // voffset -- will be set by setBufferOffsets 7170 SDValue(), // soffset -- will be set by setBufferOffsets 7171 SDValue(), // offset -- will be set by setBufferOffsets 7172 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7173 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7174 }; 7175 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7176 // We don't know the offset if vindex is non-zero, so clear it. 7177 if (IdxEn) 7178 Offset = 0; 7179 EVT VT = Op.getValueType(); 7180 auto *M = cast<MemSDNode>(Op); 7181 M->getMemOperand()->setOffset(Offset); 7182 7183 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7184 Op->getVTList(), Ops, VT, M->getMemOperand()); 7185 } 7186 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7187 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7188 SDValue Ops[] = { 7189 Op.getOperand(0), // Chain 7190 Op.getOperand(2), // src 7191 Op.getOperand(3), // cmp 7192 Op.getOperand(4), // rsrc 7193 DAG.getConstant(0, DL, MVT::i32), // vindex 7194 Offsets.first, // voffset 7195 Op.getOperand(6), // soffset 7196 Offsets.second, // offset 7197 Op.getOperand(7), // cachepolicy 7198 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7199 }; 7200 EVT VT = Op.getValueType(); 7201 auto *M = cast<MemSDNode>(Op); 7202 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7203 7204 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7205 Op->getVTList(), Ops, VT, M->getMemOperand()); 7206 } 7207 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7208 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7209 SDValue Ops[] = { 7210 Op.getOperand(0), // Chain 7211 Op.getOperand(2), // src 7212 Op.getOperand(3), // cmp 7213 Op.getOperand(4), // rsrc 7214 Op.getOperand(5), // vindex 7215 Offsets.first, // voffset 7216 Op.getOperand(7), // soffset 7217 Offsets.second, // offset 7218 Op.getOperand(8), // cachepolicy 7219 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7220 }; 7221 EVT VT = Op.getValueType(); 7222 auto *M = cast<MemSDNode>(Op); 7223 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7224 Ops[4])); 7225 7226 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7227 Op->getVTList(), Ops, VT, M->getMemOperand()); 7228 } 7229 default: 7230 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7231 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7232 return lowerImage(Op, ImageDimIntr, DAG); 7233 7234 return SDValue(); 7235 } 7236 } 7237 7238 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7239 // dwordx4 if on SI. 7240 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7241 SDVTList VTList, 7242 ArrayRef<SDValue> Ops, EVT MemVT, 7243 MachineMemOperand *MMO, 7244 SelectionDAG &DAG) const { 7245 EVT VT = VTList.VTs[0]; 7246 EVT WidenedVT = VT; 7247 EVT WidenedMemVT = MemVT; 7248 if (!Subtarget->hasDwordx3LoadStores() && 7249 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7250 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7251 WidenedVT.getVectorElementType(), 4); 7252 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7253 WidenedMemVT.getVectorElementType(), 4); 7254 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7255 } 7256 7257 assert(VTList.NumVTs == 2); 7258 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7259 7260 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7261 WidenedMemVT, MMO); 7262 if (WidenedVT != VT) { 7263 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7264 DAG.getVectorIdxConstant(0, DL)); 7265 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7266 } 7267 return NewOp; 7268 } 7269 7270 SDValue SITargetLowering::handleD16VData(SDValue VData, 7271 SelectionDAG &DAG) const { 7272 EVT StoreVT = VData.getValueType(); 7273 7274 // No change for f16 and legal vector D16 types. 7275 if (!StoreVT.isVector()) 7276 return VData; 7277 7278 SDLoc DL(VData); 7279 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7280 7281 if (Subtarget->hasUnpackedD16VMem()) { 7282 // We need to unpack the packed data to store. 7283 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7284 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7285 7286 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7287 StoreVT.getVectorNumElements()); 7288 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7289 return DAG.UnrollVectorOp(ZExt.getNode()); 7290 } 7291 7292 assert(isTypeLegal(StoreVT)); 7293 return VData; 7294 } 7295 7296 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7297 SelectionDAG &DAG) const { 7298 SDLoc DL(Op); 7299 SDValue Chain = Op.getOperand(0); 7300 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7301 MachineFunction &MF = DAG.getMachineFunction(); 7302 7303 switch (IntrinsicID) { 7304 case Intrinsic::amdgcn_exp_compr: { 7305 SDValue Src0 = Op.getOperand(4); 7306 SDValue Src1 = Op.getOperand(5); 7307 // Hack around illegal type on SI by directly selecting it. 7308 if (isTypeLegal(Src0.getValueType())) 7309 return SDValue(); 7310 7311 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7312 SDValue Undef = DAG.getUNDEF(MVT::f32); 7313 const SDValue Ops[] = { 7314 Op.getOperand(2), // tgt 7315 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7316 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7317 Undef, // src2 7318 Undef, // src3 7319 Op.getOperand(7), // vm 7320 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7321 Op.getOperand(3), // en 7322 Op.getOperand(0) // Chain 7323 }; 7324 7325 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7326 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7327 } 7328 case Intrinsic::amdgcn_s_barrier: { 7329 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7330 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7331 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7332 if (WGSize <= ST.getWavefrontSize()) 7333 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7334 Op.getOperand(0)), 0); 7335 } 7336 return SDValue(); 7337 }; 7338 case Intrinsic::amdgcn_tbuffer_store: { 7339 SDValue VData = Op.getOperand(2); 7340 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7341 if (IsD16) 7342 VData = handleD16VData(VData, DAG); 7343 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7344 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7345 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7346 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7347 unsigned IdxEn = 1; 7348 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7349 IdxEn = Idx->getZExtValue() != 0; 7350 SDValue Ops[] = { 7351 Chain, 7352 VData, // vdata 7353 Op.getOperand(3), // rsrc 7354 Op.getOperand(4), // vindex 7355 Op.getOperand(5), // voffset 7356 Op.getOperand(6), // soffset 7357 Op.getOperand(7), // offset 7358 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7359 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7360 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7361 }; 7362 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7363 AMDGPUISD::TBUFFER_STORE_FORMAT; 7364 MemSDNode *M = cast<MemSDNode>(Op); 7365 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7366 M->getMemoryVT(), M->getMemOperand()); 7367 } 7368 7369 case Intrinsic::amdgcn_struct_tbuffer_store: { 7370 SDValue VData = Op.getOperand(2); 7371 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7372 if (IsD16) 7373 VData = handleD16VData(VData, DAG); 7374 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7375 SDValue Ops[] = { 7376 Chain, 7377 VData, // vdata 7378 Op.getOperand(3), // rsrc 7379 Op.getOperand(4), // vindex 7380 Offsets.first, // voffset 7381 Op.getOperand(6), // soffset 7382 Offsets.second, // offset 7383 Op.getOperand(7), // format 7384 Op.getOperand(8), // cachepolicy, swizzled buffer 7385 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7386 }; 7387 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7388 AMDGPUISD::TBUFFER_STORE_FORMAT; 7389 MemSDNode *M = cast<MemSDNode>(Op); 7390 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7391 M->getMemoryVT(), M->getMemOperand()); 7392 } 7393 7394 case Intrinsic::amdgcn_raw_tbuffer_store: { 7395 SDValue VData = Op.getOperand(2); 7396 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7397 if (IsD16) 7398 VData = handleD16VData(VData, DAG); 7399 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7400 SDValue Ops[] = { 7401 Chain, 7402 VData, // vdata 7403 Op.getOperand(3), // rsrc 7404 DAG.getConstant(0, DL, MVT::i32), // vindex 7405 Offsets.first, // voffset 7406 Op.getOperand(5), // soffset 7407 Offsets.second, // offset 7408 Op.getOperand(6), // format 7409 Op.getOperand(7), // cachepolicy, swizzled buffer 7410 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7411 }; 7412 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7413 AMDGPUISD::TBUFFER_STORE_FORMAT; 7414 MemSDNode *M = cast<MemSDNode>(Op); 7415 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7416 M->getMemoryVT(), M->getMemOperand()); 7417 } 7418 7419 case Intrinsic::amdgcn_buffer_store: 7420 case Intrinsic::amdgcn_buffer_store_format: { 7421 SDValue VData = Op.getOperand(2); 7422 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7423 if (IsD16) 7424 VData = handleD16VData(VData, DAG); 7425 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7426 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7427 unsigned IdxEn = 1; 7428 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7429 IdxEn = Idx->getZExtValue() != 0; 7430 SDValue Ops[] = { 7431 Chain, 7432 VData, 7433 Op.getOperand(3), // rsrc 7434 Op.getOperand(4), // vindex 7435 SDValue(), // voffset -- will be set by setBufferOffsets 7436 SDValue(), // soffset -- will be set by setBufferOffsets 7437 SDValue(), // offset -- will be set by setBufferOffsets 7438 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7439 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7440 }; 7441 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7442 // We don't know the offset if vindex is non-zero, so clear it. 7443 if (IdxEn) 7444 Offset = 0; 7445 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7446 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7447 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7448 MemSDNode *M = cast<MemSDNode>(Op); 7449 M->getMemOperand()->setOffset(Offset); 7450 7451 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7452 EVT VDataType = VData.getValueType().getScalarType(); 7453 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7454 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7455 7456 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7457 M->getMemoryVT(), M->getMemOperand()); 7458 } 7459 7460 case Intrinsic::amdgcn_raw_buffer_store: 7461 case Intrinsic::amdgcn_raw_buffer_store_format: { 7462 const bool IsFormat = 7463 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7464 7465 SDValue VData = Op.getOperand(2); 7466 EVT VDataVT = VData.getValueType(); 7467 EVT EltType = VDataVT.getScalarType(); 7468 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7469 if (IsD16) 7470 VData = handleD16VData(VData, DAG); 7471 7472 if (!isTypeLegal(VDataVT)) { 7473 VData = 7474 DAG.getNode(ISD::BITCAST, DL, 7475 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7476 } 7477 7478 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7479 SDValue Ops[] = { 7480 Chain, 7481 VData, 7482 Op.getOperand(3), // rsrc 7483 DAG.getConstant(0, DL, MVT::i32), // vindex 7484 Offsets.first, // voffset 7485 Op.getOperand(5), // soffset 7486 Offsets.second, // offset 7487 Op.getOperand(6), // cachepolicy, swizzled buffer 7488 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7489 }; 7490 unsigned Opc = 7491 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7492 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7493 MemSDNode *M = cast<MemSDNode>(Op); 7494 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7495 7496 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7497 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7498 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7499 7500 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7501 M->getMemoryVT(), M->getMemOperand()); 7502 } 7503 7504 case Intrinsic::amdgcn_struct_buffer_store: 7505 case Intrinsic::amdgcn_struct_buffer_store_format: { 7506 const bool IsFormat = 7507 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7508 7509 SDValue VData = Op.getOperand(2); 7510 EVT VDataVT = VData.getValueType(); 7511 EVT EltType = VDataVT.getScalarType(); 7512 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7513 7514 if (IsD16) 7515 VData = handleD16VData(VData, DAG); 7516 7517 if (!isTypeLegal(VDataVT)) { 7518 VData = 7519 DAG.getNode(ISD::BITCAST, DL, 7520 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7521 } 7522 7523 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7524 SDValue Ops[] = { 7525 Chain, 7526 VData, 7527 Op.getOperand(3), // rsrc 7528 Op.getOperand(4), // vindex 7529 Offsets.first, // voffset 7530 Op.getOperand(6), // soffset 7531 Offsets.second, // offset 7532 Op.getOperand(7), // cachepolicy, swizzled buffer 7533 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7534 }; 7535 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7536 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7537 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7538 MemSDNode *M = cast<MemSDNode>(Op); 7539 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7540 Ops[3])); 7541 7542 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7543 EVT VDataType = VData.getValueType().getScalarType(); 7544 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7545 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7546 7547 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7548 M->getMemoryVT(), M->getMemOperand()); 7549 } 7550 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7551 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7552 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7553 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7554 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7555 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7556 unsigned IdxEn = 1; 7557 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7558 IdxEn = Idx->getZExtValue() != 0; 7559 SDValue Ops[] = { 7560 Chain, 7561 Op.getOperand(2), // vdata 7562 Op.getOperand(3), // rsrc 7563 Op.getOperand(4), // vindex 7564 SDValue(), // voffset -- will be set by setBufferOffsets 7565 SDValue(), // soffset -- will be set by setBufferOffsets 7566 SDValue(), // offset -- will be set by setBufferOffsets 7567 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7568 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7569 }; 7570 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7571 // We don't know the offset if vindex is non-zero, so clear it. 7572 if (IdxEn) 7573 Offset = 0; 7574 EVT VT = Op.getOperand(2).getValueType(); 7575 7576 auto *M = cast<MemSDNode>(Op); 7577 M->getMemOperand()->setOffset(Offset); 7578 7579 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_FADD, DL, 7580 Op->getVTList(), Ops, VT, 7581 M->getMemOperand()); 7582 } 7583 case Intrinsic::amdgcn_end_cf: 7584 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7585 Op->getOperand(2), Chain), 0); 7586 7587 default: { 7588 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7589 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7590 return lowerImage(Op, ImageDimIntr, DAG); 7591 7592 return Op; 7593 } 7594 } 7595 } 7596 7597 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7598 // offset (the offset that is included in bounds checking and swizzling, to be 7599 // split between the instruction's voffset and immoffset fields) and soffset 7600 // (the offset that is excluded from bounds checking and swizzling, to go in 7601 // the instruction's soffset field). This function takes the first kind of 7602 // offset and figures out how to split it between voffset and immoffset. 7603 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7604 SDValue Offset, SelectionDAG &DAG) const { 7605 SDLoc DL(Offset); 7606 const unsigned MaxImm = 4095; 7607 SDValue N0 = Offset; 7608 ConstantSDNode *C1 = nullptr; 7609 7610 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7611 N0 = SDValue(); 7612 else if (DAG.isBaseWithConstantOffset(N0)) { 7613 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7614 N0 = N0.getOperand(0); 7615 } 7616 7617 if (C1) { 7618 unsigned ImmOffset = C1->getZExtValue(); 7619 // If the immediate value is too big for the immoffset field, put the value 7620 // and -4096 into the immoffset field so that the value that is copied/added 7621 // for the voffset field is a multiple of 4096, and it stands more chance 7622 // of being CSEd with the copy/add for another similar load/store. 7623 // However, do not do that rounding down to a multiple of 4096 if that is a 7624 // negative number, as it appears to be illegal to have a negative offset 7625 // in the vgpr, even if adding the immediate offset makes it positive. 7626 unsigned Overflow = ImmOffset & ~MaxImm; 7627 ImmOffset -= Overflow; 7628 if ((int32_t)Overflow < 0) { 7629 Overflow += ImmOffset; 7630 ImmOffset = 0; 7631 } 7632 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7633 if (Overflow) { 7634 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7635 if (!N0) 7636 N0 = OverflowVal; 7637 else { 7638 SDValue Ops[] = { N0, OverflowVal }; 7639 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7640 } 7641 } 7642 } 7643 if (!N0) 7644 N0 = DAG.getConstant(0, DL, MVT::i32); 7645 if (!C1) 7646 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7647 return {N0, SDValue(C1, 0)}; 7648 } 7649 7650 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7651 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7652 // pointed to by Offsets. 7653 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7654 SelectionDAG &DAG, SDValue *Offsets, 7655 Align Alignment) const { 7656 SDLoc DL(CombinedOffset); 7657 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7658 uint32_t Imm = C->getZExtValue(); 7659 uint32_t SOffset, ImmOffset; 7660 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7661 Alignment)) { 7662 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7663 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7664 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7665 return SOffset + ImmOffset; 7666 } 7667 } 7668 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7669 SDValue N0 = CombinedOffset.getOperand(0); 7670 SDValue N1 = CombinedOffset.getOperand(1); 7671 uint32_t SOffset, ImmOffset; 7672 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7673 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7674 Subtarget, Alignment)) { 7675 Offsets[0] = N0; 7676 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7677 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7678 return 0; 7679 } 7680 } 7681 Offsets[0] = CombinedOffset; 7682 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7683 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7684 return 0; 7685 } 7686 7687 // Handle 8 bit and 16 bit buffer loads 7688 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7689 EVT LoadVT, SDLoc DL, 7690 ArrayRef<SDValue> Ops, 7691 MemSDNode *M) const { 7692 EVT IntVT = LoadVT.changeTypeToInteger(); 7693 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7694 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7695 7696 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7697 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7698 Ops, IntVT, 7699 M->getMemOperand()); 7700 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7701 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7702 7703 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7704 } 7705 7706 // Handle 8 bit and 16 bit buffer stores 7707 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7708 EVT VDataType, SDLoc DL, 7709 SDValue Ops[], 7710 MemSDNode *M) const { 7711 if (VDataType == MVT::f16) 7712 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7713 7714 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7715 Ops[1] = BufferStoreExt; 7716 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7717 AMDGPUISD::BUFFER_STORE_SHORT; 7718 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7719 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7720 M->getMemOperand()); 7721 } 7722 7723 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7724 ISD::LoadExtType ExtType, SDValue Op, 7725 const SDLoc &SL, EVT VT) { 7726 if (VT.bitsLT(Op.getValueType())) 7727 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7728 7729 switch (ExtType) { 7730 case ISD::SEXTLOAD: 7731 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7732 case ISD::ZEXTLOAD: 7733 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7734 case ISD::EXTLOAD: 7735 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7736 case ISD::NON_EXTLOAD: 7737 return Op; 7738 } 7739 7740 llvm_unreachable("invalid ext type"); 7741 } 7742 7743 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7744 SelectionDAG &DAG = DCI.DAG; 7745 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7746 return SDValue(); 7747 7748 // FIXME: Constant loads should all be marked invariant. 7749 unsigned AS = Ld->getAddressSpace(); 7750 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7751 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7752 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7753 return SDValue(); 7754 7755 // Don't do this early, since it may interfere with adjacent load merging for 7756 // illegal types. We can avoid losing alignment information for exotic types 7757 // pre-legalize. 7758 EVT MemVT = Ld->getMemoryVT(); 7759 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7760 MemVT.getSizeInBits() >= 32) 7761 return SDValue(); 7762 7763 SDLoc SL(Ld); 7764 7765 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7766 "unexpected vector extload"); 7767 7768 // TODO: Drop only high part of range. 7769 SDValue Ptr = Ld->getBasePtr(); 7770 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7771 MVT::i32, SL, Ld->getChain(), Ptr, 7772 Ld->getOffset(), 7773 Ld->getPointerInfo(), MVT::i32, 7774 Ld->getAlignment(), 7775 Ld->getMemOperand()->getFlags(), 7776 Ld->getAAInfo(), 7777 nullptr); // Drop ranges 7778 7779 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7780 if (MemVT.isFloatingPoint()) { 7781 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7782 "unexpected fp extload"); 7783 TruncVT = MemVT.changeTypeToInteger(); 7784 } 7785 7786 SDValue Cvt = NewLoad; 7787 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7788 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7789 DAG.getValueType(TruncVT)); 7790 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7791 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7792 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7793 } else { 7794 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7795 } 7796 7797 EVT VT = Ld->getValueType(0); 7798 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7799 7800 DCI.AddToWorklist(Cvt.getNode()); 7801 7802 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7803 // the appropriate extension from the 32-bit load. 7804 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7805 DCI.AddToWorklist(Cvt.getNode()); 7806 7807 // Handle conversion back to floating point if necessary. 7808 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7809 7810 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7811 } 7812 7813 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7814 SDLoc DL(Op); 7815 LoadSDNode *Load = cast<LoadSDNode>(Op); 7816 ISD::LoadExtType ExtType = Load->getExtensionType(); 7817 EVT MemVT = Load->getMemoryVT(); 7818 7819 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7820 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7821 return SDValue(); 7822 7823 // FIXME: Copied from PPC 7824 // First, load into 32 bits, then truncate to 1 bit. 7825 7826 SDValue Chain = Load->getChain(); 7827 SDValue BasePtr = Load->getBasePtr(); 7828 MachineMemOperand *MMO = Load->getMemOperand(); 7829 7830 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7831 7832 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7833 BasePtr, RealMemVT, MMO); 7834 7835 if (!MemVT.isVector()) { 7836 SDValue Ops[] = { 7837 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7838 NewLD.getValue(1) 7839 }; 7840 7841 return DAG.getMergeValues(Ops, DL); 7842 } 7843 7844 SmallVector<SDValue, 3> Elts; 7845 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7846 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7847 DAG.getConstant(I, DL, MVT::i32)); 7848 7849 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7850 } 7851 7852 SDValue Ops[] = { 7853 DAG.getBuildVector(MemVT, DL, Elts), 7854 NewLD.getValue(1) 7855 }; 7856 7857 return DAG.getMergeValues(Ops, DL); 7858 } 7859 7860 if (!MemVT.isVector()) 7861 return SDValue(); 7862 7863 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7864 "Custom lowering for non-i32 vectors hasn't been implemented."); 7865 7866 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7867 MemVT, *Load->getMemOperand())) { 7868 SDValue Ops[2]; 7869 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7870 return DAG.getMergeValues(Ops, DL); 7871 } 7872 7873 unsigned Alignment = Load->getAlignment(); 7874 unsigned AS = Load->getAddressSpace(); 7875 if (Subtarget->hasLDSMisalignedBug() && 7876 AS == AMDGPUAS::FLAT_ADDRESS && 7877 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7878 return SplitVectorLoad(Op, DAG); 7879 } 7880 7881 MachineFunction &MF = DAG.getMachineFunction(); 7882 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7883 // If there is a possibilty that flat instruction access scratch memory 7884 // then we need to use the same legalization rules we use for private. 7885 if (AS == AMDGPUAS::FLAT_ADDRESS && 7886 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7887 AS = MFI->hasFlatScratchInit() ? 7888 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7889 7890 unsigned NumElements = MemVT.getVectorNumElements(); 7891 7892 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7893 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7894 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7895 if (MemVT.isPow2VectorType()) 7896 return SDValue(); 7897 if (NumElements == 3) 7898 return WidenVectorLoad(Op, DAG); 7899 return SplitVectorLoad(Op, DAG); 7900 } 7901 // Non-uniform loads will be selected to MUBUF instructions, so they 7902 // have the same legalization requirements as global and private 7903 // loads. 7904 // 7905 } 7906 7907 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7908 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7909 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7910 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7911 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7912 Alignment >= 4 && NumElements < 32) { 7913 if (MemVT.isPow2VectorType()) 7914 return SDValue(); 7915 if (NumElements == 3) 7916 return WidenVectorLoad(Op, DAG); 7917 return SplitVectorLoad(Op, DAG); 7918 } 7919 // Non-uniform loads will be selected to MUBUF instructions, so they 7920 // have the same legalization requirements as global and private 7921 // loads. 7922 // 7923 } 7924 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7925 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7926 AS == AMDGPUAS::GLOBAL_ADDRESS || 7927 AS == AMDGPUAS::FLAT_ADDRESS) { 7928 if (NumElements > 4) 7929 return SplitVectorLoad(Op, DAG); 7930 // v3 loads not supported on SI. 7931 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7932 return WidenVectorLoad(Op, DAG); 7933 // v3 and v4 loads are supported for private and global memory. 7934 return SDValue(); 7935 } 7936 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7937 // Depending on the setting of the private_element_size field in the 7938 // resource descriptor, we can only make private accesses up to a certain 7939 // size. 7940 switch (Subtarget->getMaxPrivateElementSize()) { 7941 case 4: { 7942 SDValue Ops[2]; 7943 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7944 return DAG.getMergeValues(Ops, DL); 7945 } 7946 case 8: 7947 if (NumElements > 2) 7948 return SplitVectorLoad(Op, DAG); 7949 return SDValue(); 7950 case 16: 7951 // Same as global/flat 7952 if (NumElements > 4) 7953 return SplitVectorLoad(Op, DAG); 7954 // v3 loads not supported on SI. 7955 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7956 return WidenVectorLoad(Op, DAG); 7957 return SDValue(); 7958 default: 7959 llvm_unreachable("unsupported private_element_size"); 7960 } 7961 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7962 // Use ds_read_b128 or ds_read_b96 when possible. 7963 if (Subtarget->hasDS96AndDS128() && 7964 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 7965 MemVT.getStoreSize() == 12) && 7966 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 7967 Load->getAlign())) 7968 return SDValue(); 7969 7970 if (NumElements > 2) 7971 return SplitVectorLoad(Op, DAG); 7972 7973 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7974 // address is negative, then the instruction is incorrectly treated as 7975 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7976 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7977 // load later in the SILoadStoreOptimizer. 7978 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7979 NumElements == 2 && MemVT.getStoreSize() == 8 && 7980 Load->getAlignment() < 8) { 7981 return SplitVectorLoad(Op, DAG); 7982 } 7983 } 7984 return SDValue(); 7985 } 7986 7987 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7988 EVT VT = Op.getValueType(); 7989 assert(VT.getSizeInBits() == 64); 7990 7991 SDLoc DL(Op); 7992 SDValue Cond = Op.getOperand(0); 7993 7994 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7995 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7996 7997 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7998 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7999 8000 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8001 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8002 8003 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8004 8005 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8006 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8007 8008 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8009 8010 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8011 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8012 } 8013 8014 // Catch division cases where we can use shortcuts with rcp and rsq 8015 // instructions. 8016 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8017 SelectionDAG &DAG) const { 8018 SDLoc SL(Op); 8019 SDValue LHS = Op.getOperand(0); 8020 SDValue RHS = Op.getOperand(1); 8021 EVT VT = Op.getValueType(); 8022 const SDNodeFlags Flags = Op->getFlags(); 8023 8024 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8025 Flags.hasApproximateFuncs(); 8026 8027 // Without !fpmath accuracy information, we can't do more because we don't 8028 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8029 if (!AllowInaccurateRcp) 8030 return SDValue(); 8031 8032 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8033 if (CLHS->isExactlyValue(1.0)) { 8034 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8035 // the CI documentation has a worst case error of 1 ulp. 8036 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8037 // use it as long as we aren't trying to use denormals. 8038 // 8039 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8040 8041 // 1.0 / sqrt(x) -> rsq(x) 8042 8043 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8044 // error seems really high at 2^29 ULP. 8045 if (RHS.getOpcode() == ISD::FSQRT) 8046 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8047 8048 // 1.0 / x -> rcp(x) 8049 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8050 } 8051 8052 // Same as for 1.0, but expand the sign out of the constant. 8053 if (CLHS->isExactlyValue(-1.0)) { 8054 // -1.0 / x -> rcp (fneg x) 8055 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8056 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8057 } 8058 } 8059 8060 // Turn into multiply by the reciprocal. 8061 // x / y -> x * (1.0 / y) 8062 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8063 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8064 } 8065 8066 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8067 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8068 SDNodeFlags Flags) { 8069 if (GlueChain->getNumValues() <= 1) { 8070 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8071 } 8072 8073 assert(GlueChain->getNumValues() == 3); 8074 8075 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8076 switch (Opcode) { 8077 default: llvm_unreachable("no chain equivalent for opcode"); 8078 case ISD::FMUL: 8079 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8080 break; 8081 } 8082 8083 return DAG.getNode(Opcode, SL, VTList, 8084 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8085 Flags); 8086 } 8087 8088 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8089 EVT VT, SDValue A, SDValue B, SDValue C, 8090 SDValue GlueChain, SDNodeFlags Flags) { 8091 if (GlueChain->getNumValues() <= 1) { 8092 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8093 } 8094 8095 assert(GlueChain->getNumValues() == 3); 8096 8097 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8098 switch (Opcode) { 8099 default: llvm_unreachable("no chain equivalent for opcode"); 8100 case ISD::FMA: 8101 Opcode = AMDGPUISD::FMA_W_CHAIN; 8102 break; 8103 } 8104 8105 return DAG.getNode(Opcode, SL, VTList, 8106 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8107 Flags); 8108 } 8109 8110 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8111 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8112 return FastLowered; 8113 8114 SDLoc SL(Op); 8115 SDValue Src0 = Op.getOperand(0); 8116 SDValue Src1 = Op.getOperand(1); 8117 8118 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8119 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8120 8121 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8122 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8123 8124 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8125 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8126 8127 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8128 } 8129 8130 // Faster 2.5 ULP division that does not support denormals. 8131 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8132 SDLoc SL(Op); 8133 SDValue LHS = Op.getOperand(1); 8134 SDValue RHS = Op.getOperand(2); 8135 8136 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8137 8138 const APFloat K0Val(BitsToFloat(0x6f800000)); 8139 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8140 8141 const APFloat K1Val(BitsToFloat(0x2f800000)); 8142 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8143 8144 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8145 8146 EVT SetCCVT = 8147 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8148 8149 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8150 8151 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8152 8153 // TODO: Should this propagate fast-math-flags? 8154 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8155 8156 // rcp does not support denormals. 8157 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8158 8159 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8160 8161 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8162 } 8163 8164 // Returns immediate value for setting the F32 denorm mode when using the 8165 // S_DENORM_MODE instruction. 8166 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8167 const SDLoc &SL, const GCNSubtarget *ST) { 8168 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8169 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8170 ? FP_DENORM_FLUSH_NONE 8171 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8172 8173 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8174 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8175 } 8176 8177 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8178 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8179 return FastLowered; 8180 8181 // The selection matcher assumes anything with a chain selecting to a 8182 // mayRaiseFPException machine instruction. Since we're introducing a chain 8183 // here, we need to explicitly report nofpexcept for the regular fdiv 8184 // lowering. 8185 SDNodeFlags Flags = Op->getFlags(); 8186 Flags.setNoFPExcept(true); 8187 8188 SDLoc SL(Op); 8189 SDValue LHS = Op.getOperand(0); 8190 SDValue RHS = Op.getOperand(1); 8191 8192 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8193 8194 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8195 8196 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8197 {RHS, RHS, LHS}, Flags); 8198 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8199 {LHS, RHS, LHS}, Flags); 8200 8201 // Denominator is scaled to not be denormal, so using rcp is ok. 8202 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8203 DenominatorScaled, Flags); 8204 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8205 DenominatorScaled, Flags); 8206 8207 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8208 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8209 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8210 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8211 8212 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8213 8214 if (!HasFP32Denormals) { 8215 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8216 // lowering. The chain dependence is insufficient, and we need glue. We do 8217 // not need the glue variants in a strictfp function. 8218 8219 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8220 8221 SDNode *EnableDenorm; 8222 if (Subtarget->hasDenormModeInst()) { 8223 const SDValue EnableDenormValue = 8224 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8225 8226 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8227 DAG.getEntryNode(), EnableDenormValue).getNode(); 8228 } else { 8229 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8230 SL, MVT::i32); 8231 EnableDenorm = 8232 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8233 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8234 } 8235 8236 SDValue Ops[3] = { 8237 NegDivScale0, 8238 SDValue(EnableDenorm, 0), 8239 SDValue(EnableDenorm, 1) 8240 }; 8241 8242 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8243 } 8244 8245 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8246 ApproxRcp, One, NegDivScale0, Flags); 8247 8248 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8249 ApproxRcp, Fma0, Flags); 8250 8251 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8252 Fma1, Fma1, Flags); 8253 8254 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8255 NumeratorScaled, Mul, Flags); 8256 8257 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8258 Fma2, Fma1, Mul, Fma2, Flags); 8259 8260 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8261 NumeratorScaled, Fma3, Flags); 8262 8263 if (!HasFP32Denormals) { 8264 SDNode *DisableDenorm; 8265 if (Subtarget->hasDenormModeInst()) { 8266 const SDValue DisableDenormValue = 8267 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8268 8269 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8270 Fma4.getValue(1), DisableDenormValue, 8271 Fma4.getValue(2)).getNode(); 8272 } else { 8273 const SDValue DisableDenormValue = 8274 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8275 8276 DisableDenorm = DAG.getMachineNode( 8277 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8278 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8279 } 8280 8281 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8282 SDValue(DisableDenorm, 0), DAG.getRoot()); 8283 DAG.setRoot(OutputChain); 8284 } 8285 8286 SDValue Scale = NumeratorScaled.getValue(1); 8287 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8288 {Fma4, Fma1, Fma3, Scale}, Flags); 8289 8290 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8291 } 8292 8293 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8294 if (DAG.getTarget().Options.UnsafeFPMath) 8295 return lowerFastUnsafeFDIV(Op, DAG); 8296 8297 SDLoc SL(Op); 8298 SDValue X = Op.getOperand(0); 8299 SDValue Y = Op.getOperand(1); 8300 8301 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8302 8303 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8304 8305 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8306 8307 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8308 8309 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8310 8311 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8312 8313 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8314 8315 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8316 8317 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8318 8319 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8320 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8321 8322 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8323 NegDivScale0, Mul, DivScale1); 8324 8325 SDValue Scale; 8326 8327 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8328 // Workaround a hardware bug on SI where the condition output from div_scale 8329 // is not usable. 8330 8331 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8332 8333 // Figure out if the scale to use for div_fmas. 8334 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8335 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8336 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8337 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8338 8339 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8340 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8341 8342 SDValue Scale0Hi 8343 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8344 SDValue Scale1Hi 8345 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8346 8347 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8348 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8349 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8350 } else { 8351 Scale = DivScale1.getValue(1); 8352 } 8353 8354 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8355 Fma4, Fma3, Mul, Scale); 8356 8357 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8358 } 8359 8360 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8361 EVT VT = Op.getValueType(); 8362 8363 if (VT == MVT::f32) 8364 return LowerFDIV32(Op, DAG); 8365 8366 if (VT == MVT::f64) 8367 return LowerFDIV64(Op, DAG); 8368 8369 if (VT == MVT::f16) 8370 return LowerFDIV16(Op, DAG); 8371 8372 llvm_unreachable("Unexpected type for fdiv"); 8373 } 8374 8375 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8376 SDLoc DL(Op); 8377 StoreSDNode *Store = cast<StoreSDNode>(Op); 8378 EVT VT = Store->getMemoryVT(); 8379 8380 if (VT == MVT::i1) { 8381 return DAG.getTruncStore(Store->getChain(), DL, 8382 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8383 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8384 } 8385 8386 assert(VT.isVector() && 8387 Store->getValue().getValueType().getScalarType() == MVT::i32); 8388 8389 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8390 VT, *Store->getMemOperand())) { 8391 return expandUnalignedStore(Store, DAG); 8392 } 8393 8394 unsigned AS = Store->getAddressSpace(); 8395 if (Subtarget->hasLDSMisalignedBug() && 8396 AS == AMDGPUAS::FLAT_ADDRESS && 8397 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8398 return SplitVectorStore(Op, DAG); 8399 } 8400 8401 MachineFunction &MF = DAG.getMachineFunction(); 8402 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8403 // If there is a possibilty that flat instruction access scratch memory 8404 // then we need to use the same legalization rules we use for private. 8405 if (AS == AMDGPUAS::FLAT_ADDRESS && 8406 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8407 AS = MFI->hasFlatScratchInit() ? 8408 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8409 8410 unsigned NumElements = VT.getVectorNumElements(); 8411 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8412 AS == AMDGPUAS::FLAT_ADDRESS) { 8413 if (NumElements > 4) 8414 return SplitVectorStore(Op, DAG); 8415 // v3 stores not supported on SI. 8416 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8417 return SplitVectorStore(Op, DAG); 8418 return SDValue(); 8419 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8420 switch (Subtarget->getMaxPrivateElementSize()) { 8421 case 4: 8422 return scalarizeVectorStore(Store, DAG); 8423 case 8: 8424 if (NumElements > 2) 8425 return SplitVectorStore(Op, DAG); 8426 return SDValue(); 8427 case 16: 8428 if (NumElements > 4 || NumElements == 3) 8429 return SplitVectorStore(Op, DAG); 8430 return SDValue(); 8431 default: 8432 llvm_unreachable("unsupported private_element_size"); 8433 } 8434 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8435 // Use ds_write_b128 or ds_write_b96 when possible. 8436 if (Subtarget->hasDS96AndDS128() && 8437 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8438 (VT.getStoreSize() == 12)) && 8439 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8440 Store->getAlign())) 8441 return SDValue(); 8442 8443 if (NumElements > 2) 8444 return SplitVectorStore(Op, DAG); 8445 8446 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8447 // address is negative, then the instruction is incorrectly treated as 8448 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8449 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8450 // store later in the SILoadStoreOptimizer. 8451 if (!Subtarget->hasUsableDSOffset() && 8452 NumElements == 2 && VT.getStoreSize() == 8 && 8453 Store->getAlignment() < 8) { 8454 return SplitVectorStore(Op, DAG); 8455 } 8456 8457 return SDValue(); 8458 } else { 8459 llvm_unreachable("unhandled address space"); 8460 } 8461 } 8462 8463 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8464 SDLoc DL(Op); 8465 EVT VT = Op.getValueType(); 8466 SDValue Arg = Op.getOperand(0); 8467 SDValue TrigVal; 8468 8469 // Propagate fast-math flags so that the multiply we introduce can be folded 8470 // if Arg is already the result of a multiply by constant. 8471 auto Flags = Op->getFlags(); 8472 8473 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8474 8475 if (Subtarget->hasTrigReducedRange()) { 8476 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8477 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8478 } else { 8479 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8480 } 8481 8482 switch (Op.getOpcode()) { 8483 case ISD::FCOS: 8484 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8485 case ISD::FSIN: 8486 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8487 default: 8488 llvm_unreachable("Wrong trig opcode"); 8489 } 8490 } 8491 8492 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8493 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8494 assert(AtomicNode->isCompareAndSwap()); 8495 unsigned AS = AtomicNode->getAddressSpace(); 8496 8497 // No custom lowering required for local address space 8498 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8499 return Op; 8500 8501 // Non-local address space requires custom lowering for atomic compare 8502 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8503 SDLoc DL(Op); 8504 SDValue ChainIn = Op.getOperand(0); 8505 SDValue Addr = Op.getOperand(1); 8506 SDValue Old = Op.getOperand(2); 8507 SDValue New = Op.getOperand(3); 8508 EVT VT = Op.getValueType(); 8509 MVT SimpleVT = VT.getSimpleVT(); 8510 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8511 8512 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8513 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8514 8515 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8516 Ops, VT, AtomicNode->getMemOperand()); 8517 } 8518 8519 //===----------------------------------------------------------------------===// 8520 // Custom DAG optimizations 8521 //===----------------------------------------------------------------------===// 8522 8523 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8524 DAGCombinerInfo &DCI) const { 8525 EVT VT = N->getValueType(0); 8526 EVT ScalarVT = VT.getScalarType(); 8527 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8528 return SDValue(); 8529 8530 SelectionDAG &DAG = DCI.DAG; 8531 SDLoc DL(N); 8532 8533 SDValue Src = N->getOperand(0); 8534 EVT SrcVT = Src.getValueType(); 8535 8536 // TODO: We could try to match extracting the higher bytes, which would be 8537 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8538 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8539 // about in practice. 8540 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8541 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8542 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8543 DCI.AddToWorklist(Cvt.getNode()); 8544 8545 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8546 if (ScalarVT != MVT::f32) { 8547 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8548 DAG.getTargetConstant(0, DL, MVT::i32)); 8549 } 8550 return Cvt; 8551 } 8552 } 8553 8554 return SDValue(); 8555 } 8556 8557 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8558 8559 // This is a variant of 8560 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8561 // 8562 // The normal DAG combiner will do this, but only if the add has one use since 8563 // that would increase the number of instructions. 8564 // 8565 // This prevents us from seeing a constant offset that can be folded into a 8566 // memory instruction's addressing mode. If we know the resulting add offset of 8567 // a pointer can be folded into an addressing offset, we can replace the pointer 8568 // operand with the add of new constant offset. This eliminates one of the uses, 8569 // and may allow the remaining use to also be simplified. 8570 // 8571 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8572 unsigned AddrSpace, 8573 EVT MemVT, 8574 DAGCombinerInfo &DCI) const { 8575 SDValue N0 = N->getOperand(0); 8576 SDValue N1 = N->getOperand(1); 8577 8578 // We only do this to handle cases where it's profitable when there are 8579 // multiple uses of the add, so defer to the standard combine. 8580 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8581 N0->hasOneUse()) 8582 return SDValue(); 8583 8584 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8585 if (!CN1) 8586 return SDValue(); 8587 8588 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8589 if (!CAdd) 8590 return SDValue(); 8591 8592 // If the resulting offset is too large, we can't fold it into the addressing 8593 // mode offset. 8594 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8595 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8596 8597 AddrMode AM; 8598 AM.HasBaseReg = true; 8599 AM.BaseOffs = Offset.getSExtValue(); 8600 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8601 return SDValue(); 8602 8603 SelectionDAG &DAG = DCI.DAG; 8604 SDLoc SL(N); 8605 EVT VT = N->getValueType(0); 8606 8607 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8608 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8609 8610 SDNodeFlags Flags; 8611 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8612 (N0.getOpcode() == ISD::OR || 8613 N0->getFlags().hasNoUnsignedWrap())); 8614 8615 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8616 } 8617 8618 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8619 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8620 /// specific intrinsic, but they all place the pointer operand first. 8621 static unsigned getBasePtrIndex(const MemSDNode *N) { 8622 switch (N->getOpcode()) { 8623 case ISD::STORE: 8624 case ISD::INTRINSIC_W_CHAIN: 8625 case ISD::INTRINSIC_VOID: 8626 return 2; 8627 default: 8628 return 1; 8629 } 8630 } 8631 8632 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8633 DAGCombinerInfo &DCI) const { 8634 SelectionDAG &DAG = DCI.DAG; 8635 SDLoc SL(N); 8636 8637 unsigned PtrIdx = getBasePtrIndex(N); 8638 SDValue Ptr = N->getOperand(PtrIdx); 8639 8640 // TODO: We could also do this for multiplies. 8641 if (Ptr.getOpcode() == ISD::SHL) { 8642 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8643 N->getMemoryVT(), DCI); 8644 if (NewPtr) { 8645 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8646 8647 NewOps[PtrIdx] = NewPtr; 8648 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8649 } 8650 } 8651 8652 return SDValue(); 8653 } 8654 8655 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8656 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8657 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8658 (Opc == ISD::XOR && Val == 0); 8659 } 8660 8661 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8662 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8663 // integer combine opportunities since most 64-bit operations are decomposed 8664 // this way. TODO: We won't want this for SALU especially if it is an inline 8665 // immediate. 8666 SDValue SITargetLowering::splitBinaryBitConstantOp( 8667 DAGCombinerInfo &DCI, 8668 const SDLoc &SL, 8669 unsigned Opc, SDValue LHS, 8670 const ConstantSDNode *CRHS) const { 8671 uint64_t Val = CRHS->getZExtValue(); 8672 uint32_t ValLo = Lo_32(Val); 8673 uint32_t ValHi = Hi_32(Val); 8674 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8675 8676 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8677 bitOpWithConstantIsReducible(Opc, ValHi)) || 8678 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8679 // If we need to materialize a 64-bit immediate, it will be split up later 8680 // anyway. Avoid creating the harder to understand 64-bit immediate 8681 // materialization. 8682 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8683 } 8684 8685 return SDValue(); 8686 } 8687 8688 // Returns true if argument is a boolean value which is not serialized into 8689 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8690 static bool isBoolSGPR(SDValue V) { 8691 if (V.getValueType() != MVT::i1) 8692 return false; 8693 switch (V.getOpcode()) { 8694 default: break; 8695 case ISD::SETCC: 8696 case ISD::AND: 8697 case ISD::OR: 8698 case ISD::XOR: 8699 case AMDGPUISD::FP_CLASS: 8700 return true; 8701 } 8702 return false; 8703 } 8704 8705 // If a constant has all zeroes or all ones within each byte return it. 8706 // Otherwise return 0. 8707 static uint32_t getConstantPermuteMask(uint32_t C) { 8708 // 0xff for any zero byte in the mask 8709 uint32_t ZeroByteMask = 0; 8710 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8711 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8712 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8713 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8714 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8715 if ((NonZeroByteMask & C) != NonZeroByteMask) 8716 return 0; // Partial bytes selected. 8717 return C; 8718 } 8719 8720 // Check if a node selects whole bytes from its operand 0 starting at a byte 8721 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8722 // or -1 if not succeeded. 8723 // Note byte select encoding: 8724 // value 0-3 selects corresponding source byte; 8725 // value 0xc selects zero; 8726 // value 0xff selects 0xff. 8727 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8728 assert(V.getValueSizeInBits() == 32); 8729 8730 if (V.getNumOperands() != 2) 8731 return ~0; 8732 8733 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8734 if (!N1) 8735 return ~0; 8736 8737 uint32_t C = N1->getZExtValue(); 8738 8739 switch (V.getOpcode()) { 8740 default: 8741 break; 8742 case ISD::AND: 8743 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8744 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8745 } 8746 break; 8747 8748 case ISD::OR: 8749 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8750 return (0x03020100 & ~ConstMask) | ConstMask; 8751 } 8752 break; 8753 8754 case ISD::SHL: 8755 if (C % 8) 8756 return ~0; 8757 8758 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8759 8760 case ISD::SRL: 8761 if (C % 8) 8762 return ~0; 8763 8764 return uint32_t(0x0c0c0c0c03020100ull >> C); 8765 } 8766 8767 return ~0; 8768 } 8769 8770 SDValue SITargetLowering::performAndCombine(SDNode *N, 8771 DAGCombinerInfo &DCI) const { 8772 if (DCI.isBeforeLegalize()) 8773 return SDValue(); 8774 8775 SelectionDAG &DAG = DCI.DAG; 8776 EVT VT = N->getValueType(0); 8777 SDValue LHS = N->getOperand(0); 8778 SDValue RHS = N->getOperand(1); 8779 8780 8781 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8782 if (VT == MVT::i64 && CRHS) { 8783 if (SDValue Split 8784 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8785 return Split; 8786 } 8787 8788 if (CRHS && VT == MVT::i32) { 8789 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8790 // nb = number of trailing zeroes in mask 8791 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8792 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8793 uint64_t Mask = CRHS->getZExtValue(); 8794 unsigned Bits = countPopulation(Mask); 8795 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8796 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8797 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8798 unsigned Shift = CShift->getZExtValue(); 8799 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8800 unsigned Offset = NB + Shift; 8801 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8802 SDLoc SL(N); 8803 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8804 LHS->getOperand(0), 8805 DAG.getConstant(Offset, SL, MVT::i32), 8806 DAG.getConstant(Bits, SL, MVT::i32)); 8807 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8808 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8809 DAG.getValueType(NarrowVT)); 8810 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8811 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8812 return Shl; 8813 } 8814 } 8815 } 8816 8817 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8818 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8819 isa<ConstantSDNode>(LHS.getOperand(2))) { 8820 uint32_t Sel = getConstantPermuteMask(Mask); 8821 if (!Sel) 8822 return SDValue(); 8823 8824 // Select 0xc for all zero bytes 8825 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8826 SDLoc DL(N); 8827 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8828 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8829 } 8830 } 8831 8832 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8833 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8834 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8835 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8836 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8837 8838 SDValue X = LHS.getOperand(0); 8839 SDValue Y = RHS.getOperand(0); 8840 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8841 return SDValue(); 8842 8843 if (LCC == ISD::SETO) { 8844 if (X != LHS.getOperand(1)) 8845 return SDValue(); 8846 8847 if (RCC == ISD::SETUNE) { 8848 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8849 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8850 return SDValue(); 8851 8852 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8853 SIInstrFlags::N_SUBNORMAL | 8854 SIInstrFlags::N_ZERO | 8855 SIInstrFlags::P_ZERO | 8856 SIInstrFlags::P_SUBNORMAL | 8857 SIInstrFlags::P_NORMAL; 8858 8859 static_assert(((~(SIInstrFlags::S_NAN | 8860 SIInstrFlags::Q_NAN | 8861 SIInstrFlags::N_INFINITY | 8862 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8863 "mask not equal"); 8864 8865 SDLoc DL(N); 8866 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8867 X, DAG.getConstant(Mask, DL, MVT::i32)); 8868 } 8869 } 8870 } 8871 8872 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8873 std::swap(LHS, RHS); 8874 8875 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8876 RHS.hasOneUse()) { 8877 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8878 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8879 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8880 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8881 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8882 (RHS.getOperand(0) == LHS.getOperand(0) && 8883 LHS.getOperand(0) == LHS.getOperand(1))) { 8884 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8885 unsigned NewMask = LCC == ISD::SETO ? 8886 Mask->getZExtValue() & ~OrdMask : 8887 Mask->getZExtValue() & OrdMask; 8888 8889 SDLoc DL(N); 8890 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8891 DAG.getConstant(NewMask, DL, MVT::i32)); 8892 } 8893 } 8894 8895 if (VT == MVT::i32 && 8896 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8897 // and x, (sext cc from i1) => select cc, x, 0 8898 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8899 std::swap(LHS, RHS); 8900 if (isBoolSGPR(RHS.getOperand(0))) 8901 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8902 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8903 } 8904 8905 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8906 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8907 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8908 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8909 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8910 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8911 if (LHSMask != ~0u && RHSMask != ~0u) { 8912 // Canonicalize the expression in an attempt to have fewer unique masks 8913 // and therefore fewer registers used to hold the masks. 8914 if (LHSMask > RHSMask) { 8915 std::swap(LHSMask, RHSMask); 8916 std::swap(LHS, RHS); 8917 } 8918 8919 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8920 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8921 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8922 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8923 8924 // Check of we need to combine values from two sources within a byte. 8925 if (!(LHSUsedLanes & RHSUsedLanes) && 8926 // If we select high and lower word keep it for SDWA. 8927 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8928 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8929 // Each byte in each mask is either selector mask 0-3, or has higher 8930 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8931 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8932 // mask which is not 0xff wins. By anding both masks we have a correct 8933 // result except that 0x0c shall be corrected to give 0x0c only. 8934 uint32_t Mask = LHSMask & RHSMask; 8935 for (unsigned I = 0; I < 32; I += 8) { 8936 uint32_t ByteSel = 0xff << I; 8937 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8938 Mask &= (0x0c << I) & 0xffffffff; 8939 } 8940 8941 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8942 // or 0x0c. 8943 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8944 SDLoc DL(N); 8945 8946 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8947 LHS.getOperand(0), RHS.getOperand(0), 8948 DAG.getConstant(Sel, DL, MVT::i32)); 8949 } 8950 } 8951 } 8952 8953 return SDValue(); 8954 } 8955 8956 SDValue SITargetLowering::performOrCombine(SDNode *N, 8957 DAGCombinerInfo &DCI) const { 8958 SelectionDAG &DAG = DCI.DAG; 8959 SDValue LHS = N->getOperand(0); 8960 SDValue RHS = N->getOperand(1); 8961 8962 EVT VT = N->getValueType(0); 8963 if (VT == MVT::i1) { 8964 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8965 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8966 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8967 SDValue Src = LHS.getOperand(0); 8968 if (Src != RHS.getOperand(0)) 8969 return SDValue(); 8970 8971 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8972 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8973 if (!CLHS || !CRHS) 8974 return SDValue(); 8975 8976 // Only 10 bits are used. 8977 static const uint32_t MaxMask = 0x3ff; 8978 8979 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8980 SDLoc DL(N); 8981 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8982 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8983 } 8984 8985 return SDValue(); 8986 } 8987 8988 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8989 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8990 LHS.getOpcode() == AMDGPUISD::PERM && 8991 isa<ConstantSDNode>(LHS.getOperand(2))) { 8992 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8993 if (!Sel) 8994 return SDValue(); 8995 8996 Sel |= LHS.getConstantOperandVal(2); 8997 SDLoc DL(N); 8998 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8999 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9000 } 9001 9002 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9003 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9004 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9005 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9006 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9007 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9008 if (LHSMask != ~0u && RHSMask != ~0u) { 9009 // Canonicalize the expression in an attempt to have fewer unique masks 9010 // and therefore fewer registers used to hold the masks. 9011 if (LHSMask > RHSMask) { 9012 std::swap(LHSMask, RHSMask); 9013 std::swap(LHS, RHS); 9014 } 9015 9016 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9017 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9018 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9019 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9020 9021 // Check of we need to combine values from two sources within a byte. 9022 if (!(LHSUsedLanes & RHSUsedLanes) && 9023 // If we select high and lower word keep it for SDWA. 9024 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9025 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9026 // Kill zero bytes selected by other mask. Zero value is 0xc. 9027 LHSMask &= ~RHSUsedLanes; 9028 RHSMask &= ~LHSUsedLanes; 9029 // Add 4 to each active LHS lane 9030 LHSMask |= LHSUsedLanes & 0x04040404; 9031 // Combine masks 9032 uint32_t Sel = LHSMask | RHSMask; 9033 SDLoc DL(N); 9034 9035 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9036 LHS.getOperand(0), RHS.getOperand(0), 9037 DAG.getConstant(Sel, DL, MVT::i32)); 9038 } 9039 } 9040 } 9041 9042 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9043 return SDValue(); 9044 9045 // TODO: This could be a generic combine with a predicate for extracting the 9046 // high half of an integer being free. 9047 9048 // (or i64:x, (zero_extend i32:y)) -> 9049 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9050 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9051 RHS.getOpcode() != ISD::ZERO_EXTEND) 9052 std::swap(LHS, RHS); 9053 9054 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9055 SDValue ExtSrc = RHS.getOperand(0); 9056 EVT SrcVT = ExtSrc.getValueType(); 9057 if (SrcVT == MVT::i32) { 9058 SDLoc SL(N); 9059 SDValue LowLHS, HiBits; 9060 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9061 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9062 9063 DCI.AddToWorklist(LowOr.getNode()); 9064 DCI.AddToWorklist(HiBits.getNode()); 9065 9066 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9067 LowOr, HiBits); 9068 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9069 } 9070 } 9071 9072 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9073 if (CRHS) { 9074 if (SDValue Split 9075 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9076 return Split; 9077 } 9078 9079 return SDValue(); 9080 } 9081 9082 SDValue SITargetLowering::performXorCombine(SDNode *N, 9083 DAGCombinerInfo &DCI) const { 9084 EVT VT = N->getValueType(0); 9085 if (VT != MVT::i64) 9086 return SDValue(); 9087 9088 SDValue LHS = N->getOperand(0); 9089 SDValue RHS = N->getOperand(1); 9090 9091 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9092 if (CRHS) { 9093 if (SDValue Split 9094 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9095 return Split; 9096 } 9097 9098 return SDValue(); 9099 } 9100 9101 // Instructions that will be lowered with a final instruction that zeros the 9102 // high result bits. 9103 // XXX - probably only need to list legal operations. 9104 static bool fp16SrcZerosHighBits(unsigned Opc) { 9105 switch (Opc) { 9106 case ISD::FADD: 9107 case ISD::FSUB: 9108 case ISD::FMUL: 9109 case ISD::FDIV: 9110 case ISD::FREM: 9111 case ISD::FMA: 9112 case ISD::FMAD: 9113 case ISD::FCANONICALIZE: 9114 case ISD::FP_ROUND: 9115 case ISD::UINT_TO_FP: 9116 case ISD::SINT_TO_FP: 9117 case ISD::FABS: 9118 // Fabs is lowered to a bit operation, but it's an and which will clear the 9119 // high bits anyway. 9120 case ISD::FSQRT: 9121 case ISD::FSIN: 9122 case ISD::FCOS: 9123 case ISD::FPOWI: 9124 case ISD::FPOW: 9125 case ISD::FLOG: 9126 case ISD::FLOG2: 9127 case ISD::FLOG10: 9128 case ISD::FEXP: 9129 case ISD::FEXP2: 9130 case ISD::FCEIL: 9131 case ISD::FTRUNC: 9132 case ISD::FRINT: 9133 case ISD::FNEARBYINT: 9134 case ISD::FROUND: 9135 case ISD::FFLOOR: 9136 case ISD::FMINNUM: 9137 case ISD::FMAXNUM: 9138 case AMDGPUISD::FRACT: 9139 case AMDGPUISD::CLAMP: 9140 case AMDGPUISD::COS_HW: 9141 case AMDGPUISD::SIN_HW: 9142 case AMDGPUISD::FMIN3: 9143 case AMDGPUISD::FMAX3: 9144 case AMDGPUISD::FMED3: 9145 case AMDGPUISD::FMAD_FTZ: 9146 case AMDGPUISD::RCP: 9147 case AMDGPUISD::RSQ: 9148 case AMDGPUISD::RCP_IFLAG: 9149 case AMDGPUISD::LDEXP: 9150 return true; 9151 default: 9152 // fcopysign, select and others may be lowered to 32-bit bit operations 9153 // which don't zero the high bits. 9154 return false; 9155 } 9156 } 9157 9158 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9159 DAGCombinerInfo &DCI) const { 9160 if (!Subtarget->has16BitInsts() || 9161 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9162 return SDValue(); 9163 9164 EVT VT = N->getValueType(0); 9165 if (VT != MVT::i32) 9166 return SDValue(); 9167 9168 SDValue Src = N->getOperand(0); 9169 if (Src.getValueType() != MVT::i16) 9170 return SDValue(); 9171 9172 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9173 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9174 if (Src.getOpcode() == ISD::BITCAST) { 9175 SDValue BCSrc = Src.getOperand(0); 9176 if (BCSrc.getValueType() == MVT::f16 && 9177 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9178 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9179 } 9180 9181 return SDValue(); 9182 } 9183 9184 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9185 DAGCombinerInfo &DCI) 9186 const { 9187 SDValue Src = N->getOperand(0); 9188 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9189 9190 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9191 VTSign->getVT() == MVT::i8) || 9192 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9193 VTSign->getVT() == MVT::i16)) && 9194 Src.hasOneUse()) { 9195 auto *M = cast<MemSDNode>(Src); 9196 SDValue Ops[] = { 9197 Src.getOperand(0), // Chain 9198 Src.getOperand(1), // rsrc 9199 Src.getOperand(2), // vindex 9200 Src.getOperand(3), // voffset 9201 Src.getOperand(4), // soffset 9202 Src.getOperand(5), // offset 9203 Src.getOperand(6), 9204 Src.getOperand(7) 9205 }; 9206 // replace with BUFFER_LOAD_BYTE/SHORT 9207 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9208 Src.getOperand(0).getValueType()); 9209 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9210 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9211 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9212 ResList, 9213 Ops, M->getMemoryVT(), 9214 M->getMemOperand()); 9215 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9216 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9217 } 9218 return SDValue(); 9219 } 9220 9221 SDValue SITargetLowering::performClassCombine(SDNode *N, 9222 DAGCombinerInfo &DCI) const { 9223 SelectionDAG &DAG = DCI.DAG; 9224 SDValue Mask = N->getOperand(1); 9225 9226 // fp_class x, 0 -> false 9227 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9228 if (CMask->isNullValue()) 9229 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9230 } 9231 9232 if (N->getOperand(0).isUndef()) 9233 return DAG.getUNDEF(MVT::i1); 9234 9235 return SDValue(); 9236 } 9237 9238 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9239 DAGCombinerInfo &DCI) const { 9240 EVT VT = N->getValueType(0); 9241 SDValue N0 = N->getOperand(0); 9242 9243 if (N0.isUndef()) 9244 return N0; 9245 9246 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9247 N0.getOpcode() == ISD::SINT_TO_FP)) { 9248 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9249 N->getFlags()); 9250 } 9251 9252 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9253 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9254 N0.getOperand(0), N->getFlags()); 9255 } 9256 9257 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9258 } 9259 9260 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9261 unsigned MaxDepth) const { 9262 unsigned Opcode = Op.getOpcode(); 9263 if (Opcode == ISD::FCANONICALIZE) 9264 return true; 9265 9266 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9267 auto F = CFP->getValueAPF(); 9268 if (F.isNaN() && F.isSignaling()) 9269 return false; 9270 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9271 } 9272 9273 // If source is a result of another standard FP operation it is already in 9274 // canonical form. 9275 if (MaxDepth == 0) 9276 return false; 9277 9278 switch (Opcode) { 9279 // These will flush denorms if required. 9280 case ISD::FADD: 9281 case ISD::FSUB: 9282 case ISD::FMUL: 9283 case ISD::FCEIL: 9284 case ISD::FFLOOR: 9285 case ISD::FMA: 9286 case ISD::FMAD: 9287 case ISD::FSQRT: 9288 case ISD::FDIV: 9289 case ISD::FREM: 9290 case ISD::FP_ROUND: 9291 case ISD::FP_EXTEND: 9292 case AMDGPUISD::FMUL_LEGACY: 9293 case AMDGPUISD::FMAD_FTZ: 9294 case AMDGPUISD::RCP: 9295 case AMDGPUISD::RSQ: 9296 case AMDGPUISD::RSQ_CLAMP: 9297 case AMDGPUISD::RCP_LEGACY: 9298 case AMDGPUISD::RCP_IFLAG: 9299 case AMDGPUISD::DIV_SCALE: 9300 case AMDGPUISD::DIV_FMAS: 9301 case AMDGPUISD::DIV_FIXUP: 9302 case AMDGPUISD::FRACT: 9303 case AMDGPUISD::LDEXP: 9304 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9305 case AMDGPUISD::CVT_F32_UBYTE0: 9306 case AMDGPUISD::CVT_F32_UBYTE1: 9307 case AMDGPUISD::CVT_F32_UBYTE2: 9308 case AMDGPUISD::CVT_F32_UBYTE3: 9309 return true; 9310 9311 // It can/will be lowered or combined as a bit operation. 9312 // Need to check their input recursively to handle. 9313 case ISD::FNEG: 9314 case ISD::FABS: 9315 case ISD::FCOPYSIGN: 9316 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9317 9318 case ISD::FSIN: 9319 case ISD::FCOS: 9320 case ISD::FSINCOS: 9321 return Op.getValueType().getScalarType() != MVT::f16; 9322 9323 case ISD::FMINNUM: 9324 case ISD::FMAXNUM: 9325 case ISD::FMINNUM_IEEE: 9326 case ISD::FMAXNUM_IEEE: 9327 case AMDGPUISD::CLAMP: 9328 case AMDGPUISD::FMED3: 9329 case AMDGPUISD::FMAX3: 9330 case AMDGPUISD::FMIN3: { 9331 // FIXME: Shouldn't treat the generic operations different based these. 9332 // However, we aren't really required to flush the result from 9333 // minnum/maxnum.. 9334 9335 // snans will be quieted, so we only need to worry about denormals. 9336 if (Subtarget->supportsMinMaxDenormModes() || 9337 denormalsEnabledForType(DAG, Op.getValueType())) 9338 return true; 9339 9340 // Flushing may be required. 9341 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9342 // targets need to check their input recursively. 9343 9344 // FIXME: Does this apply with clamp? It's implemented with max. 9345 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9346 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9347 return false; 9348 } 9349 9350 return true; 9351 } 9352 case ISD::SELECT: { 9353 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9354 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9355 } 9356 case ISD::BUILD_VECTOR: { 9357 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9358 SDValue SrcOp = Op.getOperand(i); 9359 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9360 return false; 9361 } 9362 9363 return true; 9364 } 9365 case ISD::EXTRACT_VECTOR_ELT: 9366 case ISD::EXTRACT_SUBVECTOR: { 9367 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9368 } 9369 case ISD::INSERT_VECTOR_ELT: { 9370 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9371 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9372 } 9373 case ISD::UNDEF: 9374 // Could be anything. 9375 return false; 9376 9377 case ISD::BITCAST: { 9378 // Hack round the mess we make when legalizing extract_vector_elt 9379 SDValue Src = Op.getOperand(0); 9380 if (Src.getValueType() == MVT::i16 && 9381 Src.getOpcode() == ISD::TRUNCATE) { 9382 SDValue TruncSrc = Src.getOperand(0); 9383 if (TruncSrc.getValueType() == MVT::i32 && 9384 TruncSrc.getOpcode() == ISD::BITCAST && 9385 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9386 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9387 } 9388 } 9389 9390 return false; 9391 } 9392 case ISD::INTRINSIC_WO_CHAIN: { 9393 unsigned IntrinsicID 9394 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9395 // TODO: Handle more intrinsics 9396 switch (IntrinsicID) { 9397 case Intrinsic::amdgcn_cvt_pkrtz: 9398 case Intrinsic::amdgcn_cubeid: 9399 case Intrinsic::amdgcn_frexp_mant: 9400 case Intrinsic::amdgcn_fdot2: 9401 case Intrinsic::amdgcn_rcp: 9402 case Intrinsic::amdgcn_rsq: 9403 case Intrinsic::amdgcn_rsq_clamp: 9404 case Intrinsic::amdgcn_rcp_legacy: 9405 case Intrinsic::amdgcn_rsq_legacy: 9406 case Intrinsic::amdgcn_trig_preop: 9407 return true; 9408 default: 9409 break; 9410 } 9411 9412 LLVM_FALLTHROUGH; 9413 } 9414 default: 9415 return denormalsEnabledForType(DAG, Op.getValueType()) && 9416 DAG.isKnownNeverSNaN(Op); 9417 } 9418 9419 llvm_unreachable("invalid operation"); 9420 } 9421 9422 // Constant fold canonicalize. 9423 SDValue SITargetLowering::getCanonicalConstantFP( 9424 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9425 // Flush denormals to 0 if not enabled. 9426 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9427 return DAG.getConstantFP(0.0, SL, VT); 9428 9429 if (C.isNaN()) { 9430 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9431 if (C.isSignaling()) { 9432 // Quiet a signaling NaN. 9433 // FIXME: Is this supposed to preserve payload bits? 9434 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9435 } 9436 9437 // Make sure it is the canonical NaN bitpattern. 9438 // 9439 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9440 // immediate? 9441 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9442 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9443 } 9444 9445 // Already canonical. 9446 return DAG.getConstantFP(C, SL, VT); 9447 } 9448 9449 static bool vectorEltWillFoldAway(SDValue Op) { 9450 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9451 } 9452 9453 SDValue SITargetLowering::performFCanonicalizeCombine( 9454 SDNode *N, 9455 DAGCombinerInfo &DCI) const { 9456 SelectionDAG &DAG = DCI.DAG; 9457 SDValue N0 = N->getOperand(0); 9458 EVT VT = N->getValueType(0); 9459 9460 // fcanonicalize undef -> qnan 9461 if (N0.isUndef()) { 9462 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9463 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9464 } 9465 9466 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9467 EVT VT = N->getValueType(0); 9468 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9469 } 9470 9471 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9472 // (fcanonicalize k) 9473 // 9474 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9475 9476 // TODO: This could be better with wider vectors that will be split to v2f16, 9477 // and to consider uses since there aren't that many packed operations. 9478 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9479 isTypeLegal(MVT::v2f16)) { 9480 SDLoc SL(N); 9481 SDValue NewElts[2]; 9482 SDValue Lo = N0.getOperand(0); 9483 SDValue Hi = N0.getOperand(1); 9484 EVT EltVT = Lo.getValueType(); 9485 9486 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9487 for (unsigned I = 0; I != 2; ++I) { 9488 SDValue Op = N0.getOperand(I); 9489 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9490 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9491 CFP->getValueAPF()); 9492 } else if (Op.isUndef()) { 9493 // Handled below based on what the other operand is. 9494 NewElts[I] = Op; 9495 } else { 9496 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9497 } 9498 } 9499 9500 // If one half is undef, and one is constant, perfer a splat vector rather 9501 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9502 // cheaper to use and may be free with a packed operation. 9503 if (NewElts[0].isUndef()) { 9504 if (isa<ConstantFPSDNode>(NewElts[1])) 9505 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9506 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9507 } 9508 9509 if (NewElts[1].isUndef()) { 9510 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9511 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9512 } 9513 9514 return DAG.getBuildVector(VT, SL, NewElts); 9515 } 9516 } 9517 9518 unsigned SrcOpc = N0.getOpcode(); 9519 9520 // If it's free to do so, push canonicalizes further up the source, which may 9521 // find a canonical source. 9522 // 9523 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9524 // sNaNs. 9525 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9526 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9527 if (CRHS && N0.hasOneUse()) { 9528 SDLoc SL(N); 9529 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9530 N0.getOperand(0)); 9531 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9532 DCI.AddToWorklist(Canon0.getNode()); 9533 9534 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9535 } 9536 } 9537 9538 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9539 } 9540 9541 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9542 switch (Opc) { 9543 case ISD::FMAXNUM: 9544 case ISD::FMAXNUM_IEEE: 9545 return AMDGPUISD::FMAX3; 9546 case ISD::SMAX: 9547 return AMDGPUISD::SMAX3; 9548 case ISD::UMAX: 9549 return AMDGPUISD::UMAX3; 9550 case ISD::FMINNUM: 9551 case ISD::FMINNUM_IEEE: 9552 return AMDGPUISD::FMIN3; 9553 case ISD::SMIN: 9554 return AMDGPUISD::SMIN3; 9555 case ISD::UMIN: 9556 return AMDGPUISD::UMIN3; 9557 default: 9558 llvm_unreachable("Not a min/max opcode"); 9559 } 9560 } 9561 9562 SDValue SITargetLowering::performIntMed3ImmCombine( 9563 SelectionDAG &DAG, const SDLoc &SL, 9564 SDValue Op0, SDValue Op1, bool Signed) const { 9565 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9566 if (!K1) 9567 return SDValue(); 9568 9569 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9570 if (!K0) 9571 return SDValue(); 9572 9573 if (Signed) { 9574 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9575 return SDValue(); 9576 } else { 9577 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9578 return SDValue(); 9579 } 9580 9581 EVT VT = K0->getValueType(0); 9582 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9583 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9584 return DAG.getNode(Med3Opc, SL, VT, 9585 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9586 } 9587 9588 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9589 MVT NVT = MVT::i32; 9590 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9591 9592 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9593 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9594 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9595 9596 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9597 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9598 } 9599 9600 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9601 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9602 return C; 9603 9604 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9605 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9606 return C; 9607 } 9608 9609 return nullptr; 9610 } 9611 9612 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9613 const SDLoc &SL, 9614 SDValue Op0, 9615 SDValue Op1) const { 9616 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9617 if (!K1) 9618 return SDValue(); 9619 9620 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9621 if (!K0) 9622 return SDValue(); 9623 9624 // Ordered >= (although NaN inputs should have folded away by now). 9625 if (K0->getValueAPF() > K1->getValueAPF()) 9626 return SDValue(); 9627 9628 const MachineFunction &MF = DAG.getMachineFunction(); 9629 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9630 9631 // TODO: Check IEEE bit enabled? 9632 EVT VT = Op0.getValueType(); 9633 if (Info->getMode().DX10Clamp) { 9634 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9635 // hardware fmed3 behavior converting to a min. 9636 // FIXME: Should this be allowing -0.0? 9637 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9638 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9639 } 9640 9641 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9642 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9643 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9644 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9645 // then give the other result, which is different from med3 with a NaN 9646 // input. 9647 SDValue Var = Op0.getOperand(0); 9648 if (!DAG.isKnownNeverSNaN(Var)) 9649 return SDValue(); 9650 9651 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9652 9653 if ((!K0->hasOneUse() || 9654 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9655 (!K1->hasOneUse() || 9656 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9657 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9658 Var, SDValue(K0, 0), SDValue(K1, 0)); 9659 } 9660 } 9661 9662 return SDValue(); 9663 } 9664 9665 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9666 DAGCombinerInfo &DCI) const { 9667 SelectionDAG &DAG = DCI.DAG; 9668 9669 EVT VT = N->getValueType(0); 9670 unsigned Opc = N->getOpcode(); 9671 SDValue Op0 = N->getOperand(0); 9672 SDValue Op1 = N->getOperand(1); 9673 9674 // Only do this if the inner op has one use since this will just increases 9675 // register pressure for no benefit. 9676 9677 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9678 !VT.isVector() && 9679 (VT == MVT::i32 || VT == MVT::f32 || 9680 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9681 // max(max(a, b), c) -> max3(a, b, c) 9682 // min(min(a, b), c) -> min3(a, b, c) 9683 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9684 SDLoc DL(N); 9685 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9686 DL, 9687 N->getValueType(0), 9688 Op0.getOperand(0), 9689 Op0.getOperand(1), 9690 Op1); 9691 } 9692 9693 // Try commuted. 9694 // max(a, max(b, c)) -> max3(a, b, c) 9695 // min(a, min(b, c)) -> min3(a, b, c) 9696 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9697 SDLoc DL(N); 9698 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9699 DL, 9700 N->getValueType(0), 9701 Op0, 9702 Op1.getOperand(0), 9703 Op1.getOperand(1)); 9704 } 9705 } 9706 9707 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9708 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9709 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9710 return Med3; 9711 } 9712 9713 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9714 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9715 return Med3; 9716 } 9717 9718 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9719 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9720 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9721 (Opc == AMDGPUISD::FMIN_LEGACY && 9722 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9723 (VT == MVT::f32 || VT == MVT::f64 || 9724 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9725 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9726 Op0.hasOneUse()) { 9727 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9728 return Res; 9729 } 9730 9731 return SDValue(); 9732 } 9733 9734 static bool isClampZeroToOne(SDValue A, SDValue B) { 9735 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9736 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9737 // FIXME: Should this be allowing -0.0? 9738 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9739 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9740 } 9741 } 9742 9743 return false; 9744 } 9745 9746 // FIXME: Should only worry about snans for version with chain. 9747 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9748 DAGCombinerInfo &DCI) const { 9749 EVT VT = N->getValueType(0); 9750 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9751 // NaNs. With a NaN input, the order of the operands may change the result. 9752 9753 SelectionDAG &DAG = DCI.DAG; 9754 SDLoc SL(N); 9755 9756 SDValue Src0 = N->getOperand(0); 9757 SDValue Src1 = N->getOperand(1); 9758 SDValue Src2 = N->getOperand(2); 9759 9760 if (isClampZeroToOne(Src0, Src1)) { 9761 // const_a, const_b, x -> clamp is safe in all cases including signaling 9762 // nans. 9763 // FIXME: Should this be allowing -0.0? 9764 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9765 } 9766 9767 const MachineFunction &MF = DAG.getMachineFunction(); 9768 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9769 9770 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9771 // handling no dx10-clamp? 9772 if (Info->getMode().DX10Clamp) { 9773 // If NaNs is clamped to 0, we are free to reorder the inputs. 9774 9775 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9776 std::swap(Src0, Src1); 9777 9778 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9779 std::swap(Src1, Src2); 9780 9781 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9782 std::swap(Src0, Src1); 9783 9784 if (isClampZeroToOne(Src1, Src2)) 9785 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9786 } 9787 9788 return SDValue(); 9789 } 9790 9791 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9792 DAGCombinerInfo &DCI) const { 9793 SDValue Src0 = N->getOperand(0); 9794 SDValue Src1 = N->getOperand(1); 9795 if (Src0.isUndef() && Src1.isUndef()) 9796 return DCI.DAG.getUNDEF(N->getValueType(0)); 9797 return SDValue(); 9798 } 9799 9800 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9801 // expanded into a set of cmp/select instructions. 9802 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9803 unsigned NumElem, 9804 bool IsDivergentIdx) { 9805 if (UseDivergentRegisterIndexing) 9806 return false; 9807 9808 unsigned VecSize = EltSize * NumElem; 9809 9810 // Sub-dword vectors of size 2 dword or less have better implementation. 9811 if (VecSize <= 64 && EltSize < 32) 9812 return false; 9813 9814 // Always expand the rest of sub-dword instructions, otherwise it will be 9815 // lowered via memory. 9816 if (EltSize < 32) 9817 return true; 9818 9819 // Always do this if var-idx is divergent, otherwise it will become a loop. 9820 if (IsDivergentIdx) 9821 return true; 9822 9823 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9824 unsigned NumInsts = NumElem /* Number of compares */ + 9825 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9826 return NumInsts <= 16; 9827 } 9828 9829 static bool shouldExpandVectorDynExt(SDNode *N) { 9830 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9831 if (isa<ConstantSDNode>(Idx)) 9832 return false; 9833 9834 SDValue Vec = N->getOperand(0); 9835 EVT VecVT = Vec.getValueType(); 9836 EVT EltVT = VecVT.getVectorElementType(); 9837 unsigned EltSize = EltVT.getSizeInBits(); 9838 unsigned NumElem = VecVT.getVectorNumElements(); 9839 9840 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9841 Idx->isDivergent()); 9842 } 9843 9844 SDValue SITargetLowering::performExtractVectorEltCombine( 9845 SDNode *N, DAGCombinerInfo &DCI) const { 9846 SDValue Vec = N->getOperand(0); 9847 SelectionDAG &DAG = DCI.DAG; 9848 9849 EVT VecVT = Vec.getValueType(); 9850 EVT EltVT = VecVT.getVectorElementType(); 9851 9852 if ((Vec.getOpcode() == ISD::FNEG || 9853 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9854 SDLoc SL(N); 9855 EVT EltVT = N->getValueType(0); 9856 SDValue Idx = N->getOperand(1); 9857 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9858 Vec.getOperand(0), Idx); 9859 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9860 } 9861 9862 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9863 // => 9864 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9865 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9866 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9867 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9868 SDLoc SL(N); 9869 EVT EltVT = N->getValueType(0); 9870 SDValue Idx = N->getOperand(1); 9871 unsigned Opc = Vec.getOpcode(); 9872 9873 switch(Opc) { 9874 default: 9875 break; 9876 // TODO: Support other binary operations. 9877 case ISD::FADD: 9878 case ISD::FSUB: 9879 case ISD::FMUL: 9880 case ISD::ADD: 9881 case ISD::UMIN: 9882 case ISD::UMAX: 9883 case ISD::SMIN: 9884 case ISD::SMAX: 9885 case ISD::FMAXNUM: 9886 case ISD::FMINNUM: 9887 case ISD::FMAXNUM_IEEE: 9888 case ISD::FMINNUM_IEEE: { 9889 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9890 Vec.getOperand(0), Idx); 9891 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9892 Vec.getOperand(1), Idx); 9893 9894 DCI.AddToWorklist(Elt0.getNode()); 9895 DCI.AddToWorklist(Elt1.getNode()); 9896 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9897 } 9898 } 9899 } 9900 9901 unsigned VecSize = VecVT.getSizeInBits(); 9902 unsigned EltSize = EltVT.getSizeInBits(); 9903 9904 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9905 if (::shouldExpandVectorDynExt(N)) { 9906 SDLoc SL(N); 9907 SDValue Idx = N->getOperand(1); 9908 SDValue V; 9909 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9910 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9911 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9912 if (I == 0) 9913 V = Elt; 9914 else 9915 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9916 } 9917 return V; 9918 } 9919 9920 if (!DCI.isBeforeLegalize()) 9921 return SDValue(); 9922 9923 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9924 // elements. This exposes more load reduction opportunities by replacing 9925 // multiple small extract_vector_elements with a single 32-bit extract. 9926 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9927 if (isa<MemSDNode>(Vec) && 9928 EltSize <= 16 && 9929 EltVT.isByteSized() && 9930 VecSize > 32 && 9931 VecSize % 32 == 0 && 9932 Idx) { 9933 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9934 9935 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9936 unsigned EltIdx = BitIndex / 32; 9937 unsigned LeftoverBitIdx = BitIndex % 32; 9938 SDLoc SL(N); 9939 9940 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9941 DCI.AddToWorklist(Cast.getNode()); 9942 9943 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9944 DAG.getConstant(EltIdx, SL, MVT::i32)); 9945 DCI.AddToWorklist(Elt.getNode()); 9946 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9947 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9948 DCI.AddToWorklist(Srl.getNode()); 9949 9950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9951 DCI.AddToWorklist(Trunc.getNode()); 9952 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9953 } 9954 9955 return SDValue(); 9956 } 9957 9958 SDValue 9959 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9960 DAGCombinerInfo &DCI) const { 9961 SDValue Vec = N->getOperand(0); 9962 SDValue Idx = N->getOperand(2); 9963 EVT VecVT = Vec.getValueType(); 9964 EVT EltVT = VecVT.getVectorElementType(); 9965 9966 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9967 // => BUILD_VECTOR n x select (e, const-idx) 9968 if (!::shouldExpandVectorDynExt(N)) 9969 return SDValue(); 9970 9971 SelectionDAG &DAG = DCI.DAG; 9972 SDLoc SL(N); 9973 SDValue Ins = N->getOperand(1); 9974 EVT IdxVT = Idx.getValueType(); 9975 9976 SmallVector<SDValue, 16> Ops; 9977 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9978 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9979 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9980 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9981 Ops.push_back(V); 9982 } 9983 9984 return DAG.getBuildVector(VecVT, SL, Ops); 9985 } 9986 9987 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9988 const SDNode *N0, 9989 const SDNode *N1) const { 9990 EVT VT = N0->getValueType(0); 9991 9992 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9993 // support denormals ever. 9994 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9995 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9996 getSubtarget()->hasMadF16())) && 9997 isOperationLegal(ISD::FMAD, VT)) 9998 return ISD::FMAD; 9999 10000 const TargetOptions &Options = DAG.getTarget().Options; 10001 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10002 (N0->getFlags().hasAllowContract() && 10003 N1->getFlags().hasAllowContract())) && 10004 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10005 return ISD::FMA; 10006 } 10007 10008 return 0; 10009 } 10010 10011 // For a reassociatable opcode perform: 10012 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10013 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10014 SelectionDAG &DAG) const { 10015 EVT VT = N->getValueType(0); 10016 if (VT != MVT::i32 && VT != MVT::i64) 10017 return SDValue(); 10018 10019 unsigned Opc = N->getOpcode(); 10020 SDValue Op0 = N->getOperand(0); 10021 SDValue Op1 = N->getOperand(1); 10022 10023 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10024 return SDValue(); 10025 10026 if (Op0->isDivergent()) 10027 std::swap(Op0, Op1); 10028 10029 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10030 return SDValue(); 10031 10032 SDValue Op2 = Op1.getOperand(1); 10033 Op1 = Op1.getOperand(0); 10034 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10035 return SDValue(); 10036 10037 if (Op1->isDivergent()) 10038 std::swap(Op1, Op2); 10039 10040 // If either operand is constant this will conflict with 10041 // DAGCombiner::ReassociateOps(). 10042 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10043 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10044 return SDValue(); 10045 10046 SDLoc SL(N); 10047 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10048 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10049 } 10050 10051 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10052 EVT VT, 10053 SDValue N0, SDValue N1, SDValue N2, 10054 bool Signed) { 10055 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10056 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10057 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10058 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10059 } 10060 10061 SDValue SITargetLowering::performAddCombine(SDNode *N, 10062 DAGCombinerInfo &DCI) const { 10063 SelectionDAG &DAG = DCI.DAG; 10064 EVT VT = N->getValueType(0); 10065 SDLoc SL(N); 10066 SDValue LHS = N->getOperand(0); 10067 SDValue RHS = N->getOperand(1); 10068 10069 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10070 && Subtarget->hasMad64_32() && 10071 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10072 VT.getScalarSizeInBits() <= 64) { 10073 if (LHS.getOpcode() != ISD::MUL) 10074 std::swap(LHS, RHS); 10075 10076 SDValue MulLHS = LHS.getOperand(0); 10077 SDValue MulRHS = LHS.getOperand(1); 10078 SDValue AddRHS = RHS; 10079 10080 // TODO: Maybe restrict if SGPR inputs. 10081 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10082 numBitsUnsigned(MulRHS, DAG) <= 32) { 10083 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10084 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10085 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10086 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10087 } 10088 10089 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10090 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10091 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10092 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10093 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10094 } 10095 10096 return SDValue(); 10097 } 10098 10099 if (SDValue V = reassociateScalarOps(N, DAG)) { 10100 return V; 10101 } 10102 10103 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10104 return SDValue(); 10105 10106 // add x, zext (setcc) => addcarry x, 0, setcc 10107 // add x, sext (setcc) => subcarry x, 0, setcc 10108 unsigned Opc = LHS.getOpcode(); 10109 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10110 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10111 std::swap(RHS, LHS); 10112 10113 Opc = RHS.getOpcode(); 10114 switch (Opc) { 10115 default: break; 10116 case ISD::ZERO_EXTEND: 10117 case ISD::SIGN_EXTEND: 10118 case ISD::ANY_EXTEND: { 10119 auto Cond = RHS.getOperand(0); 10120 // If this won't be a real VOPC output, we would still need to insert an 10121 // extra instruction anyway. 10122 if (!isBoolSGPR(Cond)) 10123 break; 10124 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10125 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10126 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10127 return DAG.getNode(Opc, SL, VTList, Args); 10128 } 10129 case ISD::ADDCARRY: { 10130 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10131 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10132 if (!C || C->getZExtValue() != 0) break; 10133 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10134 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10135 } 10136 } 10137 return SDValue(); 10138 } 10139 10140 SDValue SITargetLowering::performSubCombine(SDNode *N, 10141 DAGCombinerInfo &DCI) const { 10142 SelectionDAG &DAG = DCI.DAG; 10143 EVT VT = N->getValueType(0); 10144 10145 if (VT != MVT::i32) 10146 return SDValue(); 10147 10148 SDLoc SL(N); 10149 SDValue LHS = N->getOperand(0); 10150 SDValue RHS = N->getOperand(1); 10151 10152 // sub x, zext (setcc) => subcarry x, 0, setcc 10153 // sub x, sext (setcc) => addcarry x, 0, setcc 10154 unsigned Opc = RHS.getOpcode(); 10155 switch (Opc) { 10156 default: break; 10157 case ISD::ZERO_EXTEND: 10158 case ISD::SIGN_EXTEND: 10159 case ISD::ANY_EXTEND: { 10160 auto Cond = RHS.getOperand(0); 10161 // If this won't be a real VOPC output, we would still need to insert an 10162 // extra instruction anyway. 10163 if (!isBoolSGPR(Cond)) 10164 break; 10165 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10166 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10167 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10168 return DAG.getNode(Opc, SL, VTList, Args); 10169 } 10170 } 10171 10172 if (LHS.getOpcode() == ISD::SUBCARRY) { 10173 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10174 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10175 if (!C || !C->isNullValue()) 10176 return SDValue(); 10177 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10178 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10179 } 10180 return SDValue(); 10181 } 10182 10183 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10184 DAGCombinerInfo &DCI) const { 10185 10186 if (N->getValueType(0) != MVT::i32) 10187 return SDValue(); 10188 10189 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10190 if (!C || C->getZExtValue() != 0) 10191 return SDValue(); 10192 10193 SelectionDAG &DAG = DCI.DAG; 10194 SDValue LHS = N->getOperand(0); 10195 10196 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10197 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10198 unsigned LHSOpc = LHS.getOpcode(); 10199 unsigned Opc = N->getOpcode(); 10200 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10201 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10202 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10203 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10204 } 10205 return SDValue(); 10206 } 10207 10208 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10209 DAGCombinerInfo &DCI) const { 10210 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10211 return SDValue(); 10212 10213 SelectionDAG &DAG = DCI.DAG; 10214 EVT VT = N->getValueType(0); 10215 10216 SDLoc SL(N); 10217 SDValue LHS = N->getOperand(0); 10218 SDValue RHS = N->getOperand(1); 10219 10220 // These should really be instruction patterns, but writing patterns with 10221 // source modiifiers is a pain. 10222 10223 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10224 if (LHS.getOpcode() == ISD::FADD) { 10225 SDValue A = LHS.getOperand(0); 10226 if (A == LHS.getOperand(1)) { 10227 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10228 if (FusedOp != 0) { 10229 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10230 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10231 } 10232 } 10233 } 10234 10235 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10236 if (RHS.getOpcode() == ISD::FADD) { 10237 SDValue A = RHS.getOperand(0); 10238 if (A == RHS.getOperand(1)) { 10239 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10240 if (FusedOp != 0) { 10241 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10242 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10243 } 10244 } 10245 } 10246 10247 return SDValue(); 10248 } 10249 10250 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10251 DAGCombinerInfo &DCI) const { 10252 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10253 return SDValue(); 10254 10255 SelectionDAG &DAG = DCI.DAG; 10256 SDLoc SL(N); 10257 EVT VT = N->getValueType(0); 10258 assert(!VT.isVector()); 10259 10260 // Try to get the fneg to fold into the source modifier. This undoes generic 10261 // DAG combines and folds them into the mad. 10262 // 10263 // Only do this if we are not trying to support denormals. v_mad_f32 does 10264 // not support denormals ever. 10265 SDValue LHS = N->getOperand(0); 10266 SDValue RHS = N->getOperand(1); 10267 if (LHS.getOpcode() == ISD::FADD) { 10268 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10269 SDValue A = LHS.getOperand(0); 10270 if (A == LHS.getOperand(1)) { 10271 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10272 if (FusedOp != 0){ 10273 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10274 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10275 10276 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10277 } 10278 } 10279 } 10280 10281 if (RHS.getOpcode() == ISD::FADD) { 10282 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10283 10284 SDValue A = RHS.getOperand(0); 10285 if (A == RHS.getOperand(1)) { 10286 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10287 if (FusedOp != 0){ 10288 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10289 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10290 } 10291 } 10292 } 10293 10294 return SDValue(); 10295 } 10296 10297 SDValue SITargetLowering::performFMACombine(SDNode *N, 10298 DAGCombinerInfo &DCI) const { 10299 SelectionDAG &DAG = DCI.DAG; 10300 EVT VT = N->getValueType(0); 10301 SDLoc SL(N); 10302 10303 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10304 return SDValue(); 10305 10306 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10307 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10308 SDValue Op1 = N->getOperand(0); 10309 SDValue Op2 = N->getOperand(1); 10310 SDValue FMA = N->getOperand(2); 10311 10312 if (FMA.getOpcode() != ISD::FMA || 10313 Op1.getOpcode() != ISD::FP_EXTEND || 10314 Op2.getOpcode() != ISD::FP_EXTEND) 10315 return SDValue(); 10316 10317 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10318 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10319 // is sufficient to allow generaing fdot2. 10320 const TargetOptions &Options = DAG.getTarget().Options; 10321 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10322 (N->getFlags().hasAllowContract() && 10323 FMA->getFlags().hasAllowContract())) { 10324 Op1 = Op1.getOperand(0); 10325 Op2 = Op2.getOperand(0); 10326 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10327 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10328 return SDValue(); 10329 10330 SDValue Vec1 = Op1.getOperand(0); 10331 SDValue Idx1 = Op1.getOperand(1); 10332 SDValue Vec2 = Op2.getOperand(0); 10333 10334 SDValue FMAOp1 = FMA.getOperand(0); 10335 SDValue FMAOp2 = FMA.getOperand(1); 10336 SDValue FMAAcc = FMA.getOperand(2); 10337 10338 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10339 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10340 return SDValue(); 10341 10342 FMAOp1 = FMAOp1.getOperand(0); 10343 FMAOp2 = FMAOp2.getOperand(0); 10344 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10345 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10346 return SDValue(); 10347 10348 SDValue Vec3 = FMAOp1.getOperand(0); 10349 SDValue Vec4 = FMAOp2.getOperand(0); 10350 SDValue Idx2 = FMAOp1.getOperand(1); 10351 10352 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10353 // Idx1 and Idx2 cannot be the same. 10354 Idx1 == Idx2) 10355 return SDValue(); 10356 10357 if (Vec1 == Vec2 || Vec3 == Vec4) 10358 return SDValue(); 10359 10360 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10361 return SDValue(); 10362 10363 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10364 (Vec1 == Vec4 && Vec2 == Vec3)) { 10365 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10366 DAG.getTargetConstant(0, SL, MVT::i1)); 10367 } 10368 } 10369 return SDValue(); 10370 } 10371 10372 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10373 DAGCombinerInfo &DCI) const { 10374 SelectionDAG &DAG = DCI.DAG; 10375 SDLoc SL(N); 10376 10377 SDValue LHS = N->getOperand(0); 10378 SDValue RHS = N->getOperand(1); 10379 EVT VT = LHS.getValueType(); 10380 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10381 10382 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10383 if (!CRHS) { 10384 CRHS = dyn_cast<ConstantSDNode>(LHS); 10385 if (CRHS) { 10386 std::swap(LHS, RHS); 10387 CC = getSetCCSwappedOperands(CC); 10388 } 10389 } 10390 10391 if (CRHS) { 10392 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10393 isBoolSGPR(LHS.getOperand(0))) { 10394 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10395 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10396 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10397 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10398 if ((CRHS->isAllOnesValue() && 10399 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10400 (CRHS->isNullValue() && 10401 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10402 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10403 DAG.getConstant(-1, SL, MVT::i1)); 10404 if ((CRHS->isAllOnesValue() && 10405 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10406 (CRHS->isNullValue() && 10407 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10408 return LHS.getOperand(0); 10409 } 10410 10411 uint64_t CRHSVal = CRHS->getZExtValue(); 10412 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10413 LHS.getOpcode() == ISD::SELECT && 10414 isa<ConstantSDNode>(LHS.getOperand(1)) && 10415 isa<ConstantSDNode>(LHS.getOperand(2)) && 10416 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10417 isBoolSGPR(LHS.getOperand(0))) { 10418 // Given CT != FT: 10419 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10420 // setcc (select cc, CT, CF), CF, ne => cc 10421 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10422 // setcc (select cc, CT, CF), CT, eq => cc 10423 uint64_t CT = LHS.getConstantOperandVal(1); 10424 uint64_t CF = LHS.getConstantOperandVal(2); 10425 10426 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10427 (CT == CRHSVal && CC == ISD::SETNE)) 10428 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10429 DAG.getConstant(-1, SL, MVT::i1)); 10430 if ((CF == CRHSVal && CC == ISD::SETNE) || 10431 (CT == CRHSVal && CC == ISD::SETEQ)) 10432 return LHS.getOperand(0); 10433 } 10434 } 10435 10436 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10437 VT != MVT::f16)) 10438 return SDValue(); 10439 10440 // Match isinf/isfinite pattern 10441 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10442 // (fcmp one (fabs x), inf) -> (fp_class x, 10443 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10444 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10445 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10446 if (!CRHS) 10447 return SDValue(); 10448 10449 const APFloat &APF = CRHS->getValueAPF(); 10450 if (APF.isInfinity() && !APF.isNegative()) { 10451 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10452 SIInstrFlags::N_INFINITY; 10453 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10454 SIInstrFlags::P_ZERO | 10455 SIInstrFlags::N_NORMAL | 10456 SIInstrFlags::P_NORMAL | 10457 SIInstrFlags::N_SUBNORMAL | 10458 SIInstrFlags::P_SUBNORMAL; 10459 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10460 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10461 DAG.getConstant(Mask, SL, MVT::i32)); 10462 } 10463 } 10464 10465 return SDValue(); 10466 } 10467 10468 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10469 DAGCombinerInfo &DCI) const { 10470 SelectionDAG &DAG = DCI.DAG; 10471 SDLoc SL(N); 10472 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10473 10474 SDValue Src = N->getOperand(0); 10475 SDValue Shift = N->getOperand(0); 10476 10477 // TODO: Extend type shouldn't matter (assuming legal types). 10478 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10479 Shift = Shift.getOperand(0); 10480 10481 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10482 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10483 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10484 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10485 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10486 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10487 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10488 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10489 SDLoc(Shift.getOperand(0)), MVT::i32); 10490 10491 unsigned ShiftOffset = 8 * Offset; 10492 if (Shift.getOpcode() == ISD::SHL) 10493 ShiftOffset -= C->getZExtValue(); 10494 else 10495 ShiftOffset += C->getZExtValue(); 10496 10497 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10498 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10499 MVT::f32, Shift); 10500 } 10501 } 10502 } 10503 10504 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10505 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10506 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10507 // We simplified Src. If this node is not dead, visit it again so it is 10508 // folded properly. 10509 if (N->getOpcode() != ISD::DELETED_NODE) 10510 DCI.AddToWorklist(N); 10511 return SDValue(N, 0); 10512 } 10513 10514 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10515 if (SDValue DemandedSrc = 10516 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10517 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10518 10519 return SDValue(); 10520 } 10521 10522 SDValue SITargetLowering::performClampCombine(SDNode *N, 10523 DAGCombinerInfo &DCI) const { 10524 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10525 if (!CSrc) 10526 return SDValue(); 10527 10528 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10529 const APFloat &F = CSrc->getValueAPF(); 10530 APFloat Zero = APFloat::getZero(F.getSemantics()); 10531 if (F < Zero || 10532 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10533 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10534 } 10535 10536 APFloat One(F.getSemantics(), "1.0"); 10537 if (F > One) 10538 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10539 10540 return SDValue(CSrc, 0); 10541 } 10542 10543 10544 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10545 DAGCombinerInfo &DCI) const { 10546 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10547 return SDValue(); 10548 switch (N->getOpcode()) { 10549 case ISD::ADD: 10550 return performAddCombine(N, DCI); 10551 case ISD::SUB: 10552 return performSubCombine(N, DCI); 10553 case ISD::ADDCARRY: 10554 case ISD::SUBCARRY: 10555 return performAddCarrySubCarryCombine(N, DCI); 10556 case ISD::FADD: 10557 return performFAddCombine(N, DCI); 10558 case ISD::FSUB: 10559 return performFSubCombine(N, DCI); 10560 case ISD::SETCC: 10561 return performSetCCCombine(N, DCI); 10562 case ISD::FMAXNUM: 10563 case ISD::FMINNUM: 10564 case ISD::FMAXNUM_IEEE: 10565 case ISD::FMINNUM_IEEE: 10566 case ISD::SMAX: 10567 case ISD::SMIN: 10568 case ISD::UMAX: 10569 case ISD::UMIN: 10570 case AMDGPUISD::FMIN_LEGACY: 10571 case AMDGPUISD::FMAX_LEGACY: 10572 return performMinMaxCombine(N, DCI); 10573 case ISD::FMA: 10574 return performFMACombine(N, DCI); 10575 case ISD::AND: 10576 return performAndCombine(N, DCI); 10577 case ISD::OR: 10578 return performOrCombine(N, DCI); 10579 case ISD::XOR: 10580 return performXorCombine(N, DCI); 10581 case ISD::ZERO_EXTEND: 10582 return performZeroExtendCombine(N, DCI); 10583 case ISD::SIGN_EXTEND_INREG: 10584 return performSignExtendInRegCombine(N , DCI); 10585 case AMDGPUISD::FP_CLASS: 10586 return performClassCombine(N, DCI); 10587 case ISD::FCANONICALIZE: 10588 return performFCanonicalizeCombine(N, DCI); 10589 case AMDGPUISD::RCP: 10590 return performRcpCombine(N, DCI); 10591 case AMDGPUISD::FRACT: 10592 case AMDGPUISD::RSQ: 10593 case AMDGPUISD::RCP_LEGACY: 10594 case AMDGPUISD::RCP_IFLAG: 10595 case AMDGPUISD::RSQ_CLAMP: 10596 case AMDGPUISD::LDEXP: { 10597 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10598 SDValue Src = N->getOperand(0); 10599 if (Src.isUndef()) 10600 return Src; 10601 break; 10602 } 10603 case ISD::SINT_TO_FP: 10604 case ISD::UINT_TO_FP: 10605 return performUCharToFloatCombine(N, DCI); 10606 case AMDGPUISD::CVT_F32_UBYTE0: 10607 case AMDGPUISD::CVT_F32_UBYTE1: 10608 case AMDGPUISD::CVT_F32_UBYTE2: 10609 case AMDGPUISD::CVT_F32_UBYTE3: 10610 return performCvtF32UByteNCombine(N, DCI); 10611 case AMDGPUISD::FMED3: 10612 return performFMed3Combine(N, DCI); 10613 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10614 return performCvtPkRTZCombine(N, DCI); 10615 case AMDGPUISD::CLAMP: 10616 return performClampCombine(N, DCI); 10617 case ISD::SCALAR_TO_VECTOR: { 10618 SelectionDAG &DAG = DCI.DAG; 10619 EVT VT = N->getValueType(0); 10620 10621 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10622 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10623 SDLoc SL(N); 10624 SDValue Src = N->getOperand(0); 10625 EVT EltVT = Src.getValueType(); 10626 if (EltVT == MVT::f16) 10627 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10628 10629 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10630 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10631 } 10632 10633 break; 10634 } 10635 case ISD::EXTRACT_VECTOR_ELT: 10636 return performExtractVectorEltCombine(N, DCI); 10637 case ISD::INSERT_VECTOR_ELT: 10638 return performInsertVectorEltCombine(N, DCI); 10639 case ISD::LOAD: { 10640 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10641 return Widended; 10642 LLVM_FALLTHROUGH; 10643 } 10644 default: { 10645 if (!DCI.isBeforeLegalize()) { 10646 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10647 return performMemSDNodeCombine(MemNode, DCI); 10648 } 10649 10650 break; 10651 } 10652 } 10653 10654 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10655 } 10656 10657 /// Helper function for adjustWritemask 10658 static unsigned SubIdx2Lane(unsigned Idx) { 10659 switch (Idx) { 10660 default: return 0; 10661 case AMDGPU::sub0: return 0; 10662 case AMDGPU::sub1: return 1; 10663 case AMDGPU::sub2: return 2; 10664 case AMDGPU::sub3: return 3; 10665 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10666 } 10667 } 10668 10669 /// Adjust the writemask of MIMG instructions 10670 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10671 SelectionDAG &DAG) const { 10672 unsigned Opcode = Node->getMachineOpcode(); 10673 10674 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10675 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10676 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10677 return Node; // not implemented for D16 10678 10679 SDNode *Users[5] = { nullptr }; 10680 unsigned Lane = 0; 10681 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10682 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10683 unsigned NewDmask = 0; 10684 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10685 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10686 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10687 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10688 unsigned TFCLane = 0; 10689 bool HasChain = Node->getNumValues() > 1; 10690 10691 if (OldDmask == 0) { 10692 // These are folded out, but on the chance it happens don't assert. 10693 return Node; 10694 } 10695 10696 unsigned OldBitsSet = countPopulation(OldDmask); 10697 // Work out which is the TFE/LWE lane if that is enabled. 10698 if (UsesTFC) { 10699 TFCLane = OldBitsSet; 10700 } 10701 10702 // Try to figure out the used register components 10703 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10704 I != E; ++I) { 10705 10706 // Don't look at users of the chain. 10707 if (I.getUse().getResNo() != 0) 10708 continue; 10709 10710 // Abort if we can't understand the usage 10711 if (!I->isMachineOpcode() || 10712 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10713 return Node; 10714 10715 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10716 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10717 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10718 // set, etc. 10719 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10720 10721 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10722 if (UsesTFC && Lane == TFCLane) { 10723 Users[Lane] = *I; 10724 } else { 10725 // Set which texture component corresponds to the lane. 10726 unsigned Comp; 10727 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10728 Comp = countTrailingZeros(Dmask); 10729 Dmask &= ~(1 << Comp); 10730 } 10731 10732 // Abort if we have more than one user per component. 10733 if (Users[Lane]) 10734 return Node; 10735 10736 Users[Lane] = *I; 10737 NewDmask |= 1 << Comp; 10738 } 10739 } 10740 10741 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10742 bool NoChannels = !NewDmask; 10743 if (NoChannels) { 10744 if (!UsesTFC) { 10745 // No uses of the result and not using TFC. Then do nothing. 10746 return Node; 10747 } 10748 // If the original dmask has one channel - then nothing to do 10749 if (OldBitsSet == 1) 10750 return Node; 10751 // Use an arbitrary dmask - required for the instruction to work 10752 NewDmask = 1; 10753 } 10754 // Abort if there's no change 10755 if (NewDmask == OldDmask) 10756 return Node; 10757 10758 unsigned BitsSet = countPopulation(NewDmask); 10759 10760 // Check for TFE or LWE - increase the number of channels by one to account 10761 // for the extra return value 10762 // This will need adjustment for D16 if this is also included in 10763 // adjustWriteMask (this function) but at present D16 are excluded. 10764 unsigned NewChannels = BitsSet + UsesTFC; 10765 10766 int NewOpcode = 10767 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10768 assert(NewOpcode != -1 && 10769 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10770 "failed to find equivalent MIMG op"); 10771 10772 // Adjust the writemask in the node 10773 SmallVector<SDValue, 12> Ops; 10774 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10775 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10776 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10777 10778 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10779 10780 MVT ResultVT = NewChannels == 1 ? 10781 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10782 NewChannels == 5 ? 8 : NewChannels); 10783 SDVTList NewVTList = HasChain ? 10784 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10785 10786 10787 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10788 NewVTList, Ops); 10789 10790 if (HasChain) { 10791 // Update chain. 10792 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10793 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10794 } 10795 10796 if (NewChannels == 1) { 10797 assert(Node->hasNUsesOfValue(1, 0)); 10798 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10799 SDLoc(Node), Users[Lane]->getValueType(0), 10800 SDValue(NewNode, 0)); 10801 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10802 return nullptr; 10803 } 10804 10805 // Update the users of the node with the new indices 10806 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10807 SDNode *User = Users[i]; 10808 if (!User) { 10809 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10810 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10811 if (i || !NoChannels) 10812 continue; 10813 } else { 10814 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10815 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10816 } 10817 10818 switch (Idx) { 10819 default: break; 10820 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10821 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10822 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10823 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10824 } 10825 } 10826 10827 DAG.RemoveDeadNode(Node); 10828 return nullptr; 10829 } 10830 10831 static bool isFrameIndexOp(SDValue Op) { 10832 if (Op.getOpcode() == ISD::AssertZext) 10833 Op = Op.getOperand(0); 10834 10835 return isa<FrameIndexSDNode>(Op); 10836 } 10837 10838 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10839 /// with frame index operands. 10840 /// LLVM assumes that inputs are to these instructions are registers. 10841 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10842 SelectionDAG &DAG) const { 10843 if (Node->getOpcode() == ISD::CopyToReg) { 10844 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10845 SDValue SrcVal = Node->getOperand(2); 10846 10847 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10848 // to try understanding copies to physical registers. 10849 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 10850 SDLoc SL(Node); 10851 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10852 SDValue VReg = DAG.getRegister( 10853 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10854 10855 SDNode *Glued = Node->getGluedNode(); 10856 SDValue ToVReg 10857 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10858 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10859 SDValue ToResultReg 10860 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10861 VReg, ToVReg.getValue(1)); 10862 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10863 DAG.RemoveDeadNode(Node); 10864 return ToResultReg.getNode(); 10865 } 10866 } 10867 10868 SmallVector<SDValue, 8> Ops; 10869 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10870 if (!isFrameIndexOp(Node->getOperand(i))) { 10871 Ops.push_back(Node->getOperand(i)); 10872 continue; 10873 } 10874 10875 SDLoc DL(Node); 10876 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10877 Node->getOperand(i).getValueType(), 10878 Node->getOperand(i)), 0)); 10879 } 10880 10881 return DAG.UpdateNodeOperands(Node, Ops); 10882 } 10883 10884 /// Fold the instructions after selecting them. 10885 /// Returns null if users were already updated. 10886 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10887 SelectionDAG &DAG) const { 10888 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10889 unsigned Opcode = Node->getMachineOpcode(); 10890 10891 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10892 !TII->isGather4(Opcode)) { 10893 return adjustWritemask(Node, DAG); 10894 } 10895 10896 if (Opcode == AMDGPU::INSERT_SUBREG || 10897 Opcode == AMDGPU::REG_SEQUENCE) { 10898 legalizeTargetIndependentNode(Node, DAG); 10899 return Node; 10900 } 10901 10902 switch (Opcode) { 10903 case AMDGPU::V_DIV_SCALE_F32: 10904 case AMDGPU::V_DIV_SCALE_F64: { 10905 // Satisfy the operand register constraint when one of the inputs is 10906 // undefined. Ordinarily each undef value will have its own implicit_def of 10907 // a vreg, so force these to use a single register. 10908 SDValue Src0 = Node->getOperand(0); 10909 SDValue Src1 = Node->getOperand(1); 10910 SDValue Src2 = Node->getOperand(2); 10911 10912 if ((Src0.isMachineOpcode() && 10913 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10914 (Src0 == Src1 || Src0 == Src2)) 10915 break; 10916 10917 MVT VT = Src0.getValueType().getSimpleVT(); 10918 const TargetRegisterClass *RC = 10919 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10920 10921 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10922 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10923 10924 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10925 UndefReg, Src0, SDValue()); 10926 10927 // src0 must be the same register as src1 or src2, even if the value is 10928 // undefined, so make sure we don't violate this constraint. 10929 if (Src0.isMachineOpcode() && 10930 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10931 if (Src1.isMachineOpcode() && 10932 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10933 Src0 = Src1; 10934 else if (Src2.isMachineOpcode() && 10935 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10936 Src0 = Src2; 10937 else { 10938 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10939 Src0 = UndefReg; 10940 Src1 = UndefReg; 10941 } 10942 } else 10943 break; 10944 10945 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10946 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10947 Ops.push_back(Node->getOperand(I)); 10948 10949 Ops.push_back(ImpDef.getValue(1)); 10950 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10951 } 10952 default: 10953 break; 10954 } 10955 10956 return Node; 10957 } 10958 10959 /// Assign the register class depending on the number of 10960 /// bits set in the writemask 10961 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10962 SDNode *Node) const { 10963 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10964 10965 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10966 10967 if (TII->isVOP3(MI.getOpcode())) { 10968 // Make sure constant bus requirements are respected. 10969 TII->legalizeOperandsVOP3(MRI, MI); 10970 10971 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10972 // This saves a chain-copy of registers and better ballance register 10973 // use between vgpr and agpr as agpr tuples tend to be big. 10974 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10975 unsigned Opc = MI.getOpcode(); 10976 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10977 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10978 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10979 if (I == -1) 10980 break; 10981 MachineOperand &Op = MI.getOperand(I); 10982 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10983 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10984 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 10985 continue; 10986 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10987 if (!Src || !Src->isCopy() || 10988 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10989 continue; 10990 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10991 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10992 // All uses of agpr64 and agpr32 can also accept vgpr except for 10993 // v_accvgpr_read, but we do not produce agpr reads during selection, 10994 // so no use checks are needed. 10995 MRI.setRegClass(Op.getReg(), NewRC); 10996 } 10997 } 10998 10999 return; 11000 } 11001 11002 // Replace unused atomics with the no return version. 11003 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11004 if (NoRetAtomicOp != -1) { 11005 if (!Node->hasAnyUseOfValue(0)) { 11006 MI.setDesc(TII->get(NoRetAtomicOp)); 11007 MI.RemoveOperand(0); 11008 return; 11009 } 11010 11011 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11012 // instruction, because the return type of these instructions is a vec2 of 11013 // the memory type, so it can be tied to the input operand. 11014 // This means these instructions always have a use, so we need to add a 11015 // special case to check if the atomic has only one extract_subreg use, 11016 // which itself has no uses. 11017 if ((Node->hasNUsesOfValue(1, 0) && 11018 Node->use_begin()->isMachineOpcode() && 11019 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11020 !Node->use_begin()->hasAnyUseOfValue(0))) { 11021 Register Def = MI.getOperand(0).getReg(); 11022 11023 // Change this into a noret atomic. 11024 MI.setDesc(TII->get(NoRetAtomicOp)); 11025 MI.RemoveOperand(0); 11026 11027 // If we only remove the def operand from the atomic instruction, the 11028 // extract_subreg will be left with a use of a vreg without a def. 11029 // So we need to insert an implicit_def to avoid machine verifier 11030 // errors. 11031 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11032 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11033 } 11034 return; 11035 } 11036 } 11037 11038 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11039 uint64_t Val) { 11040 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11041 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11042 } 11043 11044 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11045 const SDLoc &DL, 11046 SDValue Ptr) const { 11047 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11048 11049 // Build the half of the subregister with the constants before building the 11050 // full 128-bit register. If we are building multiple resource descriptors, 11051 // this will allow CSEing of the 2-component register. 11052 const SDValue Ops0[] = { 11053 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11054 buildSMovImm32(DAG, DL, 0), 11055 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11056 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11057 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11058 }; 11059 11060 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11061 MVT::v2i32, Ops0), 0); 11062 11063 // Combine the constants and the pointer. 11064 const SDValue Ops1[] = { 11065 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11066 Ptr, 11067 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11068 SubRegHi, 11069 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11070 }; 11071 11072 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11073 } 11074 11075 /// Return a resource descriptor with the 'Add TID' bit enabled 11076 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11077 /// of the resource descriptor) to create an offset, which is added to 11078 /// the resource pointer. 11079 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11080 SDValue Ptr, uint32_t RsrcDword1, 11081 uint64_t RsrcDword2And3) const { 11082 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11083 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11084 if (RsrcDword1) { 11085 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11086 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11087 0); 11088 } 11089 11090 SDValue DataLo = buildSMovImm32(DAG, DL, 11091 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11092 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11093 11094 const SDValue Ops[] = { 11095 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11096 PtrLo, 11097 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11098 PtrHi, 11099 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11100 DataLo, 11101 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11102 DataHi, 11103 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11104 }; 11105 11106 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11107 } 11108 11109 //===----------------------------------------------------------------------===// 11110 // SI Inline Assembly Support 11111 //===----------------------------------------------------------------------===// 11112 11113 std::pair<unsigned, const TargetRegisterClass *> 11114 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11115 StringRef Constraint, 11116 MVT VT) const { 11117 const TargetRegisterClass *RC = nullptr; 11118 if (Constraint.size() == 1) { 11119 const unsigned BitWidth = VT.getSizeInBits(); 11120 switch (Constraint[0]) { 11121 default: 11122 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11123 case 's': 11124 case 'r': 11125 switch (BitWidth) { 11126 case 16: 11127 RC = &AMDGPU::SReg_32RegClass; 11128 break; 11129 case 64: 11130 RC = &AMDGPU::SGPR_64RegClass; 11131 break; 11132 default: 11133 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11134 if (!RC) 11135 return std::make_pair(0U, nullptr); 11136 break; 11137 } 11138 break; 11139 case 'v': 11140 switch (BitWidth) { 11141 case 16: 11142 RC = &AMDGPU::VGPR_32RegClass; 11143 break; 11144 default: 11145 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11146 if (!RC) 11147 return std::make_pair(0U, nullptr); 11148 break; 11149 } 11150 break; 11151 case 'a': 11152 if (!Subtarget->hasMAIInsts()) 11153 break; 11154 switch (BitWidth) { 11155 case 16: 11156 RC = &AMDGPU::AGPR_32RegClass; 11157 break; 11158 default: 11159 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11160 if (!RC) 11161 return std::make_pair(0U, nullptr); 11162 break; 11163 } 11164 break; 11165 } 11166 // We actually support i128, i16 and f16 as inline parameters 11167 // even if they are not reported as legal 11168 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11169 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11170 return std::make_pair(0U, RC); 11171 } 11172 11173 if (Constraint.size() > 1) { 11174 if (Constraint[1] == 'v') { 11175 RC = &AMDGPU::VGPR_32RegClass; 11176 } else if (Constraint[1] == 's') { 11177 RC = &AMDGPU::SGPR_32RegClass; 11178 } else if (Constraint[1] == 'a') { 11179 RC = &AMDGPU::AGPR_32RegClass; 11180 } 11181 11182 if (RC) { 11183 uint32_t Idx; 11184 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11185 if (!Failed && Idx < RC->getNumRegs()) 11186 return std::make_pair(RC->getRegister(Idx), RC); 11187 } 11188 } 11189 11190 // FIXME: Returns VS_32 for physical SGPR constraints 11191 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11192 } 11193 11194 static bool isImmConstraint(StringRef Constraint) { 11195 if (Constraint.size() == 1) { 11196 switch (Constraint[0]) { 11197 default: break; 11198 case 'I': 11199 case 'J': 11200 case 'A': 11201 case 'B': 11202 case 'C': 11203 return true; 11204 } 11205 } else if (Constraint == "DA" || 11206 Constraint == "DB") { 11207 return true; 11208 } 11209 return false; 11210 } 11211 11212 SITargetLowering::ConstraintType 11213 SITargetLowering::getConstraintType(StringRef Constraint) const { 11214 if (Constraint.size() == 1) { 11215 switch (Constraint[0]) { 11216 default: break; 11217 case 's': 11218 case 'v': 11219 case 'a': 11220 return C_RegisterClass; 11221 } 11222 } 11223 if (isImmConstraint(Constraint)) { 11224 return C_Other; 11225 } 11226 return TargetLowering::getConstraintType(Constraint); 11227 } 11228 11229 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11230 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11231 Val = Val & maskTrailingOnes<uint64_t>(Size); 11232 } 11233 return Val; 11234 } 11235 11236 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11237 std::string &Constraint, 11238 std::vector<SDValue> &Ops, 11239 SelectionDAG &DAG) const { 11240 if (isImmConstraint(Constraint)) { 11241 uint64_t Val; 11242 if (getAsmOperandConstVal(Op, Val) && 11243 checkAsmConstraintVal(Op, Constraint, Val)) { 11244 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11245 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11246 } 11247 } else { 11248 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11249 } 11250 } 11251 11252 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11253 unsigned Size = Op.getScalarValueSizeInBits(); 11254 if (Size > 64) 11255 return false; 11256 11257 if (Size == 16 && !Subtarget->has16BitInsts()) 11258 return false; 11259 11260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11261 Val = C->getSExtValue(); 11262 return true; 11263 } 11264 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11265 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11266 return true; 11267 } 11268 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11269 if (Size != 16 || Op.getNumOperands() != 2) 11270 return false; 11271 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11272 return false; 11273 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11274 Val = C->getSExtValue(); 11275 return true; 11276 } 11277 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11278 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11279 return true; 11280 } 11281 } 11282 11283 return false; 11284 } 11285 11286 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11287 const std::string &Constraint, 11288 uint64_t Val) const { 11289 if (Constraint.size() == 1) { 11290 switch (Constraint[0]) { 11291 case 'I': 11292 return AMDGPU::isInlinableIntLiteral(Val); 11293 case 'J': 11294 return isInt<16>(Val); 11295 case 'A': 11296 return checkAsmConstraintValA(Op, Val); 11297 case 'B': 11298 return isInt<32>(Val); 11299 case 'C': 11300 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11301 AMDGPU::isInlinableIntLiteral(Val); 11302 default: 11303 break; 11304 } 11305 } else if (Constraint.size() == 2) { 11306 if (Constraint == "DA") { 11307 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11308 int64_t LoBits = static_cast<int32_t>(Val); 11309 return checkAsmConstraintValA(Op, HiBits, 32) && 11310 checkAsmConstraintValA(Op, LoBits, 32); 11311 } 11312 if (Constraint == "DB") { 11313 return true; 11314 } 11315 } 11316 llvm_unreachable("Invalid asm constraint"); 11317 } 11318 11319 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11320 uint64_t Val, 11321 unsigned MaxSize) const { 11322 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11323 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11324 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11325 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11326 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11327 return true; 11328 } 11329 return false; 11330 } 11331 11332 // Figure out which registers should be reserved for stack access. Only after 11333 // the function is legalized do we know all of the non-spill stack objects or if 11334 // calls are present. 11335 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11336 MachineRegisterInfo &MRI = MF.getRegInfo(); 11337 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11338 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11339 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11340 11341 if (Info->isEntryFunction()) { 11342 // Callable functions have fixed registers used for stack access. 11343 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11344 } 11345 11346 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11347 Info->getStackPtrOffsetReg())); 11348 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11349 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11350 11351 // We need to worry about replacing the default register with itself in case 11352 // of MIR testcases missing the MFI. 11353 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11354 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11355 11356 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11357 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11358 11359 Info->limitOccupancy(MF); 11360 11361 if (ST.isWave32() && !MF.empty()) { 11362 // Add VCC_HI def because many instructions marked as imp-use VCC where 11363 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11364 // having a use of undef. 11365 11366 const SIInstrInfo *TII = ST.getInstrInfo(); 11367 DebugLoc DL; 11368 11369 MachineBasicBlock &MBB = MF.front(); 11370 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11371 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11372 11373 for (auto &MBB : MF) { 11374 for (auto &MI : MBB) { 11375 TII->fixImplicitOperands(MI); 11376 } 11377 } 11378 } 11379 11380 TargetLoweringBase::finalizeLowering(MF); 11381 11382 // Allocate a VGPR for future SGPR Spill if 11383 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11384 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11385 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11386 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11387 Info->reserveVGPRforSGPRSpills(MF); 11388 } 11389 11390 void SITargetLowering::computeKnownBitsForFrameIndex( 11391 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11392 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11393 11394 // Set the high bits to zero based on the maximum allowed scratch size per 11395 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11396 // calculation won't overflow, so assume the sign bit is never set. 11397 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11398 } 11399 11400 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11401 KnownBits &Known, unsigned Dim) { 11402 unsigned MaxValue = 11403 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11404 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11405 } 11406 11407 void SITargetLowering::computeKnownBitsForTargetInstr( 11408 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11409 const MachineRegisterInfo &MRI, unsigned Depth) const { 11410 const MachineInstr *MI = MRI.getVRegDef(R); 11411 switch (MI->getOpcode()) { 11412 case AMDGPU::G_INTRINSIC: { 11413 switch (MI->getIntrinsicID()) { 11414 case Intrinsic::amdgcn_workitem_id_x: 11415 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11416 break; 11417 case Intrinsic::amdgcn_workitem_id_y: 11418 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11419 break; 11420 case Intrinsic::amdgcn_workitem_id_z: 11421 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11422 break; 11423 case Intrinsic::amdgcn_mbcnt_lo: 11424 case Intrinsic::amdgcn_mbcnt_hi: { 11425 // These return at most the wavefront size - 1. 11426 unsigned Size = MRI.getType(R).getSizeInBits(); 11427 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11428 break; 11429 } 11430 case Intrinsic::amdgcn_groupstaticsize: { 11431 // We can report everything over the maximum size as 0. We can't report 11432 // based on the actual size because we don't know if it's accurate or not 11433 // at any given point. 11434 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11435 break; 11436 } 11437 default: 11438 break; 11439 } 11440 } 11441 } 11442 } 11443 11444 Align SITargetLowering::computeKnownAlignForTargetInstr( 11445 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11446 unsigned Depth) const { 11447 const MachineInstr *MI = MRI.getVRegDef(R); 11448 switch (MI->getOpcode()) { 11449 case AMDGPU::G_INTRINSIC: 11450 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11451 // FIXME: Can this move to generic code? What about the case where the call 11452 // site specifies a lower alignment? 11453 Intrinsic::ID IID = MI->getIntrinsicID(); 11454 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11455 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11456 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11457 return *RetAlign; 11458 return Align(1); 11459 } 11460 default: 11461 return Align(1); 11462 } 11463 } 11464 11465 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11466 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11467 const Align CacheLineAlign = Align(64); 11468 11469 // Pre-GFX10 target did not benefit from loop alignment 11470 if (!ML || DisableLoopAlignment || 11471 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11472 getSubtarget()->hasInstFwdPrefetchBug()) 11473 return PrefAlign; 11474 11475 // On GFX10 I$ is 4 x 64 bytes cache lines. 11476 // By default prefetcher keeps one cache line behind and reads two ahead. 11477 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11478 // behind and one ahead. 11479 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11480 // If loop fits 64 bytes it always spans no more than two cache lines and 11481 // does not need an alignment. 11482 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11483 // Else if loop is less or equal 192 bytes we need two lines behind. 11484 11485 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11486 const MachineBasicBlock *Header = ML->getHeader(); 11487 if (Header->getAlignment() != PrefAlign) 11488 return Header->getAlignment(); // Already processed. 11489 11490 unsigned LoopSize = 0; 11491 for (const MachineBasicBlock *MBB : ML->blocks()) { 11492 // If inner loop block is aligned assume in average half of the alignment 11493 // size to be added as nops. 11494 if (MBB != Header) 11495 LoopSize += MBB->getAlignment().value() / 2; 11496 11497 for (const MachineInstr &MI : *MBB) { 11498 LoopSize += TII->getInstSizeInBytes(MI); 11499 if (LoopSize > 192) 11500 return PrefAlign; 11501 } 11502 } 11503 11504 if (LoopSize <= 64) 11505 return PrefAlign; 11506 11507 if (LoopSize <= 128) 11508 return CacheLineAlign; 11509 11510 // If any of parent loops is surrounded by prefetch instructions do not 11511 // insert new for inner loop, which would reset parent's settings. 11512 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11513 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11514 auto I = Exit->getFirstNonDebugInstr(); 11515 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11516 return CacheLineAlign; 11517 } 11518 } 11519 11520 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11521 MachineBasicBlock *Exit = ML->getExitBlock(); 11522 11523 if (Pre && Exit) { 11524 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11525 TII->get(AMDGPU::S_INST_PREFETCH)) 11526 .addImm(1); // prefetch 2 lines behind PC 11527 11528 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11529 TII->get(AMDGPU::S_INST_PREFETCH)) 11530 .addImm(2); // prefetch 1 line behind PC 11531 } 11532 11533 return CacheLineAlign; 11534 } 11535 11536 LLVM_ATTRIBUTE_UNUSED 11537 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11538 assert(N->getOpcode() == ISD::CopyFromReg); 11539 do { 11540 // Follow the chain until we find an INLINEASM node. 11541 N = N->getOperand(0).getNode(); 11542 if (N->getOpcode() == ISD::INLINEASM || 11543 N->getOpcode() == ISD::INLINEASM_BR) 11544 return true; 11545 } while (N->getOpcode() == ISD::CopyFromReg); 11546 return false; 11547 } 11548 11549 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11550 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11551 { 11552 switch (N->getOpcode()) { 11553 case ISD::CopyFromReg: 11554 { 11555 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11556 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11557 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11558 Register Reg = R->getReg(); 11559 11560 // FIXME: Why does this need to consider isLiveIn? 11561 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11562 return !TRI->isSGPRReg(MRI, Reg); 11563 11564 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11565 return KDA->isDivergent(V); 11566 11567 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11568 return !TRI->isSGPRReg(MRI, Reg); 11569 } 11570 break; 11571 case ISD::LOAD: { 11572 const LoadSDNode *L = cast<LoadSDNode>(N); 11573 unsigned AS = L->getAddressSpace(); 11574 // A flat load may access private memory. 11575 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11576 } break; 11577 case ISD::CALLSEQ_END: 11578 return true; 11579 break; 11580 case ISD::INTRINSIC_WO_CHAIN: 11581 { 11582 11583 } 11584 return AMDGPU::isIntrinsicSourceOfDivergence( 11585 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11586 case ISD::INTRINSIC_W_CHAIN: 11587 return AMDGPU::isIntrinsicSourceOfDivergence( 11588 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11589 } 11590 return false; 11591 } 11592 11593 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11594 EVT VT) const { 11595 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11596 case MVT::f32: 11597 return hasFP32Denormals(DAG.getMachineFunction()); 11598 case MVT::f64: 11599 case MVT::f16: 11600 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11601 default: 11602 return false; 11603 } 11604 } 11605 11606 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11607 const SelectionDAG &DAG, 11608 bool SNaN, 11609 unsigned Depth) const { 11610 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11611 const MachineFunction &MF = DAG.getMachineFunction(); 11612 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11613 11614 if (Info->getMode().DX10Clamp) 11615 return true; // Clamped to 0. 11616 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11617 } 11618 11619 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11620 SNaN, Depth); 11621 } 11622 11623 TargetLowering::AtomicExpansionKind 11624 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11625 switch (RMW->getOperation()) { 11626 case AtomicRMWInst::FAdd: { 11627 Type *Ty = RMW->getType(); 11628 11629 // We don't have a way to support 16-bit atomics now, so just leave them 11630 // as-is. 11631 if (Ty->isHalfTy()) 11632 return AtomicExpansionKind::None; 11633 11634 if (!Ty->isFloatTy()) 11635 return AtomicExpansionKind::CmpXChg; 11636 11637 // TODO: Do have these for flat. Older targets also had them for buffers. 11638 unsigned AS = RMW->getPointerAddressSpace(); 11639 11640 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11641 return RMW->use_empty() ? AtomicExpansionKind::None : 11642 AtomicExpansionKind::CmpXChg; 11643 } 11644 11645 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11646 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11647 } 11648 default: 11649 break; 11650 } 11651 11652 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11653 } 11654 11655 const TargetRegisterClass * 11656 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11657 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11658 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11659 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11660 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11661 : &AMDGPU::SReg_32RegClass; 11662 if (!TRI->isSGPRClass(RC) && !isDivergent) 11663 return TRI->getEquivalentSGPRClass(RC); 11664 else if (TRI->isSGPRClass(RC) && isDivergent) 11665 return TRI->getEquivalentVGPRClass(RC); 11666 11667 return RC; 11668 } 11669 11670 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11671 // uniform values (as produced by the mask results of control flow intrinsics) 11672 // used outside of divergent blocks. The phi users need to also be treated as 11673 // always uniform. 11674 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11675 unsigned WaveSize) { 11676 // FIXME: We asssume we never cast the mask results of a control flow 11677 // intrinsic. 11678 // Early exit if the type won't be consistent as a compile time hack. 11679 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11680 if (!IT || IT->getBitWidth() != WaveSize) 11681 return false; 11682 11683 if (!isa<Instruction>(V)) 11684 return false; 11685 if (!Visited.insert(V).second) 11686 return false; 11687 bool Result = false; 11688 for (auto U : V->users()) { 11689 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11690 if (V == U->getOperand(1)) { 11691 switch (Intrinsic->getIntrinsicID()) { 11692 default: 11693 Result = false; 11694 break; 11695 case Intrinsic::amdgcn_if_break: 11696 case Intrinsic::amdgcn_if: 11697 case Intrinsic::amdgcn_else: 11698 Result = true; 11699 break; 11700 } 11701 } 11702 if (V == U->getOperand(0)) { 11703 switch (Intrinsic->getIntrinsicID()) { 11704 default: 11705 Result = false; 11706 break; 11707 case Intrinsic::amdgcn_end_cf: 11708 case Intrinsic::amdgcn_loop: 11709 Result = true; 11710 break; 11711 } 11712 } 11713 } else { 11714 Result = hasCFUser(U, Visited, WaveSize); 11715 } 11716 if (Result) 11717 break; 11718 } 11719 return Result; 11720 } 11721 11722 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11723 const Value *V) const { 11724 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11725 if (CI->isInlineAsm()) { 11726 // FIXME: This cannot give a correct answer. This should only trigger in 11727 // the case where inline asm returns mixed SGPR and VGPR results, used 11728 // outside the defining block. We don't have a specific result to 11729 // consider, so this assumes if any value is SGPR, the overall register 11730 // also needs to be SGPR. 11731 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11732 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11733 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11734 for (auto &TC : TargetConstraints) { 11735 if (TC.Type == InlineAsm::isOutput) { 11736 ComputeConstraintToUse(TC, SDValue()); 11737 unsigned AssignedReg; 11738 const TargetRegisterClass *RC; 11739 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11740 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11741 if (RC) { 11742 MachineRegisterInfo &MRI = MF.getRegInfo(); 11743 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11744 return true; 11745 else if (SIRI->isSGPRClass(RC)) 11746 return true; 11747 } 11748 } 11749 } 11750 } 11751 } 11752 SmallPtrSet<const Value *, 16> Visited; 11753 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11754 } 11755 11756 std::pair<int, MVT> 11757 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11758 Type *Ty) const { 11759 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11760 auto Size = DL.getTypeSizeInBits(Ty); 11761 // Maximum load or store can handle 8 dwords for scalar and 4 for 11762 // vector ALU. Let's assume anything above 8 dwords is expensive 11763 // even if legal. 11764 if (Size <= 256) 11765 return Cost; 11766 11767 Cost.first = (Size + 255) / 256; 11768 return Cost; 11769 } 11770