1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// \brief Custom DAG lowering for SI 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifdef _MSC_VER 16 // Provide M_PI. 17 #define _USE_MATH_DEFINES 18 #endif 19 20 #include "SIISelLowering.h" 21 #include "AMDGPU.h" 22 #include "AMDGPUIntrinsicInfo.h" 23 #include "AMDGPUSubtarget.h" 24 #include "AMDGPUTargetMachine.h" 25 #include "SIDefines.h" 26 #include "SIInstrInfo.h" 27 #include "SIMachineFunctionInfo.h" 28 #include "SIRegisterInfo.h" 29 #include "Utils/AMDGPUBaseInfo.h" 30 #include "llvm/ADT/APFloat.h" 31 #include "llvm/ADT/APInt.h" 32 #include "llvm/ADT/ArrayRef.h" 33 #include "llvm/ADT/BitVector.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/Twine.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/MachineValueType.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/ValueTypes.h" 56 #include "llvm/IR/Constants.h" 57 #include "llvm/IR/DataLayout.h" 58 #include "llvm/IR/DebugLoc.h" 59 #include "llvm/IR/DerivedTypes.h" 60 #include "llvm/IR/DiagnosticInfo.h" 61 #include "llvm/IR/Function.h" 62 #include "llvm/IR/GlobalValue.h" 63 #include "llvm/IR/InstrTypes.h" 64 #include "llvm/IR/Instruction.h" 65 #include "llvm/IR/Instructions.h" 66 #include "llvm/IR/IntrinsicInst.h" 67 #include "llvm/IR/Type.h" 68 #include "llvm/Support/Casting.h" 69 #include "llvm/Support/CodeGen.h" 70 #include "llvm/Support/CommandLine.h" 71 #include "llvm/Support/Compiler.h" 72 #include "llvm/Support/ErrorHandling.h" 73 #include "llvm/Support/KnownBits.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Target/TargetCallingConv.h" 76 #include "llvm/Target/TargetOptions.h" 77 #include "llvm/Target/TargetRegisterInfo.h" 78 #include <cassert> 79 #include <cmath> 80 #include <cstdint> 81 #include <iterator> 82 #include <tuple> 83 #include <utility> 84 #include <vector> 85 86 using namespace llvm; 87 88 #define DEBUG_TYPE "si-lower" 89 90 STATISTIC(NumTailCalls, "Number of tail calls"); 91 92 static cl::opt<bool> EnableVGPRIndexMode( 93 "amdgpu-vgpr-index-mode", 94 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 95 cl::init(false)); 96 97 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 98 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 99 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 100 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 101 return AMDGPU::SGPR0 + Reg; 102 } 103 } 104 llvm_unreachable("Cannot allocate sgpr"); 105 } 106 107 SITargetLowering::SITargetLowering(const TargetMachine &TM, 108 const SISubtarget &STI) 109 : AMDGPUTargetLowering(TM, STI) { 110 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 111 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 112 113 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 114 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 115 116 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 117 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 118 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 119 120 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 121 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 122 123 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 124 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 125 126 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 127 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 128 129 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 130 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 131 132 if (Subtarget->has16BitInsts()) { 133 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 134 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 135 } 136 137 if (Subtarget->hasVOP3PInsts()) { 138 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 139 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 140 } 141 142 computeRegisterProperties(STI.getRegisterInfo()); 143 144 // We need to custom lower vector stores from local memory 145 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 146 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 147 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 148 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 149 setOperationAction(ISD::LOAD, MVT::i1, Custom); 150 151 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 152 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 153 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 154 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 155 setOperationAction(ISD::STORE, MVT::i1, Custom); 156 157 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 158 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 159 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 160 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 161 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 162 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 163 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 164 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 165 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 166 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 167 168 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 169 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 170 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 171 172 setOperationAction(ISD::SELECT, MVT::i1, Promote); 173 setOperationAction(ISD::SELECT, MVT::i64, Custom); 174 setOperationAction(ISD::SELECT, MVT::f64, Promote); 175 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 176 177 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 178 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 179 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 180 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 181 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 182 183 setOperationAction(ISD::SETCC, MVT::i1, Promote); 184 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 185 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 186 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 187 188 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 189 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 190 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 198 199 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 200 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 201 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 202 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 203 204 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 205 206 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 207 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 208 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 209 210 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 211 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 212 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 213 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 214 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 215 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 216 217 setOperationAction(ISD::UADDO, MVT::i32, Legal); 218 setOperationAction(ISD::USUBO, MVT::i32, Legal); 219 220 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 221 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 222 223 // We only support LOAD/STORE and vector manipulation ops for vectors 224 // with > 4 elements. 225 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 226 MVT::v2i64, MVT::v2f64}) { 227 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 228 switch (Op) { 229 case ISD::LOAD: 230 case ISD::STORE: 231 case ISD::BUILD_VECTOR: 232 case ISD::BITCAST: 233 case ISD::EXTRACT_VECTOR_ELT: 234 case ISD::INSERT_VECTOR_ELT: 235 case ISD::INSERT_SUBVECTOR: 236 case ISD::EXTRACT_SUBVECTOR: 237 case ISD::SCALAR_TO_VECTOR: 238 break; 239 case ISD::CONCAT_VECTORS: 240 setOperationAction(Op, VT, Custom); 241 break; 242 default: 243 setOperationAction(Op, VT, Expand); 244 break; 245 } 246 } 247 } 248 249 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 250 // is expanded to avoid having two separate loops in case the index is a VGPR. 251 252 // Most operations are naturally 32-bit vector operations. We only support 253 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 254 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 255 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 256 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 257 258 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 259 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 260 261 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 262 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 263 264 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 265 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 266 } 267 268 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 269 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 270 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 271 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 272 273 // Avoid stack access for these. 274 // TODO: Generalize to more vector types. 275 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 276 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 277 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 278 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 279 280 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 281 // and output demarshalling 282 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 283 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 284 285 // We can't return success/failure, only the old value, 286 // let LLVM add the comparison 287 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 288 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 289 290 if (getSubtarget()->hasFlatAddressSpace()) { 291 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 292 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 293 } 294 295 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 296 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 297 298 // On SI this is s_memtime and s_memrealtime on VI. 299 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 300 setOperationAction(ISD::TRAP, MVT::Other, Custom); 301 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 302 303 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 304 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 305 306 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 307 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 308 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 309 setOperationAction(ISD::FRINT, MVT::f64, Legal); 310 } 311 312 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 313 314 setOperationAction(ISD::FSIN, MVT::f32, Custom); 315 setOperationAction(ISD::FCOS, MVT::f32, Custom); 316 setOperationAction(ISD::FDIV, MVT::f32, Custom); 317 setOperationAction(ISD::FDIV, MVT::f64, Custom); 318 319 if (Subtarget->has16BitInsts()) { 320 setOperationAction(ISD::Constant, MVT::i16, Legal); 321 322 setOperationAction(ISD::SMIN, MVT::i16, Legal); 323 setOperationAction(ISD::SMAX, MVT::i16, Legal); 324 325 setOperationAction(ISD::UMIN, MVT::i16, Legal); 326 setOperationAction(ISD::UMAX, MVT::i16, Legal); 327 328 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 329 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 330 331 setOperationAction(ISD::ROTR, MVT::i16, Promote); 332 setOperationAction(ISD::ROTL, MVT::i16, Promote); 333 334 setOperationAction(ISD::SDIV, MVT::i16, Promote); 335 setOperationAction(ISD::UDIV, MVT::i16, Promote); 336 setOperationAction(ISD::SREM, MVT::i16, Promote); 337 setOperationAction(ISD::UREM, MVT::i16, Promote); 338 339 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 340 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 341 342 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 343 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 344 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 346 347 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 348 349 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 350 351 setOperationAction(ISD::LOAD, MVT::i16, Custom); 352 353 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 354 355 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 356 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 357 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 358 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 359 360 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 361 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 362 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 363 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 364 365 // F16 - Constant Actions. 366 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 367 368 // F16 - Load/Store Actions. 369 setOperationAction(ISD::LOAD, MVT::f16, Promote); 370 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 371 setOperationAction(ISD::STORE, MVT::f16, Promote); 372 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 373 374 // F16 - VOP1 Actions. 375 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 376 setOperationAction(ISD::FCOS, MVT::f16, Promote); 377 setOperationAction(ISD::FSIN, MVT::f16, Promote); 378 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 379 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 380 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 381 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 382 setOperationAction(ISD::FROUND, MVT::f16, Custom); 383 384 // F16 - VOP2 Actions. 385 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 386 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 387 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 388 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 389 setOperationAction(ISD::FDIV, MVT::f16, Custom); 390 391 // F16 - VOP3 Actions. 392 setOperationAction(ISD::FMA, MVT::f16, Legal); 393 if (!Subtarget->hasFP16Denormals()) 394 setOperationAction(ISD::FMAD, MVT::f16, Legal); 395 } 396 397 if (Subtarget->hasVOP3PInsts()) { 398 for (MVT VT : {MVT::v2i16, MVT::v2f16}) { 399 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 400 switch (Op) { 401 case ISD::LOAD: 402 case ISD::STORE: 403 case ISD::BUILD_VECTOR: 404 case ISD::BITCAST: 405 case ISD::EXTRACT_VECTOR_ELT: 406 case ISD::INSERT_VECTOR_ELT: 407 case ISD::INSERT_SUBVECTOR: 408 case ISD::EXTRACT_SUBVECTOR: 409 case ISD::SCALAR_TO_VECTOR: 410 break; 411 case ISD::CONCAT_VECTORS: 412 setOperationAction(Op, VT, Custom); 413 break; 414 default: 415 setOperationAction(Op, VT, Expand); 416 break; 417 } 418 } 419 } 420 421 // XXX - Do these do anything? Vector constants turn into build_vector. 422 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 423 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 424 425 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 426 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 427 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 428 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 429 430 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 431 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 432 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 433 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 434 435 setOperationAction(ISD::AND, MVT::v2i16, Promote); 436 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 437 setOperationAction(ISD::OR, MVT::v2i16, Promote); 438 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 439 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 440 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 441 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 442 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 443 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 444 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 445 446 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 447 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 448 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 449 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 450 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 451 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 452 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 453 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 454 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 455 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 456 457 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 458 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 459 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 460 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 461 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal); 462 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal); 463 464 // This isn't really legal, but this avoids the legalizer unrolling it (and 465 // allows matching fneg (fabs x) patterns) 466 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 467 468 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 470 471 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 472 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 473 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 474 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 475 } else { 476 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 477 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 478 } 479 480 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 481 setOperationAction(ISD::SELECT, VT, Custom); 482 } 483 484 setTargetDAGCombine(ISD::ADD); 485 setTargetDAGCombine(ISD::ADDCARRY); 486 setTargetDAGCombine(ISD::SUB); 487 setTargetDAGCombine(ISD::SUBCARRY); 488 setTargetDAGCombine(ISD::FADD); 489 setTargetDAGCombine(ISD::FSUB); 490 setTargetDAGCombine(ISD::FMINNUM); 491 setTargetDAGCombine(ISD::FMAXNUM); 492 setTargetDAGCombine(ISD::SMIN); 493 setTargetDAGCombine(ISD::SMAX); 494 setTargetDAGCombine(ISD::UMIN); 495 setTargetDAGCombine(ISD::UMAX); 496 setTargetDAGCombine(ISD::SETCC); 497 setTargetDAGCombine(ISD::AND); 498 setTargetDAGCombine(ISD::OR); 499 setTargetDAGCombine(ISD::XOR); 500 setTargetDAGCombine(ISD::SINT_TO_FP); 501 setTargetDAGCombine(ISD::UINT_TO_FP); 502 setTargetDAGCombine(ISD::FCANONICALIZE); 503 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 504 setTargetDAGCombine(ISD::ZERO_EXTEND); 505 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 506 setTargetDAGCombine(ISD::BUILD_VECTOR); 507 508 // All memory operations. Some folding on the pointer operand is done to help 509 // matching the constant offsets in the addressing modes. 510 setTargetDAGCombine(ISD::LOAD); 511 setTargetDAGCombine(ISD::STORE); 512 setTargetDAGCombine(ISD::ATOMIC_LOAD); 513 setTargetDAGCombine(ISD::ATOMIC_STORE); 514 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 515 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 516 setTargetDAGCombine(ISD::ATOMIC_SWAP); 517 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 518 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 519 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 520 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 521 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 522 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 523 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 524 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 525 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 526 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 527 528 setSchedulingPreference(Sched::RegPressure); 529 } 530 531 const SISubtarget *SITargetLowering::getSubtarget() const { 532 return static_cast<const SISubtarget *>(Subtarget); 533 } 534 535 //===----------------------------------------------------------------------===// 536 // TargetLowering queries 537 //===----------------------------------------------------------------------===// 538 539 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 540 // SI has some legal vector types, but no legal vector operations. Say no 541 // shuffles are legal in order to prefer scalarizing some vector operations. 542 return false; 543 } 544 545 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 546 const CallInst &CI, 547 unsigned IntrID) const { 548 switch (IntrID) { 549 case Intrinsic::amdgcn_atomic_inc: 550 case Intrinsic::amdgcn_atomic_dec: { 551 Info.opc = ISD::INTRINSIC_W_CHAIN; 552 Info.memVT = MVT::getVT(CI.getType()); 553 Info.ptrVal = CI.getOperand(0); 554 Info.align = 0; 555 556 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 557 Info.vol = !Vol || !Vol->isZero(); 558 Info.readMem = true; 559 Info.writeMem = true; 560 return true; 561 } 562 default: 563 return false; 564 } 565 } 566 567 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 568 SmallVectorImpl<Value*> &Ops, 569 Type *&AccessTy) const { 570 switch (II->getIntrinsicID()) { 571 case Intrinsic::amdgcn_atomic_inc: 572 case Intrinsic::amdgcn_atomic_dec: { 573 Value *Ptr = II->getArgOperand(0); 574 AccessTy = II->getType(); 575 Ops.push_back(Ptr); 576 return true; 577 } 578 default: 579 return false; 580 } 581 } 582 583 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 584 if (!Subtarget->hasFlatInstOffsets()) { 585 // Flat instructions do not have offsets, and only have the register 586 // address. 587 return AM.BaseOffs == 0 && AM.Scale == 0; 588 } 589 590 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 591 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 592 593 // Just r + i 594 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 595 } 596 597 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 598 if (Subtarget->hasFlatGlobalInsts()) 599 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 600 601 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 602 // Assume the we will use FLAT for all global memory accesses 603 // on VI. 604 // FIXME: This assumption is currently wrong. On VI we still use 605 // MUBUF instructions for the r + i addressing mode. As currently 606 // implemented, the MUBUF instructions only work on buffer < 4GB. 607 // It may be possible to support > 4GB buffers with MUBUF instructions, 608 // by setting the stride value in the resource descriptor which would 609 // increase the size limit to (stride * 4GB). However, this is risky, 610 // because it has never been validated. 611 return isLegalFlatAddressingMode(AM); 612 } 613 614 return isLegalMUBUFAddressingMode(AM); 615 } 616 617 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 618 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 619 // additionally can do r + r + i with addr64. 32-bit has more addressing 620 // mode options. Depending on the resource constant, it can also do 621 // (i64 r0) + (i32 r1) * (i14 i). 622 // 623 // Private arrays end up using a scratch buffer most of the time, so also 624 // assume those use MUBUF instructions. Scratch loads / stores are currently 625 // implemented as mubuf instructions with offen bit set, so slightly 626 // different than the normal addr64. 627 if (!isUInt<12>(AM.BaseOffs)) 628 return false; 629 630 // FIXME: Since we can split immediate into soffset and immediate offset, 631 // would it make sense to allow any immediate? 632 633 switch (AM.Scale) { 634 case 0: // r + i or just i, depending on HasBaseReg. 635 return true; 636 case 1: 637 return true; // We have r + r or r + i. 638 case 2: 639 if (AM.HasBaseReg) { 640 // Reject 2 * r + r. 641 return false; 642 } 643 644 // Allow 2 * r as r + r 645 // Or 2 * r + i is allowed as r + r + i. 646 return true; 647 default: // Don't allow n * r 648 return false; 649 } 650 } 651 652 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 653 const AddrMode &AM, Type *Ty, 654 unsigned AS, Instruction *I) const { 655 // No global is ever allowed as a base. 656 if (AM.BaseGV) 657 return false; 658 659 if (AS == AMDGPUASI.GLOBAL_ADDRESS) 660 return isLegalGlobalAddressingMode(AM); 661 662 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 663 // If the offset isn't a multiple of 4, it probably isn't going to be 664 // correctly aligned. 665 // FIXME: Can we get the real alignment here? 666 if (AM.BaseOffs % 4 != 0) 667 return isLegalMUBUFAddressingMode(AM); 668 669 // There are no SMRD extloads, so if we have to do a small type access we 670 // will use a MUBUF load. 671 // FIXME?: We also need to do this if unaligned, but we don't know the 672 // alignment here. 673 if (DL.getTypeStoreSize(Ty) < 4) 674 return isLegalGlobalAddressingMode(AM); 675 676 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 677 // SMRD instructions have an 8-bit, dword offset on SI. 678 if (!isUInt<8>(AM.BaseOffs / 4)) 679 return false; 680 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 681 // On CI+, this can also be a 32-bit literal constant offset. If it fits 682 // in 8-bits, it can use a smaller encoding. 683 if (!isUInt<32>(AM.BaseOffs / 4)) 684 return false; 685 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 686 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 687 if (!isUInt<20>(AM.BaseOffs)) 688 return false; 689 } else 690 llvm_unreachable("unhandled generation"); 691 692 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 693 return true; 694 695 if (AM.Scale == 1 && AM.HasBaseReg) 696 return true; 697 698 return false; 699 700 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 701 return isLegalMUBUFAddressingMode(AM); 702 } else if (AS == AMDGPUASI.LOCAL_ADDRESS || 703 AS == AMDGPUASI.REGION_ADDRESS) { 704 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 705 // field. 706 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 707 // an 8-bit dword offset but we don't know the alignment here. 708 if (!isUInt<16>(AM.BaseOffs)) 709 return false; 710 711 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 712 return true; 713 714 if (AM.Scale == 1 && AM.HasBaseReg) 715 return true; 716 717 return false; 718 } else if (AS == AMDGPUASI.FLAT_ADDRESS || 719 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) { 720 // For an unknown address space, this usually means that this is for some 721 // reason being used for pure arithmetic, and not based on some addressing 722 // computation. We don't have instructions that compute pointers with any 723 // addressing modes, so treat them as having no offset like flat 724 // instructions. 725 return isLegalFlatAddressingMode(AM); 726 } else { 727 llvm_unreachable("unhandled address space"); 728 } 729 } 730 731 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 732 const SelectionDAG &DAG) const { 733 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) { 734 return (MemVT.getSizeInBits() <= 4 * 32); 735 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 736 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 737 return (MemVT.getSizeInBits() <= MaxPrivateBits); 738 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 739 return (MemVT.getSizeInBits() <= 2 * 32); 740 } 741 return true; 742 } 743 744 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 745 unsigned AddrSpace, 746 unsigned Align, 747 bool *IsFast) const { 748 if (IsFast) 749 *IsFast = false; 750 751 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 752 // which isn't a simple VT. 753 // Until MVT is extended to handle this, simply check for the size and 754 // rely on the condition below: allow accesses if the size is a multiple of 4. 755 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 756 VT.getStoreSize() > 16)) { 757 return false; 758 } 759 760 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS || 761 AddrSpace == AMDGPUASI.REGION_ADDRESS) { 762 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 763 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 764 // with adjacent offsets. 765 bool AlignedBy4 = (Align % 4 == 0); 766 if (IsFast) 767 *IsFast = AlignedBy4; 768 769 return AlignedBy4; 770 } 771 772 // FIXME: We have to be conservative here and assume that flat operations 773 // will access scratch. If we had access to the IR function, then we 774 // could determine if any private memory was used in the function. 775 if (!Subtarget->hasUnalignedScratchAccess() && 776 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS || 777 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) { 778 return false; 779 } 780 781 if (Subtarget->hasUnalignedBufferAccess()) { 782 // If we have an uniform constant load, it still requires using a slow 783 // buffer instruction if unaligned. 784 if (IsFast) { 785 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ? 786 (Align % 4 == 0) : true; 787 } 788 789 return true; 790 } 791 792 // Smaller than dword value must be aligned. 793 if (VT.bitsLT(MVT::i32)) 794 return false; 795 796 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 797 // byte-address are ignored, thus forcing Dword alignment. 798 // This applies to private, global, and constant memory. 799 if (IsFast) 800 *IsFast = true; 801 802 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 803 } 804 805 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 806 unsigned SrcAlign, bool IsMemset, 807 bool ZeroMemset, 808 bool MemcpyStrSrc, 809 MachineFunction &MF) const { 810 // FIXME: Should account for address space here. 811 812 // The default fallback uses the private pointer size as a guess for a type to 813 // use. Make sure we switch these to 64-bit accesses. 814 815 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 816 return MVT::v4i32; 817 818 if (Size >= 8 && DstAlign >= 4) 819 return MVT::v2i32; 820 821 // Use the default. 822 return MVT::Other; 823 } 824 825 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) { 826 return AS == AMDGPUASI.GLOBAL_ADDRESS || 827 AS == AMDGPUASI.FLAT_ADDRESS || 828 AS == AMDGPUASI.CONSTANT_ADDRESS; 829 } 830 831 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 832 unsigned DestAS) const { 833 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) && 834 isFlatGlobalAddrSpace(DestAS, AMDGPUASI); 835 } 836 837 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 838 const MemSDNode *MemNode = cast<MemSDNode>(N); 839 const Value *Ptr = MemNode->getMemOperand()->getValue(); 840 const Instruction *I = dyn_cast<Instruction>(Ptr); 841 return I && I->getMetadata("amdgpu.noclobber"); 842 } 843 844 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS, 845 unsigned DestAS) const { 846 // Flat -> private/local is a simple truncate. 847 // Flat -> global is no-op 848 if (SrcAS == AMDGPUASI.FLAT_ADDRESS) 849 return true; 850 851 return isNoopAddrSpaceCast(SrcAS, DestAS); 852 } 853 854 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 855 const MemSDNode *MemNode = cast<MemSDNode>(N); 856 857 return AMDGPU::isUniformMMO(MemNode->getMemOperand()); 858 } 859 860 TargetLoweringBase::LegalizeTypeAction 861 SITargetLowering::getPreferredVectorAction(EVT VT) const { 862 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 863 return TypeSplitVector; 864 865 return TargetLoweringBase::getPreferredVectorAction(VT); 866 } 867 868 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 869 Type *Ty) const { 870 // FIXME: Could be smarter if called for vector constants. 871 return true; 872 } 873 874 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 875 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 876 switch (Op) { 877 case ISD::LOAD: 878 case ISD::STORE: 879 880 // These operations are done with 32-bit instructions anyway. 881 case ISD::AND: 882 case ISD::OR: 883 case ISD::XOR: 884 case ISD::SELECT: 885 // TODO: Extensions? 886 return true; 887 default: 888 return false; 889 } 890 } 891 892 // SimplifySetCC uses this function to determine whether or not it should 893 // create setcc with i1 operands. We don't have instructions for i1 setcc. 894 if (VT == MVT::i1 && Op == ISD::SETCC) 895 return false; 896 897 return TargetLowering::isTypeDesirableForOp(Op, VT); 898 } 899 900 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 901 const SDLoc &SL, 902 SDValue Chain, 903 uint64_t Offset) const { 904 const DataLayout &DL = DAG.getDataLayout(); 905 MachineFunction &MF = DAG.getMachineFunction(); 906 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 907 908 const ArgDescriptor *InputPtrReg; 909 const TargetRegisterClass *RC; 910 911 std::tie(InputPtrReg, RC) 912 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 913 914 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 915 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS); 916 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 917 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 918 919 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 920 DAG.getConstant(Offset, SL, PtrVT)); 921 } 922 923 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 924 const SDLoc &SL) const { 925 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 926 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 927 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 928 } 929 930 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 931 const SDLoc &SL, SDValue Val, 932 bool Signed, 933 const ISD::InputArg *Arg) const { 934 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 935 VT.bitsLT(MemVT)) { 936 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 937 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 938 } 939 940 if (MemVT.isFloatingPoint()) 941 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 942 else if (Signed) 943 Val = DAG.getSExtOrTrunc(Val, SL, VT); 944 else 945 Val = DAG.getZExtOrTrunc(Val, SL, VT); 946 947 return Val; 948 } 949 950 SDValue SITargetLowering::lowerKernargMemParameter( 951 SelectionDAG &DAG, EVT VT, EVT MemVT, 952 const SDLoc &SL, SDValue Chain, 953 uint64_t Offset, bool Signed, 954 const ISD::InputArg *Arg) const { 955 const DataLayout &DL = DAG.getDataLayout(); 956 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 957 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 958 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 959 960 unsigned Align = DL.getABITypeAlignment(Ty); 961 962 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 963 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 964 MachineMemOperand::MONonTemporal | 965 MachineMemOperand::MODereferenceable | 966 MachineMemOperand::MOInvariant); 967 968 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 969 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 970 } 971 972 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 973 const SDLoc &SL, SDValue Chain, 974 const ISD::InputArg &Arg) const { 975 MachineFunction &MF = DAG.getMachineFunction(); 976 MachineFrameInfo &MFI = MF.getFrameInfo(); 977 978 if (Arg.Flags.isByVal()) { 979 unsigned Size = Arg.Flags.getByValSize(); 980 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 981 return DAG.getFrameIndex(FrameIdx, MVT::i32); 982 } 983 984 unsigned ArgOffset = VA.getLocMemOffset(); 985 unsigned ArgSize = VA.getValVT().getStoreSize(); 986 987 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 988 989 // Create load nodes to retrieve arguments from the stack. 990 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 991 SDValue ArgValue; 992 993 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 994 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 995 MVT MemVT = VA.getValVT(); 996 997 switch (VA.getLocInfo()) { 998 default: 999 break; 1000 case CCValAssign::BCvt: 1001 MemVT = VA.getLocVT(); 1002 break; 1003 case CCValAssign::SExt: 1004 ExtType = ISD::SEXTLOAD; 1005 break; 1006 case CCValAssign::ZExt: 1007 ExtType = ISD::ZEXTLOAD; 1008 break; 1009 case CCValAssign::AExt: 1010 ExtType = ISD::EXTLOAD; 1011 break; 1012 } 1013 1014 ArgValue = DAG.getExtLoad( 1015 ExtType, SL, VA.getLocVT(), Chain, FIN, 1016 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1017 MemVT); 1018 return ArgValue; 1019 } 1020 1021 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1022 const SIMachineFunctionInfo &MFI, 1023 EVT VT, 1024 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1025 const ArgDescriptor *Reg; 1026 const TargetRegisterClass *RC; 1027 1028 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1029 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1030 } 1031 1032 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1033 CallingConv::ID CallConv, 1034 ArrayRef<ISD::InputArg> Ins, 1035 BitVector &Skipped, 1036 FunctionType *FType, 1037 SIMachineFunctionInfo *Info) { 1038 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1039 const ISD::InputArg &Arg = Ins[I]; 1040 1041 // First check if it's a PS input addr. 1042 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 1043 !Arg.Flags.isByVal() && PSInputNum <= 15) { 1044 1045 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 1046 // We can safely skip PS inputs. 1047 Skipped.set(I); 1048 ++PSInputNum; 1049 continue; 1050 } 1051 1052 Info->markPSInputAllocated(PSInputNum); 1053 if (Arg.Used) 1054 Info->markPSInputEnabled(PSInputNum); 1055 1056 ++PSInputNum; 1057 } 1058 1059 // Second split vertices into their elements. 1060 if (Arg.VT.isVector()) { 1061 ISD::InputArg NewArg = Arg; 1062 NewArg.Flags.setSplit(); 1063 NewArg.VT = Arg.VT.getVectorElementType(); 1064 1065 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 1066 // three or five element vertex only needs three or five registers, 1067 // NOT four or eight. 1068 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1069 unsigned NumElements = ParamType->getVectorNumElements(); 1070 1071 for (unsigned J = 0; J != NumElements; ++J) { 1072 Splits.push_back(NewArg); 1073 NewArg.PartOffset += NewArg.VT.getStoreSize(); 1074 } 1075 } else { 1076 Splits.push_back(Arg); 1077 } 1078 } 1079 } 1080 1081 // Allocate special inputs passed in VGPRs. 1082 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1083 MachineFunction &MF, 1084 const SIRegisterInfo &TRI, 1085 SIMachineFunctionInfo &Info) { 1086 if (Info.hasWorkItemIDX()) { 1087 unsigned Reg = AMDGPU::VGPR0; 1088 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1089 1090 CCInfo.AllocateReg(Reg); 1091 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1092 } 1093 1094 if (Info.hasWorkItemIDY()) { 1095 unsigned Reg = AMDGPU::VGPR1; 1096 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1097 1098 CCInfo.AllocateReg(Reg); 1099 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1100 } 1101 1102 if (Info.hasWorkItemIDZ()) { 1103 unsigned Reg = AMDGPU::VGPR2; 1104 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1105 1106 CCInfo.AllocateReg(Reg); 1107 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1108 } 1109 } 1110 1111 // Try to allocate a VGPR at the end of the argument list, or if no argument 1112 // VGPRs are left allocating a stack slot. 1113 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) { 1114 ArrayRef<MCPhysReg> ArgVGPRs 1115 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1116 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1117 if (RegIdx == ArgVGPRs.size()) { 1118 // Spill to stack required. 1119 int64_t Offset = CCInfo.AllocateStack(4, 4); 1120 1121 return ArgDescriptor::createStack(Offset); 1122 } 1123 1124 unsigned Reg = ArgVGPRs[RegIdx]; 1125 Reg = CCInfo.AllocateReg(Reg); 1126 assert(Reg != AMDGPU::NoRegister); 1127 1128 MachineFunction &MF = CCInfo.getMachineFunction(); 1129 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1130 return ArgDescriptor::createRegister(Reg); 1131 } 1132 1133 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1134 const TargetRegisterClass *RC, 1135 unsigned NumArgRegs) { 1136 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1137 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1138 if (RegIdx == ArgSGPRs.size()) 1139 report_fatal_error("ran out of SGPRs for arguments"); 1140 1141 unsigned Reg = ArgSGPRs[RegIdx]; 1142 Reg = CCInfo.AllocateReg(Reg); 1143 assert(Reg != AMDGPU::NoRegister); 1144 1145 MachineFunction &MF = CCInfo.getMachineFunction(); 1146 MF.addLiveIn(Reg, RC); 1147 return ArgDescriptor::createRegister(Reg); 1148 } 1149 1150 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1151 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1152 } 1153 1154 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1155 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1156 } 1157 1158 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1159 MachineFunction &MF, 1160 const SIRegisterInfo &TRI, 1161 SIMachineFunctionInfo &Info) { 1162 if (Info.hasWorkItemIDX()) 1163 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo)); 1164 1165 if (Info.hasWorkItemIDY()) 1166 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo)); 1167 1168 if (Info.hasWorkItemIDZ()) 1169 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo)); 1170 } 1171 1172 static void allocateSpecialInputSGPRs(CCState &CCInfo, 1173 MachineFunction &MF, 1174 const SIRegisterInfo &TRI, 1175 SIMachineFunctionInfo &Info) { 1176 auto &ArgInfo = Info.getArgInfo(); 1177 1178 // TODO: Unify handling with private memory pointers. 1179 1180 if (Info.hasDispatchPtr()) 1181 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1182 1183 if (Info.hasQueuePtr()) 1184 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1185 1186 if (Info.hasKernargSegmentPtr()) 1187 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1188 1189 if (Info.hasDispatchID()) 1190 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1191 1192 // flat_scratch_init is not applicable for non-kernel functions. 1193 1194 if (Info.hasWorkGroupIDX()) 1195 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1196 1197 if (Info.hasWorkGroupIDY()) 1198 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1199 1200 if (Info.hasWorkGroupIDZ()) 1201 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1202 1203 if (Info.hasImplicitArgPtr()) 1204 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1205 } 1206 1207 // Allocate special inputs passed in user SGPRs. 1208 static void allocateHSAUserSGPRs(CCState &CCInfo, 1209 MachineFunction &MF, 1210 const SIRegisterInfo &TRI, 1211 SIMachineFunctionInfo &Info) { 1212 if (Info.hasImplicitBufferPtr()) { 1213 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1214 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1215 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1216 } 1217 1218 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1219 if (Info.hasPrivateSegmentBuffer()) { 1220 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1221 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1222 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1223 } 1224 1225 if (Info.hasDispatchPtr()) { 1226 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1227 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1228 CCInfo.AllocateReg(DispatchPtrReg); 1229 } 1230 1231 if (Info.hasQueuePtr()) { 1232 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1233 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1234 CCInfo.AllocateReg(QueuePtrReg); 1235 } 1236 1237 if (Info.hasKernargSegmentPtr()) { 1238 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1239 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1240 CCInfo.AllocateReg(InputPtrReg); 1241 } 1242 1243 if (Info.hasDispatchID()) { 1244 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1245 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1246 CCInfo.AllocateReg(DispatchIDReg); 1247 } 1248 1249 if (Info.hasFlatScratchInit()) { 1250 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1251 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1252 CCInfo.AllocateReg(FlatScratchInitReg); 1253 } 1254 1255 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1256 // these from the dispatch pointer. 1257 } 1258 1259 // Allocate special input registers that are initialized per-wave. 1260 static void allocateSystemSGPRs(CCState &CCInfo, 1261 MachineFunction &MF, 1262 SIMachineFunctionInfo &Info, 1263 CallingConv::ID CallConv, 1264 bool IsShader) { 1265 if (Info.hasWorkGroupIDX()) { 1266 unsigned Reg = Info.addWorkGroupIDX(); 1267 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1268 CCInfo.AllocateReg(Reg); 1269 } 1270 1271 if (Info.hasWorkGroupIDY()) { 1272 unsigned Reg = Info.addWorkGroupIDY(); 1273 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1274 CCInfo.AllocateReg(Reg); 1275 } 1276 1277 if (Info.hasWorkGroupIDZ()) { 1278 unsigned Reg = Info.addWorkGroupIDZ(); 1279 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1280 CCInfo.AllocateReg(Reg); 1281 } 1282 1283 if (Info.hasWorkGroupInfo()) { 1284 unsigned Reg = Info.addWorkGroupInfo(); 1285 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1286 CCInfo.AllocateReg(Reg); 1287 } 1288 1289 if (Info.hasPrivateSegmentWaveByteOffset()) { 1290 // Scratch wave offset passed in system SGPR. 1291 unsigned PrivateSegmentWaveByteOffsetReg; 1292 1293 if (IsShader) { 1294 PrivateSegmentWaveByteOffsetReg = 1295 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1296 1297 // This is true if the scratch wave byte offset doesn't have a fixed 1298 // location. 1299 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1300 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1301 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1302 } 1303 } else 1304 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1305 1306 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1307 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1308 } 1309 } 1310 1311 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1312 MachineFunction &MF, 1313 const SIRegisterInfo &TRI, 1314 SIMachineFunctionInfo &Info) { 1315 // Now that we've figured out where the scratch register inputs are, see if 1316 // should reserve the arguments and use them directly. 1317 MachineFrameInfo &MFI = MF.getFrameInfo(); 1318 bool HasStackObjects = MFI.hasStackObjects(); 1319 1320 // Record that we know we have non-spill stack objects so we don't need to 1321 // check all stack objects later. 1322 if (HasStackObjects) 1323 Info.setHasNonSpillStackObjects(true); 1324 1325 // Everything live out of a block is spilled with fast regalloc, so it's 1326 // almost certain that spilling will be required. 1327 if (TM.getOptLevel() == CodeGenOpt::None) 1328 HasStackObjects = true; 1329 1330 // For now assume stack access is needed in any callee functions, so we need 1331 // the scratch registers to pass in. 1332 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1333 1334 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1335 if (ST.isAmdCodeObjectV2(MF)) { 1336 if (RequiresStackAccess) { 1337 // If we have stack objects, we unquestionably need the private buffer 1338 // resource. For the Code Object V2 ABI, this will be the first 4 user 1339 // SGPR inputs. We can reserve those and use them directly. 1340 1341 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg( 1342 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1343 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1344 1345 if (MFI.hasCalls()) { 1346 // If we have calls, we need to keep the frame register in a register 1347 // that won't be clobbered by a call, so ensure it is copied somewhere. 1348 1349 // This is not a problem for the scratch wave offset, because the same 1350 // registers are reserved in all functions. 1351 1352 // FIXME: Nothing is really ensuring this is a call preserved register, 1353 // it's just selected from the end so it happens to be. 1354 unsigned ReservedOffsetReg 1355 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1356 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1357 } else { 1358 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg( 1359 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1360 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 1361 } 1362 } else { 1363 unsigned ReservedBufferReg 1364 = TRI.reservedPrivateSegmentBufferReg(MF); 1365 unsigned ReservedOffsetReg 1366 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1367 1368 // We tentatively reserve the last registers (skipping the last two 1369 // which may contain VCC). After register allocation, we'll replace 1370 // these with the ones immediately after those which were really 1371 // allocated. In the prologue copies will be inserted from the argument 1372 // to these reserved registers. 1373 Info.setScratchRSrcReg(ReservedBufferReg); 1374 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1375 } 1376 } else { 1377 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1378 1379 // Without HSA, relocations are used for the scratch pointer and the 1380 // buffer resource setup is always inserted in the prologue. Scratch wave 1381 // offset is still in an input SGPR. 1382 Info.setScratchRSrcReg(ReservedBufferReg); 1383 1384 if (HasStackObjects && !MFI.hasCalls()) { 1385 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg( 1386 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1387 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1388 } else { 1389 unsigned ReservedOffsetReg 1390 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1391 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1392 } 1393 } 1394 } 1395 1396 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1397 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1398 return !Info->isEntryFunction(); 1399 } 1400 1401 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1402 1403 } 1404 1405 void SITargetLowering::insertCopiesSplitCSR( 1406 MachineBasicBlock *Entry, 1407 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1408 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1409 1410 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1411 if (!IStart) 1412 return; 1413 1414 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1415 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1416 MachineBasicBlock::iterator MBBI = Entry->begin(); 1417 for (const MCPhysReg *I = IStart; *I; ++I) { 1418 const TargetRegisterClass *RC = nullptr; 1419 if (AMDGPU::SReg_64RegClass.contains(*I)) 1420 RC = &AMDGPU::SGPR_64RegClass; 1421 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1422 RC = &AMDGPU::SGPR_32RegClass; 1423 else 1424 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1425 1426 unsigned NewVR = MRI->createVirtualRegister(RC); 1427 // Create copy from CSR to a virtual register. 1428 Entry->addLiveIn(*I); 1429 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1430 .addReg(*I); 1431 1432 // Insert the copy-back instructions right before the terminator. 1433 for (auto *Exit : Exits) 1434 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1435 TII->get(TargetOpcode::COPY), *I) 1436 .addReg(NewVR); 1437 } 1438 } 1439 1440 SDValue SITargetLowering::LowerFormalArguments( 1441 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1442 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1443 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1444 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1445 1446 MachineFunction &MF = DAG.getMachineFunction(); 1447 FunctionType *FType = MF.getFunction()->getFunctionType(); 1448 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1449 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1450 1451 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1452 const Function *Fn = MF.getFunction(); 1453 DiagnosticInfoUnsupported NoGraphicsHSA( 1454 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 1455 DAG.getContext()->diagnose(NoGraphicsHSA); 1456 return DAG.getEntryNode(); 1457 } 1458 1459 // Create stack objects that are used for emitting debugger prologue if 1460 // "amdgpu-debugger-emit-prologue" attribute was specified. 1461 if (ST.debuggerEmitPrologue()) 1462 createDebuggerPrologueStackObjects(MF); 1463 1464 SmallVector<ISD::InputArg, 16> Splits; 1465 SmallVector<CCValAssign, 16> ArgLocs; 1466 BitVector Skipped(Ins.size()); 1467 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1468 *DAG.getContext()); 1469 1470 bool IsShader = AMDGPU::isShader(CallConv); 1471 bool IsKernel = AMDGPU::isKernel(CallConv); 1472 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 1473 1474 if (!IsEntryFunc) { 1475 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over 1476 // this when allocating argument fixed offsets. 1477 CCInfo.AllocateStack(4, 4); 1478 } 1479 1480 if (IsShader) { 1481 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 1482 1483 // At least one interpolation mode must be enabled or else the GPU will 1484 // hang. 1485 // 1486 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 1487 // set PSInputAddr, the user wants to enable some bits after the compilation 1488 // based on run-time states. Since we can't know what the final PSInputEna 1489 // will look like, so we shouldn't do anything here and the user should take 1490 // responsibility for the correct programming. 1491 // 1492 // Otherwise, the following restrictions apply: 1493 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 1494 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 1495 // enabled too. 1496 if (CallConv == CallingConv::AMDGPU_PS) { 1497 if ((Info->getPSInputAddr() & 0x7F) == 0 || 1498 ((Info->getPSInputAddr() & 0xF) == 0 && 1499 Info->isPSInputAllocated(11))) { 1500 CCInfo.AllocateReg(AMDGPU::VGPR0); 1501 CCInfo.AllocateReg(AMDGPU::VGPR1); 1502 Info->markPSInputAllocated(0); 1503 Info->markPSInputEnabled(0); 1504 } 1505 if (Subtarget->isAmdPalOS()) { 1506 // For isAmdPalOS, the user does not enable some bits after compilation 1507 // based on run-time states; the register values being generated here are 1508 // the final ones set in hardware. Therefore we need to apply the 1509 // workaround to PSInputAddr and PSInputEnable together. (The case where 1510 // a bit is set in PSInputAddr but not PSInputEnable is where the 1511 // frontend set up an input arg for a particular interpolation mode, but 1512 // nothing uses that input arg. Really we should have an earlier pass 1513 // that removes such an arg.) 1514 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 1515 if ((PsInputBits & 0x7F) == 0 || 1516 ((PsInputBits & 0xF) == 0 && 1517 (PsInputBits >> 11 & 1))) 1518 Info->markPSInputEnabled( 1519 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 1520 } 1521 } 1522 1523 assert(!Info->hasDispatchPtr() && 1524 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 1525 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 1526 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 1527 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 1528 !Info->hasWorkItemIDZ()); 1529 } else if (IsKernel) { 1530 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 1531 } else { 1532 Splits.append(Ins.begin(), Ins.end()); 1533 } 1534 1535 if (IsEntryFunc) { 1536 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 1537 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 1538 } 1539 1540 if (IsKernel) { 1541 analyzeFormalArgumentsCompute(CCInfo, Ins); 1542 } else { 1543 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 1544 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 1545 } 1546 1547 SmallVector<SDValue, 16> Chains; 1548 1549 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 1550 const ISD::InputArg &Arg = Ins[i]; 1551 if (Skipped[i]) { 1552 InVals.push_back(DAG.getUNDEF(Arg.VT)); 1553 continue; 1554 } 1555 1556 CCValAssign &VA = ArgLocs[ArgIdx++]; 1557 MVT VT = VA.getLocVT(); 1558 1559 if (IsEntryFunc && VA.isMemLoc()) { 1560 VT = Ins[i].VT; 1561 EVT MemVT = VA.getLocVT(); 1562 1563 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) + 1564 VA.getLocMemOffset(); 1565 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 1566 1567 // The first 36 bytes of the input buffer contains information about 1568 // thread group and global sizes. 1569 SDValue Arg = lowerKernargMemParameter( 1570 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]); 1571 Chains.push_back(Arg.getValue(1)); 1572 1573 auto *ParamTy = 1574 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 1575 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1576 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 1577 // On SI local pointers are just offsets into LDS, so they are always 1578 // less than 16-bits. On CI and newer they could potentially be 1579 // real pointers, so we can't guarantee their size. 1580 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 1581 DAG.getValueType(MVT::i16)); 1582 } 1583 1584 InVals.push_back(Arg); 1585 continue; 1586 } else if (!IsEntryFunc && VA.isMemLoc()) { 1587 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 1588 InVals.push_back(Val); 1589 if (!Arg.Flags.isByVal()) 1590 Chains.push_back(Val.getValue(1)); 1591 continue; 1592 } 1593 1594 assert(VA.isRegLoc() && "Parameter must be in a register!"); 1595 1596 unsigned Reg = VA.getLocReg(); 1597 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 1598 EVT ValVT = VA.getValVT(); 1599 1600 Reg = MF.addLiveIn(Reg, RC); 1601 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1602 1603 // If this is an 8 or 16-bit value, it is really passed promoted 1604 // to 32 bits. Insert an assert[sz]ext to capture this, then 1605 // truncate to the right size. 1606 switch (VA.getLocInfo()) { 1607 case CCValAssign::Full: 1608 break; 1609 case CCValAssign::BCvt: 1610 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 1611 break; 1612 case CCValAssign::SExt: 1613 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 1614 DAG.getValueType(ValVT)); 1615 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1616 break; 1617 case CCValAssign::ZExt: 1618 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 1619 DAG.getValueType(ValVT)); 1620 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1621 break; 1622 case CCValAssign::AExt: 1623 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1624 break; 1625 default: 1626 llvm_unreachable("Unknown loc info!"); 1627 } 1628 1629 if (IsShader && Arg.VT.isVector()) { 1630 // Build a vector from the registers 1631 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1632 unsigned NumElements = ParamType->getVectorNumElements(); 1633 1634 SmallVector<SDValue, 4> Regs; 1635 Regs.push_back(Val); 1636 for (unsigned j = 1; j != NumElements; ++j) { 1637 Reg = ArgLocs[ArgIdx++].getLocReg(); 1638 Reg = MF.addLiveIn(Reg, RC); 1639 1640 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1641 Regs.push_back(Copy); 1642 } 1643 1644 // Fill up the missing vector elements 1645 NumElements = Arg.VT.getVectorNumElements() - NumElements; 1646 Regs.append(NumElements, DAG.getUNDEF(VT)); 1647 1648 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 1649 continue; 1650 } 1651 1652 InVals.push_back(Val); 1653 } 1654 1655 if (!IsEntryFunc) { 1656 // Special inputs come after user arguments. 1657 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 1658 } 1659 1660 // Start adding system SGPRs. 1661 if (IsEntryFunc) { 1662 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 1663 } else { 1664 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 1665 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 1666 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 1667 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 1668 } 1669 1670 auto &ArgUsageInfo = 1671 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 1672 ArgUsageInfo.setFuncArgInfo(*MF.getFunction(), Info->getArgInfo()); 1673 1674 unsigned StackArgSize = CCInfo.getNextStackOffset(); 1675 Info->setBytesInStackArgArea(StackArgSize); 1676 1677 return Chains.empty() ? Chain : 1678 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1679 } 1680 1681 // TODO: If return values can't fit in registers, we should return as many as 1682 // possible in registers before passing on stack. 1683 bool SITargetLowering::CanLowerReturn( 1684 CallingConv::ID CallConv, 1685 MachineFunction &MF, bool IsVarArg, 1686 const SmallVectorImpl<ISD::OutputArg> &Outs, 1687 LLVMContext &Context) const { 1688 // Replacing returns with sret/stack usage doesn't make sense for shaders. 1689 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 1690 // for shaders. Vector types should be explicitly handled by CC. 1691 if (AMDGPU::isEntryFunctionCC(CallConv)) 1692 return true; 1693 1694 SmallVector<CCValAssign, 16> RVLocs; 1695 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 1696 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 1697 } 1698 1699 SDValue 1700 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1701 bool isVarArg, 1702 const SmallVectorImpl<ISD::OutputArg> &Outs, 1703 const SmallVectorImpl<SDValue> &OutVals, 1704 const SDLoc &DL, SelectionDAG &DAG) const { 1705 MachineFunction &MF = DAG.getMachineFunction(); 1706 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1707 1708 if (AMDGPU::isKernel(CallConv)) { 1709 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 1710 OutVals, DL, DAG); 1711 } 1712 1713 bool IsShader = AMDGPU::isShader(CallConv); 1714 1715 Info->setIfReturnsVoid(Outs.size() == 0); 1716 bool IsWaveEnd = Info->returnsVoid() && IsShader; 1717 1718 SmallVector<ISD::OutputArg, 48> Splits; 1719 SmallVector<SDValue, 48> SplitVals; 1720 1721 // Split vectors into their elements. 1722 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 1723 const ISD::OutputArg &Out = Outs[i]; 1724 1725 if (IsShader && Out.VT.isVector()) { 1726 MVT VT = Out.VT.getVectorElementType(); 1727 ISD::OutputArg NewOut = Out; 1728 NewOut.Flags.setSplit(); 1729 NewOut.VT = VT; 1730 1731 // We want the original number of vector elements here, e.g. 1732 // three or five, not four or eight. 1733 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 1734 1735 for (unsigned j = 0; j != NumElements; ++j) { 1736 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 1737 DAG.getConstant(j, DL, MVT::i32)); 1738 SplitVals.push_back(Elem); 1739 Splits.push_back(NewOut); 1740 NewOut.PartOffset += NewOut.VT.getStoreSize(); 1741 } 1742 } else { 1743 SplitVals.push_back(OutVals[i]); 1744 Splits.push_back(Out); 1745 } 1746 } 1747 1748 // CCValAssign - represent the assignment of the return value to a location. 1749 SmallVector<CCValAssign, 48> RVLocs; 1750 1751 // CCState - Info about the registers and stack slots. 1752 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1753 *DAG.getContext()); 1754 1755 // Analyze outgoing return values. 1756 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg)); 1757 1758 SDValue Flag; 1759 SmallVector<SDValue, 48> RetOps; 1760 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1761 1762 // Add return address for callable functions. 1763 if (!Info->isEntryFunction()) { 1764 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1765 SDValue ReturnAddrReg = CreateLiveInRegister( 1766 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 1767 1768 // FIXME: Should be able to use a vreg here, but need a way to prevent it 1769 // from being allcoated to a CSR. 1770 1771 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 1772 MVT::i64); 1773 1774 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag); 1775 Flag = Chain.getValue(1); 1776 1777 RetOps.push_back(PhysReturnAddrReg); 1778 } 1779 1780 // Copy the result values into the output registers. 1781 for (unsigned i = 0, realRVLocIdx = 0; 1782 i != RVLocs.size(); 1783 ++i, ++realRVLocIdx) { 1784 CCValAssign &VA = RVLocs[i]; 1785 assert(VA.isRegLoc() && "Can only return in registers!"); 1786 // TODO: Partially return in registers if return values don't fit. 1787 1788 SDValue Arg = SplitVals[realRVLocIdx]; 1789 1790 // Copied from other backends. 1791 switch (VA.getLocInfo()) { 1792 case CCValAssign::Full: 1793 break; 1794 case CCValAssign::BCvt: 1795 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 1796 break; 1797 case CCValAssign::SExt: 1798 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 1799 break; 1800 case CCValAssign::ZExt: 1801 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 1802 break; 1803 case CCValAssign::AExt: 1804 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 1805 break; 1806 default: 1807 llvm_unreachable("Unknown loc info!"); 1808 } 1809 1810 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 1811 Flag = Chain.getValue(1); 1812 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1813 } 1814 1815 // FIXME: Does sret work properly? 1816 if (!Info->isEntryFunction()) { 1817 const SIRegisterInfo *TRI 1818 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo(); 1819 const MCPhysReg *I = 1820 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 1821 if (I) { 1822 for (; *I; ++I) { 1823 if (AMDGPU::SReg_64RegClass.contains(*I)) 1824 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 1825 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1826 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 1827 else 1828 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1829 } 1830 } 1831 } 1832 1833 // Update chain and glue. 1834 RetOps[0] = Chain; 1835 if (Flag.getNode()) 1836 RetOps.push_back(Flag); 1837 1838 unsigned Opc = AMDGPUISD::ENDPGM; 1839 if (!IsWaveEnd) 1840 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 1841 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 1842 } 1843 1844 SDValue SITargetLowering::LowerCallResult( 1845 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 1846 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1847 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 1848 SDValue ThisVal) const { 1849 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 1850 1851 // Assign locations to each value returned by this call. 1852 SmallVector<CCValAssign, 16> RVLocs; 1853 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 1854 *DAG.getContext()); 1855 CCInfo.AnalyzeCallResult(Ins, RetCC); 1856 1857 // Copy all of the result registers out of their specified physreg. 1858 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1859 CCValAssign VA = RVLocs[i]; 1860 SDValue Val; 1861 1862 if (VA.isRegLoc()) { 1863 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 1864 Chain = Val.getValue(1); 1865 InFlag = Val.getValue(2); 1866 } else if (VA.isMemLoc()) { 1867 report_fatal_error("TODO: return values in memory"); 1868 } else 1869 llvm_unreachable("unknown argument location type"); 1870 1871 switch (VA.getLocInfo()) { 1872 case CCValAssign::Full: 1873 break; 1874 case CCValAssign::BCvt: 1875 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 1876 break; 1877 case CCValAssign::ZExt: 1878 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 1879 DAG.getValueType(VA.getValVT())); 1880 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1881 break; 1882 case CCValAssign::SExt: 1883 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 1884 DAG.getValueType(VA.getValVT())); 1885 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1886 break; 1887 case CCValAssign::AExt: 1888 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1889 break; 1890 default: 1891 llvm_unreachable("Unknown loc info!"); 1892 } 1893 1894 InVals.push_back(Val); 1895 } 1896 1897 return Chain; 1898 } 1899 1900 // Add code to pass special inputs required depending on used features separate 1901 // from the explicit user arguments present in the IR. 1902 void SITargetLowering::passSpecialInputs( 1903 CallLoweringInfo &CLI, 1904 const SIMachineFunctionInfo &Info, 1905 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 1906 SmallVectorImpl<SDValue> &MemOpChains, 1907 SDValue Chain, 1908 SDValue StackPtr) const { 1909 // If we don't have a call site, this was a call inserted by 1910 // legalization. These can never use special inputs. 1911 if (!CLI.CS) 1912 return; 1913 1914 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 1915 assert(CalleeFunc); 1916 1917 SelectionDAG &DAG = CLI.DAG; 1918 const SDLoc &DL = CLI.DL; 1919 1920 const SISubtarget *ST = getSubtarget(); 1921 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 1922 1923 auto &ArgUsageInfo = 1924 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 1925 const AMDGPUFunctionArgInfo &CalleeArgInfo 1926 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 1927 1928 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 1929 1930 // TODO: Unify with private memory register handling. This is complicated by 1931 // the fact that at least in kernels, the input argument is not necessarily 1932 // in the same location as the input. 1933 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 1934 AMDGPUFunctionArgInfo::DISPATCH_PTR, 1935 AMDGPUFunctionArgInfo::QUEUE_PTR, 1936 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 1937 AMDGPUFunctionArgInfo::DISPATCH_ID, 1938 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 1939 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 1940 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 1941 AMDGPUFunctionArgInfo::WORKITEM_ID_X, 1942 AMDGPUFunctionArgInfo::WORKITEM_ID_Y, 1943 AMDGPUFunctionArgInfo::WORKITEM_ID_Z, 1944 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 1945 }; 1946 1947 for (auto InputID : InputRegs) { 1948 const ArgDescriptor *OutgoingArg; 1949 const TargetRegisterClass *ArgRC; 1950 1951 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 1952 if (!OutgoingArg) 1953 continue; 1954 1955 const ArgDescriptor *IncomingArg; 1956 const TargetRegisterClass *IncomingArgRC; 1957 std::tie(IncomingArg, IncomingArgRC) 1958 = CallerArgInfo.getPreloadedValue(InputID); 1959 assert(IncomingArgRC == ArgRC); 1960 1961 // All special arguments are ints for now. 1962 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 1963 SDValue InputReg; 1964 1965 if (IncomingArg) { 1966 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 1967 } else { 1968 // The implicit arg ptr is special because it doesn't have a corresponding 1969 // input for kernels, and is computed from the kernarg segment pointer. 1970 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 1971 InputReg = getImplicitArgPtr(DAG, DL); 1972 } 1973 1974 if (OutgoingArg->isRegister()) { 1975 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 1976 } else { 1977 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr, 1978 InputReg, 1979 OutgoingArg->getStackOffset()); 1980 MemOpChains.push_back(ArgStore); 1981 } 1982 } 1983 } 1984 1985 static bool canGuaranteeTCO(CallingConv::ID CC) { 1986 return CC == CallingConv::Fast; 1987 } 1988 1989 /// Return true if we might ever do TCO for calls with this calling convention. 1990 static bool mayTailCallThisCC(CallingConv::ID CC) { 1991 switch (CC) { 1992 case CallingConv::C: 1993 return true; 1994 default: 1995 return canGuaranteeTCO(CC); 1996 } 1997 } 1998 1999 bool SITargetLowering::isEligibleForTailCallOptimization( 2000 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2001 const SmallVectorImpl<ISD::OutputArg> &Outs, 2002 const SmallVectorImpl<SDValue> &OutVals, 2003 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2004 if (!mayTailCallThisCC(CalleeCC)) 2005 return false; 2006 2007 MachineFunction &MF = DAG.getMachineFunction(); 2008 const Function *CallerF = MF.getFunction(); 2009 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2010 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2011 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2012 2013 // Kernels aren't callable, and don't have a live in return address so it 2014 // doesn't make sense to do a tail call with entry functions. 2015 if (!CallerPreserved) 2016 return false; 2017 2018 bool CCMatch = CallerCC == CalleeCC; 2019 2020 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2021 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2022 return true; 2023 return false; 2024 } 2025 2026 // TODO: Can we handle var args? 2027 if (IsVarArg) 2028 return false; 2029 2030 for (const Argument &Arg : CallerF->args()) { 2031 if (Arg.hasByValAttr()) 2032 return false; 2033 } 2034 2035 LLVMContext &Ctx = *DAG.getContext(); 2036 2037 // Check that the call results are passed in the same way. 2038 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2039 CCAssignFnForCall(CalleeCC, IsVarArg), 2040 CCAssignFnForCall(CallerCC, IsVarArg))) 2041 return false; 2042 2043 // The callee has to preserve all registers the caller needs to preserve. 2044 if (!CCMatch) { 2045 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2046 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2047 return false; 2048 } 2049 2050 // Nothing more to check if the callee is taking no arguments. 2051 if (Outs.empty()) 2052 return true; 2053 2054 SmallVector<CCValAssign, 16> ArgLocs; 2055 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2056 2057 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2058 2059 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2060 // If the stack arguments for this call do not fit into our own save area then 2061 // the call cannot be made tail. 2062 // TODO: Is this really necessary? 2063 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2064 return false; 2065 2066 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2067 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2068 } 2069 2070 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2071 if (!CI->isTailCall()) 2072 return false; 2073 2074 const Function *ParentFn = CI->getParent()->getParent(); 2075 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2076 return false; 2077 2078 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2079 return (Attr.getValueAsString() != "true"); 2080 } 2081 2082 // The wave scratch offset register is used as the global base pointer. 2083 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2084 SmallVectorImpl<SDValue> &InVals) const { 2085 SelectionDAG &DAG = CLI.DAG; 2086 const SDLoc &DL = CLI.DL; 2087 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2088 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2089 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2090 SDValue Chain = CLI.Chain; 2091 SDValue Callee = CLI.Callee; 2092 bool &IsTailCall = CLI.IsTailCall; 2093 CallingConv::ID CallConv = CLI.CallConv; 2094 bool IsVarArg = CLI.IsVarArg; 2095 bool IsSibCall = false; 2096 bool IsThisReturn = false; 2097 MachineFunction &MF = DAG.getMachineFunction(); 2098 2099 if (IsVarArg) { 2100 return lowerUnhandledCall(CLI, InVals, 2101 "unsupported call to variadic function "); 2102 } 2103 2104 if (!CLI.CS.getCalledFunction()) { 2105 return lowerUnhandledCall(CLI, InVals, 2106 "unsupported indirect call to function "); 2107 } 2108 2109 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2110 return lowerUnhandledCall(CLI, InVals, 2111 "unsupported required tail call to function "); 2112 } 2113 2114 // The first 4 bytes are reserved for the callee's emergency stack slot. 2115 const unsigned CalleeUsableStackOffset = 4; 2116 2117 if (IsTailCall) { 2118 IsTailCall = isEligibleForTailCallOptimization( 2119 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2120 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2121 report_fatal_error("failed to perform tail call elimination on a call " 2122 "site marked musttail"); 2123 } 2124 2125 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2126 2127 // A sibling call is one where we're under the usual C ABI and not planning 2128 // to change that but can still do a tail call: 2129 if (!TailCallOpt && IsTailCall) 2130 IsSibCall = true; 2131 2132 if (IsTailCall) 2133 ++NumTailCalls; 2134 } 2135 2136 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) { 2137 // FIXME: Remove this hack for function pointer types. 2138 const GlobalValue *GV = GA->getGlobal(); 2139 assert(Callee.getValueType() == MVT::i32); 2140 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), 2141 false, GA->getTargetFlags()); 2142 } 2143 2144 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2145 2146 // Analyze operands of the call, assigning locations to each operand. 2147 SmallVector<CCValAssign, 16> ArgLocs; 2148 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2149 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2150 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2151 2152 // Get a count of how many bytes are to be pushed on the stack. 2153 unsigned NumBytes = CCInfo.getNextStackOffset(); 2154 2155 if (IsSibCall) { 2156 // Since we're not changing the ABI to make this a tail call, the memory 2157 // operands are already available in the caller's incoming argument space. 2158 NumBytes = 0; 2159 } 2160 2161 // FPDiff is the byte offset of the call's argument area from the callee's. 2162 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2163 // by this amount for a tail call. In a sibling call it must be 0 because the 2164 // caller will deallocate the entire stack and the callee still expects its 2165 // arguments to begin at SP+0. Completely unused for non-tail calls. 2166 int32_t FPDiff = 0; 2167 MachineFrameInfo &MFI = MF.getFrameInfo(); 2168 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2169 2170 SDValue CallerSavedFP; 2171 2172 // Adjust the stack pointer for the new arguments... 2173 // These operations are automatically eliminated by the prolog/epilog pass 2174 if (!IsSibCall) { 2175 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2176 2177 unsigned OffsetReg = Info->getScratchWaveOffsetReg(); 2178 2179 // In the HSA case, this should be an identity copy. 2180 SDValue ScratchRSrcReg 2181 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2182 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2183 2184 // TODO: Don't hardcode these registers and get from the callee function. 2185 SDValue ScratchWaveOffsetReg 2186 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32); 2187 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg); 2188 2189 if (!Info->isEntryFunction()) { 2190 // Avoid clobbering this function's FP value. In the current convention 2191 // callee will overwrite this, so do save/restore around the call site. 2192 CallerSavedFP = DAG.getCopyFromReg(Chain, DL, 2193 Info->getFrameOffsetReg(), MVT::i32); 2194 } 2195 } 2196 2197 // Stack pointer relative accesses are done by changing the offset SGPR. This 2198 // is just the VGPR offset component. 2199 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32); 2200 2201 SmallVector<SDValue, 8> MemOpChains; 2202 MVT PtrVT = MVT::i32; 2203 2204 // Walk the register/memloc assignments, inserting copies/loads. 2205 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2206 ++i, ++realArgIdx) { 2207 CCValAssign &VA = ArgLocs[i]; 2208 SDValue Arg = OutVals[realArgIdx]; 2209 2210 // Promote the value if needed. 2211 switch (VA.getLocInfo()) { 2212 case CCValAssign::Full: 2213 break; 2214 case CCValAssign::BCvt: 2215 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2216 break; 2217 case CCValAssign::ZExt: 2218 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2219 break; 2220 case CCValAssign::SExt: 2221 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2222 break; 2223 case CCValAssign::AExt: 2224 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2225 break; 2226 case CCValAssign::FPExt: 2227 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2228 break; 2229 default: 2230 llvm_unreachable("Unknown loc info!"); 2231 } 2232 2233 if (VA.isRegLoc()) { 2234 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2235 } else { 2236 assert(VA.isMemLoc()); 2237 2238 SDValue DstAddr; 2239 MachinePointerInfo DstInfo; 2240 2241 unsigned LocMemOffset = VA.getLocMemOffset(); 2242 int32_t Offset = LocMemOffset; 2243 SDValue PtrOff = DAG.getConstant(Offset, DL, MVT::i32); 2244 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 2245 2246 if (IsTailCall) { 2247 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2248 unsigned OpSize = Flags.isByVal() ? 2249 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2250 2251 Offset = Offset + FPDiff; 2252 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2253 2254 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2255 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, DstAddr, StackPtr); 2256 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2257 2258 // Make sure any stack arguments overlapping with where we're storing 2259 // are loaded before this eventual operation. Otherwise they'll be 2260 // clobbered. 2261 2262 // FIXME: Why is this really necessary? This seems to just result in a 2263 // lot of code to copy the stack and write them back to the same 2264 // locations, which are supposed to be immutable? 2265 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2266 } else { 2267 DstAddr = PtrOff; 2268 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2269 } 2270 2271 if (Outs[i].Flags.isByVal()) { 2272 SDValue SizeNode = 2273 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2274 SDValue Cpy = DAG.getMemcpy( 2275 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2276 /*isVol = */ false, /*AlwaysInline = */ true, 2277 /*isTailCall = */ false, 2278 DstInfo, MachinePointerInfo()); 2279 2280 MemOpChains.push_back(Cpy); 2281 } else { 2282 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 2283 MemOpChains.push_back(Store); 2284 } 2285 } 2286 } 2287 2288 // Copy special input registers after user input arguments. 2289 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr); 2290 2291 if (!MemOpChains.empty()) 2292 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2293 2294 // Build a sequence of copy-to-reg nodes chained together with token chain 2295 // and flag operands which copy the outgoing args into the appropriate regs. 2296 SDValue InFlag; 2297 for (auto &RegToPass : RegsToPass) { 2298 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2299 RegToPass.second, InFlag); 2300 InFlag = Chain.getValue(1); 2301 } 2302 2303 2304 SDValue PhysReturnAddrReg; 2305 if (IsTailCall) { 2306 // Since the return is being combined with the call, we need to pass on the 2307 // return address. 2308 2309 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2310 SDValue ReturnAddrReg = CreateLiveInRegister( 2311 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2312 2313 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2314 MVT::i64); 2315 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2316 InFlag = Chain.getValue(1); 2317 } 2318 2319 // We don't usually want to end the call-sequence here because we would tidy 2320 // the frame up *after* the call, however in the ABI-changing tail-call case 2321 // we've carefully laid out the parameters so that when sp is reset they'll be 2322 // in the correct location. 2323 if (IsTailCall && !IsSibCall) { 2324 Chain = DAG.getCALLSEQ_END(Chain, 2325 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2326 DAG.getTargetConstant(0, DL, MVT::i32), 2327 InFlag, DL); 2328 InFlag = Chain.getValue(1); 2329 } 2330 2331 std::vector<SDValue> Ops; 2332 Ops.push_back(Chain); 2333 Ops.push_back(Callee); 2334 2335 if (IsTailCall) { 2336 // Each tail call may have to adjust the stack by a different amount, so 2337 // this information must travel along with the operation for eventual 2338 // consumption by emitEpilogue. 2339 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2340 2341 Ops.push_back(PhysReturnAddrReg); 2342 } 2343 2344 // Add argument registers to the end of the list so that they are known live 2345 // into the call. 2346 for (auto &RegToPass : RegsToPass) { 2347 Ops.push_back(DAG.getRegister(RegToPass.first, 2348 RegToPass.second.getValueType())); 2349 } 2350 2351 // Add a register mask operand representing the call-preserved registers. 2352 2353 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo(); 2354 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2355 assert(Mask && "Missing call preserved mask for calling convention"); 2356 Ops.push_back(DAG.getRegisterMask(Mask)); 2357 2358 if (InFlag.getNode()) 2359 Ops.push_back(InFlag); 2360 2361 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2362 2363 // If we're doing a tall call, use a TC_RETURN here rather than an 2364 // actual call instruction. 2365 if (IsTailCall) { 2366 MFI.setHasTailCall(); 2367 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2368 } 2369 2370 // Returns a chain and a flag for retval copy to use. 2371 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2372 Chain = Call.getValue(0); 2373 InFlag = Call.getValue(1); 2374 2375 if (CallerSavedFP) { 2376 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32); 2377 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag); 2378 InFlag = Chain.getValue(1); 2379 } 2380 2381 uint64_t CalleePopBytes = NumBytes; 2382 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2383 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2384 InFlag, DL); 2385 if (!Ins.empty()) 2386 InFlag = Chain.getValue(1); 2387 2388 // Handle result values, copying them out of physregs into vregs that we 2389 // return. 2390 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2391 InVals, IsThisReturn, 2392 IsThisReturn ? OutVals[0] : SDValue()); 2393 } 2394 2395 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2396 SelectionDAG &DAG) const { 2397 unsigned Reg = StringSwitch<unsigned>(RegName) 2398 .Case("m0", AMDGPU::M0) 2399 .Case("exec", AMDGPU::EXEC) 2400 .Case("exec_lo", AMDGPU::EXEC_LO) 2401 .Case("exec_hi", AMDGPU::EXEC_HI) 2402 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2403 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2404 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2405 .Default(AMDGPU::NoRegister); 2406 2407 if (Reg == AMDGPU::NoRegister) { 2408 report_fatal_error(Twine("invalid register name \"" 2409 + StringRef(RegName) + "\".")); 2410 2411 } 2412 2413 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 2414 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2415 report_fatal_error(Twine("invalid register \"" 2416 + StringRef(RegName) + "\" for subtarget.")); 2417 } 2418 2419 switch (Reg) { 2420 case AMDGPU::M0: 2421 case AMDGPU::EXEC_LO: 2422 case AMDGPU::EXEC_HI: 2423 case AMDGPU::FLAT_SCR_LO: 2424 case AMDGPU::FLAT_SCR_HI: 2425 if (VT.getSizeInBits() == 32) 2426 return Reg; 2427 break; 2428 case AMDGPU::EXEC: 2429 case AMDGPU::FLAT_SCR: 2430 if (VT.getSizeInBits() == 64) 2431 return Reg; 2432 break; 2433 default: 2434 llvm_unreachable("missing register type checking"); 2435 } 2436 2437 report_fatal_error(Twine("invalid type for register \"" 2438 + StringRef(RegName) + "\".")); 2439 } 2440 2441 // If kill is not the last instruction, split the block so kill is always a 2442 // proper terminator. 2443 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2444 MachineBasicBlock *BB) const { 2445 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2446 2447 MachineBasicBlock::iterator SplitPoint(&MI); 2448 ++SplitPoint; 2449 2450 if (SplitPoint == BB->end()) { 2451 // Don't bother with a new block. 2452 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 2453 return BB; 2454 } 2455 2456 MachineFunction *MF = BB->getParent(); 2457 MachineBasicBlock *SplitBB 2458 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 2459 2460 MF->insert(++MachineFunction::iterator(BB), SplitBB); 2461 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 2462 2463 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 2464 BB->addSuccessor(SplitBB); 2465 2466 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 2467 return SplitBB; 2468 } 2469 2470 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 2471 // wavefront. If the value is uniform and just happens to be in a VGPR, this 2472 // will only do one iteration. In the worst case, this will loop 64 times. 2473 // 2474 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 2475 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 2476 const SIInstrInfo *TII, 2477 MachineRegisterInfo &MRI, 2478 MachineBasicBlock &OrigBB, 2479 MachineBasicBlock &LoopBB, 2480 const DebugLoc &DL, 2481 const MachineOperand &IdxReg, 2482 unsigned InitReg, 2483 unsigned ResultReg, 2484 unsigned PhiReg, 2485 unsigned InitSaveExecReg, 2486 int Offset, 2487 bool UseGPRIdxMode) { 2488 MachineBasicBlock::iterator I = LoopBB.begin(); 2489 2490 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2491 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2492 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2493 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2494 2495 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 2496 .addReg(InitReg) 2497 .addMBB(&OrigBB) 2498 .addReg(ResultReg) 2499 .addMBB(&LoopBB); 2500 2501 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 2502 .addReg(InitSaveExecReg) 2503 .addMBB(&OrigBB) 2504 .addReg(NewExec) 2505 .addMBB(&LoopBB); 2506 2507 // Read the next variant <- also loop target. 2508 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 2509 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 2510 2511 // Compare the just read M0 value to all possible Idx values. 2512 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 2513 .addReg(CurrentIdxReg) 2514 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 2515 2516 if (UseGPRIdxMode) { 2517 unsigned IdxReg; 2518 if (Offset == 0) { 2519 IdxReg = CurrentIdxReg; 2520 } else { 2521 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2522 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 2523 .addReg(CurrentIdxReg, RegState::Kill) 2524 .addImm(Offset); 2525 } 2526 2527 MachineInstr *SetIdx = 2528 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX)) 2529 .addReg(IdxReg, RegState::Kill); 2530 SetIdx->getOperand(2).setIsUndef(); 2531 } else { 2532 // Move index from VCC into M0 2533 if (Offset == 0) { 2534 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2535 .addReg(CurrentIdxReg, RegState::Kill); 2536 } else { 2537 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2538 .addReg(CurrentIdxReg, RegState::Kill) 2539 .addImm(Offset); 2540 } 2541 } 2542 2543 // Update EXEC, save the original EXEC value to VCC. 2544 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 2545 .addReg(CondReg, RegState::Kill); 2546 2547 MRI.setSimpleHint(NewExec, CondReg); 2548 2549 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 2550 MachineInstr *InsertPt = 2551 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 2552 .addReg(AMDGPU::EXEC) 2553 .addReg(NewExec); 2554 2555 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 2556 // s_cbranch_scc0? 2557 2558 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 2559 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 2560 .addMBB(&LoopBB); 2561 2562 return InsertPt->getIterator(); 2563 } 2564 2565 // This has slightly sub-optimal regalloc when the source vector is killed by 2566 // the read. The register allocator does not understand that the kill is 2567 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 2568 // subregister from it, using 1 more VGPR than necessary. This was saved when 2569 // this was expanded after register allocation. 2570 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 2571 MachineBasicBlock &MBB, 2572 MachineInstr &MI, 2573 unsigned InitResultReg, 2574 unsigned PhiReg, 2575 int Offset, 2576 bool UseGPRIdxMode) { 2577 MachineFunction *MF = MBB.getParent(); 2578 MachineRegisterInfo &MRI = MF->getRegInfo(); 2579 const DebugLoc &DL = MI.getDebugLoc(); 2580 MachineBasicBlock::iterator I(&MI); 2581 2582 unsigned DstReg = MI.getOperand(0).getReg(); 2583 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2584 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2585 2586 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 2587 2588 // Save the EXEC mask 2589 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 2590 .addReg(AMDGPU::EXEC); 2591 2592 // To insert the loop we need to split the block. Move everything after this 2593 // point to a new block, and insert a new empty block between the two. 2594 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 2595 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 2596 MachineFunction::iterator MBBI(MBB); 2597 ++MBBI; 2598 2599 MF->insert(MBBI, LoopBB); 2600 MF->insert(MBBI, RemainderBB); 2601 2602 LoopBB->addSuccessor(LoopBB); 2603 LoopBB->addSuccessor(RemainderBB); 2604 2605 // Move the rest of the block into a new block. 2606 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 2607 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 2608 2609 MBB.addSuccessor(LoopBB); 2610 2611 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2612 2613 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 2614 InitResultReg, DstReg, PhiReg, TmpExec, 2615 Offset, UseGPRIdxMode); 2616 2617 MachineBasicBlock::iterator First = RemainderBB->begin(); 2618 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 2619 .addReg(SaveExec); 2620 2621 return InsPt; 2622 } 2623 2624 // Returns subreg index, offset 2625 static std::pair<unsigned, int> 2626 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 2627 const TargetRegisterClass *SuperRC, 2628 unsigned VecReg, 2629 int Offset) { 2630 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 2631 2632 // Skip out of bounds offsets, or else we would end up using an undefined 2633 // register. 2634 if (Offset >= NumElts || Offset < 0) 2635 return std::make_pair(AMDGPU::sub0, Offset); 2636 2637 return std::make_pair(AMDGPU::sub0 + Offset, 0); 2638 } 2639 2640 // Return true if the index is an SGPR and was set. 2641 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 2642 MachineRegisterInfo &MRI, 2643 MachineInstr &MI, 2644 int Offset, 2645 bool UseGPRIdxMode, 2646 bool IsIndirectSrc) { 2647 MachineBasicBlock *MBB = MI.getParent(); 2648 const DebugLoc &DL = MI.getDebugLoc(); 2649 MachineBasicBlock::iterator I(&MI); 2650 2651 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2652 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 2653 2654 assert(Idx->getReg() != AMDGPU::NoRegister); 2655 2656 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 2657 return false; 2658 2659 if (UseGPRIdxMode) { 2660 unsigned IdxMode = IsIndirectSrc ? 2661 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 2662 if (Offset == 0) { 2663 MachineInstr *SetOn = 2664 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2665 .add(*Idx) 2666 .addImm(IdxMode); 2667 2668 SetOn->getOperand(3).setIsUndef(); 2669 } else { 2670 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 2671 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 2672 .add(*Idx) 2673 .addImm(Offset); 2674 MachineInstr *SetOn = 2675 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2676 .addReg(Tmp, RegState::Kill) 2677 .addImm(IdxMode); 2678 2679 SetOn->getOperand(3).setIsUndef(); 2680 } 2681 2682 return true; 2683 } 2684 2685 if (Offset == 0) { 2686 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2687 .add(*Idx); 2688 } else { 2689 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2690 .add(*Idx) 2691 .addImm(Offset); 2692 } 2693 2694 return true; 2695 } 2696 2697 // Control flow needs to be inserted if indexing with a VGPR. 2698 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 2699 MachineBasicBlock &MBB, 2700 const SISubtarget &ST) { 2701 const SIInstrInfo *TII = ST.getInstrInfo(); 2702 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2703 MachineFunction *MF = MBB.getParent(); 2704 MachineRegisterInfo &MRI = MF->getRegInfo(); 2705 2706 unsigned Dst = MI.getOperand(0).getReg(); 2707 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 2708 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2709 2710 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 2711 2712 unsigned SubReg; 2713 std::tie(SubReg, Offset) 2714 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 2715 2716 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2717 2718 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 2719 MachineBasicBlock::iterator I(&MI); 2720 const DebugLoc &DL = MI.getDebugLoc(); 2721 2722 if (UseGPRIdxMode) { 2723 // TODO: Look at the uses to avoid the copy. This may require rescheduling 2724 // to avoid interfering with other uses, so probably requires a new 2725 // optimization pass. 2726 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2727 .addReg(SrcReg, RegState::Undef, SubReg) 2728 .addReg(SrcReg, RegState::Implicit) 2729 .addReg(AMDGPU::M0, RegState::Implicit); 2730 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2731 } else { 2732 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2733 .addReg(SrcReg, RegState::Undef, SubReg) 2734 .addReg(SrcReg, RegState::Implicit); 2735 } 2736 2737 MI.eraseFromParent(); 2738 2739 return &MBB; 2740 } 2741 2742 const DebugLoc &DL = MI.getDebugLoc(); 2743 MachineBasicBlock::iterator I(&MI); 2744 2745 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2746 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2747 2748 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 2749 2750 if (UseGPRIdxMode) { 2751 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2752 .addImm(0) // Reset inside loop. 2753 .addImm(VGPRIndexMode::SRC0_ENABLE); 2754 SetOn->getOperand(3).setIsUndef(); 2755 2756 // Disable again after the loop. 2757 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2758 } 2759 2760 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode); 2761 MachineBasicBlock *LoopBB = InsPt->getParent(); 2762 2763 if (UseGPRIdxMode) { 2764 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2765 .addReg(SrcReg, RegState::Undef, SubReg) 2766 .addReg(SrcReg, RegState::Implicit) 2767 .addReg(AMDGPU::M0, RegState::Implicit); 2768 } else { 2769 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2770 .addReg(SrcReg, RegState::Undef, SubReg) 2771 .addReg(SrcReg, RegState::Implicit); 2772 } 2773 2774 MI.eraseFromParent(); 2775 2776 return LoopBB; 2777 } 2778 2779 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 2780 const TargetRegisterClass *VecRC) { 2781 switch (TRI.getRegSizeInBits(*VecRC)) { 2782 case 32: // 4 bytes 2783 return AMDGPU::V_MOVRELD_B32_V1; 2784 case 64: // 8 bytes 2785 return AMDGPU::V_MOVRELD_B32_V2; 2786 case 128: // 16 bytes 2787 return AMDGPU::V_MOVRELD_B32_V4; 2788 case 256: // 32 bytes 2789 return AMDGPU::V_MOVRELD_B32_V8; 2790 case 512: // 64 bytes 2791 return AMDGPU::V_MOVRELD_B32_V16; 2792 default: 2793 llvm_unreachable("unsupported size for MOVRELD pseudos"); 2794 } 2795 } 2796 2797 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 2798 MachineBasicBlock &MBB, 2799 const SISubtarget &ST) { 2800 const SIInstrInfo *TII = ST.getInstrInfo(); 2801 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2802 MachineFunction *MF = MBB.getParent(); 2803 MachineRegisterInfo &MRI = MF->getRegInfo(); 2804 2805 unsigned Dst = MI.getOperand(0).getReg(); 2806 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 2807 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2808 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 2809 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2810 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 2811 2812 // This can be an immediate, but will be folded later. 2813 assert(Val->getReg()); 2814 2815 unsigned SubReg; 2816 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 2817 SrcVec->getReg(), 2818 Offset); 2819 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2820 2821 if (Idx->getReg() == AMDGPU::NoRegister) { 2822 MachineBasicBlock::iterator I(&MI); 2823 const DebugLoc &DL = MI.getDebugLoc(); 2824 2825 assert(Offset == 0); 2826 2827 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 2828 .add(*SrcVec) 2829 .add(*Val) 2830 .addImm(SubReg); 2831 2832 MI.eraseFromParent(); 2833 return &MBB; 2834 } 2835 2836 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 2837 MachineBasicBlock::iterator I(&MI); 2838 const DebugLoc &DL = MI.getDebugLoc(); 2839 2840 if (UseGPRIdxMode) { 2841 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2842 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 2843 .add(*Val) 2844 .addReg(Dst, RegState::ImplicitDefine) 2845 .addReg(SrcVec->getReg(), RegState::Implicit) 2846 .addReg(AMDGPU::M0, RegState::Implicit); 2847 2848 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2849 } else { 2850 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2851 2852 BuildMI(MBB, I, DL, MovRelDesc) 2853 .addReg(Dst, RegState::Define) 2854 .addReg(SrcVec->getReg()) 2855 .add(*Val) 2856 .addImm(SubReg - AMDGPU::sub0); 2857 } 2858 2859 MI.eraseFromParent(); 2860 return &MBB; 2861 } 2862 2863 if (Val->isReg()) 2864 MRI.clearKillFlags(Val->getReg()); 2865 2866 const DebugLoc &DL = MI.getDebugLoc(); 2867 2868 if (UseGPRIdxMode) { 2869 MachineBasicBlock::iterator I(&MI); 2870 2871 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2872 .addImm(0) // Reset inside loop. 2873 .addImm(VGPRIndexMode::DST_ENABLE); 2874 SetOn->getOperand(3).setIsUndef(); 2875 2876 // Disable again after the loop. 2877 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2878 } 2879 2880 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 2881 2882 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 2883 Offset, UseGPRIdxMode); 2884 MachineBasicBlock *LoopBB = InsPt->getParent(); 2885 2886 if (UseGPRIdxMode) { 2887 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2888 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 2889 .add(*Val) // src0 2890 .addReg(Dst, RegState::ImplicitDefine) 2891 .addReg(PhiReg, RegState::Implicit) 2892 .addReg(AMDGPU::M0, RegState::Implicit); 2893 } else { 2894 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2895 2896 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 2897 .addReg(Dst, RegState::Define) 2898 .addReg(PhiReg) 2899 .add(*Val) 2900 .addImm(SubReg - AMDGPU::sub0); 2901 } 2902 2903 MI.eraseFromParent(); 2904 2905 return LoopBB; 2906 } 2907 2908 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 2909 MachineInstr &MI, MachineBasicBlock *BB) const { 2910 2911 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2912 MachineFunction *MF = BB->getParent(); 2913 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 2914 2915 if (TII->isMIMG(MI)) { 2916 if (!MI.memoperands_empty()) 2917 return BB; 2918 // Add a memoperand for mimg instructions so that they aren't assumed to 2919 // be ordered memory instuctions. 2920 2921 MachinePointerInfo PtrInfo(MFI->getImagePSV()); 2922 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable; 2923 if (MI.mayStore()) 2924 Flags |= MachineMemOperand::MOStore; 2925 2926 if (MI.mayLoad()) 2927 Flags |= MachineMemOperand::MOLoad; 2928 2929 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0); 2930 MI.addMemOperand(*MF, MMO); 2931 return BB; 2932 } 2933 2934 switch (MI.getOpcode()) { 2935 case AMDGPU::SI_INIT_M0: 2936 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 2937 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2938 .add(MI.getOperand(0)); 2939 MI.eraseFromParent(); 2940 return BB; 2941 2942 case AMDGPU::SI_INIT_EXEC: 2943 // This should be before all vector instructions. 2944 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 2945 AMDGPU::EXEC) 2946 .addImm(MI.getOperand(0).getImm()); 2947 MI.eraseFromParent(); 2948 return BB; 2949 2950 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 2951 // Extract the thread count from an SGPR input and set EXEC accordingly. 2952 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 2953 // 2954 // S_BFE_U32 count, input, {shift, 7} 2955 // S_BFM_B64 exec, count, 0 2956 // S_CMP_EQ_U32 count, 64 2957 // S_CMOV_B64 exec, -1 2958 MachineInstr *FirstMI = &*BB->begin(); 2959 MachineRegisterInfo &MRI = MF->getRegInfo(); 2960 unsigned InputReg = MI.getOperand(0).getReg(); 2961 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2962 bool Found = false; 2963 2964 // Move the COPY of the input reg to the beginning, so that we can use it. 2965 for (auto I = BB->begin(); I != &MI; I++) { 2966 if (I->getOpcode() != TargetOpcode::COPY || 2967 I->getOperand(0).getReg() != InputReg) 2968 continue; 2969 2970 if (I == FirstMI) { 2971 FirstMI = &*++BB->begin(); 2972 } else { 2973 I->removeFromParent(); 2974 BB->insert(FirstMI, &*I); 2975 } 2976 Found = true; 2977 break; 2978 } 2979 assert(Found); 2980 (void)Found; 2981 2982 // This should be before all vector instructions. 2983 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 2984 .addReg(InputReg) 2985 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000); 2986 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64), 2987 AMDGPU::EXEC) 2988 .addReg(CountReg) 2989 .addImm(0); 2990 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 2991 .addReg(CountReg, RegState::Kill) 2992 .addImm(64); 2993 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64), 2994 AMDGPU::EXEC) 2995 .addImm(-1); 2996 MI.eraseFromParent(); 2997 return BB; 2998 } 2999 3000 case AMDGPU::GET_GROUPSTATICSIZE: { 3001 DebugLoc DL = MI.getDebugLoc(); 3002 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3003 .add(MI.getOperand(0)) 3004 .addImm(MFI->getLDSSize()); 3005 MI.eraseFromParent(); 3006 return BB; 3007 } 3008 case AMDGPU::SI_INDIRECT_SRC_V1: 3009 case AMDGPU::SI_INDIRECT_SRC_V2: 3010 case AMDGPU::SI_INDIRECT_SRC_V4: 3011 case AMDGPU::SI_INDIRECT_SRC_V8: 3012 case AMDGPU::SI_INDIRECT_SRC_V16: 3013 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3014 case AMDGPU::SI_INDIRECT_DST_V1: 3015 case AMDGPU::SI_INDIRECT_DST_V2: 3016 case AMDGPU::SI_INDIRECT_DST_V4: 3017 case AMDGPU::SI_INDIRECT_DST_V8: 3018 case AMDGPU::SI_INDIRECT_DST_V16: 3019 return emitIndirectDst(MI, *BB, *getSubtarget()); 3020 case AMDGPU::SI_KILL: 3021 return splitKillBlock(MI, BB); 3022 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3023 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3024 3025 unsigned Dst = MI.getOperand(0).getReg(); 3026 unsigned Src0 = MI.getOperand(1).getReg(); 3027 unsigned Src1 = MI.getOperand(2).getReg(); 3028 const DebugLoc &DL = MI.getDebugLoc(); 3029 unsigned SrcCond = MI.getOperand(3).getReg(); 3030 3031 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3032 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3033 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3034 3035 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3036 .addReg(SrcCond); 3037 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3038 .addReg(Src0, 0, AMDGPU::sub0) 3039 .addReg(Src1, 0, AMDGPU::sub0) 3040 .addReg(SrcCondCopy); 3041 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3042 .addReg(Src0, 0, AMDGPU::sub1) 3043 .addReg(Src1, 0, AMDGPU::sub1) 3044 .addReg(SrcCondCopy); 3045 3046 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3047 .addReg(DstLo) 3048 .addImm(AMDGPU::sub0) 3049 .addReg(DstHi) 3050 .addImm(AMDGPU::sub1); 3051 MI.eraseFromParent(); 3052 return BB; 3053 } 3054 case AMDGPU::SI_BR_UNDEF: { 3055 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3056 const DebugLoc &DL = MI.getDebugLoc(); 3057 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3058 .add(MI.getOperand(0)); 3059 Br->getOperand(1).setIsUndef(true); // read undef SCC 3060 MI.eraseFromParent(); 3061 return BB; 3062 } 3063 case AMDGPU::ADJCALLSTACKUP: 3064 case AMDGPU::ADJCALLSTACKDOWN: { 3065 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3066 MachineInstrBuilder MIB(*MF, &MI); 3067 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3068 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 3069 return BB; 3070 } 3071 case AMDGPU::SI_CALL_ISEL: 3072 case AMDGPU::SI_TCRETURN_ISEL: { 3073 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3074 const DebugLoc &DL = MI.getDebugLoc(); 3075 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3076 3077 MachineRegisterInfo &MRI = MF->getRegInfo(); 3078 unsigned GlobalAddrReg = MI.getOperand(0).getReg(); 3079 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg); 3080 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET); 3081 3082 const GlobalValue *G = PCRel->getOperand(1).getGlobal(); 3083 3084 MachineInstrBuilder MIB; 3085 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) { 3086 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg) 3087 .add(MI.getOperand(0)) 3088 .addGlobalAddress(G); 3089 } else { 3090 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN)) 3091 .add(MI.getOperand(0)) 3092 .addGlobalAddress(G); 3093 3094 // There is an additional imm operand for tcreturn, but it should be in the 3095 // right place already. 3096 } 3097 3098 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) 3099 MIB.add(MI.getOperand(I)); 3100 3101 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 3102 MI.eraseFromParent(); 3103 return BB; 3104 } 3105 default: 3106 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3107 } 3108 } 3109 3110 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3111 // This currently forces unfolding various combinations of fsub into fma with 3112 // free fneg'd operands. As long as we have fast FMA (controlled by 3113 // isFMAFasterThanFMulAndFAdd), we should perform these. 3114 3115 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3116 // most of these combines appear to be cycle neutral but save on instruction 3117 // count / code size. 3118 return true; 3119 } 3120 3121 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3122 EVT VT) const { 3123 if (!VT.isVector()) { 3124 return MVT::i1; 3125 } 3126 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3127 } 3128 3129 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3130 // TODO: Should i16 be used always if legal? For now it would force VALU 3131 // shifts. 3132 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3133 } 3134 3135 // Answering this is somewhat tricky and depends on the specific device which 3136 // have different rates for fma or all f64 operations. 3137 // 3138 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3139 // regardless of which device (although the number of cycles differs between 3140 // devices), so it is always profitable for f64. 3141 // 3142 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3143 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3144 // which we can always do even without fused FP ops since it returns the same 3145 // result as the separate operations and since it is always full 3146 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3147 // however does not support denormals, so we do report fma as faster if we have 3148 // a fast fma device and require denormals. 3149 // 3150 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3151 VT = VT.getScalarType(); 3152 3153 switch (VT.getSimpleVT().SimpleTy) { 3154 case MVT::f32: 3155 // This is as fast on some subtargets. However, we always have full rate f32 3156 // mad available which returns the same result as the separate operations 3157 // which we should prefer over fma. We can't use this if we want to support 3158 // denormals, so only report this in these cases. 3159 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 3160 case MVT::f64: 3161 return true; 3162 case MVT::f16: 3163 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3164 default: 3165 break; 3166 } 3167 3168 return false; 3169 } 3170 3171 //===----------------------------------------------------------------------===// 3172 // Custom DAG Lowering Operations 3173 //===----------------------------------------------------------------------===// 3174 3175 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3176 switch (Op.getOpcode()) { 3177 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3178 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3179 case ISD::LOAD: { 3180 SDValue Result = LowerLOAD(Op, DAG); 3181 assert((!Result.getNode() || 3182 Result.getNode()->getNumValues() == 2) && 3183 "Load should return a value and a chain"); 3184 return Result; 3185 } 3186 3187 case ISD::FSIN: 3188 case ISD::FCOS: 3189 return LowerTrig(Op, DAG); 3190 case ISD::SELECT: return LowerSELECT(Op, DAG); 3191 case ISD::FDIV: return LowerFDIV(Op, DAG); 3192 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3193 case ISD::STORE: return LowerSTORE(Op, DAG); 3194 case ISD::GlobalAddress: { 3195 MachineFunction &MF = DAG.getMachineFunction(); 3196 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3197 return LowerGlobalAddress(MFI, Op, DAG); 3198 } 3199 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3200 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3201 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3202 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3203 case ISD::INSERT_VECTOR_ELT: 3204 return lowerINSERT_VECTOR_ELT(Op, DAG); 3205 case ISD::EXTRACT_VECTOR_ELT: 3206 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3207 case ISD::FP_ROUND: 3208 return lowerFP_ROUND(Op, DAG); 3209 3210 case ISD::TRAP: 3211 case ISD::DEBUGTRAP: 3212 return lowerTRAP(Op, DAG); 3213 } 3214 return SDValue(); 3215 } 3216 3217 void SITargetLowering::ReplaceNodeResults(SDNode *N, 3218 SmallVectorImpl<SDValue> &Results, 3219 SelectionDAG &DAG) const { 3220 switch (N->getOpcode()) { 3221 case ISD::INSERT_VECTOR_ELT: { 3222 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 3223 Results.push_back(Res); 3224 return; 3225 } 3226 case ISD::EXTRACT_VECTOR_ELT: { 3227 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 3228 Results.push_back(Res); 3229 return; 3230 } 3231 case ISD::INTRINSIC_WO_CHAIN: { 3232 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 3233 if (IID == Intrinsic::amdgcn_cvt_pkrtz) { 3234 SDValue Src0 = N->getOperand(1); 3235 SDValue Src1 = N->getOperand(2); 3236 SDLoc SL(N); 3237 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 3238 Src0, Src1); 3239 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 3240 return; 3241 } 3242 break; 3243 } 3244 case ISD::SELECT: { 3245 SDLoc SL(N); 3246 EVT VT = N->getValueType(0); 3247 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 3248 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 3249 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 3250 3251 EVT SelectVT = NewVT; 3252 if (NewVT.bitsLT(MVT::i32)) { 3253 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 3254 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 3255 SelectVT = MVT::i32; 3256 } 3257 3258 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 3259 N->getOperand(0), LHS, RHS); 3260 3261 if (NewVT != SelectVT) 3262 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 3263 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 3264 return; 3265 } 3266 default: 3267 break; 3268 } 3269 } 3270 3271 /// \brief Helper function for LowerBRCOND 3272 static SDNode *findUser(SDValue Value, unsigned Opcode) { 3273 3274 SDNode *Parent = Value.getNode(); 3275 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 3276 I != E; ++I) { 3277 3278 if (I.getUse().get() != Value) 3279 continue; 3280 3281 if (I->getOpcode() == Opcode) 3282 return *I; 3283 } 3284 return nullptr; 3285 } 3286 3287 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 3288 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 3289 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 3290 case Intrinsic::amdgcn_if: 3291 return AMDGPUISD::IF; 3292 case Intrinsic::amdgcn_else: 3293 return AMDGPUISD::ELSE; 3294 case Intrinsic::amdgcn_loop: 3295 return AMDGPUISD::LOOP; 3296 case Intrinsic::amdgcn_end_cf: 3297 llvm_unreachable("should not occur"); 3298 default: 3299 return 0; 3300 } 3301 } 3302 3303 // break, if_break, else_break are all only used as inputs to loop, not 3304 // directly as branch conditions. 3305 return 0; 3306 } 3307 3308 void SITargetLowering::createDebuggerPrologueStackObjects( 3309 MachineFunction &MF) const { 3310 // Create stack objects that are used for emitting debugger prologue. 3311 // 3312 // Debugger prologue writes work group IDs and work item IDs to scratch memory 3313 // at fixed location in the following format: 3314 // offset 0: work group ID x 3315 // offset 4: work group ID y 3316 // offset 8: work group ID z 3317 // offset 16: work item ID x 3318 // offset 20: work item ID y 3319 // offset 24: work item ID z 3320 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3321 int ObjectIdx = 0; 3322 3323 // For each dimension: 3324 for (unsigned i = 0; i < 3; ++i) { 3325 // Create fixed stack object for work group ID. 3326 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 3327 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 3328 // Create fixed stack object for work item ID. 3329 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 3330 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 3331 } 3332 } 3333 3334 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 3335 const Triple &TT = getTargetMachine().getTargetTriple(); 3336 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS && 3337 AMDGPU::shouldEmitConstantsToTextSection(TT); 3338 } 3339 3340 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 3341 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3342 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 3343 !shouldEmitFixup(GV) && 3344 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3345 } 3346 3347 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 3348 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 3349 } 3350 3351 /// This transforms the control flow intrinsics to get the branch destination as 3352 /// last parameter, also switches branch target with BR if the need arise 3353 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 3354 SelectionDAG &DAG) const { 3355 SDLoc DL(BRCOND); 3356 3357 SDNode *Intr = BRCOND.getOperand(1).getNode(); 3358 SDValue Target = BRCOND.getOperand(2); 3359 SDNode *BR = nullptr; 3360 SDNode *SetCC = nullptr; 3361 3362 if (Intr->getOpcode() == ISD::SETCC) { 3363 // As long as we negate the condition everything is fine 3364 SetCC = Intr; 3365 Intr = SetCC->getOperand(0).getNode(); 3366 3367 } else { 3368 // Get the target from BR if we don't negate the condition 3369 BR = findUser(BRCOND, ISD::BR); 3370 Target = BR->getOperand(1); 3371 } 3372 3373 // FIXME: This changes the types of the intrinsics instead of introducing new 3374 // nodes with the correct types. 3375 // e.g. llvm.amdgcn.loop 3376 3377 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 3378 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 3379 3380 unsigned CFNode = isCFIntrinsic(Intr); 3381 if (CFNode == 0) { 3382 // This is a uniform branch so we don't need to legalize. 3383 return BRCOND; 3384 } 3385 3386 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 3387 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 3388 3389 assert(!SetCC || 3390 (SetCC->getConstantOperandVal(1) == 1 && 3391 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 3392 ISD::SETNE)); 3393 3394 // operands of the new intrinsic call 3395 SmallVector<SDValue, 4> Ops; 3396 if (HaveChain) 3397 Ops.push_back(BRCOND.getOperand(0)); 3398 3399 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 3400 Ops.push_back(Target); 3401 3402 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 3403 3404 // build the new intrinsic call 3405 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 3406 3407 if (!HaveChain) { 3408 SDValue Ops[] = { 3409 SDValue(Result, 0), 3410 BRCOND.getOperand(0) 3411 }; 3412 3413 Result = DAG.getMergeValues(Ops, DL).getNode(); 3414 } 3415 3416 if (BR) { 3417 // Give the branch instruction our target 3418 SDValue Ops[] = { 3419 BR->getOperand(0), 3420 BRCOND.getOperand(2) 3421 }; 3422 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 3423 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 3424 BR = NewBR.getNode(); 3425 } 3426 3427 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 3428 3429 // Copy the intrinsic results to registers 3430 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 3431 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 3432 if (!CopyToReg) 3433 continue; 3434 3435 Chain = DAG.getCopyToReg( 3436 Chain, DL, 3437 CopyToReg->getOperand(1), 3438 SDValue(Result, i - 1), 3439 SDValue()); 3440 3441 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 3442 } 3443 3444 // Remove the old intrinsic from the chain 3445 DAG.ReplaceAllUsesOfValueWith( 3446 SDValue(Intr, Intr->getNumValues() - 1), 3447 Intr->getOperand(0)); 3448 3449 return Chain; 3450 } 3451 3452 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 3453 SDValue Op, 3454 const SDLoc &DL, 3455 EVT VT) const { 3456 return Op.getValueType().bitsLE(VT) ? 3457 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 3458 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 3459 } 3460 3461 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 3462 assert(Op.getValueType() == MVT::f16 && 3463 "Do not know how to custom lower FP_ROUND for non-f16 type"); 3464 3465 SDValue Src = Op.getOperand(0); 3466 EVT SrcVT = Src.getValueType(); 3467 if (SrcVT != MVT::f64) 3468 return Op; 3469 3470 SDLoc DL(Op); 3471 3472 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 3473 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 3474 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 3475 } 3476 3477 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 3478 SDLoc SL(Op); 3479 MachineFunction &MF = DAG.getMachineFunction(); 3480 SDValue Chain = Op.getOperand(0); 3481 3482 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ? 3483 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap; 3484 3485 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa && 3486 Subtarget->isTrapHandlerEnabled()) { 3487 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3488 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3489 assert(UserSGPR != AMDGPU::NoRegister); 3490 3491 SDValue QueuePtr = CreateLiveInRegister( 3492 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3493 3494 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 3495 3496 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 3497 QueuePtr, SDValue()); 3498 3499 SDValue Ops[] = { 3500 ToReg, 3501 DAG.getTargetConstant(TrapID, SL, MVT::i16), 3502 SGPR01, 3503 ToReg.getValue(1) 3504 }; 3505 3506 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 3507 } 3508 3509 switch (TrapID) { 3510 case SISubtarget::TrapIDLLVMTrap: 3511 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 3512 case SISubtarget::TrapIDLLVMDebugTrap: { 3513 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(), 3514 "debugtrap handler not supported", 3515 Op.getDebugLoc(), 3516 DS_Warning); 3517 LLVMContext &Ctx = MF.getFunction()->getContext(); 3518 Ctx.diagnose(NoTrap); 3519 return Chain; 3520 } 3521 default: 3522 llvm_unreachable("unsupported trap handler type!"); 3523 } 3524 3525 return Chain; 3526 } 3527 3528 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 3529 SelectionDAG &DAG) const { 3530 // FIXME: Use inline constants (src_{shared, private}_base) instead. 3531 if (Subtarget->hasApertureRegs()) { 3532 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ? 3533 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 3534 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 3535 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ? 3536 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 3537 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 3538 unsigned Encoding = 3539 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 3540 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 3541 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 3542 3543 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 3544 SDValue ApertureReg = SDValue( 3545 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 3546 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 3547 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 3548 } 3549 3550 MachineFunction &MF = DAG.getMachineFunction(); 3551 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3552 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3553 assert(UserSGPR != AMDGPU::NoRegister); 3554 3555 SDValue QueuePtr = CreateLiveInRegister( 3556 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3557 3558 // Offset into amd_queue_t for group_segment_aperture_base_hi / 3559 // private_segment_aperture_base_hi. 3560 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44; 3561 3562 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr, 3563 DAG.getConstant(StructOffset, DL, MVT::i64)); 3564 3565 // TODO: Use custom target PseudoSourceValue. 3566 // TODO: We should use the value from the IR intrinsic call, but it might not 3567 // be available and how do we get it? 3568 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 3569 AMDGPUASI.CONSTANT_ADDRESS)); 3570 3571 MachinePointerInfo PtrInfo(V, StructOffset); 3572 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 3573 MinAlign(64, StructOffset), 3574 MachineMemOperand::MODereferenceable | 3575 MachineMemOperand::MOInvariant); 3576 } 3577 3578 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 3579 SelectionDAG &DAG) const { 3580 SDLoc SL(Op); 3581 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 3582 3583 SDValue Src = ASC->getOperand(0); 3584 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 3585 3586 const AMDGPUTargetMachine &TM = 3587 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 3588 3589 // flat -> local/private 3590 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 3591 unsigned DestAS = ASC->getDestAddressSpace(); 3592 3593 if (DestAS == AMDGPUASI.LOCAL_ADDRESS || 3594 DestAS == AMDGPUASI.PRIVATE_ADDRESS) { 3595 unsigned NullVal = TM.getNullPointerValue(DestAS); 3596 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 3597 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 3598 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 3599 3600 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 3601 NonNull, Ptr, SegmentNullPtr); 3602 } 3603 } 3604 3605 // local/private -> flat 3606 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 3607 unsigned SrcAS = ASC->getSrcAddressSpace(); 3608 3609 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS || 3610 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) { 3611 unsigned NullVal = TM.getNullPointerValue(SrcAS); 3612 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 3613 3614 SDValue NonNull 3615 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 3616 3617 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 3618 SDValue CvtPtr 3619 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 3620 3621 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 3622 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 3623 FlatNullPtr); 3624 } 3625 } 3626 3627 // global <-> flat are no-ops and never emitted. 3628 3629 const MachineFunction &MF = DAG.getMachineFunction(); 3630 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 3631 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 3632 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 3633 3634 return DAG.getUNDEF(ASC->getValueType(0)); 3635 } 3636 3637 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3638 SelectionDAG &DAG) const { 3639 SDValue Idx = Op.getOperand(2); 3640 if (isa<ConstantSDNode>(Idx)) 3641 return SDValue(); 3642 3643 // Avoid stack access for dynamic indexing. 3644 SDLoc SL(Op); 3645 SDValue Vec = Op.getOperand(0); 3646 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1)); 3647 3648 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 3649 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val); 3650 3651 // Convert vector index to bit-index. 3652 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 3653 DAG.getConstant(16, SL, MVT::i32)); 3654 3655 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3656 3657 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32, 3658 DAG.getConstant(0xffff, SL, MVT::i32), 3659 ScaledIdx); 3660 3661 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal); 3662 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32, 3663 DAG.getNOT(SL, BFM, MVT::i32), BCVec); 3664 3665 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS); 3666 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI); 3667 } 3668 3669 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3670 SelectionDAG &DAG) const { 3671 SDLoc SL(Op); 3672 3673 EVT ResultVT = Op.getValueType(); 3674 SDValue Vec = Op.getOperand(0); 3675 SDValue Idx = Op.getOperand(1); 3676 3677 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 3678 3679 // Make sure we we do any optimizations that will make it easier to fold 3680 // source modifiers before obscuring it with bit operations. 3681 3682 // XXX - Why doesn't this get called when vector_shuffle is expanded? 3683 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 3684 return Combined; 3685 3686 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) { 3687 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3688 3689 if (CIdx->getZExtValue() == 1) { 3690 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result, 3691 DAG.getConstant(16, SL, MVT::i32)); 3692 } else { 3693 assert(CIdx->getZExtValue() == 0); 3694 } 3695 3696 if (ResultVT.bitsLT(MVT::i32)) 3697 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 3698 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 3699 } 3700 3701 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32); 3702 3703 // Convert vector index to bit-index. 3704 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen); 3705 3706 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3707 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx); 3708 3709 SDValue Result = Elt; 3710 if (ResultVT.bitsLT(MVT::i32)) 3711 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 3712 3713 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 3714 } 3715 3716 bool 3717 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 3718 // We can fold offsets for anything that doesn't require a GOT relocation. 3719 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3720 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 3721 !shouldEmitGOTReloc(GA->getGlobal()); 3722 } 3723 3724 static SDValue 3725 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 3726 const SDLoc &DL, unsigned Offset, EVT PtrVT, 3727 unsigned GAFlags = SIInstrInfo::MO_NONE) { 3728 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 3729 // lowered to the following code sequence: 3730 // 3731 // For constant address space: 3732 // s_getpc_b64 s[0:1] 3733 // s_add_u32 s0, s0, $symbol 3734 // s_addc_u32 s1, s1, 0 3735 // 3736 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 3737 // a fixup or relocation is emitted to replace $symbol with a literal 3738 // constant, which is a pc-relative offset from the encoding of the $symbol 3739 // operand to the global variable. 3740 // 3741 // For global address space: 3742 // s_getpc_b64 s[0:1] 3743 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 3744 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 3745 // 3746 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 3747 // fixups or relocations are emitted to replace $symbol@*@lo and 3748 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 3749 // which is a 64-bit pc-relative offset from the encoding of the $symbol 3750 // operand to the global variable. 3751 // 3752 // What we want here is an offset from the value returned by s_getpc 3753 // (which is the address of the s_add_u32 instruction) to the global 3754 // variable, but since the encoding of $symbol starts 4 bytes after the start 3755 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 3756 // small. This requires us to add 4 to the global variable offset in order to 3757 // compute the correct address. 3758 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 3759 GAFlags); 3760 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 3761 GAFlags == SIInstrInfo::MO_NONE ? 3762 GAFlags : GAFlags + 1); 3763 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 3764 } 3765 3766 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 3767 SDValue Op, 3768 SelectionDAG &DAG) const { 3769 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 3770 const GlobalValue *GV = GSD->getGlobal(); 3771 3772 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS && 3773 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS && 3774 // FIXME: It isn't correct to rely on the type of the pointer. This should 3775 // be removed when address space 0 is 64-bit. 3776 !GV->getType()->getElementType()->isFunctionTy()) 3777 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 3778 3779 SDLoc DL(GSD); 3780 EVT PtrVT = Op.getValueType(); 3781 3782 if (shouldEmitFixup(GV)) 3783 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 3784 else if (shouldEmitPCReloc(GV)) 3785 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 3786 SIInstrInfo::MO_REL32); 3787 3788 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 3789 SIInstrInfo::MO_GOTPCREL32); 3790 3791 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 3792 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 3793 const DataLayout &DataLayout = DAG.getDataLayout(); 3794 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 3795 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 3796 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 3797 3798 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 3799 MachineMemOperand::MODereferenceable | 3800 MachineMemOperand::MOInvariant); 3801 } 3802 3803 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 3804 const SDLoc &DL, SDValue V) const { 3805 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 3806 // the destination register. 3807 // 3808 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 3809 // so we will end up with redundant moves to m0. 3810 // 3811 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 3812 3813 // A Null SDValue creates a glue result. 3814 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 3815 V, Chain); 3816 return SDValue(M0, 0); 3817 } 3818 3819 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 3820 SDValue Op, 3821 MVT VT, 3822 unsigned Offset) const { 3823 SDLoc SL(Op); 3824 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 3825 DAG.getEntryNode(), Offset, false); 3826 // The local size values will have the hi 16-bits as zero. 3827 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 3828 DAG.getValueType(VT)); 3829 } 3830 3831 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 3832 EVT VT) { 3833 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 3834 "non-hsa intrinsic with hsa target", 3835 DL.getDebugLoc()); 3836 DAG.getContext()->diagnose(BadIntrin); 3837 return DAG.getUNDEF(VT); 3838 } 3839 3840 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 3841 EVT VT) { 3842 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 3843 "intrinsic not supported on subtarget", 3844 DL.getDebugLoc()); 3845 DAG.getContext()->diagnose(BadIntrin); 3846 return DAG.getUNDEF(VT); 3847 } 3848 3849 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3850 SelectionDAG &DAG) const { 3851 MachineFunction &MF = DAG.getMachineFunction(); 3852 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 3853 3854 EVT VT = Op.getValueType(); 3855 SDLoc DL(Op); 3856 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3857 3858 // TODO: Should this propagate fast-math-flags? 3859 3860 switch (IntrinsicID) { 3861 case Intrinsic::amdgcn_implicit_buffer_ptr: { 3862 if (getSubtarget()->isAmdCodeObjectV2(MF)) 3863 return emitNonHSAIntrinsicError(DAG, DL, VT); 3864 return getPreloadedValue(DAG, *MFI, VT, 3865 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 3866 } 3867 case Intrinsic::amdgcn_dispatch_ptr: 3868 case Intrinsic::amdgcn_queue_ptr: { 3869 if (!Subtarget->isAmdCodeObjectV2(MF)) { 3870 DiagnosticInfoUnsupported BadIntrin( 3871 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 3872 DL.getDebugLoc()); 3873 DAG.getContext()->diagnose(BadIntrin); 3874 return DAG.getUNDEF(VT); 3875 } 3876 3877 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 3878 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 3879 return getPreloadedValue(DAG, *MFI, VT, RegID); 3880 } 3881 case Intrinsic::amdgcn_implicitarg_ptr: { 3882 if (MFI->isEntryFunction()) 3883 return getImplicitArgPtr(DAG, DL); 3884 return getPreloadedValue(DAG, *MFI, VT, 3885 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 3886 } 3887 case Intrinsic::amdgcn_kernarg_segment_ptr: { 3888 return getPreloadedValue(DAG, *MFI, VT, 3889 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 3890 } 3891 case Intrinsic::amdgcn_dispatch_id: { 3892 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 3893 } 3894 case Intrinsic::amdgcn_rcp: 3895 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 3896 case Intrinsic::amdgcn_rsq: 3897 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3898 case Intrinsic::amdgcn_rsq_legacy: 3899 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3900 return emitRemovedIntrinsicError(DAG, DL, VT); 3901 3902 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 3903 case Intrinsic::amdgcn_rcp_legacy: 3904 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3905 return emitRemovedIntrinsicError(DAG, DL, VT); 3906 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 3907 case Intrinsic::amdgcn_rsq_clamp: { 3908 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 3909 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 3910 3911 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 3912 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 3913 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 3914 3915 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3916 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 3917 DAG.getConstantFP(Max, DL, VT)); 3918 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 3919 DAG.getConstantFP(Min, DL, VT)); 3920 } 3921 case Intrinsic::r600_read_ngroups_x: 3922 if (Subtarget->isAmdHsaOS()) 3923 return emitNonHSAIntrinsicError(DAG, DL, VT); 3924 3925 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3926 SI::KernelInputOffsets::NGROUPS_X, false); 3927 case Intrinsic::r600_read_ngroups_y: 3928 if (Subtarget->isAmdHsaOS()) 3929 return emitNonHSAIntrinsicError(DAG, DL, VT); 3930 3931 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3932 SI::KernelInputOffsets::NGROUPS_Y, false); 3933 case Intrinsic::r600_read_ngroups_z: 3934 if (Subtarget->isAmdHsaOS()) 3935 return emitNonHSAIntrinsicError(DAG, DL, VT); 3936 3937 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3938 SI::KernelInputOffsets::NGROUPS_Z, false); 3939 case Intrinsic::r600_read_global_size_x: 3940 if (Subtarget->isAmdHsaOS()) 3941 return emitNonHSAIntrinsicError(DAG, DL, VT); 3942 3943 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3944 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 3945 case Intrinsic::r600_read_global_size_y: 3946 if (Subtarget->isAmdHsaOS()) 3947 return emitNonHSAIntrinsicError(DAG, DL, VT); 3948 3949 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3950 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 3951 case Intrinsic::r600_read_global_size_z: 3952 if (Subtarget->isAmdHsaOS()) 3953 return emitNonHSAIntrinsicError(DAG, DL, VT); 3954 3955 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3956 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 3957 case Intrinsic::r600_read_local_size_x: 3958 if (Subtarget->isAmdHsaOS()) 3959 return emitNonHSAIntrinsicError(DAG, DL, VT); 3960 3961 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3962 SI::KernelInputOffsets::LOCAL_SIZE_X); 3963 case Intrinsic::r600_read_local_size_y: 3964 if (Subtarget->isAmdHsaOS()) 3965 return emitNonHSAIntrinsicError(DAG, DL, VT); 3966 3967 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3968 SI::KernelInputOffsets::LOCAL_SIZE_Y); 3969 case Intrinsic::r600_read_local_size_z: 3970 if (Subtarget->isAmdHsaOS()) 3971 return emitNonHSAIntrinsicError(DAG, DL, VT); 3972 3973 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3974 SI::KernelInputOffsets::LOCAL_SIZE_Z); 3975 case Intrinsic::amdgcn_workgroup_id_x: 3976 case Intrinsic::r600_read_tgid_x: 3977 return getPreloadedValue(DAG, *MFI, VT, 3978 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 3979 case Intrinsic::amdgcn_workgroup_id_y: 3980 case Intrinsic::r600_read_tgid_y: 3981 return getPreloadedValue(DAG, *MFI, VT, 3982 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 3983 case Intrinsic::amdgcn_workgroup_id_z: 3984 case Intrinsic::r600_read_tgid_z: 3985 return getPreloadedValue(DAG, *MFI, VT, 3986 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 3987 case Intrinsic::amdgcn_workitem_id_x: { 3988 case Intrinsic::r600_read_tidig_x: 3989 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 3990 SDLoc(DAG.getEntryNode()), 3991 MFI->getArgInfo().WorkItemIDX); 3992 } 3993 case Intrinsic::amdgcn_workitem_id_y: 3994 case Intrinsic::r600_read_tidig_y: 3995 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 3996 SDLoc(DAG.getEntryNode()), 3997 MFI->getArgInfo().WorkItemIDY); 3998 case Intrinsic::amdgcn_workitem_id_z: 3999 case Intrinsic::r600_read_tidig_z: 4000 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4001 SDLoc(DAG.getEntryNode()), 4002 MFI->getArgInfo().WorkItemIDZ); 4003 case AMDGPUIntrinsic::SI_load_const: { 4004 SDValue Ops[] = { 4005 Op.getOperand(1), 4006 Op.getOperand(2) 4007 }; 4008 4009 MachineMemOperand *MMO = MF.getMachineMemOperand( 4010 MachinePointerInfo(), 4011 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 4012 MachineMemOperand::MOInvariant, 4013 VT.getStoreSize(), 4); 4014 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 4015 Op->getVTList(), Ops, VT, MMO); 4016 } 4017 case Intrinsic::amdgcn_fdiv_fast: 4018 return lowerFDIV_FAST(Op, DAG); 4019 case Intrinsic::amdgcn_interp_mov: { 4020 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4021 SDValue Glue = M0.getValue(1); 4022 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 4023 Op.getOperand(2), Op.getOperand(3), Glue); 4024 } 4025 case Intrinsic::amdgcn_interp_p1: { 4026 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4027 SDValue Glue = M0.getValue(1); 4028 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 4029 Op.getOperand(2), Op.getOperand(3), Glue); 4030 } 4031 case Intrinsic::amdgcn_interp_p2: { 4032 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 4033 SDValue Glue = SDValue(M0.getNode(), 1); 4034 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 4035 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 4036 Glue); 4037 } 4038 case Intrinsic::amdgcn_sin: 4039 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 4040 4041 case Intrinsic::amdgcn_cos: 4042 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 4043 4044 case Intrinsic::amdgcn_log_clamp: { 4045 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4046 return SDValue(); 4047 4048 DiagnosticInfoUnsupported BadIntrin( 4049 *MF.getFunction(), "intrinsic not supported on subtarget", 4050 DL.getDebugLoc()); 4051 DAG.getContext()->diagnose(BadIntrin); 4052 return DAG.getUNDEF(VT); 4053 } 4054 case Intrinsic::amdgcn_ldexp: 4055 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 4056 Op.getOperand(1), Op.getOperand(2)); 4057 4058 case Intrinsic::amdgcn_fract: 4059 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 4060 4061 case Intrinsic::amdgcn_class: 4062 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 4063 Op.getOperand(1), Op.getOperand(2)); 4064 case Intrinsic::amdgcn_div_fmas: 4065 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 4066 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 4067 Op.getOperand(4)); 4068 4069 case Intrinsic::amdgcn_div_fixup: 4070 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 4071 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4072 4073 case Intrinsic::amdgcn_trig_preop: 4074 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 4075 Op.getOperand(1), Op.getOperand(2)); 4076 case Intrinsic::amdgcn_div_scale: { 4077 // 3rd parameter required to be a constant. 4078 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4079 if (!Param) 4080 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL); 4081 4082 // Translate to the operands expected by the machine instruction. The 4083 // first parameter must be the same as the first instruction. 4084 SDValue Numerator = Op.getOperand(1); 4085 SDValue Denominator = Op.getOperand(2); 4086 4087 // Note this order is opposite of the machine instruction's operations, 4088 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 4089 // intrinsic has the numerator as the first operand to match a normal 4090 // division operation. 4091 4092 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 4093 4094 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 4095 Denominator, Numerator); 4096 } 4097 case Intrinsic::amdgcn_icmp: { 4098 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4099 if (!CD) 4100 return DAG.getUNDEF(VT); 4101 4102 int CondCode = CD->getSExtValue(); 4103 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4104 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4105 return DAG.getUNDEF(VT); 4106 4107 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4108 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4109 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4110 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4111 } 4112 case Intrinsic::amdgcn_fcmp: { 4113 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4114 if (!CD) 4115 return DAG.getUNDEF(VT); 4116 4117 int CondCode = CD->getSExtValue(); 4118 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4119 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 4120 return DAG.getUNDEF(VT); 4121 4122 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4123 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4124 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4125 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4126 } 4127 case Intrinsic::amdgcn_fmed3: 4128 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 4129 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4130 case Intrinsic::amdgcn_fmul_legacy: 4131 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 4132 Op.getOperand(1), Op.getOperand(2)); 4133 case Intrinsic::amdgcn_sffbh: 4134 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 4135 case Intrinsic::amdgcn_sbfe: 4136 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 4137 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4138 case Intrinsic::amdgcn_ubfe: 4139 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 4140 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4141 case Intrinsic::amdgcn_cvt_pkrtz: { 4142 // FIXME: Stop adding cast if v2f16 legal. 4143 EVT VT = Op.getValueType(); 4144 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32, 4145 Op.getOperand(1), Op.getOperand(2)); 4146 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 4147 } 4148 case Intrinsic::amdgcn_wqm: { 4149 SDValue Src = Op.getOperand(1); 4150 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 4151 0); 4152 } 4153 case Intrinsic::amdgcn_wwm: { 4154 SDValue Src = Op.getOperand(1); 4155 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 4156 0); 4157 } 4158 default: 4159 return Op; 4160 } 4161 } 4162 4163 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4164 SelectionDAG &DAG) const { 4165 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4166 SDLoc DL(Op); 4167 MachineFunction &MF = DAG.getMachineFunction(); 4168 4169 switch (IntrID) { 4170 case Intrinsic::amdgcn_atomic_inc: 4171 case Intrinsic::amdgcn_atomic_dec: { 4172 MemSDNode *M = cast<MemSDNode>(Op); 4173 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 4174 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 4175 SDValue Ops[] = { 4176 M->getOperand(0), // Chain 4177 M->getOperand(2), // Ptr 4178 M->getOperand(3) // Value 4179 }; 4180 4181 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 4182 M->getMemoryVT(), M->getMemOperand()); 4183 } 4184 case Intrinsic::amdgcn_buffer_load: 4185 case Intrinsic::amdgcn_buffer_load_format: { 4186 SDValue Ops[] = { 4187 Op.getOperand(0), // Chain 4188 Op.getOperand(2), // rsrc 4189 Op.getOperand(3), // vindex 4190 Op.getOperand(4), // offset 4191 Op.getOperand(5), // glc 4192 Op.getOperand(6) // slc 4193 }; 4194 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4195 4196 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 4197 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 4198 EVT VT = Op.getValueType(); 4199 EVT IntVT = VT.changeTypeToInteger(); 4200 4201 MachineMemOperand *MMO = MF.getMachineMemOperand( 4202 MachinePointerInfo(MFI->getBufferPSV()), 4203 MachineMemOperand::MOLoad, 4204 VT.getStoreSize(), VT.getStoreSize()); 4205 4206 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO); 4207 } 4208 case Intrinsic::amdgcn_tbuffer_load: { 4209 SDValue Ops[] = { 4210 Op.getOperand(0), // Chain 4211 Op.getOperand(2), // rsrc 4212 Op.getOperand(3), // vindex 4213 Op.getOperand(4), // voffset 4214 Op.getOperand(5), // soffset 4215 Op.getOperand(6), // offset 4216 Op.getOperand(7), // dfmt 4217 Op.getOperand(8), // nfmt 4218 Op.getOperand(9), // glc 4219 Op.getOperand(10) // slc 4220 }; 4221 4222 EVT VT = Op.getOperand(2).getValueType(); 4223 4224 MachineMemOperand *MMO = MF.getMachineMemOperand( 4225 MachinePointerInfo(), 4226 MachineMemOperand::MOLoad, 4227 VT.getStoreSize(), VT.getStoreSize()); 4228 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 4229 Op->getVTList(), Ops, VT, MMO); 4230 } 4231 // Basic sample. 4232 case Intrinsic::amdgcn_image_sample: 4233 case Intrinsic::amdgcn_image_sample_cl: 4234 case Intrinsic::amdgcn_image_sample_d: 4235 case Intrinsic::amdgcn_image_sample_d_cl: 4236 case Intrinsic::amdgcn_image_sample_l: 4237 case Intrinsic::amdgcn_image_sample_b: 4238 case Intrinsic::amdgcn_image_sample_b_cl: 4239 case Intrinsic::amdgcn_image_sample_lz: 4240 case Intrinsic::amdgcn_image_sample_cd: 4241 case Intrinsic::amdgcn_image_sample_cd_cl: 4242 4243 // Sample with comparison. 4244 case Intrinsic::amdgcn_image_sample_c: 4245 case Intrinsic::amdgcn_image_sample_c_cl: 4246 case Intrinsic::amdgcn_image_sample_c_d: 4247 case Intrinsic::amdgcn_image_sample_c_d_cl: 4248 case Intrinsic::amdgcn_image_sample_c_l: 4249 case Intrinsic::amdgcn_image_sample_c_b: 4250 case Intrinsic::amdgcn_image_sample_c_b_cl: 4251 case Intrinsic::amdgcn_image_sample_c_lz: 4252 case Intrinsic::amdgcn_image_sample_c_cd: 4253 case Intrinsic::amdgcn_image_sample_c_cd_cl: 4254 4255 // Sample with offsets. 4256 case Intrinsic::amdgcn_image_sample_o: 4257 case Intrinsic::amdgcn_image_sample_cl_o: 4258 case Intrinsic::amdgcn_image_sample_d_o: 4259 case Intrinsic::amdgcn_image_sample_d_cl_o: 4260 case Intrinsic::amdgcn_image_sample_l_o: 4261 case Intrinsic::amdgcn_image_sample_b_o: 4262 case Intrinsic::amdgcn_image_sample_b_cl_o: 4263 case Intrinsic::amdgcn_image_sample_lz_o: 4264 case Intrinsic::amdgcn_image_sample_cd_o: 4265 case Intrinsic::amdgcn_image_sample_cd_cl_o: 4266 4267 // Sample with comparison and offsets. 4268 case Intrinsic::amdgcn_image_sample_c_o: 4269 case Intrinsic::amdgcn_image_sample_c_cl_o: 4270 case Intrinsic::amdgcn_image_sample_c_d_o: 4271 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 4272 case Intrinsic::amdgcn_image_sample_c_l_o: 4273 case Intrinsic::amdgcn_image_sample_c_b_o: 4274 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 4275 case Intrinsic::amdgcn_image_sample_c_lz_o: 4276 case Intrinsic::amdgcn_image_sample_c_cd_o: 4277 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 4278 4279 case Intrinsic::amdgcn_image_getlod: { 4280 // Replace dmask with everything disabled with undef. 4281 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5)); 4282 if (!DMask || DMask->isNullValue()) { 4283 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 4284 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op)); 4285 } 4286 4287 return SDValue(); 4288 } 4289 default: 4290 return SDValue(); 4291 } 4292 } 4293 4294 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4295 SelectionDAG &DAG) const { 4296 SDLoc DL(Op); 4297 SDValue Chain = Op.getOperand(0); 4298 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4299 MachineFunction &MF = DAG.getMachineFunction(); 4300 4301 switch (IntrinsicID) { 4302 case Intrinsic::amdgcn_exp: { 4303 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4304 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4305 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 4306 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 4307 4308 const SDValue Ops[] = { 4309 Chain, 4310 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4311 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4312 Op.getOperand(4), // src0 4313 Op.getOperand(5), // src1 4314 Op.getOperand(6), // src2 4315 Op.getOperand(7), // src3 4316 DAG.getTargetConstant(0, DL, MVT::i1), // compr 4317 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4318 }; 4319 4320 unsigned Opc = Done->isNullValue() ? 4321 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4322 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4323 } 4324 case Intrinsic::amdgcn_exp_compr: { 4325 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4326 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4327 SDValue Src0 = Op.getOperand(4); 4328 SDValue Src1 = Op.getOperand(5); 4329 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 4330 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 4331 4332 SDValue Undef = DAG.getUNDEF(MVT::f32); 4333 const SDValue Ops[] = { 4334 Chain, 4335 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4336 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4337 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 4338 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 4339 Undef, // src2 4340 Undef, // src3 4341 DAG.getTargetConstant(1, DL, MVT::i1), // compr 4342 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4343 }; 4344 4345 unsigned Opc = Done->isNullValue() ? 4346 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4347 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4348 } 4349 case Intrinsic::amdgcn_s_sendmsg: 4350 case Intrinsic::amdgcn_s_sendmsghalt: { 4351 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 4352 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 4353 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 4354 SDValue Glue = Chain.getValue(1); 4355 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 4356 Op.getOperand(2), Glue); 4357 } 4358 case Intrinsic::amdgcn_init_exec: { 4359 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 4360 Op.getOperand(2)); 4361 } 4362 case Intrinsic::amdgcn_init_exec_from_input: { 4363 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 4364 Op.getOperand(2), Op.getOperand(3)); 4365 } 4366 case AMDGPUIntrinsic::AMDGPU_kill: { 4367 SDValue Src = Op.getOperand(2); 4368 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 4369 if (!K->isNegative()) 4370 return Chain; 4371 4372 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 4373 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 4374 } 4375 4376 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 4377 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 4378 } 4379 case Intrinsic::amdgcn_s_barrier: { 4380 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 4381 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 4382 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second; 4383 if (WGSize <= ST.getWavefrontSize()) 4384 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 4385 Op.getOperand(0)), 0); 4386 } 4387 return SDValue(); 4388 }; 4389 case AMDGPUIntrinsic::SI_tbuffer_store: { 4390 4391 // Extract vindex and voffset from vaddr as appropriate 4392 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10)); 4393 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11)); 4394 SDValue VAddr = Op.getOperand(5); 4395 4396 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32); 4397 4398 assert(!(OffEn->isOne() && IdxEn->isOne()) && 4399 "Legacy intrinsic doesn't support both offset and index - use new version"); 4400 4401 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero; 4402 SDValue VOffset = OffEn->isOne() ? VAddr : Zero; 4403 4404 // Deal with the vec-3 case 4405 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4)); 4406 auto Opcode = NumChannels->getZExtValue() == 3 ? 4407 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT; 4408 4409 SDValue Ops[] = { 4410 Chain, 4411 Op.getOperand(3), // vdata 4412 Op.getOperand(2), // rsrc 4413 VIndex, 4414 VOffset, 4415 Op.getOperand(6), // soffset 4416 Op.getOperand(7), // inst_offset 4417 Op.getOperand(8), // dfmt 4418 Op.getOperand(9), // nfmt 4419 Op.getOperand(12), // glc 4420 Op.getOperand(13), // slc 4421 }; 4422 4423 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && 4424 "Value of tfe other than zero is unsupported"); 4425 4426 EVT VT = Op.getOperand(3).getValueType(); 4427 MachineMemOperand *MMO = MF.getMachineMemOperand( 4428 MachinePointerInfo(), 4429 MachineMemOperand::MOStore, 4430 VT.getStoreSize(), 4); 4431 return DAG.getMemIntrinsicNode(Opcode, DL, 4432 Op->getVTList(), Ops, VT, MMO); 4433 } 4434 4435 case Intrinsic::amdgcn_tbuffer_store: { 4436 SDValue Ops[] = { 4437 Chain, 4438 Op.getOperand(2), // vdata 4439 Op.getOperand(3), // rsrc 4440 Op.getOperand(4), // vindex 4441 Op.getOperand(5), // voffset 4442 Op.getOperand(6), // soffset 4443 Op.getOperand(7), // offset 4444 Op.getOperand(8), // dfmt 4445 Op.getOperand(9), // nfmt 4446 Op.getOperand(10), // glc 4447 Op.getOperand(11) // slc 4448 }; 4449 EVT VT = Op.getOperand(3).getValueType(); 4450 MachineMemOperand *MMO = MF.getMachineMemOperand( 4451 MachinePointerInfo(), 4452 MachineMemOperand::MOStore, 4453 VT.getStoreSize(), 4); 4454 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 4455 Op->getVTList(), Ops, VT, MMO); 4456 } 4457 4458 default: 4459 return Op; 4460 } 4461 } 4462 4463 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 4464 SDLoc DL(Op); 4465 LoadSDNode *Load = cast<LoadSDNode>(Op); 4466 ISD::LoadExtType ExtType = Load->getExtensionType(); 4467 EVT MemVT = Load->getMemoryVT(); 4468 4469 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 4470 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 4471 return SDValue(); 4472 4473 // FIXME: Copied from PPC 4474 // First, load into 32 bits, then truncate to 1 bit. 4475 4476 SDValue Chain = Load->getChain(); 4477 SDValue BasePtr = Load->getBasePtr(); 4478 MachineMemOperand *MMO = Load->getMemOperand(); 4479 4480 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 4481 4482 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 4483 BasePtr, RealMemVT, MMO); 4484 4485 SDValue Ops[] = { 4486 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 4487 NewLD.getValue(1) 4488 }; 4489 4490 return DAG.getMergeValues(Ops, DL); 4491 } 4492 4493 if (!MemVT.isVector()) 4494 return SDValue(); 4495 4496 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 4497 "Custom lowering for non-i32 vectors hasn't been implemented."); 4498 4499 unsigned AS = Load->getAddressSpace(); 4500 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 4501 AS, Load->getAlignment())) { 4502 SDValue Ops[2]; 4503 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 4504 return DAG.getMergeValues(Ops, DL); 4505 } 4506 4507 MachineFunction &MF = DAG.getMachineFunction(); 4508 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4509 // If there is a possibilty that flat instruction access scratch memory 4510 // then we need to use the same legalization rules we use for private. 4511 if (AS == AMDGPUASI.FLAT_ADDRESS) 4512 AS = MFI->hasFlatScratchInit() ? 4513 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4514 4515 unsigned NumElements = MemVT.getVectorNumElements(); 4516 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 4517 if (isMemOpUniform(Load)) 4518 return SDValue(); 4519 // Non-uniform loads will be selected to MUBUF instructions, so they 4520 // have the same legalization requirements as global and private 4521 // loads. 4522 // 4523 } 4524 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) { 4525 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) && 4526 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load)) 4527 return SDValue(); 4528 // Non-uniform loads will be selected to MUBUF instructions, so they 4529 // have the same legalization requirements as global and private 4530 // loads. 4531 // 4532 } 4533 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS || 4534 AS == AMDGPUASI.FLAT_ADDRESS) { 4535 if (NumElements > 4) 4536 return SplitVectorLoad(Op, DAG); 4537 // v4 loads are supported for private and global memory. 4538 return SDValue(); 4539 } 4540 if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4541 // Depending on the setting of the private_element_size field in the 4542 // resource descriptor, we can only make private accesses up to a certain 4543 // size. 4544 switch (Subtarget->getMaxPrivateElementSize()) { 4545 case 4: 4546 return scalarizeVectorLoad(Load, DAG); 4547 case 8: 4548 if (NumElements > 2) 4549 return SplitVectorLoad(Op, DAG); 4550 return SDValue(); 4551 case 16: 4552 // Same as global/flat 4553 if (NumElements > 4) 4554 return SplitVectorLoad(Op, DAG); 4555 return SDValue(); 4556 default: 4557 llvm_unreachable("unsupported private_element_size"); 4558 } 4559 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4560 if (NumElements > 2) 4561 return SplitVectorLoad(Op, DAG); 4562 4563 if (NumElements == 2) 4564 return SDValue(); 4565 4566 // If properly aligned, if we split we might be able to use ds_read_b64. 4567 return SplitVectorLoad(Op, DAG); 4568 } 4569 return SDValue(); 4570 } 4571 4572 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4573 if (Op.getValueType() != MVT::i64) 4574 return SDValue(); 4575 4576 SDLoc DL(Op); 4577 SDValue Cond = Op.getOperand(0); 4578 4579 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 4580 SDValue One = DAG.getConstant(1, DL, MVT::i32); 4581 4582 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 4583 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 4584 4585 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 4586 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 4587 4588 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 4589 4590 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 4591 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 4592 4593 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 4594 4595 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 4596 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 4597 } 4598 4599 // Catch division cases where we can use shortcuts with rcp and rsq 4600 // instructions. 4601 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 4602 SelectionDAG &DAG) const { 4603 SDLoc SL(Op); 4604 SDValue LHS = Op.getOperand(0); 4605 SDValue RHS = Op.getOperand(1); 4606 EVT VT = Op.getValueType(); 4607 const SDNodeFlags Flags = Op->getFlags(); 4608 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || 4609 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal(); 4610 4611 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 4612 return SDValue(); 4613 4614 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 4615 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 4616 if (CLHS->isExactlyValue(1.0)) { 4617 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 4618 // the CI documentation has a worst case error of 1 ulp. 4619 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 4620 // use it as long as we aren't trying to use denormals. 4621 // 4622 // v_rcp_f16 and v_rsq_f16 DO support denormals. 4623 4624 // 1.0 / sqrt(x) -> rsq(x) 4625 4626 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 4627 // error seems really high at 2^29 ULP. 4628 if (RHS.getOpcode() == ISD::FSQRT) 4629 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 4630 4631 // 1.0 / x -> rcp(x) 4632 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 4633 } 4634 4635 // Same as for 1.0, but expand the sign out of the constant. 4636 if (CLHS->isExactlyValue(-1.0)) { 4637 // -1.0 / x -> rcp (fneg x) 4638 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 4639 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 4640 } 4641 } 4642 } 4643 4644 if (Unsafe) { 4645 // Turn into multiply by the reciprocal. 4646 // x / y -> x * (1.0 / y) 4647 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 4648 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 4649 } 4650 4651 return SDValue(); 4652 } 4653 4654 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 4655 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 4656 if (GlueChain->getNumValues() <= 1) { 4657 return DAG.getNode(Opcode, SL, VT, A, B); 4658 } 4659 4660 assert(GlueChain->getNumValues() == 3); 4661 4662 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 4663 switch (Opcode) { 4664 default: llvm_unreachable("no chain equivalent for opcode"); 4665 case ISD::FMUL: 4666 Opcode = AMDGPUISD::FMUL_W_CHAIN; 4667 break; 4668 } 4669 4670 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 4671 GlueChain.getValue(2)); 4672 } 4673 4674 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 4675 EVT VT, SDValue A, SDValue B, SDValue C, 4676 SDValue GlueChain) { 4677 if (GlueChain->getNumValues() <= 1) { 4678 return DAG.getNode(Opcode, SL, VT, A, B, C); 4679 } 4680 4681 assert(GlueChain->getNumValues() == 3); 4682 4683 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 4684 switch (Opcode) { 4685 default: llvm_unreachable("no chain equivalent for opcode"); 4686 case ISD::FMA: 4687 Opcode = AMDGPUISD::FMA_W_CHAIN; 4688 break; 4689 } 4690 4691 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 4692 GlueChain.getValue(2)); 4693 } 4694 4695 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 4696 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 4697 return FastLowered; 4698 4699 SDLoc SL(Op); 4700 SDValue Src0 = Op.getOperand(0); 4701 SDValue Src1 = Op.getOperand(1); 4702 4703 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4704 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4705 4706 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 4707 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 4708 4709 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 4710 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 4711 4712 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 4713 } 4714 4715 // Faster 2.5 ULP division that does not support denormals. 4716 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 4717 SDLoc SL(Op); 4718 SDValue LHS = Op.getOperand(1); 4719 SDValue RHS = Op.getOperand(2); 4720 4721 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 4722 4723 const APFloat K0Val(BitsToFloat(0x6f800000)); 4724 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 4725 4726 const APFloat K1Val(BitsToFloat(0x2f800000)); 4727 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 4728 4729 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 4730 4731 EVT SetCCVT = 4732 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 4733 4734 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 4735 4736 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 4737 4738 // TODO: Should this propagate fast-math-flags? 4739 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 4740 4741 // rcp does not support denormals. 4742 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 4743 4744 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 4745 4746 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 4747 } 4748 4749 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 4750 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 4751 return FastLowered; 4752 4753 SDLoc SL(Op); 4754 SDValue LHS = Op.getOperand(0); 4755 SDValue RHS = Op.getOperand(1); 4756 4757 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 4758 4759 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 4760 4761 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 4762 RHS, RHS, LHS); 4763 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 4764 LHS, RHS, LHS); 4765 4766 // Denominator is scaled to not be denormal, so using rcp is ok. 4767 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 4768 DenominatorScaled); 4769 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 4770 DenominatorScaled); 4771 4772 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 4773 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 4774 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 4775 4776 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 4777 4778 if (!Subtarget->hasFP32Denormals()) { 4779 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 4780 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 4781 SL, MVT::i32); 4782 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 4783 DAG.getEntryNode(), 4784 EnableDenormValue, BitField); 4785 SDValue Ops[3] = { 4786 NegDivScale0, 4787 EnableDenorm.getValue(0), 4788 EnableDenorm.getValue(1) 4789 }; 4790 4791 NegDivScale0 = DAG.getMergeValues(Ops, SL); 4792 } 4793 4794 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 4795 ApproxRcp, One, NegDivScale0); 4796 4797 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 4798 ApproxRcp, Fma0); 4799 4800 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 4801 Fma1, Fma1); 4802 4803 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 4804 NumeratorScaled, Mul); 4805 4806 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 4807 4808 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 4809 NumeratorScaled, Fma3); 4810 4811 if (!Subtarget->hasFP32Denormals()) { 4812 const SDValue DisableDenormValue = 4813 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 4814 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 4815 Fma4.getValue(1), 4816 DisableDenormValue, 4817 BitField, 4818 Fma4.getValue(2)); 4819 4820 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 4821 DisableDenorm, DAG.getRoot()); 4822 DAG.setRoot(OutputChain); 4823 } 4824 4825 SDValue Scale = NumeratorScaled.getValue(1); 4826 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 4827 Fma4, Fma1, Fma3, Scale); 4828 4829 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 4830 } 4831 4832 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 4833 if (DAG.getTarget().Options.UnsafeFPMath) 4834 return lowerFastUnsafeFDIV(Op, DAG); 4835 4836 SDLoc SL(Op); 4837 SDValue X = Op.getOperand(0); 4838 SDValue Y = Op.getOperand(1); 4839 4840 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 4841 4842 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 4843 4844 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 4845 4846 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 4847 4848 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 4849 4850 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 4851 4852 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 4853 4854 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 4855 4856 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 4857 4858 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 4859 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 4860 4861 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 4862 NegDivScale0, Mul, DivScale1); 4863 4864 SDValue Scale; 4865 4866 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 4867 // Workaround a hardware bug on SI where the condition output from div_scale 4868 // is not usable. 4869 4870 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 4871 4872 // Figure out if the scale to use for div_fmas. 4873 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 4874 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 4875 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 4876 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 4877 4878 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 4879 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 4880 4881 SDValue Scale0Hi 4882 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 4883 SDValue Scale1Hi 4884 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 4885 4886 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 4887 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 4888 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 4889 } else { 4890 Scale = DivScale1.getValue(1); 4891 } 4892 4893 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 4894 Fma4, Fma3, Mul, Scale); 4895 4896 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 4897 } 4898 4899 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 4900 EVT VT = Op.getValueType(); 4901 4902 if (VT == MVT::f32) 4903 return LowerFDIV32(Op, DAG); 4904 4905 if (VT == MVT::f64) 4906 return LowerFDIV64(Op, DAG); 4907 4908 if (VT == MVT::f16) 4909 return LowerFDIV16(Op, DAG); 4910 4911 llvm_unreachable("Unexpected type for fdiv"); 4912 } 4913 4914 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 4915 SDLoc DL(Op); 4916 StoreSDNode *Store = cast<StoreSDNode>(Op); 4917 EVT VT = Store->getMemoryVT(); 4918 4919 if (VT == MVT::i1) { 4920 return DAG.getTruncStore(Store->getChain(), DL, 4921 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 4922 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 4923 } 4924 4925 assert(VT.isVector() && 4926 Store->getValue().getValueType().getScalarType() == MVT::i32); 4927 4928 unsigned AS = Store->getAddressSpace(); 4929 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 4930 AS, Store->getAlignment())) { 4931 return expandUnalignedStore(Store, DAG); 4932 } 4933 4934 MachineFunction &MF = DAG.getMachineFunction(); 4935 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4936 // If there is a possibilty that flat instruction access scratch memory 4937 // then we need to use the same legalization rules we use for private. 4938 if (AS == AMDGPUASI.FLAT_ADDRESS) 4939 AS = MFI->hasFlatScratchInit() ? 4940 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4941 4942 unsigned NumElements = VT.getVectorNumElements(); 4943 if (AS == AMDGPUASI.GLOBAL_ADDRESS || 4944 AS == AMDGPUASI.FLAT_ADDRESS) { 4945 if (NumElements > 4) 4946 return SplitVectorStore(Op, DAG); 4947 return SDValue(); 4948 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4949 switch (Subtarget->getMaxPrivateElementSize()) { 4950 case 4: 4951 return scalarizeVectorStore(Store, DAG); 4952 case 8: 4953 if (NumElements > 2) 4954 return SplitVectorStore(Op, DAG); 4955 return SDValue(); 4956 case 16: 4957 if (NumElements > 4) 4958 return SplitVectorStore(Op, DAG); 4959 return SDValue(); 4960 default: 4961 llvm_unreachable("unsupported private_element_size"); 4962 } 4963 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4964 if (NumElements > 2) 4965 return SplitVectorStore(Op, DAG); 4966 4967 if (NumElements == 2) 4968 return Op; 4969 4970 // If properly aligned, if we split we might be able to use ds_write_b64. 4971 return SplitVectorStore(Op, DAG); 4972 } else { 4973 llvm_unreachable("unhandled address space"); 4974 } 4975 } 4976 4977 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 4978 SDLoc DL(Op); 4979 EVT VT = Op.getValueType(); 4980 SDValue Arg = Op.getOperand(0); 4981 // TODO: Should this propagate fast-math-flags? 4982 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 4983 DAG.getNode(ISD::FMUL, DL, VT, Arg, 4984 DAG.getConstantFP(0.5/M_PI, DL, 4985 VT))); 4986 4987 switch (Op.getOpcode()) { 4988 case ISD::FCOS: 4989 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 4990 case ISD::FSIN: 4991 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 4992 default: 4993 llvm_unreachable("Wrong trig opcode"); 4994 } 4995 } 4996 4997 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 4998 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 4999 assert(AtomicNode->isCompareAndSwap()); 5000 unsigned AS = AtomicNode->getAddressSpace(); 5001 5002 // No custom lowering required for local address space 5003 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI)) 5004 return Op; 5005 5006 // Non-local address space requires custom lowering for atomic compare 5007 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 5008 SDLoc DL(Op); 5009 SDValue ChainIn = Op.getOperand(0); 5010 SDValue Addr = Op.getOperand(1); 5011 SDValue Old = Op.getOperand(2); 5012 SDValue New = Op.getOperand(3); 5013 EVT VT = Op.getValueType(); 5014 MVT SimpleVT = VT.getSimpleVT(); 5015 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 5016 5017 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 5018 SDValue Ops[] = { ChainIn, Addr, NewOld }; 5019 5020 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 5021 Ops, VT, AtomicNode->getMemOperand()); 5022 } 5023 5024 //===----------------------------------------------------------------------===// 5025 // Custom DAG optimizations 5026 //===----------------------------------------------------------------------===// 5027 5028 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 5029 DAGCombinerInfo &DCI) const { 5030 EVT VT = N->getValueType(0); 5031 EVT ScalarVT = VT.getScalarType(); 5032 if (ScalarVT != MVT::f32) 5033 return SDValue(); 5034 5035 SelectionDAG &DAG = DCI.DAG; 5036 SDLoc DL(N); 5037 5038 SDValue Src = N->getOperand(0); 5039 EVT SrcVT = Src.getValueType(); 5040 5041 // TODO: We could try to match extracting the higher bytes, which would be 5042 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 5043 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 5044 // about in practice. 5045 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 5046 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 5047 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 5048 DCI.AddToWorklist(Cvt.getNode()); 5049 return Cvt; 5050 } 5051 } 5052 5053 return SDValue(); 5054 } 5055 5056 /// \brief Return true if the given offset Size in bytes can be folded into 5057 /// the immediate offsets of a memory instruction for the given address space. 5058 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 5059 const SISubtarget &STI) { 5060 auto AMDGPUASI = STI.getAMDGPUAS(); 5061 if (AS == AMDGPUASI.GLOBAL_ADDRESS) { 5062 // MUBUF instructions a 12-bit offset in bytes. 5063 return isUInt<12>(OffsetSize); 5064 } 5065 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 5066 // SMRD instructions have an 8-bit offset in dwords on SI and 5067 // a 20-bit offset in bytes on VI. 5068 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 5069 return isUInt<20>(OffsetSize); 5070 else 5071 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 5072 } 5073 if (AS == AMDGPUASI.LOCAL_ADDRESS || 5074 AS == AMDGPUASI.REGION_ADDRESS) { 5075 // The single offset versions have a 16-bit offset in bytes. 5076 return isUInt<16>(OffsetSize); 5077 } 5078 // Indirect register addressing does not use any offsets. 5079 return false; 5080 } 5081 5082 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 5083 5084 // This is a variant of 5085 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 5086 // 5087 // The normal DAG combiner will do this, but only if the add has one use since 5088 // that would increase the number of instructions. 5089 // 5090 // This prevents us from seeing a constant offset that can be folded into a 5091 // memory instruction's addressing mode. If we know the resulting add offset of 5092 // a pointer can be folded into an addressing offset, we can replace the pointer 5093 // operand with the add of new constant offset. This eliminates one of the uses, 5094 // and may allow the remaining use to also be simplified. 5095 // 5096 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 5097 unsigned AddrSpace, 5098 DAGCombinerInfo &DCI) const { 5099 SDValue N0 = N->getOperand(0); 5100 SDValue N1 = N->getOperand(1); 5101 5102 if (N0.getOpcode() != ISD::ADD) 5103 return SDValue(); 5104 5105 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 5106 if (!CN1) 5107 return SDValue(); 5108 5109 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5110 if (!CAdd) 5111 return SDValue(); 5112 5113 // If the resulting offset is too large, we can't fold it into the addressing 5114 // mode offset. 5115 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 5116 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget())) 5117 return SDValue(); 5118 5119 SelectionDAG &DAG = DCI.DAG; 5120 SDLoc SL(N); 5121 EVT VT = N->getValueType(0); 5122 5123 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 5124 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 5125 5126 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 5127 } 5128 5129 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 5130 DAGCombinerInfo &DCI) const { 5131 SDValue Ptr = N->getBasePtr(); 5132 SelectionDAG &DAG = DCI.DAG; 5133 SDLoc SL(N); 5134 5135 // TODO: We could also do this for multiplies. 5136 unsigned AS = N->getAddressSpace(); 5137 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) { 5138 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 5139 if (NewPtr) { 5140 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 5141 5142 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 5143 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 5144 } 5145 } 5146 5147 return SDValue(); 5148 } 5149 5150 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 5151 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 5152 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 5153 (Opc == ISD::XOR && Val == 0); 5154 } 5155 5156 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 5157 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 5158 // integer combine opportunities since most 64-bit operations are decomposed 5159 // this way. TODO: We won't want this for SALU especially if it is an inline 5160 // immediate. 5161 SDValue SITargetLowering::splitBinaryBitConstantOp( 5162 DAGCombinerInfo &DCI, 5163 const SDLoc &SL, 5164 unsigned Opc, SDValue LHS, 5165 const ConstantSDNode *CRHS) const { 5166 uint64_t Val = CRHS->getZExtValue(); 5167 uint32_t ValLo = Lo_32(Val); 5168 uint32_t ValHi = Hi_32(Val); 5169 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5170 5171 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 5172 bitOpWithConstantIsReducible(Opc, ValHi)) || 5173 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 5174 // If we need to materialize a 64-bit immediate, it will be split up later 5175 // anyway. Avoid creating the harder to understand 64-bit immediate 5176 // materialization. 5177 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 5178 } 5179 5180 return SDValue(); 5181 } 5182 5183 // Returns true if argument is a boolean value which is not serialized into 5184 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 5185 static bool isBoolSGPR(SDValue V) { 5186 if (V.getValueType() != MVT::i1) 5187 return false; 5188 switch (V.getOpcode()) { 5189 default: break; 5190 case ISD::SETCC: 5191 case ISD::AND: 5192 case ISD::OR: 5193 case ISD::XOR: 5194 case AMDGPUISD::FP_CLASS: 5195 return true; 5196 } 5197 return false; 5198 } 5199 5200 SDValue SITargetLowering::performAndCombine(SDNode *N, 5201 DAGCombinerInfo &DCI) const { 5202 if (DCI.isBeforeLegalize()) 5203 return SDValue(); 5204 5205 SelectionDAG &DAG = DCI.DAG; 5206 EVT VT = N->getValueType(0); 5207 SDValue LHS = N->getOperand(0); 5208 SDValue RHS = N->getOperand(1); 5209 5210 5211 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5212 if (VT == MVT::i64 && CRHS) { 5213 if (SDValue Split 5214 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 5215 return Split; 5216 } 5217 5218 if (CRHS && VT == MVT::i32) { 5219 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 5220 // nb = number of trailing zeroes in mask 5221 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 5222 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 5223 uint64_t Mask = CRHS->getZExtValue(); 5224 unsigned Bits = countPopulation(Mask); 5225 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 5226 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 5227 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 5228 unsigned Shift = CShift->getZExtValue(); 5229 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 5230 unsigned Offset = NB + Shift; 5231 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 5232 SDLoc SL(N); 5233 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 5234 LHS->getOperand(0), 5235 DAG.getConstant(Offset, SL, MVT::i32), 5236 DAG.getConstant(Bits, SL, MVT::i32)); 5237 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 5238 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 5239 DAG.getValueType(NarrowVT)); 5240 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 5241 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 5242 return Shl; 5243 } 5244 } 5245 } 5246 } 5247 5248 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 5249 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 5250 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 5251 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 5252 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 5253 5254 SDValue X = LHS.getOperand(0); 5255 SDValue Y = RHS.getOperand(0); 5256 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 5257 return SDValue(); 5258 5259 if (LCC == ISD::SETO) { 5260 if (X != LHS.getOperand(1)) 5261 return SDValue(); 5262 5263 if (RCC == ISD::SETUNE) { 5264 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 5265 if (!C1 || !C1->isInfinity() || C1->isNegative()) 5266 return SDValue(); 5267 5268 const uint32_t Mask = SIInstrFlags::N_NORMAL | 5269 SIInstrFlags::N_SUBNORMAL | 5270 SIInstrFlags::N_ZERO | 5271 SIInstrFlags::P_ZERO | 5272 SIInstrFlags::P_SUBNORMAL | 5273 SIInstrFlags::P_NORMAL; 5274 5275 static_assert(((~(SIInstrFlags::S_NAN | 5276 SIInstrFlags::Q_NAN | 5277 SIInstrFlags::N_INFINITY | 5278 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 5279 "mask not equal"); 5280 5281 SDLoc DL(N); 5282 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5283 X, DAG.getConstant(Mask, DL, MVT::i32)); 5284 } 5285 } 5286 } 5287 5288 if (VT == MVT::i32 && 5289 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 5290 // and x, (sext cc from i1) => select cc, x, 0 5291 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 5292 std::swap(LHS, RHS); 5293 if (isBoolSGPR(RHS.getOperand(0))) 5294 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 5295 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 5296 } 5297 5298 return SDValue(); 5299 } 5300 5301 SDValue SITargetLowering::performOrCombine(SDNode *N, 5302 DAGCombinerInfo &DCI) const { 5303 SelectionDAG &DAG = DCI.DAG; 5304 SDValue LHS = N->getOperand(0); 5305 SDValue RHS = N->getOperand(1); 5306 5307 EVT VT = N->getValueType(0); 5308 if (VT == MVT::i1) { 5309 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 5310 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 5311 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 5312 SDValue Src = LHS.getOperand(0); 5313 if (Src != RHS.getOperand(0)) 5314 return SDValue(); 5315 5316 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 5317 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 5318 if (!CLHS || !CRHS) 5319 return SDValue(); 5320 5321 // Only 10 bits are used. 5322 static const uint32_t MaxMask = 0x3ff; 5323 5324 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 5325 SDLoc DL(N); 5326 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5327 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 5328 } 5329 5330 return SDValue(); 5331 } 5332 5333 if (VT != MVT::i64) 5334 return SDValue(); 5335 5336 // TODO: This could be a generic combine with a predicate for extracting the 5337 // high half of an integer being free. 5338 5339 // (or i64:x, (zero_extend i32:y)) -> 5340 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 5341 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 5342 RHS.getOpcode() != ISD::ZERO_EXTEND) 5343 std::swap(LHS, RHS); 5344 5345 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 5346 SDValue ExtSrc = RHS.getOperand(0); 5347 EVT SrcVT = ExtSrc.getValueType(); 5348 if (SrcVT == MVT::i32) { 5349 SDLoc SL(N); 5350 SDValue LowLHS, HiBits; 5351 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 5352 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 5353 5354 DCI.AddToWorklist(LowOr.getNode()); 5355 DCI.AddToWorklist(HiBits.getNode()); 5356 5357 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 5358 LowOr, HiBits); 5359 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5360 } 5361 } 5362 5363 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5364 if (CRHS) { 5365 if (SDValue Split 5366 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 5367 return Split; 5368 } 5369 5370 return SDValue(); 5371 } 5372 5373 SDValue SITargetLowering::performXorCombine(SDNode *N, 5374 DAGCombinerInfo &DCI) const { 5375 EVT VT = N->getValueType(0); 5376 if (VT != MVT::i64) 5377 return SDValue(); 5378 5379 SDValue LHS = N->getOperand(0); 5380 SDValue RHS = N->getOperand(1); 5381 5382 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5383 if (CRHS) { 5384 if (SDValue Split 5385 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 5386 return Split; 5387 } 5388 5389 return SDValue(); 5390 } 5391 5392 // Instructions that will be lowered with a final instruction that zeros the 5393 // high result bits. 5394 // XXX - probably only need to list legal operations. 5395 static bool fp16SrcZerosHighBits(unsigned Opc) { 5396 switch (Opc) { 5397 case ISD::FADD: 5398 case ISD::FSUB: 5399 case ISD::FMUL: 5400 case ISD::FDIV: 5401 case ISD::FREM: 5402 case ISD::FMA: 5403 case ISD::FMAD: 5404 case ISD::FCANONICALIZE: 5405 case ISD::FP_ROUND: 5406 case ISD::UINT_TO_FP: 5407 case ISD::SINT_TO_FP: 5408 case ISD::FABS: 5409 // Fabs is lowered to a bit operation, but it's an and which will clear the 5410 // high bits anyway. 5411 case ISD::FSQRT: 5412 case ISD::FSIN: 5413 case ISD::FCOS: 5414 case ISD::FPOWI: 5415 case ISD::FPOW: 5416 case ISD::FLOG: 5417 case ISD::FLOG2: 5418 case ISD::FLOG10: 5419 case ISD::FEXP: 5420 case ISD::FEXP2: 5421 case ISD::FCEIL: 5422 case ISD::FTRUNC: 5423 case ISD::FRINT: 5424 case ISD::FNEARBYINT: 5425 case ISD::FROUND: 5426 case ISD::FFLOOR: 5427 case ISD::FMINNUM: 5428 case ISD::FMAXNUM: 5429 case AMDGPUISD::FRACT: 5430 case AMDGPUISD::CLAMP: 5431 case AMDGPUISD::COS_HW: 5432 case AMDGPUISD::SIN_HW: 5433 case AMDGPUISD::FMIN3: 5434 case AMDGPUISD::FMAX3: 5435 case AMDGPUISD::FMED3: 5436 case AMDGPUISD::FMAD_FTZ: 5437 case AMDGPUISD::RCP: 5438 case AMDGPUISD::RSQ: 5439 case AMDGPUISD::LDEXP: 5440 return true; 5441 default: 5442 // fcopysign, select and others may be lowered to 32-bit bit operations 5443 // which don't zero the high bits. 5444 return false; 5445 } 5446 } 5447 5448 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 5449 DAGCombinerInfo &DCI) const { 5450 if (!Subtarget->has16BitInsts() || 5451 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 5452 return SDValue(); 5453 5454 EVT VT = N->getValueType(0); 5455 if (VT != MVT::i32) 5456 return SDValue(); 5457 5458 SDValue Src = N->getOperand(0); 5459 if (Src.getValueType() != MVT::i16) 5460 return SDValue(); 5461 5462 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 5463 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 5464 if (Src.getOpcode() == ISD::BITCAST) { 5465 SDValue BCSrc = Src.getOperand(0); 5466 if (BCSrc.getValueType() == MVT::f16 && 5467 fp16SrcZerosHighBits(BCSrc.getOpcode())) 5468 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 5469 } 5470 5471 return SDValue(); 5472 } 5473 5474 SDValue SITargetLowering::performClassCombine(SDNode *N, 5475 DAGCombinerInfo &DCI) const { 5476 SelectionDAG &DAG = DCI.DAG; 5477 SDValue Mask = N->getOperand(1); 5478 5479 // fp_class x, 0 -> false 5480 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 5481 if (CMask->isNullValue()) 5482 return DAG.getConstant(0, SDLoc(N), MVT::i1); 5483 } 5484 5485 if (N->getOperand(0).isUndef()) 5486 return DAG.getUNDEF(MVT::i1); 5487 5488 return SDValue(); 5489 } 5490 5491 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 5492 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 5493 return true; 5494 5495 return DAG.isKnownNeverNaN(Op); 5496 } 5497 5498 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op, 5499 const SISubtarget *ST, unsigned MaxDepth=5) { 5500 // If source is a result of another standard FP operation it is already in 5501 // canonical form. 5502 5503 switch (Op.getOpcode()) { 5504 default: 5505 break; 5506 5507 // These will flush denorms if required. 5508 case ISD::FADD: 5509 case ISD::FSUB: 5510 case ISD::FMUL: 5511 case ISD::FSQRT: 5512 case ISD::FCEIL: 5513 case ISD::FFLOOR: 5514 case ISD::FMA: 5515 case ISD::FMAD: 5516 5517 case ISD::FCANONICALIZE: 5518 return true; 5519 5520 case ISD::FP_ROUND: 5521 return Op.getValueType().getScalarType() != MVT::f16 || 5522 ST->hasFP16Denormals(); 5523 5524 case ISD::FP_EXTEND: 5525 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 || 5526 ST->hasFP16Denormals(); 5527 5528 case ISD::FP16_TO_FP: 5529 case ISD::FP_TO_FP16: 5530 return ST->hasFP16Denormals(); 5531 5532 // It can/will be lowered or combined as a bit operation. 5533 // Need to check their input recursively to handle. 5534 case ISD::FNEG: 5535 case ISD::FABS: 5536 return (MaxDepth > 0) && 5537 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1); 5538 5539 case ISD::FSIN: 5540 case ISD::FCOS: 5541 case ISD::FSINCOS: 5542 return Op.getValueType().getScalarType() != MVT::f16; 5543 5544 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. 5545 // For such targets need to check their input recursively. 5546 case ISD::FMINNUM: 5547 case ISD::FMAXNUM: 5548 case ISD::FMINNAN: 5549 case ISD::FMAXNAN: 5550 5551 if (ST->supportsMinMaxDenormModes() && 5552 DAG.isKnownNeverNaN(Op.getOperand(0)) && 5553 DAG.isKnownNeverNaN(Op.getOperand(1))) 5554 return true; 5555 5556 return (MaxDepth > 0) && 5557 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) && 5558 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1); 5559 5560 case ISD::ConstantFP: { 5561 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF(); 5562 return !F.isDenormal() && !(F.isNaN() && F.isSignaling()); 5563 } 5564 } 5565 return false; 5566 } 5567 5568 // Constant fold canonicalize. 5569 SDValue SITargetLowering::performFCanonicalizeCombine( 5570 SDNode *N, 5571 DAGCombinerInfo &DCI) const { 5572 SelectionDAG &DAG = DCI.DAG; 5573 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0)); 5574 5575 if (!CFP) { 5576 SDValue N0 = N->getOperand(0); 5577 EVT VT = N0.getValueType().getScalarType(); 5578 auto ST = getSubtarget(); 5579 5580 if (((VT == MVT::f32 && ST->hasFP32Denormals()) || 5581 (VT == MVT::f64 && ST->hasFP64Denormals()) || 5582 (VT == MVT::f16 && ST->hasFP16Denormals())) && 5583 DAG.isKnownNeverNaN(N0)) 5584 return N0; 5585 5586 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction()); 5587 5588 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) && 5589 isCanonicalized(DAG, N0, ST)) 5590 return N0; 5591 5592 return SDValue(); 5593 } 5594 5595 const APFloat &C = CFP->getValueAPF(); 5596 5597 // Flush denormals to 0 if not enabled. 5598 if (C.isDenormal()) { 5599 EVT VT = N->getValueType(0); 5600 EVT SVT = VT.getScalarType(); 5601 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals()) 5602 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5603 5604 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals()) 5605 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5606 5607 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals()) 5608 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5609 } 5610 5611 if (C.isNaN()) { 5612 EVT VT = N->getValueType(0); 5613 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 5614 if (C.isSignaling()) { 5615 // Quiet a signaling NaN. 5616 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 5617 } 5618 5619 // Make sure it is the canonical NaN bitpattern. 5620 // 5621 // TODO: Can we use -1 as the canonical NaN value since it's an inline 5622 // immediate? 5623 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 5624 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 5625 } 5626 5627 return N->getOperand(0); 5628 } 5629 5630 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 5631 switch (Opc) { 5632 case ISD::FMAXNUM: 5633 return AMDGPUISD::FMAX3; 5634 case ISD::SMAX: 5635 return AMDGPUISD::SMAX3; 5636 case ISD::UMAX: 5637 return AMDGPUISD::UMAX3; 5638 case ISD::FMINNUM: 5639 return AMDGPUISD::FMIN3; 5640 case ISD::SMIN: 5641 return AMDGPUISD::SMIN3; 5642 case ISD::UMIN: 5643 return AMDGPUISD::UMIN3; 5644 default: 5645 llvm_unreachable("Not a min/max opcode"); 5646 } 5647 } 5648 5649 SDValue SITargetLowering::performIntMed3ImmCombine( 5650 SelectionDAG &DAG, const SDLoc &SL, 5651 SDValue Op0, SDValue Op1, bool Signed) const { 5652 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 5653 if (!K1) 5654 return SDValue(); 5655 5656 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 5657 if (!K0) 5658 return SDValue(); 5659 5660 if (Signed) { 5661 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 5662 return SDValue(); 5663 } else { 5664 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 5665 return SDValue(); 5666 } 5667 5668 EVT VT = K0->getValueType(0); 5669 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 5670 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 5671 return DAG.getNode(Med3Opc, SL, VT, 5672 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 5673 } 5674 5675 // If there isn't a 16-bit med3 operation, convert to 32-bit. 5676 MVT NVT = MVT::i32; 5677 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5678 5679 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 5680 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 5681 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 5682 5683 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 5684 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 5685 } 5686 5687 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 5688 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 5689 return C; 5690 5691 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 5692 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 5693 return C; 5694 } 5695 5696 return nullptr; 5697 } 5698 5699 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 5700 const SDLoc &SL, 5701 SDValue Op0, 5702 SDValue Op1) const { 5703 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 5704 if (!K1) 5705 return SDValue(); 5706 5707 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 5708 if (!K0) 5709 return SDValue(); 5710 5711 // Ordered >= (although NaN inputs should have folded away by now). 5712 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 5713 if (Cmp == APFloat::cmpGreaterThan) 5714 return SDValue(); 5715 5716 // TODO: Check IEEE bit enabled? 5717 EVT VT = Op0.getValueType(); 5718 if (Subtarget->enableDX10Clamp()) { 5719 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 5720 // hardware fmed3 behavior converting to a min. 5721 // FIXME: Should this be allowing -0.0? 5722 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 5723 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 5724 } 5725 5726 // med3 for f16 is only available on gfx9+, and not available for v2f16. 5727 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 5728 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 5729 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 5730 // then give the other result, which is different from med3 with a NaN 5731 // input. 5732 SDValue Var = Op0.getOperand(0); 5733 if (!isKnownNeverSNan(DAG, Var)) 5734 return SDValue(); 5735 5736 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 5737 Var, SDValue(K0, 0), SDValue(K1, 0)); 5738 } 5739 5740 return SDValue(); 5741 } 5742 5743 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 5744 DAGCombinerInfo &DCI) const { 5745 SelectionDAG &DAG = DCI.DAG; 5746 5747 EVT VT = N->getValueType(0); 5748 unsigned Opc = N->getOpcode(); 5749 SDValue Op0 = N->getOperand(0); 5750 SDValue Op1 = N->getOperand(1); 5751 5752 // Only do this if the inner op has one use since this will just increases 5753 // register pressure for no benefit. 5754 5755 5756 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 5757 VT != MVT::f64 && 5758 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) { 5759 // max(max(a, b), c) -> max3(a, b, c) 5760 // min(min(a, b), c) -> min3(a, b, c) 5761 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 5762 SDLoc DL(N); 5763 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 5764 DL, 5765 N->getValueType(0), 5766 Op0.getOperand(0), 5767 Op0.getOperand(1), 5768 Op1); 5769 } 5770 5771 // Try commuted. 5772 // max(a, max(b, c)) -> max3(a, b, c) 5773 // min(a, min(b, c)) -> min3(a, b, c) 5774 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 5775 SDLoc DL(N); 5776 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 5777 DL, 5778 N->getValueType(0), 5779 Op0, 5780 Op1.getOperand(0), 5781 Op1.getOperand(1)); 5782 } 5783 } 5784 5785 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 5786 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 5787 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 5788 return Med3; 5789 } 5790 5791 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 5792 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 5793 return Med3; 5794 } 5795 5796 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 5797 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 5798 (Opc == AMDGPUISD::FMIN_LEGACY && 5799 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 5800 (VT == MVT::f32 || VT == MVT::f64 || 5801 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 5802 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 5803 Op0.hasOneUse()) { 5804 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 5805 return Res; 5806 } 5807 5808 return SDValue(); 5809 } 5810 5811 static bool isClampZeroToOne(SDValue A, SDValue B) { 5812 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 5813 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 5814 // FIXME: Should this be allowing -0.0? 5815 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 5816 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 5817 } 5818 } 5819 5820 return false; 5821 } 5822 5823 // FIXME: Should only worry about snans for version with chain. 5824 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 5825 DAGCombinerInfo &DCI) const { 5826 EVT VT = N->getValueType(0); 5827 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 5828 // NaNs. With a NaN input, the order of the operands may change the result. 5829 5830 SelectionDAG &DAG = DCI.DAG; 5831 SDLoc SL(N); 5832 5833 SDValue Src0 = N->getOperand(0); 5834 SDValue Src1 = N->getOperand(1); 5835 SDValue Src2 = N->getOperand(2); 5836 5837 if (isClampZeroToOne(Src0, Src1)) { 5838 // const_a, const_b, x -> clamp is safe in all cases including signaling 5839 // nans. 5840 // FIXME: Should this be allowing -0.0? 5841 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 5842 } 5843 5844 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 5845 // handling no dx10-clamp? 5846 if (Subtarget->enableDX10Clamp()) { 5847 // If NaNs is clamped to 0, we are free to reorder the inputs. 5848 5849 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 5850 std::swap(Src0, Src1); 5851 5852 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 5853 std::swap(Src1, Src2); 5854 5855 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 5856 std::swap(Src0, Src1); 5857 5858 if (isClampZeroToOne(Src1, Src2)) 5859 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 5860 } 5861 5862 return SDValue(); 5863 } 5864 5865 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 5866 DAGCombinerInfo &DCI) const { 5867 SDValue Src0 = N->getOperand(0); 5868 SDValue Src1 = N->getOperand(1); 5869 if (Src0.isUndef() && Src1.isUndef()) 5870 return DCI.DAG.getUNDEF(N->getValueType(0)); 5871 return SDValue(); 5872 } 5873 5874 SDValue SITargetLowering::performExtractVectorEltCombine( 5875 SDNode *N, DAGCombinerInfo &DCI) const { 5876 SDValue Vec = N->getOperand(0); 5877 5878 SelectionDAG &DAG = DCI.DAG; 5879 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) { 5880 SDLoc SL(N); 5881 EVT EltVT = N->getValueType(0); 5882 SDValue Idx = N->getOperand(1); 5883 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5884 Vec.getOperand(0), Idx); 5885 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt); 5886 } 5887 5888 return SDValue(); 5889 } 5890 5891 static bool convertBuildVectorCastElt(SelectionDAG &DAG, 5892 SDValue &Lo, SDValue &Hi) { 5893 if (Hi.getOpcode() == ISD::BITCAST && 5894 Hi.getOperand(0).getValueType() == MVT::f16 && 5895 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) { 5896 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo); 5897 Hi = Hi.getOperand(0); 5898 return true; 5899 } 5900 5901 return false; 5902 } 5903 5904 SDValue SITargetLowering::performBuildVectorCombine( 5905 SDNode *N, DAGCombinerInfo &DCI) const { 5906 SDLoc SL(N); 5907 5908 if (!isTypeLegal(MVT::v2i16)) 5909 return SDValue(); 5910 SelectionDAG &DAG = DCI.DAG; 5911 EVT VT = N->getValueType(0); 5912 5913 if (VT == MVT::v2i16) { 5914 SDValue Lo = N->getOperand(0); 5915 SDValue Hi = N->getOperand(1); 5916 5917 // v2i16 build_vector (const|undef), (bitcast f16:$x) 5918 // -> bitcast (v2f16 build_vector const|undef, $x 5919 if (convertBuildVectorCastElt(DAG, Lo, Hi)) { 5920 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi }); 5921 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 5922 } 5923 5924 if (convertBuildVectorCastElt(DAG, Hi, Lo)) { 5925 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo }); 5926 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 5927 } 5928 } 5929 5930 return SDValue(); 5931 } 5932 5933 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 5934 const SDNode *N0, 5935 const SDNode *N1) const { 5936 EVT VT = N0->getValueType(0); 5937 5938 // Only do this if we are not trying to support denormals. v_mad_f32 does not 5939 // support denormals ever. 5940 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 5941 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 5942 return ISD::FMAD; 5943 5944 const TargetOptions &Options = DAG.getTarget().Options; 5945 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 5946 (N0->getFlags().hasUnsafeAlgebra() && 5947 N1->getFlags().hasUnsafeAlgebra())) && 5948 isFMAFasterThanFMulAndFAdd(VT)) { 5949 return ISD::FMA; 5950 } 5951 5952 return 0; 5953 } 5954 5955 SDValue SITargetLowering::performAddCombine(SDNode *N, 5956 DAGCombinerInfo &DCI) const { 5957 SelectionDAG &DAG = DCI.DAG; 5958 EVT VT = N->getValueType(0); 5959 5960 if (VT != MVT::i32) 5961 return SDValue(); 5962 5963 SDLoc SL(N); 5964 SDValue LHS = N->getOperand(0); 5965 SDValue RHS = N->getOperand(1); 5966 5967 // add x, zext (setcc) => addcarry x, 0, setcc 5968 // add x, sext (setcc) => subcarry x, 0, setcc 5969 unsigned Opc = LHS.getOpcode(); 5970 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 5971 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 5972 std::swap(RHS, LHS); 5973 5974 Opc = RHS.getOpcode(); 5975 switch (Opc) { 5976 default: break; 5977 case ISD::ZERO_EXTEND: 5978 case ISD::SIGN_EXTEND: 5979 case ISD::ANY_EXTEND: { 5980 auto Cond = RHS.getOperand(0); 5981 if (!isBoolSGPR(Cond)) 5982 break; 5983 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 5984 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 5985 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 5986 return DAG.getNode(Opc, SL, VTList, Args); 5987 } 5988 case ISD::ADDCARRY: { 5989 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 5990 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 5991 if (!C || C->getZExtValue() != 0) break; 5992 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 5993 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 5994 } 5995 } 5996 return SDValue(); 5997 } 5998 5999 SDValue SITargetLowering::performSubCombine(SDNode *N, 6000 DAGCombinerInfo &DCI) const { 6001 SelectionDAG &DAG = DCI.DAG; 6002 EVT VT = N->getValueType(0); 6003 6004 if (VT != MVT::i32) 6005 return SDValue(); 6006 6007 SDLoc SL(N); 6008 SDValue LHS = N->getOperand(0); 6009 SDValue RHS = N->getOperand(1); 6010 6011 unsigned Opc = LHS.getOpcode(); 6012 if (Opc != ISD::SUBCARRY) 6013 std::swap(RHS, LHS); 6014 6015 if (LHS.getOpcode() == ISD::SUBCARRY) { 6016 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 6017 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6018 if (!C || C->getZExtValue() != 0) 6019 return SDValue(); 6020 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 6021 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 6022 } 6023 return SDValue(); 6024 } 6025 6026 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 6027 DAGCombinerInfo &DCI) const { 6028 6029 if (N->getValueType(0) != MVT::i32) 6030 return SDValue(); 6031 6032 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6033 if (!C || C->getZExtValue() != 0) 6034 return SDValue(); 6035 6036 SelectionDAG &DAG = DCI.DAG; 6037 SDValue LHS = N->getOperand(0); 6038 6039 // addcarry (add x, y), 0, cc => addcarry x, y, cc 6040 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 6041 unsigned LHSOpc = LHS.getOpcode(); 6042 unsigned Opc = N->getOpcode(); 6043 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 6044 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 6045 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 6046 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 6047 } 6048 return SDValue(); 6049 } 6050 6051 SDValue SITargetLowering::performFAddCombine(SDNode *N, 6052 DAGCombinerInfo &DCI) const { 6053 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6054 return SDValue(); 6055 6056 SelectionDAG &DAG = DCI.DAG; 6057 EVT VT = N->getValueType(0); 6058 6059 SDLoc SL(N); 6060 SDValue LHS = N->getOperand(0); 6061 SDValue RHS = N->getOperand(1); 6062 6063 // These should really be instruction patterns, but writing patterns with 6064 // source modiifiers is a pain. 6065 6066 // fadd (fadd (a, a), b) -> mad 2.0, a, b 6067 if (LHS.getOpcode() == ISD::FADD) { 6068 SDValue A = LHS.getOperand(0); 6069 if (A == LHS.getOperand(1)) { 6070 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6071 if (FusedOp != 0) { 6072 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6073 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 6074 } 6075 } 6076 } 6077 6078 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 6079 if (RHS.getOpcode() == ISD::FADD) { 6080 SDValue A = RHS.getOperand(0); 6081 if (A == RHS.getOperand(1)) { 6082 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6083 if (FusedOp != 0) { 6084 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6085 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 6086 } 6087 } 6088 } 6089 6090 return SDValue(); 6091 } 6092 6093 SDValue SITargetLowering::performFSubCombine(SDNode *N, 6094 DAGCombinerInfo &DCI) const { 6095 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6096 return SDValue(); 6097 6098 SelectionDAG &DAG = DCI.DAG; 6099 SDLoc SL(N); 6100 EVT VT = N->getValueType(0); 6101 assert(!VT.isVector()); 6102 6103 // Try to get the fneg to fold into the source modifier. This undoes generic 6104 // DAG combines and folds them into the mad. 6105 // 6106 // Only do this if we are not trying to support denormals. v_mad_f32 does 6107 // not support denormals ever. 6108 SDValue LHS = N->getOperand(0); 6109 SDValue RHS = N->getOperand(1); 6110 if (LHS.getOpcode() == ISD::FADD) { 6111 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 6112 SDValue A = LHS.getOperand(0); 6113 if (A == LHS.getOperand(1)) { 6114 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6115 if (FusedOp != 0){ 6116 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6117 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 6118 6119 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 6120 } 6121 } 6122 } 6123 6124 if (RHS.getOpcode() == ISD::FADD) { 6125 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 6126 6127 SDValue A = RHS.getOperand(0); 6128 if (A == RHS.getOperand(1)) { 6129 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6130 if (FusedOp != 0){ 6131 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 6132 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 6133 } 6134 } 6135 } 6136 6137 return SDValue(); 6138 } 6139 6140 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 6141 DAGCombinerInfo &DCI) const { 6142 SelectionDAG &DAG = DCI.DAG; 6143 SDLoc SL(N); 6144 6145 SDValue LHS = N->getOperand(0); 6146 SDValue RHS = N->getOperand(1); 6147 EVT VT = LHS.getValueType(); 6148 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6149 6150 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 6151 if (!CRHS) { 6152 CRHS = dyn_cast<ConstantSDNode>(LHS); 6153 if (CRHS) { 6154 std::swap(LHS, RHS); 6155 CC = getSetCCSwappedOperands(CC); 6156 } 6157 } 6158 6159 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 6160 isBoolSGPR(LHS.getOperand(0))) { 6161 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 6162 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 6163 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 6164 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 6165 if ((CRHS->isAllOnesValue() && 6166 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 6167 (CRHS->isNullValue() && 6168 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 6169 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 6170 DAG.getConstant(-1, SL, MVT::i1)); 6171 if ((CRHS->isAllOnesValue() && 6172 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 6173 (CRHS->isNullValue() && 6174 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 6175 return LHS.getOperand(0); 6176 } 6177 6178 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 6179 VT != MVT::f16)) 6180 return SDValue(); 6181 6182 // Match isinf pattern 6183 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 6184 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 6185 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 6186 if (!CRHS) 6187 return SDValue(); 6188 6189 const APFloat &APF = CRHS->getValueAPF(); 6190 if (APF.isInfinity() && !APF.isNegative()) { 6191 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 6192 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 6193 DAG.getConstant(Mask, SL, MVT::i32)); 6194 } 6195 } 6196 6197 return SDValue(); 6198 } 6199 6200 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 6201 DAGCombinerInfo &DCI) const { 6202 SelectionDAG &DAG = DCI.DAG; 6203 SDLoc SL(N); 6204 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 6205 6206 SDValue Src = N->getOperand(0); 6207 SDValue Srl = N->getOperand(0); 6208 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 6209 Srl = Srl.getOperand(0); 6210 6211 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 6212 if (Srl.getOpcode() == ISD::SRL) { 6213 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 6214 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 6215 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 6216 6217 if (const ConstantSDNode *C = 6218 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 6219 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 6220 EVT(MVT::i32)); 6221 6222 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 6223 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 6224 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 6225 MVT::f32, Srl); 6226 } 6227 } 6228 } 6229 6230 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 6231 6232 KnownBits Known; 6233 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 6234 !DCI.isBeforeLegalizeOps()); 6235 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6236 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) || 6237 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 6238 DCI.CommitTargetLoweringOpt(TLO); 6239 } 6240 6241 return SDValue(); 6242 } 6243 6244 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 6245 DAGCombinerInfo &DCI) const { 6246 switch (N->getOpcode()) { 6247 default: 6248 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 6249 case ISD::ADD: 6250 return performAddCombine(N, DCI); 6251 case ISD::SUB: 6252 return performSubCombine(N, DCI); 6253 case ISD::ADDCARRY: 6254 case ISD::SUBCARRY: 6255 return performAddCarrySubCarryCombine(N, DCI); 6256 case ISD::FADD: 6257 return performFAddCombine(N, DCI); 6258 case ISD::FSUB: 6259 return performFSubCombine(N, DCI); 6260 case ISD::SETCC: 6261 return performSetCCCombine(N, DCI); 6262 case ISD::FMAXNUM: 6263 case ISD::FMINNUM: 6264 case ISD::SMAX: 6265 case ISD::SMIN: 6266 case ISD::UMAX: 6267 case ISD::UMIN: 6268 case AMDGPUISD::FMIN_LEGACY: 6269 case AMDGPUISD::FMAX_LEGACY: { 6270 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 6271 getTargetMachine().getOptLevel() > CodeGenOpt::None) 6272 return performMinMaxCombine(N, DCI); 6273 break; 6274 } 6275 case ISD::LOAD: 6276 case ISD::STORE: 6277 case ISD::ATOMIC_LOAD: 6278 case ISD::ATOMIC_STORE: 6279 case ISD::ATOMIC_CMP_SWAP: 6280 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 6281 case ISD::ATOMIC_SWAP: 6282 case ISD::ATOMIC_LOAD_ADD: 6283 case ISD::ATOMIC_LOAD_SUB: 6284 case ISD::ATOMIC_LOAD_AND: 6285 case ISD::ATOMIC_LOAD_OR: 6286 case ISD::ATOMIC_LOAD_XOR: 6287 case ISD::ATOMIC_LOAD_NAND: 6288 case ISD::ATOMIC_LOAD_MIN: 6289 case ISD::ATOMIC_LOAD_MAX: 6290 case ISD::ATOMIC_LOAD_UMIN: 6291 case ISD::ATOMIC_LOAD_UMAX: 6292 case AMDGPUISD::ATOMIC_INC: 6293 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics. 6294 if (DCI.isBeforeLegalize()) 6295 break; 6296 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 6297 case ISD::AND: 6298 return performAndCombine(N, DCI); 6299 case ISD::OR: 6300 return performOrCombine(N, DCI); 6301 case ISD::XOR: 6302 return performXorCombine(N, DCI); 6303 case ISD::ZERO_EXTEND: 6304 return performZeroExtendCombine(N, DCI); 6305 case AMDGPUISD::FP_CLASS: 6306 return performClassCombine(N, DCI); 6307 case ISD::FCANONICALIZE: 6308 return performFCanonicalizeCombine(N, DCI); 6309 case AMDGPUISD::FRACT: 6310 case AMDGPUISD::RCP: 6311 case AMDGPUISD::RSQ: 6312 case AMDGPUISD::RCP_LEGACY: 6313 case AMDGPUISD::RSQ_LEGACY: 6314 case AMDGPUISD::RSQ_CLAMP: 6315 case AMDGPUISD::LDEXP: { 6316 SDValue Src = N->getOperand(0); 6317 if (Src.isUndef()) 6318 return Src; 6319 break; 6320 } 6321 case ISD::SINT_TO_FP: 6322 case ISD::UINT_TO_FP: 6323 return performUCharToFloatCombine(N, DCI); 6324 case AMDGPUISD::CVT_F32_UBYTE0: 6325 case AMDGPUISD::CVT_F32_UBYTE1: 6326 case AMDGPUISD::CVT_F32_UBYTE2: 6327 case AMDGPUISD::CVT_F32_UBYTE3: 6328 return performCvtF32UByteNCombine(N, DCI); 6329 case AMDGPUISD::FMED3: 6330 return performFMed3Combine(N, DCI); 6331 case AMDGPUISD::CVT_PKRTZ_F16_F32: 6332 return performCvtPkRTZCombine(N, DCI); 6333 case ISD::SCALAR_TO_VECTOR: { 6334 SelectionDAG &DAG = DCI.DAG; 6335 EVT VT = N->getValueType(0); 6336 6337 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 6338 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 6339 SDLoc SL(N); 6340 SDValue Src = N->getOperand(0); 6341 EVT EltVT = Src.getValueType(); 6342 if (EltVT == MVT::f16) 6343 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 6344 6345 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 6346 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 6347 } 6348 6349 break; 6350 } 6351 case ISD::EXTRACT_VECTOR_ELT: 6352 return performExtractVectorEltCombine(N, DCI); 6353 case ISD::BUILD_VECTOR: 6354 return performBuildVectorCombine(N, DCI); 6355 } 6356 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 6357 } 6358 6359 /// \brief Helper function for adjustWritemask 6360 static unsigned SubIdx2Lane(unsigned Idx) { 6361 switch (Idx) { 6362 default: return 0; 6363 case AMDGPU::sub0: return 0; 6364 case AMDGPU::sub1: return 1; 6365 case AMDGPU::sub2: return 2; 6366 case AMDGPU::sub3: return 3; 6367 } 6368 } 6369 6370 /// \brief Adjust the writemask of MIMG instructions 6371 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 6372 SelectionDAG &DAG) const { 6373 SDNode *Users[4] = { }; 6374 unsigned Lane = 0; 6375 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 6376 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 6377 unsigned NewDmask = 0; 6378 6379 // Try to figure out the used register components 6380 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 6381 I != E; ++I) { 6382 6383 // Don't look at users of the chain. 6384 if (I.getUse().getResNo() != 0) 6385 continue; 6386 6387 // Abort if we can't understand the usage 6388 if (!I->isMachineOpcode() || 6389 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 6390 return; 6391 6392 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 6393 // Note that subregs are packed, i.e. Lane==0 is the first bit set 6394 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 6395 // set, etc. 6396 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 6397 6398 // Set which texture component corresponds to the lane. 6399 unsigned Comp; 6400 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 6401 assert(Dmask); 6402 Comp = countTrailingZeros(Dmask); 6403 Dmask &= ~(1 << Comp); 6404 } 6405 6406 // Abort if we have more than one user per component 6407 if (Users[Lane]) 6408 return; 6409 6410 Users[Lane] = *I; 6411 NewDmask |= 1 << Comp; 6412 } 6413 6414 // Abort if there's no change 6415 if (NewDmask == OldDmask) 6416 return; 6417 6418 // Adjust the writemask in the node 6419 std::vector<SDValue> Ops; 6420 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 6421 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 6422 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 6423 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 6424 6425 // If we only got one lane, replace it with a copy 6426 // (if NewDmask has only one bit set...) 6427 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 6428 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 6429 MVT::i32); 6430 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 6431 SDLoc(), Users[Lane]->getValueType(0), 6432 SDValue(Node, 0), RC); 6433 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 6434 return; 6435 } 6436 6437 // Update the users of the node with the new indices 6438 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 6439 SDNode *User = Users[i]; 6440 if (!User) 6441 continue; 6442 6443 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 6444 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 6445 6446 switch (Idx) { 6447 default: break; 6448 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 6449 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 6450 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 6451 } 6452 } 6453 } 6454 6455 static bool isFrameIndexOp(SDValue Op) { 6456 if (Op.getOpcode() == ISD::AssertZext) 6457 Op = Op.getOperand(0); 6458 6459 return isa<FrameIndexSDNode>(Op); 6460 } 6461 6462 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 6463 /// with frame index operands. 6464 /// LLVM assumes that inputs are to these instructions are registers. 6465 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 6466 SelectionDAG &DAG) const { 6467 if (Node->getOpcode() == ISD::CopyToReg) { 6468 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 6469 SDValue SrcVal = Node->getOperand(2); 6470 6471 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 6472 // to try understanding copies to physical registers. 6473 if (SrcVal.getValueType() == MVT::i1 && 6474 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 6475 SDLoc SL(Node); 6476 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 6477 SDValue VReg = DAG.getRegister( 6478 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 6479 6480 SDNode *Glued = Node->getGluedNode(); 6481 SDValue ToVReg 6482 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 6483 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 6484 SDValue ToResultReg 6485 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 6486 VReg, ToVReg.getValue(1)); 6487 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 6488 DAG.RemoveDeadNode(Node); 6489 return ToResultReg.getNode(); 6490 } 6491 } 6492 6493 SmallVector<SDValue, 8> Ops; 6494 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 6495 if (!isFrameIndexOp(Node->getOperand(i))) { 6496 Ops.push_back(Node->getOperand(i)); 6497 continue; 6498 } 6499 6500 SDLoc DL(Node); 6501 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 6502 Node->getOperand(i).getValueType(), 6503 Node->getOperand(i)), 0)); 6504 } 6505 6506 DAG.UpdateNodeOperands(Node, Ops); 6507 return Node; 6508 } 6509 6510 /// \brief Fold the instructions after selecting them. 6511 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 6512 SelectionDAG &DAG) const { 6513 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6514 unsigned Opcode = Node->getMachineOpcode(); 6515 6516 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 6517 !TII->isGather4(Opcode)) 6518 adjustWritemask(Node, DAG); 6519 6520 if (Opcode == AMDGPU::INSERT_SUBREG || 6521 Opcode == AMDGPU::REG_SEQUENCE) { 6522 legalizeTargetIndependentNode(Node, DAG); 6523 return Node; 6524 } 6525 6526 switch (Opcode) { 6527 case AMDGPU::V_DIV_SCALE_F32: 6528 case AMDGPU::V_DIV_SCALE_F64: { 6529 // Satisfy the operand register constraint when one of the inputs is 6530 // undefined. Ordinarily each undef value will have its own implicit_def of 6531 // a vreg, so force these to use a single register. 6532 SDValue Src0 = Node->getOperand(0); 6533 SDValue Src1 = Node->getOperand(1); 6534 SDValue Src2 = Node->getOperand(2); 6535 6536 if ((Src0.isMachineOpcode() && 6537 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 6538 (Src0 == Src1 || Src0 == Src2)) 6539 break; 6540 6541 MVT VT = Src0.getValueType().getSimpleVT(); 6542 const TargetRegisterClass *RC = getRegClassFor(VT); 6543 6544 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 6545 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 6546 6547 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 6548 UndefReg, Src0, SDValue()); 6549 6550 // src0 must be the same register as src1 or src2, even if the value is 6551 // undefined, so make sure we don't violate this constraint. 6552 if (Src0.isMachineOpcode() && 6553 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 6554 if (Src1.isMachineOpcode() && 6555 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 6556 Src0 = Src1; 6557 else if (Src2.isMachineOpcode() && 6558 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 6559 Src0 = Src2; 6560 else { 6561 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 6562 Src0 = UndefReg; 6563 Src1 = UndefReg; 6564 } 6565 } else 6566 break; 6567 6568 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 6569 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 6570 Ops.push_back(Node->getOperand(I)); 6571 6572 Ops.push_back(ImpDef.getValue(1)); 6573 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 6574 } 6575 default: 6576 break; 6577 } 6578 6579 return Node; 6580 } 6581 6582 /// \brief Assign the register class depending on the number of 6583 /// bits set in the writemask 6584 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 6585 SDNode *Node) const { 6586 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6587 6588 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 6589 6590 if (TII->isVOP3(MI.getOpcode())) { 6591 // Make sure constant bus requirements are respected. 6592 TII->legalizeOperandsVOP3(MRI, MI); 6593 return; 6594 } 6595 6596 if (TII->isMIMG(MI)) { 6597 unsigned VReg = MI.getOperand(0).getReg(); 6598 const TargetRegisterClass *RC = MRI.getRegClass(VReg); 6599 // TODO: Need mapping tables to handle other cases (register classes). 6600 if (RC != &AMDGPU::VReg_128RegClass) 6601 return; 6602 6603 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4; 6604 unsigned Writemask = MI.getOperand(DmaskIdx).getImm(); 6605 unsigned BitsSet = 0; 6606 for (unsigned i = 0; i < 4; ++i) 6607 BitsSet += Writemask & (1 << i) ? 1 : 0; 6608 switch (BitsSet) { 6609 default: return; 6610 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 6611 case 2: RC = &AMDGPU::VReg_64RegClass; break; 6612 case 3: RC = &AMDGPU::VReg_96RegClass; break; 6613 } 6614 6615 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet); 6616 MI.setDesc(TII->get(NewOpcode)); 6617 MRI.setRegClass(VReg, RC); 6618 return; 6619 } 6620 6621 // Replace unused atomics with the no return version. 6622 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 6623 if (NoRetAtomicOp != -1) { 6624 if (!Node->hasAnyUseOfValue(0)) { 6625 MI.setDesc(TII->get(NoRetAtomicOp)); 6626 MI.RemoveOperand(0); 6627 return; 6628 } 6629 6630 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 6631 // instruction, because the return type of these instructions is a vec2 of 6632 // the memory type, so it can be tied to the input operand. 6633 // This means these instructions always have a use, so we need to add a 6634 // special case to check if the atomic has only one extract_subreg use, 6635 // which itself has no uses. 6636 if ((Node->hasNUsesOfValue(1, 0) && 6637 Node->use_begin()->isMachineOpcode() && 6638 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 6639 !Node->use_begin()->hasAnyUseOfValue(0))) { 6640 unsigned Def = MI.getOperand(0).getReg(); 6641 6642 // Change this into a noret atomic. 6643 MI.setDesc(TII->get(NoRetAtomicOp)); 6644 MI.RemoveOperand(0); 6645 6646 // If we only remove the def operand from the atomic instruction, the 6647 // extract_subreg will be left with a use of a vreg without a def. 6648 // So we need to insert an implicit_def to avoid machine verifier 6649 // errors. 6650 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 6651 TII->get(AMDGPU::IMPLICIT_DEF), Def); 6652 } 6653 return; 6654 } 6655 } 6656 6657 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 6658 uint64_t Val) { 6659 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 6660 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 6661 } 6662 6663 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 6664 const SDLoc &DL, 6665 SDValue Ptr) const { 6666 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6667 6668 // Build the half of the subregister with the constants before building the 6669 // full 128-bit register. If we are building multiple resource descriptors, 6670 // this will allow CSEing of the 2-component register. 6671 const SDValue Ops0[] = { 6672 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 6673 buildSMovImm32(DAG, DL, 0), 6674 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 6675 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 6676 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 6677 }; 6678 6679 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 6680 MVT::v2i32, Ops0), 0); 6681 6682 // Combine the constants and the pointer. 6683 const SDValue Ops1[] = { 6684 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 6685 Ptr, 6686 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 6687 SubRegHi, 6688 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 6689 }; 6690 6691 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 6692 } 6693 6694 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 6695 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 6696 /// of the resource descriptor) to create an offset, which is added to 6697 /// the resource pointer. 6698 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 6699 SDValue Ptr, uint32_t RsrcDword1, 6700 uint64_t RsrcDword2And3) const { 6701 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 6702 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 6703 if (RsrcDword1) { 6704 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 6705 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 6706 0); 6707 } 6708 6709 SDValue DataLo = buildSMovImm32(DAG, DL, 6710 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 6711 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 6712 6713 const SDValue Ops[] = { 6714 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 6715 PtrLo, 6716 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 6717 PtrHi, 6718 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 6719 DataLo, 6720 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 6721 DataHi, 6722 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 6723 }; 6724 6725 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 6726 } 6727 6728 //===----------------------------------------------------------------------===// 6729 // SI Inline Assembly Support 6730 //===----------------------------------------------------------------------===// 6731 6732 std::pair<unsigned, const TargetRegisterClass *> 6733 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 6734 StringRef Constraint, 6735 MVT VT) const { 6736 if (!isTypeLegal(VT)) 6737 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6738 6739 if (Constraint.size() == 1) { 6740 switch (Constraint[0]) { 6741 case 's': 6742 case 'r': 6743 switch (VT.getSizeInBits()) { 6744 default: 6745 return std::make_pair(0U, nullptr); 6746 case 32: 6747 case 16: 6748 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 6749 case 64: 6750 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 6751 case 128: 6752 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 6753 case 256: 6754 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 6755 case 512: 6756 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 6757 } 6758 6759 case 'v': 6760 switch (VT.getSizeInBits()) { 6761 default: 6762 return std::make_pair(0U, nullptr); 6763 case 32: 6764 case 16: 6765 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 6766 case 64: 6767 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 6768 case 96: 6769 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 6770 case 128: 6771 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 6772 case 256: 6773 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 6774 case 512: 6775 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 6776 } 6777 } 6778 } 6779 6780 if (Constraint.size() > 1) { 6781 const TargetRegisterClass *RC = nullptr; 6782 if (Constraint[1] == 'v') { 6783 RC = &AMDGPU::VGPR_32RegClass; 6784 } else if (Constraint[1] == 's') { 6785 RC = &AMDGPU::SGPR_32RegClass; 6786 } 6787 6788 if (RC) { 6789 uint32_t Idx; 6790 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 6791 if (!Failed && Idx < RC->getNumRegs()) 6792 return std::make_pair(RC->getRegister(Idx), RC); 6793 } 6794 } 6795 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6796 } 6797 6798 SITargetLowering::ConstraintType 6799 SITargetLowering::getConstraintType(StringRef Constraint) const { 6800 if (Constraint.size() == 1) { 6801 switch (Constraint[0]) { 6802 default: break; 6803 case 's': 6804 case 'v': 6805 return C_RegisterClass; 6806 } 6807 } 6808 return TargetLowering::getConstraintType(Constraint); 6809 } 6810 6811 // Figure out which registers should be reserved for stack access. Only after 6812 // the function is legalized do we know all of the non-spill stack objects or if 6813 // calls are present. 6814 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 6815 MachineRegisterInfo &MRI = MF.getRegInfo(); 6816 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 6817 const MachineFrameInfo &MFI = MF.getFrameInfo(); 6818 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 6819 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 6820 6821 if (Info->isEntryFunction()) { 6822 // Callable functions have fixed registers used for stack access. 6823 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 6824 } 6825 6826 // We have to assume the SP is needed in case there are calls in the function 6827 // during lowering. Calls are only detected after the function is 6828 // lowered. We're about to reserve registers, so don't bother using it if we 6829 // aren't really going to use it. 6830 bool NeedSP = !Info->isEntryFunction() || 6831 MFI.hasVarSizedObjects() || 6832 MFI.hasCalls(); 6833 6834 if (NeedSP) { 6835 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF); 6836 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 6837 6838 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()); 6839 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 6840 Info->getStackPtrOffsetReg())); 6841 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 6842 } 6843 6844 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 6845 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 6846 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 6847 Info->getScratchWaveOffsetReg()); 6848 6849 TargetLoweringBase::finalizeLowering(MF); 6850 } 6851