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->getKillTerminatorFromPseudo(MI.getOpcode())); 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->getKillTerminatorFromPseudo(MI.getOpcode())); 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_F32_COND_IMM_PSEUDO: 3021 case AMDGPU::SI_KILL_I1_PSEUDO: 3022 return splitKillBlock(MI, BB); 3023 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3024 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3025 3026 unsigned Dst = MI.getOperand(0).getReg(); 3027 unsigned Src0 = MI.getOperand(1).getReg(); 3028 unsigned Src1 = MI.getOperand(2).getReg(); 3029 const DebugLoc &DL = MI.getDebugLoc(); 3030 unsigned SrcCond = MI.getOperand(3).getReg(); 3031 3032 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3033 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3034 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3035 3036 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3037 .addReg(SrcCond); 3038 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3039 .addReg(Src0, 0, AMDGPU::sub0) 3040 .addReg(Src1, 0, AMDGPU::sub0) 3041 .addReg(SrcCondCopy); 3042 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3043 .addReg(Src0, 0, AMDGPU::sub1) 3044 .addReg(Src1, 0, AMDGPU::sub1) 3045 .addReg(SrcCondCopy); 3046 3047 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3048 .addReg(DstLo) 3049 .addImm(AMDGPU::sub0) 3050 .addReg(DstHi) 3051 .addImm(AMDGPU::sub1); 3052 MI.eraseFromParent(); 3053 return BB; 3054 } 3055 case AMDGPU::SI_BR_UNDEF: { 3056 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3057 const DebugLoc &DL = MI.getDebugLoc(); 3058 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3059 .add(MI.getOperand(0)); 3060 Br->getOperand(1).setIsUndef(true); // read undef SCC 3061 MI.eraseFromParent(); 3062 return BB; 3063 } 3064 case AMDGPU::ADJCALLSTACKUP: 3065 case AMDGPU::ADJCALLSTACKDOWN: { 3066 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3067 MachineInstrBuilder MIB(*MF, &MI); 3068 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3069 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 3070 return BB; 3071 } 3072 case AMDGPU::SI_CALL_ISEL: 3073 case AMDGPU::SI_TCRETURN_ISEL: { 3074 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3075 const DebugLoc &DL = MI.getDebugLoc(); 3076 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3077 3078 MachineRegisterInfo &MRI = MF->getRegInfo(); 3079 unsigned GlobalAddrReg = MI.getOperand(0).getReg(); 3080 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg); 3081 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET); 3082 3083 const GlobalValue *G = PCRel->getOperand(1).getGlobal(); 3084 3085 MachineInstrBuilder MIB; 3086 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) { 3087 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg) 3088 .add(MI.getOperand(0)) 3089 .addGlobalAddress(G); 3090 } else { 3091 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN)) 3092 .add(MI.getOperand(0)) 3093 .addGlobalAddress(G); 3094 3095 // There is an additional imm operand for tcreturn, but it should be in the 3096 // right place already. 3097 } 3098 3099 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) 3100 MIB.add(MI.getOperand(I)); 3101 3102 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 3103 MI.eraseFromParent(); 3104 return BB; 3105 } 3106 default: 3107 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3108 } 3109 } 3110 3111 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3112 return isTypeLegal(VT.getScalarType()); 3113 } 3114 3115 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3116 // This currently forces unfolding various combinations of fsub into fma with 3117 // free fneg'd operands. As long as we have fast FMA (controlled by 3118 // isFMAFasterThanFMulAndFAdd), we should perform these. 3119 3120 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3121 // most of these combines appear to be cycle neutral but save on instruction 3122 // count / code size. 3123 return true; 3124 } 3125 3126 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3127 EVT VT) const { 3128 if (!VT.isVector()) { 3129 return MVT::i1; 3130 } 3131 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3132 } 3133 3134 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3135 // TODO: Should i16 be used always if legal? For now it would force VALU 3136 // shifts. 3137 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3138 } 3139 3140 // Answering this is somewhat tricky and depends on the specific device which 3141 // have different rates for fma or all f64 operations. 3142 // 3143 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3144 // regardless of which device (although the number of cycles differs between 3145 // devices), so it is always profitable for f64. 3146 // 3147 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3148 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3149 // which we can always do even without fused FP ops since it returns the same 3150 // result as the separate operations and since it is always full 3151 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3152 // however does not support denormals, so we do report fma as faster if we have 3153 // a fast fma device and require denormals. 3154 // 3155 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3156 VT = VT.getScalarType(); 3157 3158 switch (VT.getSimpleVT().SimpleTy) { 3159 case MVT::f32: 3160 // This is as fast on some subtargets. However, we always have full rate f32 3161 // mad available which returns the same result as the separate operations 3162 // which we should prefer over fma. We can't use this if we want to support 3163 // denormals, so only report this in these cases. 3164 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 3165 case MVT::f64: 3166 return true; 3167 case MVT::f16: 3168 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3169 default: 3170 break; 3171 } 3172 3173 return false; 3174 } 3175 3176 //===----------------------------------------------------------------------===// 3177 // Custom DAG Lowering Operations 3178 //===----------------------------------------------------------------------===// 3179 3180 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3181 switch (Op.getOpcode()) { 3182 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3183 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3184 case ISD::LOAD: { 3185 SDValue Result = LowerLOAD(Op, DAG); 3186 assert((!Result.getNode() || 3187 Result.getNode()->getNumValues() == 2) && 3188 "Load should return a value and a chain"); 3189 return Result; 3190 } 3191 3192 case ISD::FSIN: 3193 case ISD::FCOS: 3194 return LowerTrig(Op, DAG); 3195 case ISD::SELECT: return LowerSELECT(Op, DAG); 3196 case ISD::FDIV: return LowerFDIV(Op, DAG); 3197 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3198 case ISD::STORE: return LowerSTORE(Op, DAG); 3199 case ISD::GlobalAddress: { 3200 MachineFunction &MF = DAG.getMachineFunction(); 3201 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3202 return LowerGlobalAddress(MFI, Op, DAG); 3203 } 3204 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3205 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3206 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3207 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3208 case ISD::INSERT_VECTOR_ELT: 3209 return lowerINSERT_VECTOR_ELT(Op, DAG); 3210 case ISD::EXTRACT_VECTOR_ELT: 3211 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3212 case ISD::FP_ROUND: 3213 return lowerFP_ROUND(Op, DAG); 3214 3215 case ISD::TRAP: 3216 case ISD::DEBUGTRAP: 3217 return lowerTRAP(Op, DAG); 3218 } 3219 return SDValue(); 3220 } 3221 3222 void SITargetLowering::ReplaceNodeResults(SDNode *N, 3223 SmallVectorImpl<SDValue> &Results, 3224 SelectionDAG &DAG) const { 3225 switch (N->getOpcode()) { 3226 case ISD::INSERT_VECTOR_ELT: { 3227 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 3228 Results.push_back(Res); 3229 return; 3230 } 3231 case ISD::EXTRACT_VECTOR_ELT: { 3232 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 3233 Results.push_back(Res); 3234 return; 3235 } 3236 case ISD::INTRINSIC_WO_CHAIN: { 3237 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 3238 if (IID == Intrinsic::amdgcn_cvt_pkrtz) { 3239 SDValue Src0 = N->getOperand(1); 3240 SDValue Src1 = N->getOperand(2); 3241 SDLoc SL(N); 3242 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 3243 Src0, Src1); 3244 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 3245 return; 3246 } 3247 break; 3248 } 3249 case ISD::SELECT: { 3250 SDLoc SL(N); 3251 EVT VT = N->getValueType(0); 3252 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 3253 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 3254 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 3255 3256 EVT SelectVT = NewVT; 3257 if (NewVT.bitsLT(MVT::i32)) { 3258 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 3259 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 3260 SelectVT = MVT::i32; 3261 } 3262 3263 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 3264 N->getOperand(0), LHS, RHS); 3265 3266 if (NewVT != SelectVT) 3267 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 3268 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 3269 return; 3270 } 3271 default: 3272 break; 3273 } 3274 } 3275 3276 /// \brief Helper function for LowerBRCOND 3277 static SDNode *findUser(SDValue Value, unsigned Opcode) { 3278 3279 SDNode *Parent = Value.getNode(); 3280 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 3281 I != E; ++I) { 3282 3283 if (I.getUse().get() != Value) 3284 continue; 3285 3286 if (I->getOpcode() == Opcode) 3287 return *I; 3288 } 3289 return nullptr; 3290 } 3291 3292 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 3293 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 3294 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 3295 case Intrinsic::amdgcn_if: 3296 return AMDGPUISD::IF; 3297 case Intrinsic::amdgcn_else: 3298 return AMDGPUISD::ELSE; 3299 case Intrinsic::amdgcn_loop: 3300 return AMDGPUISD::LOOP; 3301 case Intrinsic::amdgcn_end_cf: 3302 llvm_unreachable("should not occur"); 3303 default: 3304 return 0; 3305 } 3306 } 3307 3308 // break, if_break, else_break are all only used as inputs to loop, not 3309 // directly as branch conditions. 3310 return 0; 3311 } 3312 3313 void SITargetLowering::createDebuggerPrologueStackObjects( 3314 MachineFunction &MF) const { 3315 // Create stack objects that are used for emitting debugger prologue. 3316 // 3317 // Debugger prologue writes work group IDs and work item IDs to scratch memory 3318 // at fixed location in the following format: 3319 // offset 0: work group ID x 3320 // offset 4: work group ID y 3321 // offset 8: work group ID z 3322 // offset 16: work item ID x 3323 // offset 20: work item ID y 3324 // offset 24: work item ID z 3325 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3326 int ObjectIdx = 0; 3327 3328 // For each dimension: 3329 for (unsigned i = 0; i < 3; ++i) { 3330 // Create fixed stack object for work group ID. 3331 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 3332 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 3333 // Create fixed stack object for work item ID. 3334 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 3335 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 3336 } 3337 } 3338 3339 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 3340 const Triple &TT = getTargetMachine().getTargetTriple(); 3341 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS && 3342 AMDGPU::shouldEmitConstantsToTextSection(TT); 3343 } 3344 3345 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 3346 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3347 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 3348 !shouldEmitFixup(GV) && 3349 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3350 } 3351 3352 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 3353 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 3354 } 3355 3356 /// This transforms the control flow intrinsics to get the branch destination as 3357 /// last parameter, also switches branch target with BR if the need arise 3358 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 3359 SelectionDAG &DAG) const { 3360 SDLoc DL(BRCOND); 3361 3362 SDNode *Intr = BRCOND.getOperand(1).getNode(); 3363 SDValue Target = BRCOND.getOperand(2); 3364 SDNode *BR = nullptr; 3365 SDNode *SetCC = nullptr; 3366 3367 if (Intr->getOpcode() == ISD::SETCC) { 3368 // As long as we negate the condition everything is fine 3369 SetCC = Intr; 3370 Intr = SetCC->getOperand(0).getNode(); 3371 3372 } else { 3373 // Get the target from BR if we don't negate the condition 3374 BR = findUser(BRCOND, ISD::BR); 3375 Target = BR->getOperand(1); 3376 } 3377 3378 // FIXME: This changes the types of the intrinsics instead of introducing new 3379 // nodes with the correct types. 3380 // e.g. llvm.amdgcn.loop 3381 3382 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 3383 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 3384 3385 unsigned CFNode = isCFIntrinsic(Intr); 3386 if (CFNode == 0) { 3387 // This is a uniform branch so we don't need to legalize. 3388 return BRCOND; 3389 } 3390 3391 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 3392 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 3393 3394 assert(!SetCC || 3395 (SetCC->getConstantOperandVal(1) == 1 && 3396 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 3397 ISD::SETNE)); 3398 3399 // operands of the new intrinsic call 3400 SmallVector<SDValue, 4> Ops; 3401 if (HaveChain) 3402 Ops.push_back(BRCOND.getOperand(0)); 3403 3404 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 3405 Ops.push_back(Target); 3406 3407 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 3408 3409 // build the new intrinsic call 3410 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 3411 3412 if (!HaveChain) { 3413 SDValue Ops[] = { 3414 SDValue(Result, 0), 3415 BRCOND.getOperand(0) 3416 }; 3417 3418 Result = DAG.getMergeValues(Ops, DL).getNode(); 3419 } 3420 3421 if (BR) { 3422 // Give the branch instruction our target 3423 SDValue Ops[] = { 3424 BR->getOperand(0), 3425 BRCOND.getOperand(2) 3426 }; 3427 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 3428 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 3429 BR = NewBR.getNode(); 3430 } 3431 3432 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 3433 3434 // Copy the intrinsic results to registers 3435 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 3436 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 3437 if (!CopyToReg) 3438 continue; 3439 3440 Chain = DAG.getCopyToReg( 3441 Chain, DL, 3442 CopyToReg->getOperand(1), 3443 SDValue(Result, i - 1), 3444 SDValue()); 3445 3446 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 3447 } 3448 3449 // Remove the old intrinsic from the chain 3450 DAG.ReplaceAllUsesOfValueWith( 3451 SDValue(Intr, Intr->getNumValues() - 1), 3452 Intr->getOperand(0)); 3453 3454 return Chain; 3455 } 3456 3457 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 3458 SDValue Op, 3459 const SDLoc &DL, 3460 EVT VT) const { 3461 return Op.getValueType().bitsLE(VT) ? 3462 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 3463 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 3464 } 3465 3466 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 3467 assert(Op.getValueType() == MVT::f16 && 3468 "Do not know how to custom lower FP_ROUND for non-f16 type"); 3469 3470 SDValue Src = Op.getOperand(0); 3471 EVT SrcVT = Src.getValueType(); 3472 if (SrcVT != MVT::f64) 3473 return Op; 3474 3475 SDLoc DL(Op); 3476 3477 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 3478 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 3479 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 3480 } 3481 3482 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 3483 SDLoc SL(Op); 3484 MachineFunction &MF = DAG.getMachineFunction(); 3485 SDValue Chain = Op.getOperand(0); 3486 3487 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ? 3488 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap; 3489 3490 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa && 3491 Subtarget->isTrapHandlerEnabled()) { 3492 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3493 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3494 assert(UserSGPR != AMDGPU::NoRegister); 3495 3496 SDValue QueuePtr = CreateLiveInRegister( 3497 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3498 3499 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 3500 3501 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 3502 QueuePtr, SDValue()); 3503 3504 SDValue Ops[] = { 3505 ToReg, 3506 DAG.getTargetConstant(TrapID, SL, MVT::i16), 3507 SGPR01, 3508 ToReg.getValue(1) 3509 }; 3510 3511 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 3512 } 3513 3514 switch (TrapID) { 3515 case SISubtarget::TrapIDLLVMTrap: 3516 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 3517 case SISubtarget::TrapIDLLVMDebugTrap: { 3518 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(), 3519 "debugtrap handler not supported", 3520 Op.getDebugLoc(), 3521 DS_Warning); 3522 LLVMContext &Ctx = MF.getFunction()->getContext(); 3523 Ctx.diagnose(NoTrap); 3524 return Chain; 3525 } 3526 default: 3527 llvm_unreachable("unsupported trap handler type!"); 3528 } 3529 3530 return Chain; 3531 } 3532 3533 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 3534 SelectionDAG &DAG) const { 3535 // FIXME: Use inline constants (src_{shared, private}_base) instead. 3536 if (Subtarget->hasApertureRegs()) { 3537 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ? 3538 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 3539 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 3540 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ? 3541 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 3542 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 3543 unsigned Encoding = 3544 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 3545 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 3546 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 3547 3548 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 3549 SDValue ApertureReg = SDValue( 3550 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 3551 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 3552 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 3553 } 3554 3555 MachineFunction &MF = DAG.getMachineFunction(); 3556 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3557 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3558 assert(UserSGPR != AMDGPU::NoRegister); 3559 3560 SDValue QueuePtr = CreateLiveInRegister( 3561 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3562 3563 // Offset into amd_queue_t for group_segment_aperture_base_hi / 3564 // private_segment_aperture_base_hi. 3565 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44; 3566 3567 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr, 3568 DAG.getConstant(StructOffset, DL, MVT::i64)); 3569 3570 // TODO: Use custom target PseudoSourceValue. 3571 // TODO: We should use the value from the IR intrinsic call, but it might not 3572 // be available and how do we get it? 3573 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 3574 AMDGPUASI.CONSTANT_ADDRESS)); 3575 3576 MachinePointerInfo PtrInfo(V, StructOffset); 3577 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 3578 MinAlign(64, StructOffset), 3579 MachineMemOperand::MODereferenceable | 3580 MachineMemOperand::MOInvariant); 3581 } 3582 3583 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 3584 SelectionDAG &DAG) const { 3585 SDLoc SL(Op); 3586 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 3587 3588 SDValue Src = ASC->getOperand(0); 3589 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 3590 3591 const AMDGPUTargetMachine &TM = 3592 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 3593 3594 // flat -> local/private 3595 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 3596 unsigned DestAS = ASC->getDestAddressSpace(); 3597 3598 if (DestAS == AMDGPUASI.LOCAL_ADDRESS || 3599 DestAS == AMDGPUASI.PRIVATE_ADDRESS) { 3600 unsigned NullVal = TM.getNullPointerValue(DestAS); 3601 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 3602 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 3603 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 3604 3605 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 3606 NonNull, Ptr, SegmentNullPtr); 3607 } 3608 } 3609 3610 // local/private -> flat 3611 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 3612 unsigned SrcAS = ASC->getSrcAddressSpace(); 3613 3614 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS || 3615 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) { 3616 unsigned NullVal = TM.getNullPointerValue(SrcAS); 3617 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 3618 3619 SDValue NonNull 3620 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 3621 3622 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 3623 SDValue CvtPtr 3624 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 3625 3626 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 3627 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 3628 FlatNullPtr); 3629 } 3630 } 3631 3632 // global <-> flat are no-ops and never emitted. 3633 3634 const MachineFunction &MF = DAG.getMachineFunction(); 3635 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 3636 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 3637 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 3638 3639 return DAG.getUNDEF(ASC->getValueType(0)); 3640 } 3641 3642 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3643 SelectionDAG &DAG) const { 3644 SDValue Idx = Op.getOperand(2); 3645 if (isa<ConstantSDNode>(Idx)) 3646 return SDValue(); 3647 3648 // Avoid stack access for dynamic indexing. 3649 SDLoc SL(Op); 3650 SDValue Vec = Op.getOperand(0); 3651 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1)); 3652 3653 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 3654 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val); 3655 3656 // Convert vector index to bit-index. 3657 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 3658 DAG.getConstant(16, SL, MVT::i32)); 3659 3660 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3661 3662 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32, 3663 DAG.getConstant(0xffff, SL, MVT::i32), 3664 ScaledIdx); 3665 3666 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal); 3667 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32, 3668 DAG.getNOT(SL, BFM, MVT::i32), BCVec); 3669 3670 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS); 3671 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI); 3672 } 3673 3674 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3675 SelectionDAG &DAG) const { 3676 SDLoc SL(Op); 3677 3678 EVT ResultVT = Op.getValueType(); 3679 SDValue Vec = Op.getOperand(0); 3680 SDValue Idx = Op.getOperand(1); 3681 3682 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 3683 3684 // Make sure we we do any optimizations that will make it easier to fold 3685 // source modifiers before obscuring it with bit operations. 3686 3687 // XXX - Why doesn't this get called when vector_shuffle is expanded? 3688 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 3689 return Combined; 3690 3691 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) { 3692 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3693 3694 if (CIdx->getZExtValue() == 1) { 3695 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result, 3696 DAG.getConstant(16, SL, MVT::i32)); 3697 } else { 3698 assert(CIdx->getZExtValue() == 0); 3699 } 3700 3701 if (ResultVT.bitsLT(MVT::i32)) 3702 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 3703 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 3704 } 3705 3706 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32); 3707 3708 // Convert vector index to bit-index. 3709 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen); 3710 3711 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3712 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx); 3713 3714 SDValue Result = Elt; 3715 if (ResultVT.bitsLT(MVT::i32)) 3716 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 3717 3718 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 3719 } 3720 3721 bool 3722 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 3723 // We can fold offsets for anything that doesn't require a GOT relocation. 3724 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3725 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 3726 !shouldEmitGOTReloc(GA->getGlobal()); 3727 } 3728 3729 static SDValue 3730 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 3731 const SDLoc &DL, unsigned Offset, EVT PtrVT, 3732 unsigned GAFlags = SIInstrInfo::MO_NONE) { 3733 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 3734 // lowered to the following code sequence: 3735 // 3736 // For constant address space: 3737 // s_getpc_b64 s[0:1] 3738 // s_add_u32 s0, s0, $symbol 3739 // s_addc_u32 s1, s1, 0 3740 // 3741 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 3742 // a fixup or relocation is emitted to replace $symbol with a literal 3743 // constant, which is a pc-relative offset from the encoding of the $symbol 3744 // operand to the global variable. 3745 // 3746 // For global address space: 3747 // s_getpc_b64 s[0:1] 3748 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 3749 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 3750 // 3751 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 3752 // fixups or relocations are emitted to replace $symbol@*@lo and 3753 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 3754 // which is a 64-bit pc-relative offset from the encoding of the $symbol 3755 // operand to the global variable. 3756 // 3757 // What we want here is an offset from the value returned by s_getpc 3758 // (which is the address of the s_add_u32 instruction) to the global 3759 // variable, but since the encoding of $symbol starts 4 bytes after the start 3760 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 3761 // small. This requires us to add 4 to the global variable offset in order to 3762 // compute the correct address. 3763 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 3764 GAFlags); 3765 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 3766 GAFlags == SIInstrInfo::MO_NONE ? 3767 GAFlags : GAFlags + 1); 3768 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 3769 } 3770 3771 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 3772 SDValue Op, 3773 SelectionDAG &DAG) const { 3774 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 3775 const GlobalValue *GV = GSD->getGlobal(); 3776 3777 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS && 3778 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS && 3779 // FIXME: It isn't correct to rely on the type of the pointer. This should 3780 // be removed when address space 0 is 64-bit. 3781 !GV->getType()->getElementType()->isFunctionTy()) 3782 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 3783 3784 SDLoc DL(GSD); 3785 EVT PtrVT = Op.getValueType(); 3786 3787 if (shouldEmitFixup(GV)) 3788 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 3789 else if (shouldEmitPCReloc(GV)) 3790 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 3791 SIInstrInfo::MO_REL32); 3792 3793 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 3794 SIInstrInfo::MO_GOTPCREL32); 3795 3796 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 3797 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 3798 const DataLayout &DataLayout = DAG.getDataLayout(); 3799 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 3800 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 3801 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 3802 3803 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 3804 MachineMemOperand::MODereferenceable | 3805 MachineMemOperand::MOInvariant); 3806 } 3807 3808 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 3809 const SDLoc &DL, SDValue V) const { 3810 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 3811 // the destination register. 3812 // 3813 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 3814 // so we will end up with redundant moves to m0. 3815 // 3816 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 3817 3818 // A Null SDValue creates a glue result. 3819 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 3820 V, Chain); 3821 return SDValue(M0, 0); 3822 } 3823 3824 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 3825 SDValue Op, 3826 MVT VT, 3827 unsigned Offset) const { 3828 SDLoc SL(Op); 3829 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 3830 DAG.getEntryNode(), Offset, false); 3831 // The local size values will have the hi 16-bits as zero. 3832 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 3833 DAG.getValueType(VT)); 3834 } 3835 3836 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 3837 EVT VT) { 3838 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 3839 "non-hsa intrinsic with hsa target", 3840 DL.getDebugLoc()); 3841 DAG.getContext()->diagnose(BadIntrin); 3842 return DAG.getUNDEF(VT); 3843 } 3844 3845 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 3846 EVT VT) { 3847 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 3848 "intrinsic not supported on subtarget", 3849 DL.getDebugLoc()); 3850 DAG.getContext()->diagnose(BadIntrin); 3851 return DAG.getUNDEF(VT); 3852 } 3853 3854 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3855 SelectionDAG &DAG) const { 3856 MachineFunction &MF = DAG.getMachineFunction(); 3857 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 3858 3859 EVT VT = Op.getValueType(); 3860 SDLoc DL(Op); 3861 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3862 3863 // TODO: Should this propagate fast-math-flags? 3864 3865 switch (IntrinsicID) { 3866 case Intrinsic::amdgcn_implicit_buffer_ptr: { 3867 if (getSubtarget()->isAmdCodeObjectV2(MF)) 3868 return emitNonHSAIntrinsicError(DAG, DL, VT); 3869 return getPreloadedValue(DAG, *MFI, VT, 3870 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 3871 } 3872 case Intrinsic::amdgcn_dispatch_ptr: 3873 case Intrinsic::amdgcn_queue_ptr: { 3874 if (!Subtarget->isAmdCodeObjectV2(MF)) { 3875 DiagnosticInfoUnsupported BadIntrin( 3876 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 3877 DL.getDebugLoc()); 3878 DAG.getContext()->diagnose(BadIntrin); 3879 return DAG.getUNDEF(VT); 3880 } 3881 3882 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 3883 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 3884 return getPreloadedValue(DAG, *MFI, VT, RegID); 3885 } 3886 case Intrinsic::amdgcn_implicitarg_ptr: { 3887 if (MFI->isEntryFunction()) 3888 return getImplicitArgPtr(DAG, DL); 3889 return getPreloadedValue(DAG, *MFI, VT, 3890 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 3891 } 3892 case Intrinsic::amdgcn_kernarg_segment_ptr: { 3893 return getPreloadedValue(DAG, *MFI, VT, 3894 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 3895 } 3896 case Intrinsic::amdgcn_dispatch_id: { 3897 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 3898 } 3899 case Intrinsic::amdgcn_rcp: 3900 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 3901 case Intrinsic::amdgcn_rsq: 3902 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3903 case Intrinsic::amdgcn_rsq_legacy: 3904 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3905 return emitRemovedIntrinsicError(DAG, DL, VT); 3906 3907 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 3908 case Intrinsic::amdgcn_rcp_legacy: 3909 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3910 return emitRemovedIntrinsicError(DAG, DL, VT); 3911 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 3912 case Intrinsic::amdgcn_rsq_clamp: { 3913 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 3914 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 3915 3916 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 3917 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 3918 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 3919 3920 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3921 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 3922 DAG.getConstantFP(Max, DL, VT)); 3923 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 3924 DAG.getConstantFP(Min, DL, VT)); 3925 } 3926 case Intrinsic::r600_read_ngroups_x: 3927 if (Subtarget->isAmdHsaOS()) 3928 return emitNonHSAIntrinsicError(DAG, DL, VT); 3929 3930 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3931 SI::KernelInputOffsets::NGROUPS_X, false); 3932 case Intrinsic::r600_read_ngroups_y: 3933 if (Subtarget->isAmdHsaOS()) 3934 return emitNonHSAIntrinsicError(DAG, DL, VT); 3935 3936 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3937 SI::KernelInputOffsets::NGROUPS_Y, false); 3938 case Intrinsic::r600_read_ngroups_z: 3939 if (Subtarget->isAmdHsaOS()) 3940 return emitNonHSAIntrinsicError(DAG, DL, VT); 3941 3942 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3943 SI::KernelInputOffsets::NGROUPS_Z, false); 3944 case Intrinsic::r600_read_global_size_x: 3945 if (Subtarget->isAmdHsaOS()) 3946 return emitNonHSAIntrinsicError(DAG, DL, VT); 3947 3948 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3949 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 3950 case Intrinsic::r600_read_global_size_y: 3951 if (Subtarget->isAmdHsaOS()) 3952 return emitNonHSAIntrinsicError(DAG, DL, VT); 3953 3954 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3955 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 3956 case Intrinsic::r600_read_global_size_z: 3957 if (Subtarget->isAmdHsaOS()) 3958 return emitNonHSAIntrinsicError(DAG, DL, VT); 3959 3960 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3961 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 3962 case Intrinsic::r600_read_local_size_x: 3963 if (Subtarget->isAmdHsaOS()) 3964 return emitNonHSAIntrinsicError(DAG, DL, VT); 3965 3966 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3967 SI::KernelInputOffsets::LOCAL_SIZE_X); 3968 case Intrinsic::r600_read_local_size_y: 3969 if (Subtarget->isAmdHsaOS()) 3970 return emitNonHSAIntrinsicError(DAG, DL, VT); 3971 3972 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3973 SI::KernelInputOffsets::LOCAL_SIZE_Y); 3974 case Intrinsic::r600_read_local_size_z: 3975 if (Subtarget->isAmdHsaOS()) 3976 return emitNonHSAIntrinsicError(DAG, DL, VT); 3977 3978 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3979 SI::KernelInputOffsets::LOCAL_SIZE_Z); 3980 case Intrinsic::amdgcn_workgroup_id_x: 3981 case Intrinsic::r600_read_tgid_x: 3982 return getPreloadedValue(DAG, *MFI, VT, 3983 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 3984 case Intrinsic::amdgcn_workgroup_id_y: 3985 case Intrinsic::r600_read_tgid_y: 3986 return getPreloadedValue(DAG, *MFI, VT, 3987 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 3988 case Intrinsic::amdgcn_workgroup_id_z: 3989 case Intrinsic::r600_read_tgid_z: 3990 return getPreloadedValue(DAG, *MFI, VT, 3991 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 3992 case Intrinsic::amdgcn_workitem_id_x: { 3993 case Intrinsic::r600_read_tidig_x: 3994 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 3995 SDLoc(DAG.getEntryNode()), 3996 MFI->getArgInfo().WorkItemIDX); 3997 } 3998 case Intrinsic::amdgcn_workitem_id_y: 3999 case Intrinsic::r600_read_tidig_y: 4000 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4001 SDLoc(DAG.getEntryNode()), 4002 MFI->getArgInfo().WorkItemIDY); 4003 case Intrinsic::amdgcn_workitem_id_z: 4004 case Intrinsic::r600_read_tidig_z: 4005 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4006 SDLoc(DAG.getEntryNode()), 4007 MFI->getArgInfo().WorkItemIDZ); 4008 case AMDGPUIntrinsic::SI_load_const: { 4009 SDValue Ops[] = { 4010 Op.getOperand(1), 4011 Op.getOperand(2) 4012 }; 4013 4014 MachineMemOperand *MMO = MF.getMachineMemOperand( 4015 MachinePointerInfo(), 4016 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 4017 MachineMemOperand::MOInvariant, 4018 VT.getStoreSize(), 4); 4019 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 4020 Op->getVTList(), Ops, VT, MMO); 4021 } 4022 case Intrinsic::amdgcn_fdiv_fast: 4023 return lowerFDIV_FAST(Op, DAG); 4024 case Intrinsic::amdgcn_interp_mov: { 4025 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4026 SDValue Glue = M0.getValue(1); 4027 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 4028 Op.getOperand(2), Op.getOperand(3), Glue); 4029 } 4030 case Intrinsic::amdgcn_interp_p1: { 4031 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4032 SDValue Glue = M0.getValue(1); 4033 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 4034 Op.getOperand(2), Op.getOperand(3), Glue); 4035 } 4036 case Intrinsic::amdgcn_interp_p2: { 4037 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 4038 SDValue Glue = SDValue(M0.getNode(), 1); 4039 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 4040 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 4041 Glue); 4042 } 4043 case Intrinsic::amdgcn_sin: 4044 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 4045 4046 case Intrinsic::amdgcn_cos: 4047 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 4048 4049 case Intrinsic::amdgcn_log_clamp: { 4050 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4051 return SDValue(); 4052 4053 DiagnosticInfoUnsupported BadIntrin( 4054 *MF.getFunction(), "intrinsic not supported on subtarget", 4055 DL.getDebugLoc()); 4056 DAG.getContext()->diagnose(BadIntrin); 4057 return DAG.getUNDEF(VT); 4058 } 4059 case Intrinsic::amdgcn_ldexp: 4060 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 4061 Op.getOperand(1), Op.getOperand(2)); 4062 4063 case Intrinsic::amdgcn_fract: 4064 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 4065 4066 case Intrinsic::amdgcn_class: 4067 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 4068 Op.getOperand(1), Op.getOperand(2)); 4069 case Intrinsic::amdgcn_div_fmas: 4070 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 4071 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 4072 Op.getOperand(4)); 4073 4074 case Intrinsic::amdgcn_div_fixup: 4075 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 4076 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4077 4078 case Intrinsic::amdgcn_trig_preop: 4079 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 4080 Op.getOperand(1), Op.getOperand(2)); 4081 case Intrinsic::amdgcn_div_scale: { 4082 // 3rd parameter required to be a constant. 4083 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4084 if (!Param) 4085 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL); 4086 4087 // Translate to the operands expected by the machine instruction. The 4088 // first parameter must be the same as the first instruction. 4089 SDValue Numerator = Op.getOperand(1); 4090 SDValue Denominator = Op.getOperand(2); 4091 4092 // Note this order is opposite of the machine instruction's operations, 4093 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 4094 // intrinsic has the numerator as the first operand to match a normal 4095 // division operation. 4096 4097 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 4098 4099 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 4100 Denominator, Numerator); 4101 } 4102 case Intrinsic::amdgcn_icmp: { 4103 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4104 if (!CD) 4105 return DAG.getUNDEF(VT); 4106 4107 int CondCode = CD->getSExtValue(); 4108 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4109 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4110 return DAG.getUNDEF(VT); 4111 4112 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4113 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4114 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4115 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4116 } 4117 case Intrinsic::amdgcn_fcmp: { 4118 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4119 if (!CD) 4120 return DAG.getUNDEF(VT); 4121 4122 int CondCode = CD->getSExtValue(); 4123 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4124 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 4125 return DAG.getUNDEF(VT); 4126 4127 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4128 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4129 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4130 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4131 } 4132 case Intrinsic::amdgcn_fmed3: 4133 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 4134 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4135 case Intrinsic::amdgcn_fmul_legacy: 4136 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 4137 Op.getOperand(1), Op.getOperand(2)); 4138 case Intrinsic::amdgcn_sffbh: 4139 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 4140 case Intrinsic::amdgcn_sbfe: 4141 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 4142 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4143 case Intrinsic::amdgcn_ubfe: 4144 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 4145 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4146 case Intrinsic::amdgcn_cvt_pkrtz: { 4147 // FIXME: Stop adding cast if v2f16 legal. 4148 EVT VT = Op.getValueType(); 4149 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32, 4150 Op.getOperand(1), Op.getOperand(2)); 4151 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 4152 } 4153 case Intrinsic::amdgcn_wqm: { 4154 SDValue Src = Op.getOperand(1); 4155 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 4156 0); 4157 } 4158 case Intrinsic::amdgcn_wwm: { 4159 SDValue Src = Op.getOperand(1); 4160 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 4161 0); 4162 } 4163 default: 4164 return Op; 4165 } 4166 } 4167 4168 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4169 SelectionDAG &DAG) const { 4170 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4171 SDLoc DL(Op); 4172 MachineFunction &MF = DAG.getMachineFunction(); 4173 4174 switch (IntrID) { 4175 case Intrinsic::amdgcn_atomic_inc: 4176 case Intrinsic::amdgcn_atomic_dec: { 4177 MemSDNode *M = cast<MemSDNode>(Op); 4178 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 4179 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 4180 SDValue Ops[] = { 4181 M->getOperand(0), // Chain 4182 M->getOperand(2), // Ptr 4183 M->getOperand(3) // Value 4184 }; 4185 4186 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 4187 M->getMemoryVT(), M->getMemOperand()); 4188 } 4189 case Intrinsic::amdgcn_buffer_load: 4190 case Intrinsic::amdgcn_buffer_load_format: { 4191 SDValue Ops[] = { 4192 Op.getOperand(0), // Chain 4193 Op.getOperand(2), // rsrc 4194 Op.getOperand(3), // vindex 4195 Op.getOperand(4), // offset 4196 Op.getOperand(5), // glc 4197 Op.getOperand(6) // slc 4198 }; 4199 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4200 4201 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 4202 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 4203 EVT VT = Op.getValueType(); 4204 EVT IntVT = VT.changeTypeToInteger(); 4205 4206 MachineMemOperand *MMO = MF.getMachineMemOperand( 4207 MachinePointerInfo(MFI->getBufferPSV()), 4208 MachineMemOperand::MOLoad, 4209 VT.getStoreSize(), VT.getStoreSize()); 4210 4211 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO); 4212 } 4213 case Intrinsic::amdgcn_tbuffer_load: { 4214 SDValue Ops[] = { 4215 Op.getOperand(0), // Chain 4216 Op.getOperand(2), // rsrc 4217 Op.getOperand(3), // vindex 4218 Op.getOperand(4), // voffset 4219 Op.getOperand(5), // soffset 4220 Op.getOperand(6), // offset 4221 Op.getOperand(7), // dfmt 4222 Op.getOperand(8), // nfmt 4223 Op.getOperand(9), // glc 4224 Op.getOperand(10) // slc 4225 }; 4226 4227 EVT VT = Op.getOperand(2).getValueType(); 4228 4229 MachineMemOperand *MMO = MF.getMachineMemOperand( 4230 MachinePointerInfo(), 4231 MachineMemOperand::MOLoad, 4232 VT.getStoreSize(), VT.getStoreSize()); 4233 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 4234 Op->getVTList(), Ops, VT, MMO); 4235 } 4236 // Basic sample. 4237 case Intrinsic::amdgcn_image_sample: 4238 case Intrinsic::amdgcn_image_sample_cl: 4239 case Intrinsic::amdgcn_image_sample_d: 4240 case Intrinsic::amdgcn_image_sample_d_cl: 4241 case Intrinsic::amdgcn_image_sample_l: 4242 case Intrinsic::amdgcn_image_sample_b: 4243 case Intrinsic::amdgcn_image_sample_b_cl: 4244 case Intrinsic::amdgcn_image_sample_lz: 4245 case Intrinsic::amdgcn_image_sample_cd: 4246 case Intrinsic::amdgcn_image_sample_cd_cl: 4247 4248 // Sample with comparison. 4249 case Intrinsic::amdgcn_image_sample_c: 4250 case Intrinsic::amdgcn_image_sample_c_cl: 4251 case Intrinsic::amdgcn_image_sample_c_d: 4252 case Intrinsic::amdgcn_image_sample_c_d_cl: 4253 case Intrinsic::amdgcn_image_sample_c_l: 4254 case Intrinsic::amdgcn_image_sample_c_b: 4255 case Intrinsic::amdgcn_image_sample_c_b_cl: 4256 case Intrinsic::amdgcn_image_sample_c_lz: 4257 case Intrinsic::amdgcn_image_sample_c_cd: 4258 case Intrinsic::amdgcn_image_sample_c_cd_cl: 4259 4260 // Sample with offsets. 4261 case Intrinsic::amdgcn_image_sample_o: 4262 case Intrinsic::amdgcn_image_sample_cl_o: 4263 case Intrinsic::amdgcn_image_sample_d_o: 4264 case Intrinsic::amdgcn_image_sample_d_cl_o: 4265 case Intrinsic::amdgcn_image_sample_l_o: 4266 case Intrinsic::amdgcn_image_sample_b_o: 4267 case Intrinsic::amdgcn_image_sample_b_cl_o: 4268 case Intrinsic::amdgcn_image_sample_lz_o: 4269 case Intrinsic::amdgcn_image_sample_cd_o: 4270 case Intrinsic::amdgcn_image_sample_cd_cl_o: 4271 4272 // Sample with comparison and offsets. 4273 case Intrinsic::amdgcn_image_sample_c_o: 4274 case Intrinsic::amdgcn_image_sample_c_cl_o: 4275 case Intrinsic::amdgcn_image_sample_c_d_o: 4276 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 4277 case Intrinsic::amdgcn_image_sample_c_l_o: 4278 case Intrinsic::amdgcn_image_sample_c_b_o: 4279 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 4280 case Intrinsic::amdgcn_image_sample_c_lz_o: 4281 case Intrinsic::amdgcn_image_sample_c_cd_o: 4282 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 4283 4284 case Intrinsic::amdgcn_image_getlod: { 4285 // Replace dmask with everything disabled with undef. 4286 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5)); 4287 if (!DMask || DMask->isNullValue()) { 4288 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 4289 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op)); 4290 } 4291 4292 return SDValue(); 4293 } 4294 default: 4295 return SDValue(); 4296 } 4297 } 4298 4299 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4300 SelectionDAG &DAG) const { 4301 SDLoc DL(Op); 4302 SDValue Chain = Op.getOperand(0); 4303 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4304 MachineFunction &MF = DAG.getMachineFunction(); 4305 4306 switch (IntrinsicID) { 4307 case Intrinsic::amdgcn_exp: { 4308 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4309 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4310 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 4311 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 4312 4313 const SDValue Ops[] = { 4314 Chain, 4315 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4316 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4317 Op.getOperand(4), // src0 4318 Op.getOperand(5), // src1 4319 Op.getOperand(6), // src2 4320 Op.getOperand(7), // src3 4321 DAG.getTargetConstant(0, DL, MVT::i1), // compr 4322 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4323 }; 4324 4325 unsigned Opc = Done->isNullValue() ? 4326 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4327 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4328 } 4329 case Intrinsic::amdgcn_exp_compr: { 4330 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4331 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4332 SDValue Src0 = Op.getOperand(4); 4333 SDValue Src1 = Op.getOperand(5); 4334 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 4335 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 4336 4337 SDValue Undef = DAG.getUNDEF(MVT::f32); 4338 const SDValue Ops[] = { 4339 Chain, 4340 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4341 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4342 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 4343 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 4344 Undef, // src2 4345 Undef, // src3 4346 DAG.getTargetConstant(1, DL, MVT::i1), // compr 4347 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4348 }; 4349 4350 unsigned Opc = Done->isNullValue() ? 4351 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4352 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4353 } 4354 case Intrinsic::amdgcn_s_sendmsg: 4355 case Intrinsic::amdgcn_s_sendmsghalt: { 4356 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 4357 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 4358 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 4359 SDValue Glue = Chain.getValue(1); 4360 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 4361 Op.getOperand(2), Glue); 4362 } 4363 case Intrinsic::amdgcn_init_exec: { 4364 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 4365 Op.getOperand(2)); 4366 } 4367 case Intrinsic::amdgcn_init_exec_from_input: { 4368 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 4369 Op.getOperand(2), Op.getOperand(3)); 4370 } 4371 case AMDGPUIntrinsic::AMDGPU_kill: { 4372 SDValue Src = Op.getOperand(2); 4373 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 4374 if (!K->isNegative()) 4375 return Chain; 4376 4377 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 4378 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 4379 } 4380 4381 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 4382 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 4383 } 4384 case Intrinsic::amdgcn_s_barrier: { 4385 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 4386 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 4387 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second; 4388 if (WGSize <= ST.getWavefrontSize()) 4389 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 4390 Op.getOperand(0)), 0); 4391 } 4392 return SDValue(); 4393 }; 4394 case AMDGPUIntrinsic::SI_tbuffer_store: { 4395 4396 // Extract vindex and voffset from vaddr as appropriate 4397 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10)); 4398 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11)); 4399 SDValue VAddr = Op.getOperand(5); 4400 4401 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32); 4402 4403 assert(!(OffEn->isOne() && IdxEn->isOne()) && 4404 "Legacy intrinsic doesn't support both offset and index - use new version"); 4405 4406 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero; 4407 SDValue VOffset = OffEn->isOne() ? VAddr : Zero; 4408 4409 // Deal with the vec-3 case 4410 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4)); 4411 auto Opcode = NumChannels->getZExtValue() == 3 ? 4412 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT; 4413 4414 SDValue Ops[] = { 4415 Chain, 4416 Op.getOperand(3), // vdata 4417 Op.getOperand(2), // rsrc 4418 VIndex, 4419 VOffset, 4420 Op.getOperand(6), // soffset 4421 Op.getOperand(7), // inst_offset 4422 Op.getOperand(8), // dfmt 4423 Op.getOperand(9), // nfmt 4424 Op.getOperand(12), // glc 4425 Op.getOperand(13), // slc 4426 }; 4427 4428 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && 4429 "Value of tfe other than zero is unsupported"); 4430 4431 EVT VT = Op.getOperand(3).getValueType(); 4432 MachineMemOperand *MMO = MF.getMachineMemOperand( 4433 MachinePointerInfo(), 4434 MachineMemOperand::MOStore, 4435 VT.getStoreSize(), 4); 4436 return DAG.getMemIntrinsicNode(Opcode, DL, 4437 Op->getVTList(), Ops, VT, MMO); 4438 } 4439 4440 case Intrinsic::amdgcn_tbuffer_store: { 4441 SDValue Ops[] = { 4442 Chain, 4443 Op.getOperand(2), // vdata 4444 Op.getOperand(3), // rsrc 4445 Op.getOperand(4), // vindex 4446 Op.getOperand(5), // voffset 4447 Op.getOperand(6), // soffset 4448 Op.getOperand(7), // offset 4449 Op.getOperand(8), // dfmt 4450 Op.getOperand(9), // nfmt 4451 Op.getOperand(10), // glc 4452 Op.getOperand(11) // slc 4453 }; 4454 EVT VT = Op.getOperand(3).getValueType(); 4455 MachineMemOperand *MMO = MF.getMachineMemOperand( 4456 MachinePointerInfo(), 4457 MachineMemOperand::MOStore, 4458 VT.getStoreSize(), 4); 4459 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 4460 Op->getVTList(), Ops, VT, MMO); 4461 } 4462 4463 default: 4464 return Op; 4465 } 4466 } 4467 4468 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 4469 SDLoc DL(Op); 4470 LoadSDNode *Load = cast<LoadSDNode>(Op); 4471 ISD::LoadExtType ExtType = Load->getExtensionType(); 4472 EVT MemVT = Load->getMemoryVT(); 4473 4474 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 4475 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 4476 return SDValue(); 4477 4478 // FIXME: Copied from PPC 4479 // First, load into 32 bits, then truncate to 1 bit. 4480 4481 SDValue Chain = Load->getChain(); 4482 SDValue BasePtr = Load->getBasePtr(); 4483 MachineMemOperand *MMO = Load->getMemOperand(); 4484 4485 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 4486 4487 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 4488 BasePtr, RealMemVT, MMO); 4489 4490 SDValue Ops[] = { 4491 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 4492 NewLD.getValue(1) 4493 }; 4494 4495 return DAG.getMergeValues(Ops, DL); 4496 } 4497 4498 if (!MemVT.isVector()) 4499 return SDValue(); 4500 4501 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 4502 "Custom lowering for non-i32 vectors hasn't been implemented."); 4503 4504 unsigned AS = Load->getAddressSpace(); 4505 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 4506 AS, Load->getAlignment())) { 4507 SDValue Ops[2]; 4508 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 4509 return DAG.getMergeValues(Ops, DL); 4510 } 4511 4512 MachineFunction &MF = DAG.getMachineFunction(); 4513 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4514 // If there is a possibilty that flat instruction access scratch memory 4515 // then we need to use the same legalization rules we use for private. 4516 if (AS == AMDGPUASI.FLAT_ADDRESS) 4517 AS = MFI->hasFlatScratchInit() ? 4518 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4519 4520 unsigned NumElements = MemVT.getVectorNumElements(); 4521 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 4522 if (isMemOpUniform(Load)) 4523 return SDValue(); 4524 // Non-uniform loads will be selected to MUBUF instructions, so they 4525 // have the same legalization requirements as global and private 4526 // loads. 4527 // 4528 } 4529 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) { 4530 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) && 4531 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load)) 4532 return SDValue(); 4533 // Non-uniform loads will be selected to MUBUF instructions, so they 4534 // have the same legalization requirements as global and private 4535 // loads. 4536 // 4537 } 4538 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS || 4539 AS == AMDGPUASI.FLAT_ADDRESS) { 4540 if (NumElements > 4) 4541 return SplitVectorLoad(Op, DAG); 4542 // v4 loads are supported for private and global memory. 4543 return SDValue(); 4544 } 4545 if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4546 // Depending on the setting of the private_element_size field in the 4547 // resource descriptor, we can only make private accesses up to a certain 4548 // size. 4549 switch (Subtarget->getMaxPrivateElementSize()) { 4550 case 4: 4551 return scalarizeVectorLoad(Load, DAG); 4552 case 8: 4553 if (NumElements > 2) 4554 return SplitVectorLoad(Op, DAG); 4555 return SDValue(); 4556 case 16: 4557 // Same as global/flat 4558 if (NumElements > 4) 4559 return SplitVectorLoad(Op, DAG); 4560 return SDValue(); 4561 default: 4562 llvm_unreachable("unsupported private_element_size"); 4563 } 4564 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4565 if (NumElements > 2) 4566 return SplitVectorLoad(Op, DAG); 4567 4568 if (NumElements == 2) 4569 return SDValue(); 4570 4571 // If properly aligned, if we split we might be able to use ds_read_b64. 4572 return SplitVectorLoad(Op, DAG); 4573 } 4574 return SDValue(); 4575 } 4576 4577 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4578 if (Op.getValueType() != MVT::i64) 4579 return SDValue(); 4580 4581 SDLoc DL(Op); 4582 SDValue Cond = Op.getOperand(0); 4583 4584 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 4585 SDValue One = DAG.getConstant(1, DL, MVT::i32); 4586 4587 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 4588 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 4589 4590 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 4591 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 4592 4593 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 4594 4595 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 4596 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 4597 4598 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 4599 4600 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 4601 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 4602 } 4603 4604 // Catch division cases where we can use shortcuts with rcp and rsq 4605 // instructions. 4606 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 4607 SelectionDAG &DAG) const { 4608 SDLoc SL(Op); 4609 SDValue LHS = Op.getOperand(0); 4610 SDValue RHS = Op.getOperand(1); 4611 EVT VT = Op.getValueType(); 4612 const SDNodeFlags Flags = Op->getFlags(); 4613 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || 4614 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal(); 4615 4616 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 4617 return SDValue(); 4618 4619 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 4620 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 4621 if (CLHS->isExactlyValue(1.0)) { 4622 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 4623 // the CI documentation has a worst case error of 1 ulp. 4624 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 4625 // use it as long as we aren't trying to use denormals. 4626 // 4627 // v_rcp_f16 and v_rsq_f16 DO support denormals. 4628 4629 // 1.0 / sqrt(x) -> rsq(x) 4630 4631 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 4632 // error seems really high at 2^29 ULP. 4633 if (RHS.getOpcode() == ISD::FSQRT) 4634 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 4635 4636 // 1.0 / x -> rcp(x) 4637 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 4638 } 4639 4640 // Same as for 1.0, but expand the sign out of the constant. 4641 if (CLHS->isExactlyValue(-1.0)) { 4642 // -1.0 / x -> rcp (fneg x) 4643 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 4644 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 4645 } 4646 } 4647 } 4648 4649 if (Unsafe) { 4650 // Turn into multiply by the reciprocal. 4651 // x / y -> x * (1.0 / y) 4652 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 4653 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 4654 } 4655 4656 return SDValue(); 4657 } 4658 4659 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 4660 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 4661 if (GlueChain->getNumValues() <= 1) { 4662 return DAG.getNode(Opcode, SL, VT, A, B); 4663 } 4664 4665 assert(GlueChain->getNumValues() == 3); 4666 4667 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 4668 switch (Opcode) { 4669 default: llvm_unreachable("no chain equivalent for opcode"); 4670 case ISD::FMUL: 4671 Opcode = AMDGPUISD::FMUL_W_CHAIN; 4672 break; 4673 } 4674 4675 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 4676 GlueChain.getValue(2)); 4677 } 4678 4679 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 4680 EVT VT, SDValue A, SDValue B, SDValue C, 4681 SDValue GlueChain) { 4682 if (GlueChain->getNumValues() <= 1) { 4683 return DAG.getNode(Opcode, SL, VT, A, B, C); 4684 } 4685 4686 assert(GlueChain->getNumValues() == 3); 4687 4688 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 4689 switch (Opcode) { 4690 default: llvm_unreachable("no chain equivalent for opcode"); 4691 case ISD::FMA: 4692 Opcode = AMDGPUISD::FMA_W_CHAIN; 4693 break; 4694 } 4695 4696 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 4697 GlueChain.getValue(2)); 4698 } 4699 4700 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 4701 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 4702 return FastLowered; 4703 4704 SDLoc SL(Op); 4705 SDValue Src0 = Op.getOperand(0); 4706 SDValue Src1 = Op.getOperand(1); 4707 4708 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4709 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4710 4711 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 4712 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 4713 4714 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 4715 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 4716 4717 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 4718 } 4719 4720 // Faster 2.5 ULP division that does not support denormals. 4721 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 4722 SDLoc SL(Op); 4723 SDValue LHS = Op.getOperand(1); 4724 SDValue RHS = Op.getOperand(2); 4725 4726 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 4727 4728 const APFloat K0Val(BitsToFloat(0x6f800000)); 4729 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 4730 4731 const APFloat K1Val(BitsToFloat(0x2f800000)); 4732 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 4733 4734 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 4735 4736 EVT SetCCVT = 4737 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 4738 4739 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 4740 4741 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 4742 4743 // TODO: Should this propagate fast-math-flags? 4744 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 4745 4746 // rcp does not support denormals. 4747 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 4748 4749 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 4750 4751 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 4752 } 4753 4754 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 4755 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 4756 return FastLowered; 4757 4758 SDLoc SL(Op); 4759 SDValue LHS = Op.getOperand(0); 4760 SDValue RHS = Op.getOperand(1); 4761 4762 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 4763 4764 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 4765 4766 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 4767 RHS, RHS, LHS); 4768 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 4769 LHS, RHS, LHS); 4770 4771 // Denominator is scaled to not be denormal, so using rcp is ok. 4772 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 4773 DenominatorScaled); 4774 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 4775 DenominatorScaled); 4776 4777 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 4778 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 4779 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 4780 4781 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 4782 4783 if (!Subtarget->hasFP32Denormals()) { 4784 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 4785 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 4786 SL, MVT::i32); 4787 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 4788 DAG.getEntryNode(), 4789 EnableDenormValue, BitField); 4790 SDValue Ops[3] = { 4791 NegDivScale0, 4792 EnableDenorm.getValue(0), 4793 EnableDenorm.getValue(1) 4794 }; 4795 4796 NegDivScale0 = DAG.getMergeValues(Ops, SL); 4797 } 4798 4799 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 4800 ApproxRcp, One, NegDivScale0); 4801 4802 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 4803 ApproxRcp, Fma0); 4804 4805 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 4806 Fma1, Fma1); 4807 4808 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 4809 NumeratorScaled, Mul); 4810 4811 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 4812 4813 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 4814 NumeratorScaled, Fma3); 4815 4816 if (!Subtarget->hasFP32Denormals()) { 4817 const SDValue DisableDenormValue = 4818 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 4819 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 4820 Fma4.getValue(1), 4821 DisableDenormValue, 4822 BitField, 4823 Fma4.getValue(2)); 4824 4825 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 4826 DisableDenorm, DAG.getRoot()); 4827 DAG.setRoot(OutputChain); 4828 } 4829 4830 SDValue Scale = NumeratorScaled.getValue(1); 4831 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 4832 Fma4, Fma1, Fma3, Scale); 4833 4834 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 4835 } 4836 4837 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 4838 if (DAG.getTarget().Options.UnsafeFPMath) 4839 return lowerFastUnsafeFDIV(Op, DAG); 4840 4841 SDLoc SL(Op); 4842 SDValue X = Op.getOperand(0); 4843 SDValue Y = Op.getOperand(1); 4844 4845 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 4846 4847 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 4848 4849 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 4850 4851 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 4852 4853 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 4854 4855 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 4856 4857 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 4858 4859 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 4860 4861 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 4862 4863 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 4864 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 4865 4866 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 4867 NegDivScale0, Mul, DivScale1); 4868 4869 SDValue Scale; 4870 4871 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 4872 // Workaround a hardware bug on SI where the condition output from div_scale 4873 // is not usable. 4874 4875 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 4876 4877 // Figure out if the scale to use for div_fmas. 4878 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 4879 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 4880 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 4881 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 4882 4883 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 4884 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 4885 4886 SDValue Scale0Hi 4887 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 4888 SDValue Scale1Hi 4889 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 4890 4891 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 4892 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 4893 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 4894 } else { 4895 Scale = DivScale1.getValue(1); 4896 } 4897 4898 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 4899 Fma4, Fma3, Mul, Scale); 4900 4901 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 4902 } 4903 4904 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 4905 EVT VT = Op.getValueType(); 4906 4907 if (VT == MVT::f32) 4908 return LowerFDIV32(Op, DAG); 4909 4910 if (VT == MVT::f64) 4911 return LowerFDIV64(Op, DAG); 4912 4913 if (VT == MVT::f16) 4914 return LowerFDIV16(Op, DAG); 4915 4916 llvm_unreachable("Unexpected type for fdiv"); 4917 } 4918 4919 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 4920 SDLoc DL(Op); 4921 StoreSDNode *Store = cast<StoreSDNode>(Op); 4922 EVT VT = Store->getMemoryVT(); 4923 4924 if (VT == MVT::i1) { 4925 return DAG.getTruncStore(Store->getChain(), DL, 4926 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 4927 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 4928 } 4929 4930 assert(VT.isVector() && 4931 Store->getValue().getValueType().getScalarType() == MVT::i32); 4932 4933 unsigned AS = Store->getAddressSpace(); 4934 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 4935 AS, Store->getAlignment())) { 4936 return expandUnalignedStore(Store, DAG); 4937 } 4938 4939 MachineFunction &MF = DAG.getMachineFunction(); 4940 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4941 // If there is a possibilty that flat instruction access scratch memory 4942 // then we need to use the same legalization rules we use for private. 4943 if (AS == AMDGPUASI.FLAT_ADDRESS) 4944 AS = MFI->hasFlatScratchInit() ? 4945 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4946 4947 unsigned NumElements = VT.getVectorNumElements(); 4948 if (AS == AMDGPUASI.GLOBAL_ADDRESS || 4949 AS == AMDGPUASI.FLAT_ADDRESS) { 4950 if (NumElements > 4) 4951 return SplitVectorStore(Op, DAG); 4952 return SDValue(); 4953 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4954 switch (Subtarget->getMaxPrivateElementSize()) { 4955 case 4: 4956 return scalarizeVectorStore(Store, DAG); 4957 case 8: 4958 if (NumElements > 2) 4959 return SplitVectorStore(Op, DAG); 4960 return SDValue(); 4961 case 16: 4962 if (NumElements > 4) 4963 return SplitVectorStore(Op, DAG); 4964 return SDValue(); 4965 default: 4966 llvm_unreachable("unsupported private_element_size"); 4967 } 4968 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4969 if (NumElements > 2) 4970 return SplitVectorStore(Op, DAG); 4971 4972 if (NumElements == 2) 4973 return Op; 4974 4975 // If properly aligned, if we split we might be able to use ds_write_b64. 4976 return SplitVectorStore(Op, DAG); 4977 } else { 4978 llvm_unreachable("unhandled address space"); 4979 } 4980 } 4981 4982 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 4983 SDLoc DL(Op); 4984 EVT VT = Op.getValueType(); 4985 SDValue Arg = Op.getOperand(0); 4986 // TODO: Should this propagate fast-math-flags? 4987 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 4988 DAG.getNode(ISD::FMUL, DL, VT, Arg, 4989 DAG.getConstantFP(0.5/M_PI, DL, 4990 VT))); 4991 4992 switch (Op.getOpcode()) { 4993 case ISD::FCOS: 4994 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 4995 case ISD::FSIN: 4996 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 4997 default: 4998 llvm_unreachable("Wrong trig opcode"); 4999 } 5000 } 5001 5002 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 5003 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 5004 assert(AtomicNode->isCompareAndSwap()); 5005 unsigned AS = AtomicNode->getAddressSpace(); 5006 5007 // No custom lowering required for local address space 5008 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI)) 5009 return Op; 5010 5011 // Non-local address space requires custom lowering for atomic compare 5012 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 5013 SDLoc DL(Op); 5014 SDValue ChainIn = Op.getOperand(0); 5015 SDValue Addr = Op.getOperand(1); 5016 SDValue Old = Op.getOperand(2); 5017 SDValue New = Op.getOperand(3); 5018 EVT VT = Op.getValueType(); 5019 MVT SimpleVT = VT.getSimpleVT(); 5020 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 5021 5022 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 5023 SDValue Ops[] = { ChainIn, Addr, NewOld }; 5024 5025 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 5026 Ops, VT, AtomicNode->getMemOperand()); 5027 } 5028 5029 //===----------------------------------------------------------------------===// 5030 // Custom DAG optimizations 5031 //===----------------------------------------------------------------------===// 5032 5033 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 5034 DAGCombinerInfo &DCI) const { 5035 EVT VT = N->getValueType(0); 5036 EVT ScalarVT = VT.getScalarType(); 5037 if (ScalarVT != MVT::f32) 5038 return SDValue(); 5039 5040 SelectionDAG &DAG = DCI.DAG; 5041 SDLoc DL(N); 5042 5043 SDValue Src = N->getOperand(0); 5044 EVT SrcVT = Src.getValueType(); 5045 5046 // TODO: We could try to match extracting the higher bytes, which would be 5047 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 5048 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 5049 // about in practice. 5050 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 5051 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 5052 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 5053 DCI.AddToWorklist(Cvt.getNode()); 5054 return Cvt; 5055 } 5056 } 5057 5058 return SDValue(); 5059 } 5060 5061 /// \brief Return true if the given offset Size in bytes can be folded into 5062 /// the immediate offsets of a memory instruction for the given address space. 5063 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 5064 const SISubtarget &STI) { 5065 auto AMDGPUASI = STI.getAMDGPUAS(); 5066 if (AS == AMDGPUASI.GLOBAL_ADDRESS) { 5067 // MUBUF instructions a 12-bit offset in bytes. 5068 return isUInt<12>(OffsetSize); 5069 } 5070 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 5071 // SMRD instructions have an 8-bit offset in dwords on SI and 5072 // a 20-bit offset in bytes on VI. 5073 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 5074 return isUInt<20>(OffsetSize); 5075 else 5076 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 5077 } 5078 if (AS == AMDGPUASI.LOCAL_ADDRESS || 5079 AS == AMDGPUASI.REGION_ADDRESS) { 5080 // The single offset versions have a 16-bit offset in bytes. 5081 return isUInt<16>(OffsetSize); 5082 } 5083 // Indirect register addressing does not use any offsets. 5084 return false; 5085 } 5086 5087 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 5088 5089 // This is a variant of 5090 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 5091 // 5092 // The normal DAG combiner will do this, but only if the add has one use since 5093 // that would increase the number of instructions. 5094 // 5095 // This prevents us from seeing a constant offset that can be folded into a 5096 // memory instruction's addressing mode. If we know the resulting add offset of 5097 // a pointer can be folded into an addressing offset, we can replace the pointer 5098 // operand with the add of new constant offset. This eliminates one of the uses, 5099 // and may allow the remaining use to also be simplified. 5100 // 5101 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 5102 unsigned AddrSpace, 5103 DAGCombinerInfo &DCI) const { 5104 SDValue N0 = N->getOperand(0); 5105 SDValue N1 = N->getOperand(1); 5106 5107 if (N0.getOpcode() != ISD::ADD) 5108 return SDValue(); 5109 5110 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 5111 if (!CN1) 5112 return SDValue(); 5113 5114 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5115 if (!CAdd) 5116 return SDValue(); 5117 5118 // If the resulting offset is too large, we can't fold it into the addressing 5119 // mode offset. 5120 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 5121 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget())) 5122 return SDValue(); 5123 5124 SelectionDAG &DAG = DCI.DAG; 5125 SDLoc SL(N); 5126 EVT VT = N->getValueType(0); 5127 5128 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 5129 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 5130 5131 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 5132 } 5133 5134 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 5135 DAGCombinerInfo &DCI) const { 5136 SDValue Ptr = N->getBasePtr(); 5137 SelectionDAG &DAG = DCI.DAG; 5138 SDLoc SL(N); 5139 5140 // TODO: We could also do this for multiplies. 5141 unsigned AS = N->getAddressSpace(); 5142 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) { 5143 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 5144 if (NewPtr) { 5145 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 5146 5147 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 5148 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 5149 } 5150 } 5151 5152 return SDValue(); 5153 } 5154 5155 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 5156 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 5157 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 5158 (Opc == ISD::XOR && Val == 0); 5159 } 5160 5161 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 5162 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 5163 // integer combine opportunities since most 64-bit operations are decomposed 5164 // this way. TODO: We won't want this for SALU especially if it is an inline 5165 // immediate. 5166 SDValue SITargetLowering::splitBinaryBitConstantOp( 5167 DAGCombinerInfo &DCI, 5168 const SDLoc &SL, 5169 unsigned Opc, SDValue LHS, 5170 const ConstantSDNode *CRHS) const { 5171 uint64_t Val = CRHS->getZExtValue(); 5172 uint32_t ValLo = Lo_32(Val); 5173 uint32_t ValHi = Hi_32(Val); 5174 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5175 5176 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 5177 bitOpWithConstantIsReducible(Opc, ValHi)) || 5178 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 5179 // If we need to materialize a 64-bit immediate, it will be split up later 5180 // anyway. Avoid creating the harder to understand 64-bit immediate 5181 // materialization. 5182 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 5183 } 5184 5185 return SDValue(); 5186 } 5187 5188 // Returns true if argument is a boolean value which is not serialized into 5189 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 5190 static bool isBoolSGPR(SDValue V) { 5191 if (V.getValueType() != MVT::i1) 5192 return false; 5193 switch (V.getOpcode()) { 5194 default: break; 5195 case ISD::SETCC: 5196 case ISD::AND: 5197 case ISD::OR: 5198 case ISD::XOR: 5199 case AMDGPUISD::FP_CLASS: 5200 return true; 5201 } 5202 return false; 5203 } 5204 5205 SDValue SITargetLowering::performAndCombine(SDNode *N, 5206 DAGCombinerInfo &DCI) const { 5207 if (DCI.isBeforeLegalize()) 5208 return SDValue(); 5209 5210 SelectionDAG &DAG = DCI.DAG; 5211 EVT VT = N->getValueType(0); 5212 SDValue LHS = N->getOperand(0); 5213 SDValue RHS = N->getOperand(1); 5214 5215 5216 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5217 if (VT == MVT::i64 && CRHS) { 5218 if (SDValue Split 5219 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 5220 return Split; 5221 } 5222 5223 if (CRHS && VT == MVT::i32) { 5224 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 5225 // nb = number of trailing zeroes in mask 5226 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 5227 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 5228 uint64_t Mask = CRHS->getZExtValue(); 5229 unsigned Bits = countPopulation(Mask); 5230 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 5231 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 5232 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 5233 unsigned Shift = CShift->getZExtValue(); 5234 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 5235 unsigned Offset = NB + Shift; 5236 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 5237 SDLoc SL(N); 5238 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 5239 LHS->getOperand(0), 5240 DAG.getConstant(Offset, SL, MVT::i32), 5241 DAG.getConstant(Bits, SL, MVT::i32)); 5242 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 5243 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 5244 DAG.getValueType(NarrowVT)); 5245 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 5246 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 5247 return Shl; 5248 } 5249 } 5250 } 5251 } 5252 5253 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 5254 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 5255 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 5256 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 5257 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 5258 5259 SDValue X = LHS.getOperand(0); 5260 SDValue Y = RHS.getOperand(0); 5261 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 5262 return SDValue(); 5263 5264 if (LCC == ISD::SETO) { 5265 if (X != LHS.getOperand(1)) 5266 return SDValue(); 5267 5268 if (RCC == ISD::SETUNE) { 5269 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 5270 if (!C1 || !C1->isInfinity() || C1->isNegative()) 5271 return SDValue(); 5272 5273 const uint32_t Mask = SIInstrFlags::N_NORMAL | 5274 SIInstrFlags::N_SUBNORMAL | 5275 SIInstrFlags::N_ZERO | 5276 SIInstrFlags::P_ZERO | 5277 SIInstrFlags::P_SUBNORMAL | 5278 SIInstrFlags::P_NORMAL; 5279 5280 static_assert(((~(SIInstrFlags::S_NAN | 5281 SIInstrFlags::Q_NAN | 5282 SIInstrFlags::N_INFINITY | 5283 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 5284 "mask not equal"); 5285 5286 SDLoc DL(N); 5287 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5288 X, DAG.getConstant(Mask, DL, MVT::i32)); 5289 } 5290 } 5291 } 5292 5293 if (VT == MVT::i32 && 5294 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 5295 // and x, (sext cc from i1) => select cc, x, 0 5296 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 5297 std::swap(LHS, RHS); 5298 if (isBoolSGPR(RHS.getOperand(0))) 5299 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 5300 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 5301 } 5302 5303 return SDValue(); 5304 } 5305 5306 SDValue SITargetLowering::performOrCombine(SDNode *N, 5307 DAGCombinerInfo &DCI) const { 5308 SelectionDAG &DAG = DCI.DAG; 5309 SDValue LHS = N->getOperand(0); 5310 SDValue RHS = N->getOperand(1); 5311 5312 EVT VT = N->getValueType(0); 5313 if (VT == MVT::i1) { 5314 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 5315 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 5316 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 5317 SDValue Src = LHS.getOperand(0); 5318 if (Src != RHS.getOperand(0)) 5319 return SDValue(); 5320 5321 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 5322 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 5323 if (!CLHS || !CRHS) 5324 return SDValue(); 5325 5326 // Only 10 bits are used. 5327 static const uint32_t MaxMask = 0x3ff; 5328 5329 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 5330 SDLoc DL(N); 5331 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5332 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 5333 } 5334 5335 return SDValue(); 5336 } 5337 5338 if (VT != MVT::i64) 5339 return SDValue(); 5340 5341 // TODO: This could be a generic combine with a predicate for extracting the 5342 // high half of an integer being free. 5343 5344 // (or i64:x, (zero_extend i32:y)) -> 5345 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 5346 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 5347 RHS.getOpcode() != ISD::ZERO_EXTEND) 5348 std::swap(LHS, RHS); 5349 5350 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 5351 SDValue ExtSrc = RHS.getOperand(0); 5352 EVT SrcVT = ExtSrc.getValueType(); 5353 if (SrcVT == MVT::i32) { 5354 SDLoc SL(N); 5355 SDValue LowLHS, HiBits; 5356 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 5357 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 5358 5359 DCI.AddToWorklist(LowOr.getNode()); 5360 DCI.AddToWorklist(HiBits.getNode()); 5361 5362 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 5363 LowOr, HiBits); 5364 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5365 } 5366 } 5367 5368 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5369 if (CRHS) { 5370 if (SDValue Split 5371 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 5372 return Split; 5373 } 5374 5375 return SDValue(); 5376 } 5377 5378 SDValue SITargetLowering::performXorCombine(SDNode *N, 5379 DAGCombinerInfo &DCI) const { 5380 EVT VT = N->getValueType(0); 5381 if (VT != MVT::i64) 5382 return SDValue(); 5383 5384 SDValue LHS = N->getOperand(0); 5385 SDValue RHS = N->getOperand(1); 5386 5387 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5388 if (CRHS) { 5389 if (SDValue Split 5390 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 5391 return Split; 5392 } 5393 5394 return SDValue(); 5395 } 5396 5397 // Instructions that will be lowered with a final instruction that zeros the 5398 // high result bits. 5399 // XXX - probably only need to list legal operations. 5400 static bool fp16SrcZerosHighBits(unsigned Opc) { 5401 switch (Opc) { 5402 case ISD::FADD: 5403 case ISD::FSUB: 5404 case ISD::FMUL: 5405 case ISD::FDIV: 5406 case ISD::FREM: 5407 case ISD::FMA: 5408 case ISD::FMAD: 5409 case ISD::FCANONICALIZE: 5410 case ISD::FP_ROUND: 5411 case ISD::UINT_TO_FP: 5412 case ISD::SINT_TO_FP: 5413 case ISD::FABS: 5414 // Fabs is lowered to a bit operation, but it's an and which will clear the 5415 // high bits anyway. 5416 case ISD::FSQRT: 5417 case ISD::FSIN: 5418 case ISD::FCOS: 5419 case ISD::FPOWI: 5420 case ISD::FPOW: 5421 case ISD::FLOG: 5422 case ISD::FLOG2: 5423 case ISD::FLOG10: 5424 case ISD::FEXP: 5425 case ISD::FEXP2: 5426 case ISD::FCEIL: 5427 case ISD::FTRUNC: 5428 case ISD::FRINT: 5429 case ISD::FNEARBYINT: 5430 case ISD::FROUND: 5431 case ISD::FFLOOR: 5432 case ISD::FMINNUM: 5433 case ISD::FMAXNUM: 5434 case AMDGPUISD::FRACT: 5435 case AMDGPUISD::CLAMP: 5436 case AMDGPUISD::COS_HW: 5437 case AMDGPUISD::SIN_HW: 5438 case AMDGPUISD::FMIN3: 5439 case AMDGPUISD::FMAX3: 5440 case AMDGPUISD::FMED3: 5441 case AMDGPUISD::FMAD_FTZ: 5442 case AMDGPUISD::RCP: 5443 case AMDGPUISD::RSQ: 5444 case AMDGPUISD::LDEXP: 5445 return true; 5446 default: 5447 // fcopysign, select and others may be lowered to 32-bit bit operations 5448 // which don't zero the high bits. 5449 return false; 5450 } 5451 } 5452 5453 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 5454 DAGCombinerInfo &DCI) const { 5455 if (!Subtarget->has16BitInsts() || 5456 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 5457 return SDValue(); 5458 5459 EVT VT = N->getValueType(0); 5460 if (VT != MVT::i32) 5461 return SDValue(); 5462 5463 SDValue Src = N->getOperand(0); 5464 if (Src.getValueType() != MVT::i16) 5465 return SDValue(); 5466 5467 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 5468 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 5469 if (Src.getOpcode() == ISD::BITCAST) { 5470 SDValue BCSrc = Src.getOperand(0); 5471 if (BCSrc.getValueType() == MVT::f16 && 5472 fp16SrcZerosHighBits(BCSrc.getOpcode())) 5473 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 5474 } 5475 5476 return SDValue(); 5477 } 5478 5479 SDValue SITargetLowering::performClassCombine(SDNode *N, 5480 DAGCombinerInfo &DCI) const { 5481 SelectionDAG &DAG = DCI.DAG; 5482 SDValue Mask = N->getOperand(1); 5483 5484 // fp_class x, 0 -> false 5485 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 5486 if (CMask->isNullValue()) 5487 return DAG.getConstant(0, SDLoc(N), MVT::i1); 5488 } 5489 5490 if (N->getOperand(0).isUndef()) 5491 return DAG.getUNDEF(MVT::i1); 5492 5493 return SDValue(); 5494 } 5495 5496 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 5497 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 5498 return true; 5499 5500 return DAG.isKnownNeverNaN(Op); 5501 } 5502 5503 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op, 5504 const SISubtarget *ST, unsigned MaxDepth=5) { 5505 // If source is a result of another standard FP operation it is already in 5506 // canonical form. 5507 5508 switch (Op.getOpcode()) { 5509 default: 5510 break; 5511 5512 // These will flush denorms if required. 5513 case ISD::FADD: 5514 case ISD::FSUB: 5515 case ISD::FMUL: 5516 case ISD::FSQRT: 5517 case ISD::FCEIL: 5518 case ISD::FFLOOR: 5519 case ISD::FMA: 5520 case ISD::FMAD: 5521 5522 case ISD::FCANONICALIZE: 5523 return true; 5524 5525 case ISD::FP_ROUND: 5526 return Op.getValueType().getScalarType() != MVT::f16 || 5527 ST->hasFP16Denormals(); 5528 5529 case ISD::FP_EXTEND: 5530 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 || 5531 ST->hasFP16Denormals(); 5532 5533 case ISD::FP16_TO_FP: 5534 case ISD::FP_TO_FP16: 5535 return ST->hasFP16Denormals(); 5536 5537 // It can/will be lowered or combined as a bit operation. 5538 // Need to check their input recursively to handle. 5539 case ISD::FNEG: 5540 case ISD::FABS: 5541 return (MaxDepth > 0) && 5542 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1); 5543 5544 case ISD::FSIN: 5545 case ISD::FCOS: 5546 case ISD::FSINCOS: 5547 return Op.getValueType().getScalarType() != MVT::f16; 5548 5549 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. 5550 // For such targets need to check their input recursively. 5551 case ISD::FMINNUM: 5552 case ISD::FMAXNUM: 5553 case ISD::FMINNAN: 5554 case ISD::FMAXNAN: 5555 5556 if (ST->supportsMinMaxDenormModes() && 5557 DAG.isKnownNeverNaN(Op.getOperand(0)) && 5558 DAG.isKnownNeverNaN(Op.getOperand(1))) 5559 return true; 5560 5561 return (MaxDepth > 0) && 5562 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) && 5563 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1); 5564 5565 case ISD::ConstantFP: { 5566 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF(); 5567 return !F.isDenormal() && !(F.isNaN() && F.isSignaling()); 5568 } 5569 } 5570 return false; 5571 } 5572 5573 // Constant fold canonicalize. 5574 SDValue SITargetLowering::performFCanonicalizeCombine( 5575 SDNode *N, 5576 DAGCombinerInfo &DCI) const { 5577 SelectionDAG &DAG = DCI.DAG; 5578 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0)); 5579 5580 if (!CFP) { 5581 SDValue N0 = N->getOperand(0); 5582 EVT VT = N0.getValueType().getScalarType(); 5583 auto ST = getSubtarget(); 5584 5585 if (((VT == MVT::f32 && ST->hasFP32Denormals()) || 5586 (VT == MVT::f64 && ST->hasFP64Denormals()) || 5587 (VT == MVT::f16 && ST->hasFP16Denormals())) && 5588 DAG.isKnownNeverNaN(N0)) 5589 return N0; 5590 5591 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction()); 5592 5593 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) && 5594 isCanonicalized(DAG, N0, ST)) 5595 return N0; 5596 5597 return SDValue(); 5598 } 5599 5600 const APFloat &C = CFP->getValueAPF(); 5601 5602 // Flush denormals to 0 if not enabled. 5603 if (C.isDenormal()) { 5604 EVT VT = N->getValueType(0); 5605 EVT SVT = VT.getScalarType(); 5606 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals()) 5607 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5608 5609 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals()) 5610 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5611 5612 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals()) 5613 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5614 } 5615 5616 if (C.isNaN()) { 5617 EVT VT = N->getValueType(0); 5618 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 5619 if (C.isSignaling()) { 5620 // Quiet a signaling NaN. 5621 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 5622 } 5623 5624 // Make sure it is the canonical NaN bitpattern. 5625 // 5626 // TODO: Can we use -1 as the canonical NaN value since it's an inline 5627 // immediate? 5628 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 5629 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 5630 } 5631 5632 return N->getOperand(0); 5633 } 5634 5635 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 5636 switch (Opc) { 5637 case ISD::FMAXNUM: 5638 return AMDGPUISD::FMAX3; 5639 case ISD::SMAX: 5640 return AMDGPUISD::SMAX3; 5641 case ISD::UMAX: 5642 return AMDGPUISD::UMAX3; 5643 case ISD::FMINNUM: 5644 return AMDGPUISD::FMIN3; 5645 case ISD::SMIN: 5646 return AMDGPUISD::SMIN3; 5647 case ISD::UMIN: 5648 return AMDGPUISD::UMIN3; 5649 default: 5650 llvm_unreachable("Not a min/max opcode"); 5651 } 5652 } 5653 5654 SDValue SITargetLowering::performIntMed3ImmCombine( 5655 SelectionDAG &DAG, const SDLoc &SL, 5656 SDValue Op0, SDValue Op1, bool Signed) const { 5657 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 5658 if (!K1) 5659 return SDValue(); 5660 5661 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 5662 if (!K0) 5663 return SDValue(); 5664 5665 if (Signed) { 5666 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 5667 return SDValue(); 5668 } else { 5669 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 5670 return SDValue(); 5671 } 5672 5673 EVT VT = K0->getValueType(0); 5674 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 5675 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 5676 return DAG.getNode(Med3Opc, SL, VT, 5677 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 5678 } 5679 5680 // If there isn't a 16-bit med3 operation, convert to 32-bit. 5681 MVT NVT = MVT::i32; 5682 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5683 5684 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 5685 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 5686 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 5687 5688 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 5689 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 5690 } 5691 5692 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 5693 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 5694 return C; 5695 5696 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 5697 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 5698 return C; 5699 } 5700 5701 return nullptr; 5702 } 5703 5704 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 5705 const SDLoc &SL, 5706 SDValue Op0, 5707 SDValue Op1) const { 5708 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 5709 if (!K1) 5710 return SDValue(); 5711 5712 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 5713 if (!K0) 5714 return SDValue(); 5715 5716 // Ordered >= (although NaN inputs should have folded away by now). 5717 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 5718 if (Cmp == APFloat::cmpGreaterThan) 5719 return SDValue(); 5720 5721 // TODO: Check IEEE bit enabled? 5722 EVT VT = Op0.getValueType(); 5723 if (Subtarget->enableDX10Clamp()) { 5724 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 5725 // hardware fmed3 behavior converting to a min. 5726 // FIXME: Should this be allowing -0.0? 5727 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 5728 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 5729 } 5730 5731 // med3 for f16 is only available on gfx9+, and not available for v2f16. 5732 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 5733 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 5734 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 5735 // then give the other result, which is different from med3 with a NaN 5736 // input. 5737 SDValue Var = Op0.getOperand(0); 5738 if (!isKnownNeverSNan(DAG, Var)) 5739 return SDValue(); 5740 5741 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 5742 Var, SDValue(K0, 0), SDValue(K1, 0)); 5743 } 5744 5745 return SDValue(); 5746 } 5747 5748 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 5749 DAGCombinerInfo &DCI) const { 5750 SelectionDAG &DAG = DCI.DAG; 5751 5752 EVT VT = N->getValueType(0); 5753 unsigned Opc = N->getOpcode(); 5754 SDValue Op0 = N->getOperand(0); 5755 SDValue Op1 = N->getOperand(1); 5756 5757 // Only do this if the inner op has one use since this will just increases 5758 // register pressure for no benefit. 5759 5760 5761 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 5762 VT != MVT::f64 && 5763 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) { 5764 // max(max(a, b), c) -> max3(a, b, c) 5765 // min(min(a, b), c) -> min3(a, b, c) 5766 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 5767 SDLoc DL(N); 5768 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 5769 DL, 5770 N->getValueType(0), 5771 Op0.getOperand(0), 5772 Op0.getOperand(1), 5773 Op1); 5774 } 5775 5776 // Try commuted. 5777 // max(a, max(b, c)) -> max3(a, b, c) 5778 // min(a, min(b, c)) -> min3(a, b, c) 5779 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 5780 SDLoc DL(N); 5781 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 5782 DL, 5783 N->getValueType(0), 5784 Op0, 5785 Op1.getOperand(0), 5786 Op1.getOperand(1)); 5787 } 5788 } 5789 5790 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 5791 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 5792 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 5793 return Med3; 5794 } 5795 5796 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 5797 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 5798 return Med3; 5799 } 5800 5801 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 5802 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 5803 (Opc == AMDGPUISD::FMIN_LEGACY && 5804 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 5805 (VT == MVT::f32 || VT == MVT::f64 || 5806 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 5807 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 5808 Op0.hasOneUse()) { 5809 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 5810 return Res; 5811 } 5812 5813 return SDValue(); 5814 } 5815 5816 static bool isClampZeroToOne(SDValue A, SDValue B) { 5817 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 5818 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 5819 // FIXME: Should this be allowing -0.0? 5820 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 5821 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 5822 } 5823 } 5824 5825 return false; 5826 } 5827 5828 // FIXME: Should only worry about snans for version with chain. 5829 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 5830 DAGCombinerInfo &DCI) const { 5831 EVT VT = N->getValueType(0); 5832 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 5833 // NaNs. With a NaN input, the order of the operands may change the result. 5834 5835 SelectionDAG &DAG = DCI.DAG; 5836 SDLoc SL(N); 5837 5838 SDValue Src0 = N->getOperand(0); 5839 SDValue Src1 = N->getOperand(1); 5840 SDValue Src2 = N->getOperand(2); 5841 5842 if (isClampZeroToOne(Src0, Src1)) { 5843 // const_a, const_b, x -> clamp is safe in all cases including signaling 5844 // nans. 5845 // FIXME: Should this be allowing -0.0? 5846 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 5847 } 5848 5849 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 5850 // handling no dx10-clamp? 5851 if (Subtarget->enableDX10Clamp()) { 5852 // If NaNs is clamped to 0, we are free to reorder the inputs. 5853 5854 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 5855 std::swap(Src0, Src1); 5856 5857 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 5858 std::swap(Src1, Src2); 5859 5860 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 5861 std::swap(Src0, Src1); 5862 5863 if (isClampZeroToOne(Src1, Src2)) 5864 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 5865 } 5866 5867 return SDValue(); 5868 } 5869 5870 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 5871 DAGCombinerInfo &DCI) const { 5872 SDValue Src0 = N->getOperand(0); 5873 SDValue Src1 = N->getOperand(1); 5874 if (Src0.isUndef() && Src1.isUndef()) 5875 return DCI.DAG.getUNDEF(N->getValueType(0)); 5876 return SDValue(); 5877 } 5878 5879 SDValue SITargetLowering::performExtractVectorEltCombine( 5880 SDNode *N, DAGCombinerInfo &DCI) const { 5881 SDValue Vec = N->getOperand(0); 5882 5883 SelectionDAG &DAG = DCI.DAG; 5884 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) { 5885 SDLoc SL(N); 5886 EVT EltVT = N->getValueType(0); 5887 SDValue Idx = N->getOperand(1); 5888 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5889 Vec.getOperand(0), Idx); 5890 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt); 5891 } 5892 5893 return SDValue(); 5894 } 5895 5896 static bool convertBuildVectorCastElt(SelectionDAG &DAG, 5897 SDValue &Lo, SDValue &Hi) { 5898 if (Hi.getOpcode() == ISD::BITCAST && 5899 Hi.getOperand(0).getValueType() == MVT::f16 && 5900 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) { 5901 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo); 5902 Hi = Hi.getOperand(0); 5903 return true; 5904 } 5905 5906 return false; 5907 } 5908 5909 SDValue SITargetLowering::performBuildVectorCombine( 5910 SDNode *N, DAGCombinerInfo &DCI) const { 5911 SDLoc SL(N); 5912 5913 if (!isTypeLegal(MVT::v2i16)) 5914 return SDValue(); 5915 SelectionDAG &DAG = DCI.DAG; 5916 EVT VT = N->getValueType(0); 5917 5918 if (VT == MVT::v2i16) { 5919 SDValue Lo = N->getOperand(0); 5920 SDValue Hi = N->getOperand(1); 5921 5922 // v2i16 build_vector (const|undef), (bitcast f16:$x) 5923 // -> bitcast (v2f16 build_vector const|undef, $x 5924 if (convertBuildVectorCastElt(DAG, Lo, Hi)) { 5925 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi }); 5926 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 5927 } 5928 5929 if (convertBuildVectorCastElt(DAG, Hi, Lo)) { 5930 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo }); 5931 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 5932 } 5933 } 5934 5935 return SDValue(); 5936 } 5937 5938 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 5939 const SDNode *N0, 5940 const SDNode *N1) const { 5941 EVT VT = N0->getValueType(0); 5942 5943 // Only do this if we are not trying to support denormals. v_mad_f32 does not 5944 // support denormals ever. 5945 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 5946 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 5947 return ISD::FMAD; 5948 5949 const TargetOptions &Options = DAG.getTarget().Options; 5950 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 5951 (N0->getFlags().hasUnsafeAlgebra() && 5952 N1->getFlags().hasUnsafeAlgebra())) && 5953 isFMAFasterThanFMulAndFAdd(VT)) { 5954 return ISD::FMA; 5955 } 5956 5957 return 0; 5958 } 5959 5960 SDValue SITargetLowering::performAddCombine(SDNode *N, 5961 DAGCombinerInfo &DCI) const { 5962 SelectionDAG &DAG = DCI.DAG; 5963 EVT VT = N->getValueType(0); 5964 5965 if (VT != MVT::i32) 5966 return SDValue(); 5967 5968 SDLoc SL(N); 5969 SDValue LHS = N->getOperand(0); 5970 SDValue RHS = N->getOperand(1); 5971 5972 // add x, zext (setcc) => addcarry x, 0, setcc 5973 // add x, sext (setcc) => subcarry x, 0, setcc 5974 unsigned Opc = LHS.getOpcode(); 5975 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 5976 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 5977 std::swap(RHS, LHS); 5978 5979 Opc = RHS.getOpcode(); 5980 switch (Opc) { 5981 default: break; 5982 case ISD::ZERO_EXTEND: 5983 case ISD::SIGN_EXTEND: 5984 case ISD::ANY_EXTEND: { 5985 auto Cond = RHS.getOperand(0); 5986 if (!isBoolSGPR(Cond)) 5987 break; 5988 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 5989 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 5990 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 5991 return DAG.getNode(Opc, SL, VTList, Args); 5992 } 5993 case ISD::ADDCARRY: { 5994 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 5995 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 5996 if (!C || C->getZExtValue() != 0) break; 5997 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 5998 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 5999 } 6000 } 6001 return SDValue(); 6002 } 6003 6004 SDValue SITargetLowering::performSubCombine(SDNode *N, 6005 DAGCombinerInfo &DCI) const { 6006 SelectionDAG &DAG = DCI.DAG; 6007 EVT VT = N->getValueType(0); 6008 6009 if (VT != MVT::i32) 6010 return SDValue(); 6011 6012 SDLoc SL(N); 6013 SDValue LHS = N->getOperand(0); 6014 SDValue RHS = N->getOperand(1); 6015 6016 unsigned Opc = LHS.getOpcode(); 6017 if (Opc != ISD::SUBCARRY) 6018 std::swap(RHS, LHS); 6019 6020 if (LHS.getOpcode() == ISD::SUBCARRY) { 6021 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 6022 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6023 if (!C || C->getZExtValue() != 0) 6024 return SDValue(); 6025 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 6026 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 6027 } 6028 return SDValue(); 6029 } 6030 6031 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 6032 DAGCombinerInfo &DCI) const { 6033 6034 if (N->getValueType(0) != MVT::i32) 6035 return SDValue(); 6036 6037 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6038 if (!C || C->getZExtValue() != 0) 6039 return SDValue(); 6040 6041 SelectionDAG &DAG = DCI.DAG; 6042 SDValue LHS = N->getOperand(0); 6043 6044 // addcarry (add x, y), 0, cc => addcarry x, y, cc 6045 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 6046 unsigned LHSOpc = LHS.getOpcode(); 6047 unsigned Opc = N->getOpcode(); 6048 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 6049 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 6050 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 6051 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 6052 } 6053 return SDValue(); 6054 } 6055 6056 SDValue SITargetLowering::performFAddCombine(SDNode *N, 6057 DAGCombinerInfo &DCI) const { 6058 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6059 return SDValue(); 6060 6061 SelectionDAG &DAG = DCI.DAG; 6062 EVT VT = N->getValueType(0); 6063 6064 SDLoc SL(N); 6065 SDValue LHS = N->getOperand(0); 6066 SDValue RHS = N->getOperand(1); 6067 6068 // These should really be instruction patterns, but writing patterns with 6069 // source modiifiers is a pain. 6070 6071 // fadd (fadd (a, a), b) -> mad 2.0, a, b 6072 if (LHS.getOpcode() == ISD::FADD) { 6073 SDValue A = LHS.getOperand(0); 6074 if (A == LHS.getOperand(1)) { 6075 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6076 if (FusedOp != 0) { 6077 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6078 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 6079 } 6080 } 6081 } 6082 6083 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 6084 if (RHS.getOpcode() == ISD::FADD) { 6085 SDValue A = RHS.getOperand(0); 6086 if (A == RHS.getOperand(1)) { 6087 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6088 if (FusedOp != 0) { 6089 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6090 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 6091 } 6092 } 6093 } 6094 6095 return SDValue(); 6096 } 6097 6098 SDValue SITargetLowering::performFSubCombine(SDNode *N, 6099 DAGCombinerInfo &DCI) const { 6100 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6101 return SDValue(); 6102 6103 SelectionDAG &DAG = DCI.DAG; 6104 SDLoc SL(N); 6105 EVT VT = N->getValueType(0); 6106 assert(!VT.isVector()); 6107 6108 // Try to get the fneg to fold into the source modifier. This undoes generic 6109 // DAG combines and folds them into the mad. 6110 // 6111 // Only do this if we are not trying to support denormals. v_mad_f32 does 6112 // not support denormals ever. 6113 SDValue LHS = N->getOperand(0); 6114 SDValue RHS = N->getOperand(1); 6115 if (LHS.getOpcode() == ISD::FADD) { 6116 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 6117 SDValue A = LHS.getOperand(0); 6118 if (A == LHS.getOperand(1)) { 6119 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6120 if (FusedOp != 0){ 6121 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6122 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 6123 6124 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 6125 } 6126 } 6127 } 6128 6129 if (RHS.getOpcode() == ISD::FADD) { 6130 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 6131 6132 SDValue A = RHS.getOperand(0); 6133 if (A == RHS.getOperand(1)) { 6134 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6135 if (FusedOp != 0){ 6136 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 6137 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 6138 } 6139 } 6140 } 6141 6142 return SDValue(); 6143 } 6144 6145 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 6146 DAGCombinerInfo &DCI) const { 6147 SelectionDAG &DAG = DCI.DAG; 6148 SDLoc SL(N); 6149 6150 SDValue LHS = N->getOperand(0); 6151 SDValue RHS = N->getOperand(1); 6152 EVT VT = LHS.getValueType(); 6153 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6154 6155 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 6156 if (!CRHS) { 6157 CRHS = dyn_cast<ConstantSDNode>(LHS); 6158 if (CRHS) { 6159 std::swap(LHS, RHS); 6160 CC = getSetCCSwappedOperands(CC); 6161 } 6162 } 6163 6164 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 6165 isBoolSGPR(LHS.getOperand(0))) { 6166 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 6167 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 6168 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 6169 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 6170 if ((CRHS->isAllOnesValue() && 6171 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 6172 (CRHS->isNullValue() && 6173 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 6174 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 6175 DAG.getConstant(-1, SL, MVT::i1)); 6176 if ((CRHS->isAllOnesValue() && 6177 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 6178 (CRHS->isNullValue() && 6179 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 6180 return LHS.getOperand(0); 6181 } 6182 6183 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 6184 VT != MVT::f16)) 6185 return SDValue(); 6186 6187 // Match isinf pattern 6188 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 6189 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 6190 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 6191 if (!CRHS) 6192 return SDValue(); 6193 6194 const APFloat &APF = CRHS->getValueAPF(); 6195 if (APF.isInfinity() && !APF.isNegative()) { 6196 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 6197 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 6198 DAG.getConstant(Mask, SL, MVT::i32)); 6199 } 6200 } 6201 6202 return SDValue(); 6203 } 6204 6205 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 6206 DAGCombinerInfo &DCI) const { 6207 SelectionDAG &DAG = DCI.DAG; 6208 SDLoc SL(N); 6209 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 6210 6211 SDValue Src = N->getOperand(0); 6212 SDValue Srl = N->getOperand(0); 6213 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 6214 Srl = Srl.getOperand(0); 6215 6216 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 6217 if (Srl.getOpcode() == ISD::SRL) { 6218 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 6219 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 6220 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 6221 6222 if (const ConstantSDNode *C = 6223 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 6224 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 6225 EVT(MVT::i32)); 6226 6227 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 6228 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 6229 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 6230 MVT::f32, Srl); 6231 } 6232 } 6233 } 6234 6235 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 6236 6237 KnownBits Known; 6238 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 6239 !DCI.isBeforeLegalizeOps()); 6240 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6241 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) || 6242 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 6243 DCI.CommitTargetLoweringOpt(TLO); 6244 } 6245 6246 return SDValue(); 6247 } 6248 6249 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 6250 DAGCombinerInfo &DCI) const { 6251 switch (N->getOpcode()) { 6252 default: 6253 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 6254 case ISD::ADD: 6255 return performAddCombine(N, DCI); 6256 case ISD::SUB: 6257 return performSubCombine(N, DCI); 6258 case ISD::ADDCARRY: 6259 case ISD::SUBCARRY: 6260 return performAddCarrySubCarryCombine(N, DCI); 6261 case ISD::FADD: 6262 return performFAddCombine(N, DCI); 6263 case ISD::FSUB: 6264 return performFSubCombine(N, DCI); 6265 case ISD::SETCC: 6266 return performSetCCCombine(N, DCI); 6267 case ISD::FMAXNUM: 6268 case ISD::FMINNUM: 6269 case ISD::SMAX: 6270 case ISD::SMIN: 6271 case ISD::UMAX: 6272 case ISD::UMIN: 6273 case AMDGPUISD::FMIN_LEGACY: 6274 case AMDGPUISD::FMAX_LEGACY: { 6275 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 6276 getTargetMachine().getOptLevel() > CodeGenOpt::None) 6277 return performMinMaxCombine(N, DCI); 6278 break; 6279 } 6280 case ISD::LOAD: 6281 case ISD::STORE: 6282 case ISD::ATOMIC_LOAD: 6283 case ISD::ATOMIC_STORE: 6284 case ISD::ATOMIC_CMP_SWAP: 6285 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 6286 case ISD::ATOMIC_SWAP: 6287 case ISD::ATOMIC_LOAD_ADD: 6288 case ISD::ATOMIC_LOAD_SUB: 6289 case ISD::ATOMIC_LOAD_AND: 6290 case ISD::ATOMIC_LOAD_OR: 6291 case ISD::ATOMIC_LOAD_XOR: 6292 case ISD::ATOMIC_LOAD_NAND: 6293 case ISD::ATOMIC_LOAD_MIN: 6294 case ISD::ATOMIC_LOAD_MAX: 6295 case ISD::ATOMIC_LOAD_UMIN: 6296 case ISD::ATOMIC_LOAD_UMAX: 6297 case AMDGPUISD::ATOMIC_INC: 6298 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics. 6299 if (DCI.isBeforeLegalize()) 6300 break; 6301 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 6302 case ISD::AND: 6303 return performAndCombine(N, DCI); 6304 case ISD::OR: 6305 return performOrCombine(N, DCI); 6306 case ISD::XOR: 6307 return performXorCombine(N, DCI); 6308 case ISD::ZERO_EXTEND: 6309 return performZeroExtendCombine(N, DCI); 6310 case AMDGPUISD::FP_CLASS: 6311 return performClassCombine(N, DCI); 6312 case ISD::FCANONICALIZE: 6313 return performFCanonicalizeCombine(N, DCI); 6314 case AMDGPUISD::FRACT: 6315 case AMDGPUISD::RCP: 6316 case AMDGPUISD::RSQ: 6317 case AMDGPUISD::RCP_LEGACY: 6318 case AMDGPUISD::RSQ_LEGACY: 6319 case AMDGPUISD::RSQ_CLAMP: 6320 case AMDGPUISD::LDEXP: { 6321 SDValue Src = N->getOperand(0); 6322 if (Src.isUndef()) 6323 return Src; 6324 break; 6325 } 6326 case ISD::SINT_TO_FP: 6327 case ISD::UINT_TO_FP: 6328 return performUCharToFloatCombine(N, DCI); 6329 case AMDGPUISD::CVT_F32_UBYTE0: 6330 case AMDGPUISD::CVT_F32_UBYTE1: 6331 case AMDGPUISD::CVT_F32_UBYTE2: 6332 case AMDGPUISD::CVT_F32_UBYTE3: 6333 return performCvtF32UByteNCombine(N, DCI); 6334 case AMDGPUISD::FMED3: 6335 return performFMed3Combine(N, DCI); 6336 case AMDGPUISD::CVT_PKRTZ_F16_F32: 6337 return performCvtPkRTZCombine(N, DCI); 6338 case ISD::SCALAR_TO_VECTOR: { 6339 SelectionDAG &DAG = DCI.DAG; 6340 EVT VT = N->getValueType(0); 6341 6342 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 6343 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 6344 SDLoc SL(N); 6345 SDValue Src = N->getOperand(0); 6346 EVT EltVT = Src.getValueType(); 6347 if (EltVT == MVT::f16) 6348 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 6349 6350 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 6351 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 6352 } 6353 6354 break; 6355 } 6356 case ISD::EXTRACT_VECTOR_ELT: 6357 return performExtractVectorEltCombine(N, DCI); 6358 case ISD::BUILD_VECTOR: 6359 return performBuildVectorCombine(N, DCI); 6360 } 6361 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 6362 } 6363 6364 /// \brief Helper function for adjustWritemask 6365 static unsigned SubIdx2Lane(unsigned Idx) { 6366 switch (Idx) { 6367 default: return 0; 6368 case AMDGPU::sub0: return 0; 6369 case AMDGPU::sub1: return 1; 6370 case AMDGPU::sub2: return 2; 6371 case AMDGPU::sub3: return 3; 6372 } 6373 } 6374 6375 /// \brief Adjust the writemask of MIMG instructions 6376 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 6377 SelectionDAG &DAG) const { 6378 SDNode *Users[4] = { }; 6379 unsigned Lane = 0; 6380 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 6381 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 6382 unsigned NewDmask = 0; 6383 6384 // Try to figure out the used register components 6385 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 6386 I != E; ++I) { 6387 6388 // Don't look at users of the chain. 6389 if (I.getUse().getResNo() != 0) 6390 continue; 6391 6392 // Abort if we can't understand the usage 6393 if (!I->isMachineOpcode() || 6394 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 6395 return; 6396 6397 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 6398 // Note that subregs are packed, i.e. Lane==0 is the first bit set 6399 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 6400 // set, etc. 6401 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 6402 6403 // Set which texture component corresponds to the lane. 6404 unsigned Comp; 6405 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 6406 assert(Dmask); 6407 Comp = countTrailingZeros(Dmask); 6408 Dmask &= ~(1 << Comp); 6409 } 6410 6411 // Abort if we have more than one user per component 6412 if (Users[Lane]) 6413 return; 6414 6415 Users[Lane] = *I; 6416 NewDmask |= 1 << Comp; 6417 } 6418 6419 // Abort if there's no change 6420 if (NewDmask == OldDmask) 6421 return; 6422 6423 // Adjust the writemask in the node 6424 std::vector<SDValue> Ops; 6425 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 6426 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 6427 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 6428 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 6429 6430 // If we only got one lane, replace it with a copy 6431 // (if NewDmask has only one bit set...) 6432 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 6433 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 6434 MVT::i32); 6435 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 6436 SDLoc(), Users[Lane]->getValueType(0), 6437 SDValue(Node, 0), RC); 6438 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 6439 return; 6440 } 6441 6442 // Update the users of the node with the new indices 6443 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 6444 SDNode *User = Users[i]; 6445 if (!User) 6446 continue; 6447 6448 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 6449 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 6450 6451 switch (Idx) { 6452 default: break; 6453 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 6454 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 6455 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 6456 } 6457 } 6458 } 6459 6460 static bool isFrameIndexOp(SDValue Op) { 6461 if (Op.getOpcode() == ISD::AssertZext) 6462 Op = Op.getOperand(0); 6463 6464 return isa<FrameIndexSDNode>(Op); 6465 } 6466 6467 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 6468 /// with frame index operands. 6469 /// LLVM assumes that inputs are to these instructions are registers. 6470 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 6471 SelectionDAG &DAG) const { 6472 if (Node->getOpcode() == ISD::CopyToReg) { 6473 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 6474 SDValue SrcVal = Node->getOperand(2); 6475 6476 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 6477 // to try understanding copies to physical registers. 6478 if (SrcVal.getValueType() == MVT::i1 && 6479 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 6480 SDLoc SL(Node); 6481 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 6482 SDValue VReg = DAG.getRegister( 6483 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 6484 6485 SDNode *Glued = Node->getGluedNode(); 6486 SDValue ToVReg 6487 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 6488 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 6489 SDValue ToResultReg 6490 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 6491 VReg, ToVReg.getValue(1)); 6492 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 6493 DAG.RemoveDeadNode(Node); 6494 return ToResultReg.getNode(); 6495 } 6496 } 6497 6498 SmallVector<SDValue, 8> Ops; 6499 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 6500 if (!isFrameIndexOp(Node->getOperand(i))) { 6501 Ops.push_back(Node->getOperand(i)); 6502 continue; 6503 } 6504 6505 SDLoc DL(Node); 6506 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 6507 Node->getOperand(i).getValueType(), 6508 Node->getOperand(i)), 0)); 6509 } 6510 6511 return DAG.UpdateNodeOperands(Node, Ops); 6512 } 6513 6514 /// \brief Fold the instructions after selecting them. 6515 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 6516 SelectionDAG &DAG) const { 6517 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6518 unsigned Opcode = Node->getMachineOpcode(); 6519 6520 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 6521 !TII->isGather4(Opcode)) 6522 adjustWritemask(Node, DAG); 6523 6524 if (Opcode == AMDGPU::INSERT_SUBREG || 6525 Opcode == AMDGPU::REG_SEQUENCE) { 6526 legalizeTargetIndependentNode(Node, DAG); 6527 return Node; 6528 } 6529 6530 switch (Opcode) { 6531 case AMDGPU::V_DIV_SCALE_F32: 6532 case AMDGPU::V_DIV_SCALE_F64: { 6533 // Satisfy the operand register constraint when one of the inputs is 6534 // undefined. Ordinarily each undef value will have its own implicit_def of 6535 // a vreg, so force these to use a single register. 6536 SDValue Src0 = Node->getOperand(0); 6537 SDValue Src1 = Node->getOperand(1); 6538 SDValue Src2 = Node->getOperand(2); 6539 6540 if ((Src0.isMachineOpcode() && 6541 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 6542 (Src0 == Src1 || Src0 == Src2)) 6543 break; 6544 6545 MVT VT = Src0.getValueType().getSimpleVT(); 6546 const TargetRegisterClass *RC = getRegClassFor(VT); 6547 6548 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 6549 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 6550 6551 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 6552 UndefReg, Src0, SDValue()); 6553 6554 // src0 must be the same register as src1 or src2, even if the value is 6555 // undefined, so make sure we don't violate this constraint. 6556 if (Src0.isMachineOpcode() && 6557 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 6558 if (Src1.isMachineOpcode() && 6559 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 6560 Src0 = Src1; 6561 else if (Src2.isMachineOpcode() && 6562 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 6563 Src0 = Src2; 6564 else { 6565 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 6566 Src0 = UndefReg; 6567 Src1 = UndefReg; 6568 } 6569 } else 6570 break; 6571 6572 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 6573 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 6574 Ops.push_back(Node->getOperand(I)); 6575 6576 Ops.push_back(ImpDef.getValue(1)); 6577 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 6578 } 6579 default: 6580 break; 6581 } 6582 6583 return Node; 6584 } 6585 6586 /// \brief Assign the register class depending on the number of 6587 /// bits set in the writemask 6588 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 6589 SDNode *Node) const { 6590 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6591 6592 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 6593 6594 if (TII->isVOP3(MI.getOpcode())) { 6595 // Make sure constant bus requirements are respected. 6596 TII->legalizeOperandsVOP3(MRI, MI); 6597 return; 6598 } 6599 6600 if (TII->isMIMG(MI)) { 6601 unsigned VReg = MI.getOperand(0).getReg(); 6602 const TargetRegisterClass *RC = MRI.getRegClass(VReg); 6603 // TODO: Need mapping tables to handle other cases (register classes). 6604 if (RC != &AMDGPU::VReg_128RegClass) 6605 return; 6606 6607 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4; 6608 unsigned Writemask = MI.getOperand(DmaskIdx).getImm(); 6609 unsigned BitsSet = 0; 6610 for (unsigned i = 0; i < 4; ++i) 6611 BitsSet += Writemask & (1 << i) ? 1 : 0; 6612 switch (BitsSet) { 6613 default: return; 6614 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 6615 case 2: RC = &AMDGPU::VReg_64RegClass; break; 6616 case 3: RC = &AMDGPU::VReg_96RegClass; break; 6617 } 6618 6619 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet); 6620 MI.setDesc(TII->get(NewOpcode)); 6621 MRI.setRegClass(VReg, RC); 6622 return; 6623 } 6624 6625 // Replace unused atomics with the no return version. 6626 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 6627 if (NoRetAtomicOp != -1) { 6628 if (!Node->hasAnyUseOfValue(0)) { 6629 MI.setDesc(TII->get(NoRetAtomicOp)); 6630 MI.RemoveOperand(0); 6631 return; 6632 } 6633 6634 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 6635 // instruction, because the return type of these instructions is a vec2 of 6636 // the memory type, so it can be tied to the input operand. 6637 // This means these instructions always have a use, so we need to add a 6638 // special case to check if the atomic has only one extract_subreg use, 6639 // which itself has no uses. 6640 if ((Node->hasNUsesOfValue(1, 0) && 6641 Node->use_begin()->isMachineOpcode() && 6642 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 6643 !Node->use_begin()->hasAnyUseOfValue(0))) { 6644 unsigned Def = MI.getOperand(0).getReg(); 6645 6646 // Change this into a noret atomic. 6647 MI.setDesc(TII->get(NoRetAtomicOp)); 6648 MI.RemoveOperand(0); 6649 6650 // If we only remove the def operand from the atomic instruction, the 6651 // extract_subreg will be left with a use of a vreg without a def. 6652 // So we need to insert an implicit_def to avoid machine verifier 6653 // errors. 6654 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 6655 TII->get(AMDGPU::IMPLICIT_DEF), Def); 6656 } 6657 return; 6658 } 6659 } 6660 6661 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 6662 uint64_t Val) { 6663 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 6664 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 6665 } 6666 6667 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 6668 const SDLoc &DL, 6669 SDValue Ptr) const { 6670 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6671 6672 // Build the half of the subregister with the constants before building the 6673 // full 128-bit register. If we are building multiple resource descriptors, 6674 // this will allow CSEing of the 2-component register. 6675 const SDValue Ops0[] = { 6676 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 6677 buildSMovImm32(DAG, DL, 0), 6678 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 6679 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 6680 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 6681 }; 6682 6683 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 6684 MVT::v2i32, Ops0), 0); 6685 6686 // Combine the constants and the pointer. 6687 const SDValue Ops1[] = { 6688 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 6689 Ptr, 6690 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 6691 SubRegHi, 6692 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 6693 }; 6694 6695 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 6696 } 6697 6698 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 6699 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 6700 /// of the resource descriptor) to create an offset, which is added to 6701 /// the resource pointer. 6702 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 6703 SDValue Ptr, uint32_t RsrcDword1, 6704 uint64_t RsrcDword2And3) const { 6705 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 6706 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 6707 if (RsrcDword1) { 6708 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 6709 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 6710 0); 6711 } 6712 6713 SDValue DataLo = buildSMovImm32(DAG, DL, 6714 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 6715 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 6716 6717 const SDValue Ops[] = { 6718 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 6719 PtrLo, 6720 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 6721 PtrHi, 6722 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 6723 DataLo, 6724 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 6725 DataHi, 6726 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 6727 }; 6728 6729 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 6730 } 6731 6732 //===----------------------------------------------------------------------===// 6733 // SI Inline Assembly Support 6734 //===----------------------------------------------------------------------===// 6735 6736 std::pair<unsigned, const TargetRegisterClass *> 6737 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 6738 StringRef Constraint, 6739 MVT VT) const { 6740 if (!isTypeLegal(VT)) 6741 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6742 6743 if (Constraint.size() == 1) { 6744 switch (Constraint[0]) { 6745 case 's': 6746 case 'r': 6747 switch (VT.getSizeInBits()) { 6748 default: 6749 return std::make_pair(0U, nullptr); 6750 case 32: 6751 case 16: 6752 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 6753 case 64: 6754 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 6755 case 128: 6756 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 6757 case 256: 6758 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 6759 case 512: 6760 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 6761 } 6762 6763 case 'v': 6764 switch (VT.getSizeInBits()) { 6765 default: 6766 return std::make_pair(0U, nullptr); 6767 case 32: 6768 case 16: 6769 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 6770 case 64: 6771 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 6772 case 96: 6773 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 6774 case 128: 6775 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 6776 case 256: 6777 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 6778 case 512: 6779 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 6780 } 6781 } 6782 } 6783 6784 if (Constraint.size() > 1) { 6785 const TargetRegisterClass *RC = nullptr; 6786 if (Constraint[1] == 'v') { 6787 RC = &AMDGPU::VGPR_32RegClass; 6788 } else if (Constraint[1] == 's') { 6789 RC = &AMDGPU::SGPR_32RegClass; 6790 } 6791 6792 if (RC) { 6793 uint32_t Idx; 6794 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 6795 if (!Failed && Idx < RC->getNumRegs()) 6796 return std::make_pair(RC->getRegister(Idx), RC); 6797 } 6798 } 6799 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6800 } 6801 6802 SITargetLowering::ConstraintType 6803 SITargetLowering::getConstraintType(StringRef Constraint) const { 6804 if (Constraint.size() == 1) { 6805 switch (Constraint[0]) { 6806 default: break; 6807 case 's': 6808 case 'v': 6809 return C_RegisterClass; 6810 } 6811 } 6812 return TargetLowering::getConstraintType(Constraint); 6813 } 6814 6815 // Figure out which registers should be reserved for stack access. Only after 6816 // the function is legalized do we know all of the non-spill stack objects or if 6817 // calls are present. 6818 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 6819 MachineRegisterInfo &MRI = MF.getRegInfo(); 6820 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 6821 const MachineFrameInfo &MFI = MF.getFrameInfo(); 6822 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 6823 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 6824 6825 if (Info->isEntryFunction()) { 6826 // Callable functions have fixed registers used for stack access. 6827 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 6828 } 6829 6830 // We have to assume the SP is needed in case there are calls in the function 6831 // during lowering. Calls are only detected after the function is 6832 // lowered. We're about to reserve registers, so don't bother using it if we 6833 // aren't really going to use it. 6834 bool NeedSP = !Info->isEntryFunction() || 6835 MFI.hasVarSizedObjects() || 6836 MFI.hasCalls(); 6837 6838 if (NeedSP) { 6839 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF); 6840 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 6841 6842 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()); 6843 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 6844 Info->getStackPtrOffsetReg())); 6845 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 6846 } 6847 6848 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 6849 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 6850 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 6851 Info->getScratchWaveOffsetReg()); 6852 6853 TargetLoweringBase::finalizeLowering(MF); 6854 } 6855