1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUSubtarget.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 19 #include "SIDefines.h" 20 #include "SIInstrInfo.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "SIRegisterInfo.h" 23 #include "Utils/AMDGPUBaseInfo.h" 24 #include "llvm/ADT/APFloat.h" 25 #include "llvm/ADT/APInt.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/BitVector.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/ADT/StringSwitch.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CallingConvLower.h" 36 #include "llvm/CodeGen/DAGCombine.h" 37 #include "llvm/CodeGen/FunctionLoweringInfo.h" 38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetCallingConv.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/ValueTypes.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugLoc.h" 58 #include "llvm/IR/DerivedTypes.h" 59 #include "llvm/IR/DiagnosticInfo.h" 60 #include "llvm/IR/Function.h" 61 #include "llvm/IR/GlobalValue.h" 62 #include "llvm/IR/InstrTypes.h" 63 #include "llvm/IR/Instruction.h" 64 #include "llvm/IR/Instructions.h" 65 #include "llvm/IR/IntrinsicInst.h" 66 #include "llvm/IR/Type.h" 67 #include "llvm/Support/Casting.h" 68 #include "llvm/Support/CodeGen.h" 69 #include "llvm/Support/CommandLine.h" 70 #include "llvm/Support/Compiler.h" 71 #include "llvm/Support/ErrorHandling.h" 72 #include "llvm/Support/KnownBits.h" 73 #include "llvm/Support/MachineValueType.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Target/TargetOptions.h" 76 #include <cassert> 77 #include <cmath> 78 #include <cstdint> 79 #include <iterator> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 86 #define DEBUG_TYPE "si-lower" 87 88 STATISTIC(NumTailCalls, "Number of tail calls"); 89 90 static cl::opt<bool> DisableLoopAlignment( 91 "amdgpu-disable-loop-alignment", 92 cl::desc("Do not align and prefetch loops"), 93 cl::init(false)); 94 95 static cl::opt<bool> VGPRReserveforSGPRSpill( 96 "amdgpu-reserve-vgpr-for-sgpr-spill", 97 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 98 99 static cl::opt<bool> UseDivergentRegisterIndexing( 100 "amdgpu-use-divergent-register-indexing", 101 cl::Hidden, 102 cl::desc("Use indirect register addressing for divergent indexes"), 103 cl::init(false)); 104 105 static bool hasFP32Denormals(const MachineFunction &MF) { 106 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 107 return Info->getMode().allFP32Denormals(); 108 } 109 110 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 111 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 112 return Info->getMode().allFP64FP16Denormals(); 113 } 114 115 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 116 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 117 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 118 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 119 return AMDGPU::SGPR0 + Reg; 120 } 121 } 122 llvm_unreachable("Cannot allocate sgpr"); 123 } 124 125 SITargetLowering::SITargetLowering(const TargetMachine &TM, 126 const GCNSubtarget &STI) 127 : AMDGPUTargetLowering(TM, STI), 128 Subtarget(&STI) { 129 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 130 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 131 132 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 133 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 134 135 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 136 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 137 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 138 139 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 140 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 141 142 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 143 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 144 145 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 146 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 147 148 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 149 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 150 151 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 152 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 153 154 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 155 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 156 157 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 158 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 159 160 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 161 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 162 163 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 164 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 165 166 if (Subtarget->has16BitInsts()) { 167 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 168 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 169 170 // Unless there are also VOP3P operations, not operations are really legal. 171 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 172 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 173 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 174 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 175 } 176 177 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 178 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 179 180 computeRegisterProperties(Subtarget->getRegisterInfo()); 181 182 // The boolean content concept here is too inflexible. Compares only ever 183 // really produce a 1-bit result. Any copy/extend from these will turn into a 184 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 185 // it's what most targets use. 186 setBooleanContents(ZeroOrOneBooleanContent); 187 setBooleanVectorContents(ZeroOrOneBooleanContent); 188 189 // We need to custom lower vector stores from local memory 190 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 196 setOperationAction(ISD::LOAD, MVT::i1, Custom); 197 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 198 199 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 204 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 205 setOperationAction(ISD::STORE, MVT::i1, Custom); 206 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 207 208 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 209 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 210 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 211 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 212 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 213 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 214 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 215 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 216 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 217 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 218 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 219 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 220 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 221 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 222 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 223 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 224 225 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 227 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 228 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 229 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 230 231 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 232 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 233 234 setOperationAction(ISD::SELECT, MVT::i1, Promote); 235 setOperationAction(ISD::SELECT, MVT::i64, Custom); 236 setOperationAction(ISD::SELECT, MVT::f64, Promote); 237 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 238 239 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 242 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 243 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 244 245 setOperationAction(ISD::SETCC, MVT::i1, Promote); 246 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 247 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 248 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 249 250 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 251 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 252 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 253 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 254 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 255 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 256 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 257 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 258 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 267 268 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 269 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 270 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 271 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 272 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 273 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 274 275 setOperationAction(ISD::UADDO, MVT::i32, Legal); 276 setOperationAction(ISD::USUBO, MVT::i32, Legal); 277 278 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 279 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 280 281 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 282 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 283 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 284 285 #if 0 286 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 287 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 288 #endif 289 290 // We only support LOAD/STORE and vector manipulation ops for vectors 291 // with > 4 elements. 292 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 293 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 294 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 295 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 296 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 297 switch (Op) { 298 case ISD::LOAD: 299 case ISD::STORE: 300 case ISD::BUILD_VECTOR: 301 case ISD::BITCAST: 302 case ISD::EXTRACT_VECTOR_ELT: 303 case ISD::INSERT_VECTOR_ELT: 304 case ISD::INSERT_SUBVECTOR: 305 case ISD::EXTRACT_SUBVECTOR: 306 case ISD::SCALAR_TO_VECTOR: 307 break; 308 case ISD::CONCAT_VECTORS: 309 setOperationAction(Op, VT, Custom); 310 break; 311 default: 312 setOperationAction(Op, VT, Expand); 313 break; 314 } 315 } 316 } 317 318 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 319 320 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 321 // is expanded to avoid having two separate loops in case the index is a VGPR. 322 323 // Most operations are naturally 32-bit vector operations. We only support 324 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 325 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 326 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 327 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 328 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 330 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 331 332 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 333 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 334 335 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 336 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 337 } 338 339 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 340 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 341 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 344 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 345 346 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 347 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 348 349 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 350 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 351 } 352 353 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 354 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 355 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 358 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 359 360 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 361 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 362 363 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 364 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 365 } 366 367 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 368 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 369 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 372 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 373 374 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 375 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 376 377 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 378 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 379 } 380 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 383 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 384 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 385 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 387 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 388 389 // Avoid stack access for these. 390 // TODO: Generalize to more vector types. 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 395 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 401 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 404 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 405 406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 409 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 410 411 // Deal with vec3 vector operations when widened to vec4. 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 416 417 // Deal with vec5 vector operations when widened to vec8. 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 420 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 421 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 422 423 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 424 // and output demarshalling 425 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 426 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 427 428 // We can't return success/failure, only the old value, 429 // let LLVM add the comparison 430 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 431 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 432 433 if (Subtarget->hasFlatAddressSpace()) { 434 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 435 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 436 } 437 438 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 439 440 // FIXME: This should be narrowed to i32, but that only happens if i64 is 441 // illegal. 442 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 443 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 444 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 445 446 // On SI this is s_memtime and s_memrealtime on VI. 447 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 448 setOperationAction(ISD::TRAP, MVT::Other, Custom); 449 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 450 451 if (Subtarget->has16BitInsts()) { 452 setOperationAction(ISD::FPOW, MVT::f16, Promote); 453 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 454 setOperationAction(ISD::FLOG, MVT::f16, Custom); 455 setOperationAction(ISD::FEXP, MVT::f16, Custom); 456 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 457 } 458 459 if (Subtarget->hasMadMacF32Insts()) 460 setOperationAction(ISD::FMAD, MVT::f32, Legal); 461 462 if (!Subtarget->hasBFI()) { 463 // fcopysign can be done in a single instruction with BFI. 464 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 465 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 466 } 467 468 if (!Subtarget->hasBCNT(32)) 469 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 470 471 if (!Subtarget->hasBCNT(64)) 472 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 473 474 if (Subtarget->hasFFBH()) 475 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 476 477 if (Subtarget->hasFFBL()) 478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 479 480 // We only really have 32-bit BFE instructions (and 16-bit on VI). 481 // 482 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 483 // effort to match them now. We want this to be false for i64 cases when the 484 // extraction isn't restricted to the upper or lower half. Ideally we would 485 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 486 // span the midpoint are probably relatively rare, so don't worry about them 487 // for now. 488 if (Subtarget->hasBFE()) 489 setHasExtractBitsInsn(true); 490 491 // Clamp modifier on add/sub 492 if (Subtarget->hasIntClamp()) { 493 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 494 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 495 } 496 497 if (Subtarget->hasAddNoCarry()) { 498 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 502 } 503 504 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 508 509 510 // These are really only legal for ieee_mode functions. We should be avoiding 511 // them for functions that don't have ieee_mode enabled, so just say they are 512 // legal. 513 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 517 518 519 if (Subtarget->haveRoundOpsF64()) { 520 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 521 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 522 setOperationAction(ISD::FRINT, MVT::f64, Legal); 523 } else { 524 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 525 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 526 setOperationAction(ISD::FRINT, MVT::f64, Custom); 527 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 528 } 529 530 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 531 532 setOperationAction(ISD::FSIN, MVT::f32, Custom); 533 setOperationAction(ISD::FCOS, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f64, Custom); 536 537 if (Subtarget->has16BitInsts()) { 538 setOperationAction(ISD::Constant, MVT::i16, Legal); 539 540 setOperationAction(ISD::SMIN, MVT::i16, Legal); 541 setOperationAction(ISD::SMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::UMIN, MVT::i16, Legal); 544 setOperationAction(ISD::UMAX, MVT::i16, Legal); 545 546 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 547 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 548 549 setOperationAction(ISD::ROTR, MVT::i16, Expand); 550 setOperationAction(ISD::ROTL, MVT::i16, Expand); 551 552 setOperationAction(ISD::SDIV, MVT::i16, Promote); 553 setOperationAction(ISD::UDIV, MVT::i16, Promote); 554 setOperationAction(ISD::SREM, MVT::i16, Promote); 555 setOperationAction(ISD::UREM, MVT::i16, Promote); 556 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 557 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 558 559 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 560 561 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 566 567 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 568 569 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::LOAD, MVT::i16, Custom); 572 573 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 574 575 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 576 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 577 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 579 580 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 582 583 // F16 - Constant Actions. 584 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 585 586 // F16 - Load/Store Actions. 587 setOperationAction(ISD::LOAD, MVT::f16, Promote); 588 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 589 setOperationAction(ISD::STORE, MVT::f16, Promote); 590 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 591 592 // F16 - VOP1 Actions. 593 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 594 setOperationAction(ISD::FCOS, MVT::f16, Custom); 595 setOperationAction(ISD::FSIN, MVT::f16, Custom); 596 597 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 598 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 599 600 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 601 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 602 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 604 setOperationAction(ISD::FROUND, MVT::f16, Custom); 605 606 // F16 - VOP2 Actions. 607 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 608 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 609 610 setOperationAction(ISD::FDIV, MVT::f16, Custom); 611 612 // F16 - VOP3 Actions. 613 setOperationAction(ISD::FMA, MVT::f16, Legal); 614 if (STI.hasMadF16()) 615 setOperationAction(ISD::FMAD, MVT::f16, Legal); 616 617 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 618 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 619 switch (Op) { 620 case ISD::LOAD: 621 case ISD::STORE: 622 case ISD::BUILD_VECTOR: 623 case ISD::BITCAST: 624 case ISD::EXTRACT_VECTOR_ELT: 625 case ISD::INSERT_VECTOR_ELT: 626 case ISD::INSERT_SUBVECTOR: 627 case ISD::EXTRACT_SUBVECTOR: 628 case ISD::SCALAR_TO_VECTOR: 629 break; 630 case ISD::CONCAT_VECTORS: 631 setOperationAction(Op, VT, Custom); 632 break; 633 default: 634 setOperationAction(Op, VT, Expand); 635 break; 636 } 637 } 638 } 639 640 // v_perm_b32 can handle either of these. 641 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 643 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 644 645 // XXX - Do these do anything? Vector constants turn into build_vector. 646 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 647 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 648 649 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 650 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 653 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 654 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 655 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 656 657 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 658 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 659 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 660 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 661 662 setOperationAction(ISD::AND, MVT::v2i16, Promote); 663 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 664 setOperationAction(ISD::OR, MVT::v2i16, Promote); 665 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 666 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 668 669 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 670 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 671 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 672 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 673 674 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 675 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 676 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 677 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 678 679 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 682 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 683 684 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 686 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 687 688 if (!Subtarget->hasVOP3PInsts()) { 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 690 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 691 } 692 693 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 694 // This isn't really legal, but this avoids the legalizer unrolling it (and 695 // allows matching fneg (fabs x) patterns) 696 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 697 698 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 700 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 701 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 702 703 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 704 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 705 706 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 707 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 708 } 709 710 if (Subtarget->hasVOP3PInsts()) { 711 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 712 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 713 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 716 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 717 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 719 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 720 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 721 722 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 725 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 726 727 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 730 731 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 732 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 733 734 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 735 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 741 742 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 744 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 745 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 746 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 747 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 748 749 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 750 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 752 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 753 754 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 757 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 758 759 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 762 763 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 764 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 765 766 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 768 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 769 770 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 772 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 773 } 774 775 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 776 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 777 778 if (Subtarget->has16BitInsts()) { 779 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 780 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 781 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 782 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 783 } else { 784 // Legalization hack. 785 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 786 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 787 788 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 789 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 790 } 791 792 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 793 setOperationAction(ISD::SELECT, VT, Custom); 794 } 795 796 setOperationAction(ISD::SMULO, MVT::i64, Custom); 797 setOperationAction(ISD::UMULO, MVT::i64, Custom); 798 799 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 801 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 802 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 803 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 805 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 806 807 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 808 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 809 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 810 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 811 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 812 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 813 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 815 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 816 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 817 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 818 819 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 820 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 821 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 822 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 823 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 824 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 825 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 826 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 827 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 828 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 829 830 setTargetDAGCombine(ISD::ADD); 831 setTargetDAGCombine(ISD::ADDCARRY); 832 setTargetDAGCombine(ISD::SUB); 833 setTargetDAGCombine(ISD::SUBCARRY); 834 setTargetDAGCombine(ISD::FADD); 835 setTargetDAGCombine(ISD::FSUB); 836 setTargetDAGCombine(ISD::FMINNUM); 837 setTargetDAGCombine(ISD::FMAXNUM); 838 setTargetDAGCombine(ISD::FMINNUM_IEEE); 839 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 840 setTargetDAGCombine(ISD::FMA); 841 setTargetDAGCombine(ISD::SMIN); 842 setTargetDAGCombine(ISD::SMAX); 843 setTargetDAGCombine(ISD::UMIN); 844 setTargetDAGCombine(ISD::UMAX); 845 setTargetDAGCombine(ISD::SETCC); 846 setTargetDAGCombine(ISD::AND); 847 setTargetDAGCombine(ISD::OR); 848 setTargetDAGCombine(ISD::XOR); 849 setTargetDAGCombine(ISD::SINT_TO_FP); 850 setTargetDAGCombine(ISD::UINT_TO_FP); 851 setTargetDAGCombine(ISD::FCANONICALIZE); 852 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 853 setTargetDAGCombine(ISD::ZERO_EXTEND); 854 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 855 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 856 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 857 858 // All memory operations. Some folding on the pointer operand is done to help 859 // matching the constant offsets in the addressing modes. 860 setTargetDAGCombine(ISD::LOAD); 861 setTargetDAGCombine(ISD::STORE); 862 setTargetDAGCombine(ISD::ATOMIC_LOAD); 863 setTargetDAGCombine(ISD::ATOMIC_STORE); 864 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 865 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 866 setTargetDAGCombine(ISD::ATOMIC_SWAP); 867 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 868 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 870 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 871 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 872 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 873 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 874 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 875 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 876 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 877 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 878 setTargetDAGCombine(ISD::INTRINSIC_VOID); 879 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 880 881 // FIXME: In other contexts we pretend this is a per-function property. 882 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 883 884 setSchedulingPreference(Sched::RegPressure); 885 } 886 887 const GCNSubtarget *SITargetLowering::getSubtarget() const { 888 return Subtarget; 889 } 890 891 //===----------------------------------------------------------------------===// 892 // TargetLowering queries 893 //===----------------------------------------------------------------------===// 894 895 // v_mad_mix* support a conversion from f16 to f32. 896 // 897 // There is only one special case when denormals are enabled we don't currently, 898 // where this is OK to use. 899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 900 EVT DestVT, EVT SrcVT) const { 901 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 902 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 903 DestVT.getScalarType() == MVT::f32 && 904 SrcVT.getScalarType() == MVT::f16 && 905 // TODO: This probably only requires no input flushing? 906 !hasFP32Denormals(DAG.getMachineFunction()); 907 } 908 909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 910 // SI has some legal vector types, but no legal vector operations. Say no 911 // shuffles are legal in order to prefer scalarizing some vector operations. 912 return false; 913 } 914 915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 916 CallingConv::ID CC, 917 EVT VT) const { 918 if (CC == CallingConv::AMDGPU_KERNEL) 919 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 920 921 if (VT.isVector()) { 922 EVT ScalarVT = VT.getScalarType(); 923 unsigned Size = ScalarVT.getSizeInBits(); 924 if (Size == 16) { 925 if (Subtarget->has16BitInsts()) 926 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 927 return VT.isInteger() ? MVT::i32 : MVT::f32; 928 } 929 930 if (Size < 16) 931 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 932 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 933 } 934 935 if (VT.getSizeInBits() > 32) 936 return MVT::i32; 937 938 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 939 } 940 941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 942 CallingConv::ID CC, 943 EVT VT) const { 944 if (CC == CallingConv::AMDGPU_KERNEL) 945 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 946 947 if (VT.isVector()) { 948 unsigned NumElts = VT.getVectorNumElements(); 949 EVT ScalarVT = VT.getScalarType(); 950 unsigned Size = ScalarVT.getSizeInBits(); 951 952 // FIXME: Should probably promote 8-bit vectors to i16. 953 if (Size == 16 && Subtarget->has16BitInsts()) 954 return (NumElts + 1) / 2; 955 956 if (Size <= 32) 957 return NumElts; 958 959 if (Size > 32) 960 return NumElts * ((Size + 31) / 32); 961 } else if (VT.getSizeInBits() > 32) 962 return (VT.getSizeInBits() + 31) / 32; 963 964 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 965 } 966 967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 968 LLVMContext &Context, CallingConv::ID CC, 969 EVT VT, EVT &IntermediateVT, 970 unsigned &NumIntermediates, MVT &RegisterVT) const { 971 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 972 unsigned NumElts = VT.getVectorNumElements(); 973 EVT ScalarVT = VT.getScalarType(); 974 unsigned Size = ScalarVT.getSizeInBits(); 975 // FIXME: We should fix the ABI to be the same on targets without 16-bit 976 // support, but unless we can properly handle 3-vectors, it will be still be 977 // inconsistent. 978 if (Size == 16 && Subtarget->has16BitInsts()) { 979 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 980 IntermediateVT = RegisterVT; 981 NumIntermediates = (NumElts + 1) / 2; 982 return NumIntermediates; 983 } 984 985 if (Size == 32) { 986 RegisterVT = ScalarVT.getSimpleVT(); 987 IntermediateVT = RegisterVT; 988 NumIntermediates = NumElts; 989 return NumIntermediates; 990 } 991 992 if (Size < 16 && Subtarget->has16BitInsts()) { 993 // FIXME: Should probably form v2i16 pieces 994 RegisterVT = MVT::i16; 995 IntermediateVT = ScalarVT; 996 NumIntermediates = NumElts; 997 return NumIntermediates; 998 } 999 1000 1001 if (Size != 16 && Size <= 32) { 1002 RegisterVT = MVT::i32; 1003 IntermediateVT = ScalarVT; 1004 NumIntermediates = NumElts; 1005 return NumIntermediates; 1006 } 1007 1008 if (Size > 32) { 1009 RegisterVT = MVT::i32; 1010 IntermediateVT = RegisterVT; 1011 NumIntermediates = NumElts * ((Size + 31) / 32); 1012 return NumIntermediates; 1013 } 1014 } 1015 1016 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1017 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1018 } 1019 1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1021 assert(DMaskLanes != 0); 1022 1023 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1024 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1025 return EVT::getVectorVT(Ty->getContext(), 1026 EVT::getEVT(VT->getElementType()), 1027 NumElts); 1028 } 1029 1030 return EVT::getEVT(Ty); 1031 } 1032 1033 // Peek through TFE struct returns to only use the data size. 1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1035 auto *ST = dyn_cast<StructType>(Ty); 1036 if (!ST) 1037 return memVTFromImageData(Ty, DMaskLanes); 1038 1039 // Some intrinsics return an aggregate type - special case to work out the 1040 // correct memVT. 1041 // 1042 // Only limited forms of aggregate type currently expected. 1043 if (ST->getNumContainedTypes() != 2 || 1044 !ST->getContainedType(1)->isIntegerTy(32)) 1045 return EVT(); 1046 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1047 } 1048 1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1050 const CallInst &CI, 1051 MachineFunction &MF, 1052 unsigned IntrID) const { 1053 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1054 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1055 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1056 (Intrinsic::ID)IntrID); 1057 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1058 return false; 1059 1060 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1061 1062 if (RsrcIntr->IsImage) { 1063 Info.ptrVal = MFI->getImagePSV( 1064 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1065 CI.getArgOperand(RsrcIntr->RsrcArg)); 1066 Info.align.reset(); 1067 } else { 1068 Info.ptrVal = MFI->getBufferPSV( 1069 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1070 CI.getArgOperand(RsrcIntr->RsrcArg)); 1071 } 1072 1073 Info.flags = MachineMemOperand::MODereferenceable; 1074 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1075 unsigned DMaskLanes = 4; 1076 1077 if (RsrcIntr->IsImage) { 1078 const AMDGPU::ImageDimIntrinsicInfo *Intr 1079 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1080 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1081 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1082 1083 if (!BaseOpcode->Gather4) { 1084 // If this isn't a gather, we may have excess loaded elements in the 1085 // IR type. Check the dmask for the real number of elements loaded. 1086 unsigned DMask 1087 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1088 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1089 } 1090 1091 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1092 } else 1093 Info.memVT = EVT::getEVT(CI.getType()); 1094 1095 // FIXME: What does alignment mean for an image? 1096 Info.opc = ISD::INTRINSIC_W_CHAIN; 1097 Info.flags |= MachineMemOperand::MOLoad; 1098 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1099 Info.opc = ISD::INTRINSIC_VOID; 1100 1101 Type *DataTy = CI.getArgOperand(0)->getType(); 1102 if (RsrcIntr->IsImage) { 1103 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1104 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1105 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1106 } else 1107 Info.memVT = EVT::getEVT(DataTy); 1108 1109 Info.flags |= MachineMemOperand::MOStore; 1110 } else { 1111 // Atomic 1112 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1113 ISD::INTRINSIC_W_CHAIN; 1114 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1115 Info.flags = MachineMemOperand::MOLoad | 1116 MachineMemOperand::MOStore | 1117 MachineMemOperand::MODereferenceable; 1118 1119 // XXX - Should this be volatile without known ordering? 1120 Info.flags |= MachineMemOperand::MOVolatile; 1121 } 1122 return true; 1123 } 1124 1125 switch (IntrID) { 1126 case Intrinsic::amdgcn_atomic_inc: 1127 case Intrinsic::amdgcn_atomic_dec: 1128 case Intrinsic::amdgcn_ds_ordered_add: 1129 case Intrinsic::amdgcn_ds_ordered_swap: 1130 case Intrinsic::amdgcn_ds_fadd: 1131 case Intrinsic::amdgcn_ds_fmin: 1132 case Intrinsic::amdgcn_ds_fmax: { 1133 Info.opc = ISD::INTRINSIC_W_CHAIN; 1134 Info.memVT = MVT::getVT(CI.getType()); 1135 Info.ptrVal = CI.getOperand(0); 1136 Info.align.reset(); 1137 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1138 1139 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1140 if (!Vol->isZero()) 1141 Info.flags |= MachineMemOperand::MOVolatile; 1142 1143 return true; 1144 } 1145 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1146 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1147 1148 Info.opc = ISD::INTRINSIC_W_CHAIN; 1149 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1150 Info.ptrVal = MFI->getBufferPSV( 1151 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1152 CI.getArgOperand(1)); 1153 Info.align.reset(); 1154 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1155 1156 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1157 if (!Vol || !Vol->isZero()) 1158 Info.flags |= MachineMemOperand::MOVolatile; 1159 1160 return true; 1161 } 1162 case Intrinsic::amdgcn_ds_append: 1163 case Intrinsic::amdgcn_ds_consume: { 1164 Info.opc = ISD::INTRINSIC_W_CHAIN; 1165 Info.memVT = MVT::getVT(CI.getType()); 1166 Info.ptrVal = CI.getOperand(0); 1167 Info.align.reset(); 1168 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1169 1170 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1171 if (!Vol->isZero()) 1172 Info.flags |= MachineMemOperand::MOVolatile; 1173 1174 return true; 1175 } 1176 case Intrinsic::amdgcn_global_atomic_csub: { 1177 Info.opc = ISD::INTRINSIC_W_CHAIN; 1178 Info.memVT = MVT::getVT(CI.getType()); 1179 Info.ptrVal = CI.getOperand(0); 1180 Info.align.reset(); 1181 Info.flags = MachineMemOperand::MOLoad | 1182 MachineMemOperand::MOStore | 1183 MachineMemOperand::MOVolatile; 1184 return true; 1185 } 1186 case Intrinsic::amdgcn_global_atomic_fadd: { 1187 Info.opc = ISD::INTRINSIC_W_CHAIN; 1188 Info.memVT = MVT::getVT(CI.getType()); 1189 Info.ptrVal = CI.getOperand(0); 1190 Info.align.reset(); 1191 Info.flags = MachineMemOperand::MOLoad | 1192 MachineMemOperand::MOStore | 1193 MachineMemOperand::MODereferenceable | 1194 MachineMemOperand::MOVolatile; 1195 return true; 1196 } 1197 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1198 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1199 Info.opc = ISD::INTRINSIC_W_CHAIN; 1200 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1201 Info.ptrVal = MFI->getImagePSV( 1202 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5)); 1203 Info.align.reset(); 1204 Info.flags = MachineMemOperand::MOLoad | 1205 MachineMemOperand::MODereferenceable; 1206 return true; 1207 } 1208 case Intrinsic::amdgcn_ds_gws_init: 1209 case Intrinsic::amdgcn_ds_gws_barrier: 1210 case Intrinsic::amdgcn_ds_gws_sema_v: 1211 case Intrinsic::amdgcn_ds_gws_sema_br: 1212 case Intrinsic::amdgcn_ds_gws_sema_p: 1213 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1214 Info.opc = ISD::INTRINSIC_VOID; 1215 1216 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1217 Info.ptrVal = 1218 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1219 1220 // This is an abstract access, but we need to specify a type and size. 1221 Info.memVT = MVT::i32; 1222 Info.size = 4; 1223 Info.align = Align(4); 1224 1225 Info.flags = MachineMemOperand::MOStore; 1226 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1227 Info.flags = MachineMemOperand::MOLoad; 1228 return true; 1229 } 1230 default: 1231 return false; 1232 } 1233 } 1234 1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1236 SmallVectorImpl<Value*> &Ops, 1237 Type *&AccessTy) const { 1238 switch (II->getIntrinsicID()) { 1239 case Intrinsic::amdgcn_atomic_inc: 1240 case Intrinsic::amdgcn_atomic_dec: 1241 case Intrinsic::amdgcn_ds_ordered_add: 1242 case Intrinsic::amdgcn_ds_ordered_swap: 1243 case Intrinsic::amdgcn_ds_append: 1244 case Intrinsic::amdgcn_ds_consume: 1245 case Intrinsic::amdgcn_ds_fadd: 1246 case Intrinsic::amdgcn_ds_fmin: 1247 case Intrinsic::amdgcn_ds_fmax: 1248 case Intrinsic::amdgcn_global_atomic_fadd: 1249 case Intrinsic::amdgcn_global_atomic_csub: { 1250 Value *Ptr = II->getArgOperand(0); 1251 AccessTy = II->getType(); 1252 Ops.push_back(Ptr); 1253 return true; 1254 } 1255 default: 1256 return false; 1257 } 1258 } 1259 1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1261 if (!Subtarget->hasFlatInstOffsets()) { 1262 // Flat instructions do not have offsets, and only have the register 1263 // address. 1264 return AM.BaseOffs == 0 && AM.Scale == 0; 1265 } 1266 1267 return AM.Scale == 0 && 1268 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1269 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1270 /*Signed=*/false)); 1271 } 1272 1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1274 if (Subtarget->hasFlatGlobalInsts()) 1275 return AM.Scale == 0 && 1276 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1277 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1278 /*Signed=*/true)); 1279 1280 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1281 // Assume the we will use FLAT for all global memory accesses 1282 // on VI. 1283 // FIXME: This assumption is currently wrong. On VI we still use 1284 // MUBUF instructions for the r + i addressing mode. As currently 1285 // implemented, the MUBUF instructions only work on buffer < 4GB. 1286 // It may be possible to support > 4GB buffers with MUBUF instructions, 1287 // by setting the stride value in the resource descriptor which would 1288 // increase the size limit to (stride * 4GB). However, this is risky, 1289 // because it has never been validated. 1290 return isLegalFlatAddressingMode(AM); 1291 } 1292 1293 return isLegalMUBUFAddressingMode(AM); 1294 } 1295 1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1297 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1298 // additionally can do r + r + i with addr64. 32-bit has more addressing 1299 // mode options. Depending on the resource constant, it can also do 1300 // (i64 r0) + (i32 r1) * (i14 i). 1301 // 1302 // Private arrays end up using a scratch buffer most of the time, so also 1303 // assume those use MUBUF instructions. Scratch loads / stores are currently 1304 // implemented as mubuf instructions with offen bit set, so slightly 1305 // different than the normal addr64. 1306 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1307 return false; 1308 1309 // FIXME: Since we can split immediate into soffset and immediate offset, 1310 // would it make sense to allow any immediate? 1311 1312 switch (AM.Scale) { 1313 case 0: // r + i or just i, depending on HasBaseReg. 1314 return true; 1315 case 1: 1316 return true; // We have r + r or r + i. 1317 case 2: 1318 if (AM.HasBaseReg) { 1319 // Reject 2 * r + r. 1320 return false; 1321 } 1322 1323 // Allow 2 * r as r + r 1324 // Or 2 * r + i is allowed as r + r + i. 1325 return true; 1326 default: // Don't allow n * r 1327 return false; 1328 } 1329 } 1330 1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1332 const AddrMode &AM, Type *Ty, 1333 unsigned AS, Instruction *I) const { 1334 // No global is ever allowed as a base. 1335 if (AM.BaseGV) 1336 return false; 1337 1338 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1339 return isLegalGlobalAddressingMode(AM); 1340 1341 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1342 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1343 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1344 // If the offset isn't a multiple of 4, it probably isn't going to be 1345 // correctly aligned. 1346 // FIXME: Can we get the real alignment here? 1347 if (AM.BaseOffs % 4 != 0) 1348 return isLegalMUBUFAddressingMode(AM); 1349 1350 // There are no SMRD extloads, so if we have to do a small type access we 1351 // will use a MUBUF load. 1352 // FIXME?: We also need to do this if unaligned, but we don't know the 1353 // alignment here. 1354 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1355 return isLegalGlobalAddressingMode(AM); 1356 1357 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1358 // SMRD instructions have an 8-bit, dword offset on SI. 1359 if (!isUInt<8>(AM.BaseOffs / 4)) 1360 return false; 1361 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1362 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1363 // in 8-bits, it can use a smaller encoding. 1364 if (!isUInt<32>(AM.BaseOffs / 4)) 1365 return false; 1366 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1367 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1368 if (!isUInt<20>(AM.BaseOffs)) 1369 return false; 1370 } else 1371 llvm_unreachable("unhandled generation"); 1372 1373 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1374 return true; 1375 1376 if (AM.Scale == 1 && AM.HasBaseReg) 1377 return true; 1378 1379 return false; 1380 1381 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1382 return isLegalMUBUFAddressingMode(AM); 1383 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1384 AS == AMDGPUAS::REGION_ADDRESS) { 1385 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1386 // field. 1387 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1388 // an 8-bit dword offset but we don't know the alignment here. 1389 if (!isUInt<16>(AM.BaseOffs)) 1390 return false; 1391 1392 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1393 return true; 1394 1395 if (AM.Scale == 1 && AM.HasBaseReg) 1396 return true; 1397 1398 return false; 1399 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1400 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1401 // For an unknown address space, this usually means that this is for some 1402 // reason being used for pure arithmetic, and not based on some addressing 1403 // computation. We don't have instructions that compute pointers with any 1404 // addressing modes, so treat them as having no offset like flat 1405 // instructions. 1406 return isLegalFlatAddressingMode(AM); 1407 } 1408 1409 // Assume a user alias of global for unknown address spaces. 1410 return isLegalGlobalAddressingMode(AM); 1411 } 1412 1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1414 const SelectionDAG &DAG) const { 1415 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1416 return (MemVT.getSizeInBits() <= 4 * 32); 1417 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1418 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1419 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1420 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1421 return (MemVT.getSizeInBits() <= 2 * 32); 1422 } 1423 return true; 1424 } 1425 1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1427 unsigned Size, unsigned AddrSpace, Align Alignment, 1428 MachineMemOperand::Flags Flags, bool *IsFast) const { 1429 if (IsFast) 1430 *IsFast = false; 1431 1432 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1433 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1434 // Check if alignment requirements for ds_read/write instructions are 1435 // disabled. 1436 if (Subtarget->hasUnalignedDSAccess() && 1437 Subtarget->hasUnalignedAccessMode() && 1438 !Subtarget->hasLDSMisalignedBug()) { 1439 if (IsFast) 1440 *IsFast = Alignment != Align(2); 1441 return true; 1442 } 1443 1444 if (Size == 64) { 1445 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1446 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1447 // with adjacent offsets. 1448 bool AlignedBy4 = Alignment >= Align(4); 1449 if (IsFast) 1450 *IsFast = AlignedBy4; 1451 1452 return AlignedBy4; 1453 } 1454 if (Size == 96) { 1455 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1456 bool Aligned = Alignment >= Align(16); 1457 if (IsFast) 1458 *IsFast = Aligned; 1459 1460 return Aligned; 1461 } 1462 if (Size == 128) { 1463 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1464 // can do a 8 byte aligned, 16 byte access in a single operation using 1465 // ds_read2/write2_b64. 1466 bool Aligned = Alignment >= Align(8); 1467 if (IsFast) 1468 *IsFast = Aligned; 1469 1470 return Aligned; 1471 } 1472 } 1473 1474 // FIXME: We have to be conservative here and assume that flat operations 1475 // will access scratch. If we had access to the IR function, then we 1476 // could determine if any private memory was used in the function. 1477 if (!Subtarget->hasUnalignedScratchAccess() && 1478 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1479 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1480 bool AlignedBy4 = Alignment >= Align(4); 1481 if (IsFast) 1482 *IsFast = AlignedBy4; 1483 1484 return AlignedBy4; 1485 } 1486 1487 if (Subtarget->hasUnalignedBufferAccess() && 1488 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1489 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1490 // If we have an uniform constant load, it still requires using a slow 1491 // buffer instruction if unaligned. 1492 if (IsFast) { 1493 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1494 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1495 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1496 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1497 Alignment >= Align(4) : Alignment != Align(2); 1498 } 1499 1500 return true; 1501 } 1502 1503 // Smaller than dword value must be aligned. 1504 if (Size < 32) 1505 return false; 1506 1507 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1508 // byte-address are ignored, thus forcing Dword alignment. 1509 // This applies to private, global, and constant memory. 1510 if (IsFast) 1511 *IsFast = true; 1512 1513 return Size >= 32 && Alignment >= Align(4); 1514 } 1515 1516 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1517 EVT VT, unsigned AddrSpace, unsigned Alignment, 1518 MachineMemOperand::Flags Flags, bool *IsFast) const { 1519 if (IsFast) 1520 *IsFast = false; 1521 1522 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1523 // which isn't a simple VT. 1524 // Until MVT is extended to handle this, simply check for the size and 1525 // rely on the condition below: allow accesses if the size is a multiple of 4. 1526 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1527 VT.getStoreSize() > 16)) { 1528 return false; 1529 } 1530 1531 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1532 Align(Alignment), Flags, IsFast); 1533 } 1534 1535 EVT SITargetLowering::getOptimalMemOpType( 1536 const MemOp &Op, const AttributeList &FuncAttributes) const { 1537 // FIXME: Should account for address space here. 1538 1539 // The default fallback uses the private pointer size as a guess for a type to 1540 // use. Make sure we switch these to 64-bit accesses. 1541 1542 if (Op.size() >= 16 && 1543 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1544 return MVT::v4i32; 1545 1546 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1547 return MVT::v2i32; 1548 1549 // Use the default. 1550 return MVT::Other; 1551 } 1552 1553 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1554 const MemSDNode *MemNode = cast<MemSDNode>(N); 1555 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1556 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1557 return I && I->getMetadata("amdgpu.noclobber"); 1558 } 1559 1560 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1561 unsigned DestAS) const { 1562 // Flat -> private/local is a simple truncate. 1563 // Flat -> global is no-op 1564 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1565 return true; 1566 1567 const GCNTargetMachine &TM = 1568 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1569 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1570 } 1571 1572 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1573 const MemSDNode *MemNode = cast<MemSDNode>(N); 1574 1575 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1576 } 1577 1578 TargetLoweringBase::LegalizeTypeAction 1579 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1580 int NumElts = VT.getVectorNumElements(); 1581 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1582 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1583 return TargetLoweringBase::getPreferredVectorAction(VT); 1584 } 1585 1586 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1587 Type *Ty) const { 1588 // FIXME: Could be smarter if called for vector constants. 1589 return true; 1590 } 1591 1592 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1593 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1594 switch (Op) { 1595 case ISD::LOAD: 1596 case ISD::STORE: 1597 1598 // These operations are done with 32-bit instructions anyway. 1599 case ISD::AND: 1600 case ISD::OR: 1601 case ISD::XOR: 1602 case ISD::SELECT: 1603 // TODO: Extensions? 1604 return true; 1605 default: 1606 return false; 1607 } 1608 } 1609 1610 // SimplifySetCC uses this function to determine whether or not it should 1611 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1612 if (VT == MVT::i1 && Op == ISD::SETCC) 1613 return false; 1614 1615 return TargetLowering::isTypeDesirableForOp(Op, VT); 1616 } 1617 1618 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1619 const SDLoc &SL, 1620 SDValue Chain, 1621 uint64_t Offset) const { 1622 const DataLayout &DL = DAG.getDataLayout(); 1623 MachineFunction &MF = DAG.getMachineFunction(); 1624 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1625 1626 const ArgDescriptor *InputPtrReg; 1627 const TargetRegisterClass *RC; 1628 LLT ArgTy; 1629 1630 std::tie(InputPtrReg, RC, ArgTy) = 1631 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1632 1633 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1634 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1635 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1636 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1637 1638 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1639 } 1640 1641 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1642 const SDLoc &SL) const { 1643 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1644 FIRST_IMPLICIT); 1645 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1646 } 1647 1648 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1649 const SDLoc &SL, SDValue Val, 1650 bool Signed, 1651 const ISD::InputArg *Arg) const { 1652 // First, if it is a widened vector, narrow it. 1653 if (VT.isVector() && 1654 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1655 EVT NarrowedVT = 1656 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1657 VT.getVectorNumElements()); 1658 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1659 DAG.getConstant(0, SL, MVT::i32)); 1660 } 1661 1662 // Then convert the vector elements or scalar value. 1663 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1664 VT.bitsLT(MemVT)) { 1665 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1666 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1667 } 1668 1669 if (MemVT.isFloatingPoint()) 1670 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1671 else if (Signed) 1672 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1673 else 1674 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1675 1676 return Val; 1677 } 1678 1679 SDValue SITargetLowering::lowerKernargMemParameter( 1680 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1681 uint64_t Offset, Align Alignment, bool Signed, 1682 const ISD::InputArg *Arg) const { 1683 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1684 1685 // Try to avoid using an extload by loading earlier than the argument address, 1686 // and extracting the relevant bits. The load should hopefully be merged with 1687 // the previous argument. 1688 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1689 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1690 int64_t AlignDownOffset = alignDown(Offset, 4); 1691 int64_t OffsetDiff = Offset - AlignDownOffset; 1692 1693 EVT IntVT = MemVT.changeTypeToInteger(); 1694 1695 // TODO: If we passed in the base kernel offset we could have a better 1696 // alignment than 4, but we don't really need it. 1697 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1698 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1699 MachineMemOperand::MODereferenceable | 1700 MachineMemOperand::MOInvariant); 1701 1702 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1703 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1704 1705 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1706 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1707 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1708 1709 1710 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1711 } 1712 1713 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1714 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1715 MachineMemOperand::MODereferenceable | 1716 MachineMemOperand::MOInvariant); 1717 1718 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1719 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1720 } 1721 1722 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1723 const SDLoc &SL, SDValue Chain, 1724 const ISD::InputArg &Arg) const { 1725 MachineFunction &MF = DAG.getMachineFunction(); 1726 MachineFrameInfo &MFI = MF.getFrameInfo(); 1727 1728 if (Arg.Flags.isByVal()) { 1729 unsigned Size = Arg.Flags.getByValSize(); 1730 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1731 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1732 } 1733 1734 unsigned ArgOffset = VA.getLocMemOffset(); 1735 unsigned ArgSize = VA.getValVT().getStoreSize(); 1736 1737 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1738 1739 // Create load nodes to retrieve arguments from the stack. 1740 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1741 SDValue ArgValue; 1742 1743 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1744 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1745 MVT MemVT = VA.getValVT(); 1746 1747 switch (VA.getLocInfo()) { 1748 default: 1749 break; 1750 case CCValAssign::BCvt: 1751 MemVT = VA.getLocVT(); 1752 break; 1753 case CCValAssign::SExt: 1754 ExtType = ISD::SEXTLOAD; 1755 break; 1756 case CCValAssign::ZExt: 1757 ExtType = ISD::ZEXTLOAD; 1758 break; 1759 case CCValAssign::AExt: 1760 ExtType = ISD::EXTLOAD; 1761 break; 1762 } 1763 1764 ArgValue = DAG.getExtLoad( 1765 ExtType, SL, VA.getLocVT(), Chain, FIN, 1766 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1767 MemVT); 1768 return ArgValue; 1769 } 1770 1771 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1772 const SIMachineFunctionInfo &MFI, 1773 EVT VT, 1774 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1775 const ArgDescriptor *Reg; 1776 const TargetRegisterClass *RC; 1777 LLT Ty; 1778 1779 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1780 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1781 } 1782 1783 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1784 CallingConv::ID CallConv, 1785 ArrayRef<ISD::InputArg> Ins, 1786 BitVector &Skipped, 1787 FunctionType *FType, 1788 SIMachineFunctionInfo *Info) { 1789 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1790 const ISD::InputArg *Arg = &Ins[I]; 1791 1792 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1793 "vector type argument should have been split"); 1794 1795 // First check if it's a PS input addr. 1796 if (CallConv == CallingConv::AMDGPU_PS && 1797 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1798 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1799 1800 // Inconveniently only the first part of the split is marked as isSplit, 1801 // so skip to the end. We only want to increment PSInputNum once for the 1802 // entire split argument. 1803 if (Arg->Flags.isSplit()) { 1804 while (!Arg->Flags.isSplitEnd()) { 1805 assert((!Arg->VT.isVector() || 1806 Arg->VT.getScalarSizeInBits() == 16) && 1807 "unexpected vector split in ps argument type"); 1808 if (!SkipArg) 1809 Splits.push_back(*Arg); 1810 Arg = &Ins[++I]; 1811 } 1812 } 1813 1814 if (SkipArg) { 1815 // We can safely skip PS inputs. 1816 Skipped.set(Arg->getOrigArgIndex()); 1817 ++PSInputNum; 1818 continue; 1819 } 1820 1821 Info->markPSInputAllocated(PSInputNum); 1822 if (Arg->Used) 1823 Info->markPSInputEnabled(PSInputNum); 1824 1825 ++PSInputNum; 1826 } 1827 1828 Splits.push_back(*Arg); 1829 } 1830 } 1831 1832 // Allocate special inputs passed in VGPRs. 1833 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1834 MachineFunction &MF, 1835 const SIRegisterInfo &TRI, 1836 SIMachineFunctionInfo &Info) const { 1837 const LLT S32 = LLT::scalar(32); 1838 MachineRegisterInfo &MRI = MF.getRegInfo(); 1839 1840 if (Info.hasWorkItemIDX()) { 1841 Register Reg = AMDGPU::VGPR0; 1842 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1843 1844 CCInfo.AllocateReg(Reg); 1845 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1846 } 1847 1848 if (Info.hasWorkItemIDY()) { 1849 Register Reg = AMDGPU::VGPR1; 1850 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1851 1852 CCInfo.AllocateReg(Reg); 1853 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1854 } 1855 1856 if (Info.hasWorkItemIDZ()) { 1857 Register Reg = AMDGPU::VGPR2; 1858 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1859 1860 CCInfo.AllocateReg(Reg); 1861 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1862 } 1863 } 1864 1865 // Try to allocate a VGPR at the end of the argument list, or if no argument 1866 // VGPRs are left allocating a stack slot. 1867 // If \p Mask is is given it indicates bitfield position in the register. 1868 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1869 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1870 ArgDescriptor Arg = ArgDescriptor()) { 1871 if (Arg.isSet()) 1872 return ArgDescriptor::createArg(Arg, Mask); 1873 1874 ArrayRef<MCPhysReg> ArgVGPRs 1875 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1876 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1877 if (RegIdx == ArgVGPRs.size()) { 1878 // Spill to stack required. 1879 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1880 1881 return ArgDescriptor::createStack(Offset, Mask); 1882 } 1883 1884 unsigned Reg = ArgVGPRs[RegIdx]; 1885 Reg = CCInfo.AllocateReg(Reg); 1886 assert(Reg != AMDGPU::NoRegister); 1887 1888 MachineFunction &MF = CCInfo.getMachineFunction(); 1889 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1890 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1891 return ArgDescriptor::createRegister(Reg, Mask); 1892 } 1893 1894 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1895 const TargetRegisterClass *RC, 1896 unsigned NumArgRegs) { 1897 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1898 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1899 if (RegIdx == ArgSGPRs.size()) 1900 report_fatal_error("ran out of SGPRs for arguments"); 1901 1902 unsigned Reg = ArgSGPRs[RegIdx]; 1903 Reg = CCInfo.AllocateReg(Reg); 1904 assert(Reg != AMDGPU::NoRegister); 1905 1906 MachineFunction &MF = CCInfo.getMachineFunction(); 1907 MF.addLiveIn(Reg, RC); 1908 return ArgDescriptor::createRegister(Reg); 1909 } 1910 1911 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1912 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1913 } 1914 1915 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1916 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1917 } 1918 1919 /// Allocate implicit function VGPR arguments at the end of allocated user 1920 /// arguments. 1921 void SITargetLowering::allocateSpecialInputVGPRs( 1922 CCState &CCInfo, MachineFunction &MF, 1923 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1924 const unsigned Mask = 0x3ff; 1925 ArgDescriptor Arg; 1926 1927 if (Info.hasWorkItemIDX()) { 1928 Arg = allocateVGPR32Input(CCInfo, Mask); 1929 Info.setWorkItemIDX(Arg); 1930 } 1931 1932 if (Info.hasWorkItemIDY()) { 1933 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1934 Info.setWorkItemIDY(Arg); 1935 } 1936 1937 if (Info.hasWorkItemIDZ()) 1938 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1939 } 1940 1941 /// Allocate implicit function VGPR arguments in fixed registers. 1942 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1943 CCState &CCInfo, MachineFunction &MF, 1944 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1945 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1946 if (!Reg) 1947 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1948 1949 const unsigned Mask = 0x3ff; 1950 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1951 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1952 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1953 } 1954 1955 void SITargetLowering::allocateSpecialInputSGPRs( 1956 CCState &CCInfo, 1957 MachineFunction &MF, 1958 const SIRegisterInfo &TRI, 1959 SIMachineFunctionInfo &Info) const { 1960 auto &ArgInfo = Info.getArgInfo(); 1961 1962 // TODO: Unify handling with private memory pointers. 1963 1964 if (Info.hasDispatchPtr()) 1965 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1966 1967 if (Info.hasQueuePtr()) 1968 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1969 1970 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1971 // constant offset from the kernarg segment. 1972 if (Info.hasImplicitArgPtr()) 1973 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1974 1975 if (Info.hasDispatchID()) 1976 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1977 1978 // flat_scratch_init is not applicable for non-kernel functions. 1979 1980 if (Info.hasWorkGroupIDX()) 1981 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1982 1983 if (Info.hasWorkGroupIDY()) 1984 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1985 1986 if (Info.hasWorkGroupIDZ()) 1987 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1988 } 1989 1990 // Allocate special inputs passed in user SGPRs. 1991 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1992 MachineFunction &MF, 1993 const SIRegisterInfo &TRI, 1994 SIMachineFunctionInfo &Info) const { 1995 if (Info.hasImplicitBufferPtr()) { 1996 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1997 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1998 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1999 } 2000 2001 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2002 if (Info.hasPrivateSegmentBuffer()) { 2003 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2004 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2005 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2006 } 2007 2008 if (Info.hasDispatchPtr()) { 2009 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2010 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2011 CCInfo.AllocateReg(DispatchPtrReg); 2012 } 2013 2014 if (Info.hasQueuePtr()) { 2015 Register QueuePtrReg = Info.addQueuePtr(TRI); 2016 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2017 CCInfo.AllocateReg(QueuePtrReg); 2018 } 2019 2020 if (Info.hasKernargSegmentPtr()) { 2021 MachineRegisterInfo &MRI = MF.getRegInfo(); 2022 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2023 CCInfo.AllocateReg(InputPtrReg); 2024 2025 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2026 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2027 } 2028 2029 if (Info.hasDispatchID()) { 2030 Register DispatchIDReg = Info.addDispatchID(TRI); 2031 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2032 CCInfo.AllocateReg(DispatchIDReg); 2033 } 2034 2035 if (Info.hasFlatScratchInit()) { 2036 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2037 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2038 CCInfo.AllocateReg(FlatScratchInitReg); 2039 } 2040 2041 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2042 // these from the dispatch pointer. 2043 } 2044 2045 // Allocate special input registers that are initialized per-wave. 2046 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2047 MachineFunction &MF, 2048 SIMachineFunctionInfo &Info, 2049 CallingConv::ID CallConv, 2050 bool IsShader) const { 2051 if (Info.hasWorkGroupIDX()) { 2052 Register Reg = Info.addWorkGroupIDX(); 2053 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2054 CCInfo.AllocateReg(Reg); 2055 } 2056 2057 if (Info.hasWorkGroupIDY()) { 2058 Register Reg = Info.addWorkGroupIDY(); 2059 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2060 CCInfo.AllocateReg(Reg); 2061 } 2062 2063 if (Info.hasWorkGroupIDZ()) { 2064 Register Reg = Info.addWorkGroupIDZ(); 2065 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2066 CCInfo.AllocateReg(Reg); 2067 } 2068 2069 if (Info.hasWorkGroupInfo()) { 2070 Register Reg = Info.addWorkGroupInfo(); 2071 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2072 CCInfo.AllocateReg(Reg); 2073 } 2074 2075 if (Info.hasPrivateSegmentWaveByteOffset()) { 2076 // Scratch wave offset passed in system SGPR. 2077 unsigned PrivateSegmentWaveByteOffsetReg; 2078 2079 if (IsShader) { 2080 PrivateSegmentWaveByteOffsetReg = 2081 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2082 2083 // This is true if the scratch wave byte offset doesn't have a fixed 2084 // location. 2085 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2086 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2087 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2088 } 2089 } else 2090 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2091 2092 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2093 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2094 } 2095 } 2096 2097 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2098 MachineFunction &MF, 2099 const SIRegisterInfo &TRI, 2100 SIMachineFunctionInfo &Info) { 2101 // Now that we've figured out where the scratch register inputs are, see if 2102 // should reserve the arguments and use them directly. 2103 MachineFrameInfo &MFI = MF.getFrameInfo(); 2104 bool HasStackObjects = MFI.hasStackObjects(); 2105 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2106 2107 // Record that we know we have non-spill stack objects so we don't need to 2108 // check all stack objects later. 2109 if (HasStackObjects) 2110 Info.setHasNonSpillStackObjects(true); 2111 2112 // Everything live out of a block is spilled with fast regalloc, so it's 2113 // almost certain that spilling will be required. 2114 if (TM.getOptLevel() == CodeGenOpt::None) 2115 HasStackObjects = true; 2116 2117 // For now assume stack access is needed in any callee functions, so we need 2118 // the scratch registers to pass in. 2119 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2120 2121 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2122 // If we have stack objects, we unquestionably need the private buffer 2123 // resource. For the Code Object V2 ABI, this will be the first 4 user 2124 // SGPR inputs. We can reserve those and use them directly. 2125 2126 Register PrivateSegmentBufferReg = 2127 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2128 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2129 } else { 2130 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2131 // We tentatively reserve the last registers (skipping the last registers 2132 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2133 // we'll replace these with the ones immediately after those which were 2134 // really allocated. In the prologue copies will be inserted from the 2135 // argument to these reserved registers. 2136 2137 // Without HSA, relocations are used for the scratch pointer and the 2138 // buffer resource setup is always inserted in the prologue. Scratch wave 2139 // offset is still in an input SGPR. 2140 Info.setScratchRSrcReg(ReservedBufferReg); 2141 } 2142 2143 MachineRegisterInfo &MRI = MF.getRegInfo(); 2144 2145 // For entry functions we have to set up the stack pointer if we use it, 2146 // whereas non-entry functions get this "for free". This means there is no 2147 // intrinsic advantage to using S32 over S34 in cases where we do not have 2148 // calls but do need a frame pointer (i.e. if we are requested to have one 2149 // because frame pointer elimination is disabled). To keep things simple we 2150 // only ever use S32 as the call ABI stack pointer, and so using it does not 2151 // imply we need a separate frame pointer. 2152 // 2153 // Try to use s32 as the SP, but move it if it would interfere with input 2154 // arguments. This won't work with calls though. 2155 // 2156 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2157 // registers. 2158 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2159 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2160 } else { 2161 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2162 2163 if (MFI.hasCalls()) 2164 report_fatal_error("call in graphics shader with too many input SGPRs"); 2165 2166 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2167 if (!MRI.isLiveIn(Reg)) { 2168 Info.setStackPtrOffsetReg(Reg); 2169 break; 2170 } 2171 } 2172 2173 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2174 report_fatal_error("failed to find register for SP"); 2175 } 2176 2177 // hasFP should be accurate for entry functions even before the frame is 2178 // finalized, because it does not rely on the known stack size, only 2179 // properties like whether variable sized objects are present. 2180 if (ST.getFrameLowering()->hasFP(MF)) { 2181 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2182 } 2183 } 2184 2185 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2186 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2187 return !Info->isEntryFunction(); 2188 } 2189 2190 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2191 2192 } 2193 2194 void SITargetLowering::insertCopiesSplitCSR( 2195 MachineBasicBlock *Entry, 2196 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2197 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2198 2199 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2200 if (!IStart) 2201 return; 2202 2203 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2204 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2205 MachineBasicBlock::iterator MBBI = Entry->begin(); 2206 for (const MCPhysReg *I = IStart; *I; ++I) { 2207 const TargetRegisterClass *RC = nullptr; 2208 if (AMDGPU::SReg_64RegClass.contains(*I)) 2209 RC = &AMDGPU::SGPR_64RegClass; 2210 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2211 RC = &AMDGPU::SGPR_32RegClass; 2212 else 2213 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2214 2215 Register NewVR = MRI->createVirtualRegister(RC); 2216 // Create copy from CSR to a virtual register. 2217 Entry->addLiveIn(*I); 2218 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2219 .addReg(*I); 2220 2221 // Insert the copy-back instructions right before the terminator. 2222 for (auto *Exit : Exits) 2223 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2224 TII->get(TargetOpcode::COPY), *I) 2225 .addReg(NewVR); 2226 } 2227 } 2228 2229 SDValue SITargetLowering::LowerFormalArguments( 2230 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2231 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2232 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2233 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2234 2235 MachineFunction &MF = DAG.getMachineFunction(); 2236 const Function &Fn = MF.getFunction(); 2237 FunctionType *FType = MF.getFunction().getFunctionType(); 2238 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2239 2240 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2241 DiagnosticInfoUnsupported NoGraphicsHSA( 2242 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2243 DAG.getContext()->diagnose(NoGraphicsHSA); 2244 return DAG.getEntryNode(); 2245 } 2246 2247 SmallVector<ISD::InputArg, 16> Splits; 2248 SmallVector<CCValAssign, 16> ArgLocs; 2249 BitVector Skipped(Ins.size()); 2250 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2251 *DAG.getContext()); 2252 2253 bool IsShader = AMDGPU::isShader(CallConv); 2254 bool IsKernel = AMDGPU::isKernel(CallConv); 2255 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2256 2257 if (IsShader) { 2258 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2259 2260 // At least one interpolation mode must be enabled or else the GPU will 2261 // hang. 2262 // 2263 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2264 // set PSInputAddr, the user wants to enable some bits after the compilation 2265 // based on run-time states. Since we can't know what the final PSInputEna 2266 // will look like, so we shouldn't do anything here and the user should take 2267 // responsibility for the correct programming. 2268 // 2269 // Otherwise, the following restrictions apply: 2270 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2271 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2272 // enabled too. 2273 if (CallConv == CallingConv::AMDGPU_PS) { 2274 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2275 ((Info->getPSInputAddr() & 0xF) == 0 && 2276 Info->isPSInputAllocated(11))) { 2277 CCInfo.AllocateReg(AMDGPU::VGPR0); 2278 CCInfo.AllocateReg(AMDGPU::VGPR1); 2279 Info->markPSInputAllocated(0); 2280 Info->markPSInputEnabled(0); 2281 } 2282 if (Subtarget->isAmdPalOS()) { 2283 // For isAmdPalOS, the user does not enable some bits after compilation 2284 // based on run-time states; the register values being generated here are 2285 // the final ones set in hardware. Therefore we need to apply the 2286 // workaround to PSInputAddr and PSInputEnable together. (The case where 2287 // a bit is set in PSInputAddr but not PSInputEnable is where the 2288 // frontend set up an input arg for a particular interpolation mode, but 2289 // nothing uses that input arg. Really we should have an earlier pass 2290 // that removes such an arg.) 2291 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2292 if ((PsInputBits & 0x7F) == 0 || 2293 ((PsInputBits & 0xF) == 0 && 2294 (PsInputBits >> 11 & 1))) 2295 Info->markPSInputEnabled( 2296 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2297 } 2298 } 2299 2300 assert(!Info->hasDispatchPtr() && 2301 !Info->hasKernargSegmentPtr() && 2302 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2303 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2304 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2305 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2306 !Info->hasWorkItemIDZ()); 2307 } else if (IsKernel) { 2308 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2309 } else { 2310 Splits.append(Ins.begin(), Ins.end()); 2311 } 2312 2313 if (IsEntryFunc) { 2314 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2315 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2316 } else { 2317 // For the fixed ABI, pass workitem IDs in the last argument register. 2318 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2319 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2320 } 2321 2322 if (IsKernel) { 2323 analyzeFormalArgumentsCompute(CCInfo, Ins); 2324 } else { 2325 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2326 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2327 } 2328 2329 SmallVector<SDValue, 16> Chains; 2330 2331 // FIXME: This is the minimum kernel argument alignment. We should improve 2332 // this to the maximum alignment of the arguments. 2333 // 2334 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2335 // kern arg offset. 2336 const Align KernelArgBaseAlign = Align(16); 2337 2338 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2339 const ISD::InputArg &Arg = Ins[i]; 2340 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2341 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2342 continue; 2343 } 2344 2345 CCValAssign &VA = ArgLocs[ArgIdx++]; 2346 MVT VT = VA.getLocVT(); 2347 2348 if (IsEntryFunc && VA.isMemLoc()) { 2349 VT = Ins[i].VT; 2350 EVT MemVT = VA.getLocVT(); 2351 2352 const uint64_t Offset = VA.getLocMemOffset(); 2353 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2354 2355 if (Arg.Flags.isByRef()) { 2356 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2357 2358 const GCNTargetMachine &TM = 2359 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2360 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2361 Arg.Flags.getPointerAddrSpace())) { 2362 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2363 Arg.Flags.getPointerAddrSpace()); 2364 } 2365 2366 InVals.push_back(Ptr); 2367 continue; 2368 } 2369 2370 SDValue Arg = lowerKernargMemParameter( 2371 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2372 Chains.push_back(Arg.getValue(1)); 2373 2374 auto *ParamTy = 2375 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2376 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2377 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2378 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2379 // On SI local pointers are just offsets into LDS, so they are always 2380 // less than 16-bits. On CI and newer they could potentially be 2381 // real pointers, so we can't guarantee their size. 2382 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2383 DAG.getValueType(MVT::i16)); 2384 } 2385 2386 InVals.push_back(Arg); 2387 continue; 2388 } else if (!IsEntryFunc && VA.isMemLoc()) { 2389 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2390 InVals.push_back(Val); 2391 if (!Arg.Flags.isByVal()) 2392 Chains.push_back(Val.getValue(1)); 2393 continue; 2394 } 2395 2396 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2397 2398 Register Reg = VA.getLocReg(); 2399 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2400 EVT ValVT = VA.getValVT(); 2401 2402 Reg = MF.addLiveIn(Reg, RC); 2403 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2404 2405 if (Arg.Flags.isSRet()) { 2406 // The return object should be reasonably addressable. 2407 2408 // FIXME: This helps when the return is a real sret. If it is a 2409 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2410 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2411 unsigned NumBits 2412 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2413 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2414 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2415 } 2416 2417 // If this is an 8 or 16-bit value, it is really passed promoted 2418 // to 32 bits. Insert an assert[sz]ext to capture this, then 2419 // truncate to the right size. 2420 switch (VA.getLocInfo()) { 2421 case CCValAssign::Full: 2422 break; 2423 case CCValAssign::BCvt: 2424 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2425 break; 2426 case CCValAssign::SExt: 2427 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2428 DAG.getValueType(ValVT)); 2429 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2430 break; 2431 case CCValAssign::ZExt: 2432 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2433 DAG.getValueType(ValVT)); 2434 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2435 break; 2436 case CCValAssign::AExt: 2437 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2438 break; 2439 default: 2440 llvm_unreachable("Unknown loc info!"); 2441 } 2442 2443 InVals.push_back(Val); 2444 } 2445 2446 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2447 // Special inputs come after user arguments. 2448 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2449 } 2450 2451 // Start adding system SGPRs. 2452 if (IsEntryFunc) { 2453 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2454 } else { 2455 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2456 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2457 } 2458 2459 auto &ArgUsageInfo = 2460 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2461 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2462 2463 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2464 Info->setBytesInStackArgArea(StackArgSize); 2465 2466 return Chains.empty() ? Chain : 2467 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2468 } 2469 2470 // TODO: If return values can't fit in registers, we should return as many as 2471 // possible in registers before passing on stack. 2472 bool SITargetLowering::CanLowerReturn( 2473 CallingConv::ID CallConv, 2474 MachineFunction &MF, bool IsVarArg, 2475 const SmallVectorImpl<ISD::OutputArg> &Outs, 2476 LLVMContext &Context) const { 2477 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2478 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2479 // for shaders. Vector types should be explicitly handled by CC. 2480 if (AMDGPU::isEntryFunctionCC(CallConv)) 2481 return true; 2482 2483 SmallVector<CCValAssign, 16> RVLocs; 2484 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2485 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2486 } 2487 2488 SDValue 2489 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2490 bool isVarArg, 2491 const SmallVectorImpl<ISD::OutputArg> &Outs, 2492 const SmallVectorImpl<SDValue> &OutVals, 2493 const SDLoc &DL, SelectionDAG &DAG) const { 2494 MachineFunction &MF = DAG.getMachineFunction(); 2495 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2496 2497 if (AMDGPU::isKernel(CallConv)) { 2498 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2499 OutVals, DL, DAG); 2500 } 2501 2502 bool IsShader = AMDGPU::isShader(CallConv); 2503 2504 Info->setIfReturnsVoid(Outs.empty()); 2505 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2506 2507 // CCValAssign - represent the assignment of the return value to a location. 2508 SmallVector<CCValAssign, 48> RVLocs; 2509 SmallVector<ISD::OutputArg, 48> Splits; 2510 2511 // CCState - Info about the registers and stack slots. 2512 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2513 *DAG.getContext()); 2514 2515 // Analyze outgoing return values. 2516 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2517 2518 SDValue Flag; 2519 SmallVector<SDValue, 48> RetOps; 2520 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2521 2522 // Add return address for callable functions. 2523 if (!Info->isEntryFunction()) { 2524 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2525 SDValue ReturnAddrReg = CreateLiveInRegister( 2526 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2527 2528 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2529 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2530 MVT::i64); 2531 Chain = 2532 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2533 Flag = Chain.getValue(1); 2534 RetOps.push_back(ReturnAddrVirtualReg); 2535 } 2536 2537 // Copy the result values into the output registers. 2538 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2539 ++I, ++RealRVLocIdx) { 2540 CCValAssign &VA = RVLocs[I]; 2541 assert(VA.isRegLoc() && "Can only return in registers!"); 2542 // TODO: Partially return in registers if return values don't fit. 2543 SDValue Arg = OutVals[RealRVLocIdx]; 2544 2545 // Copied from other backends. 2546 switch (VA.getLocInfo()) { 2547 case CCValAssign::Full: 2548 break; 2549 case CCValAssign::BCvt: 2550 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2551 break; 2552 case CCValAssign::SExt: 2553 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2554 break; 2555 case CCValAssign::ZExt: 2556 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2557 break; 2558 case CCValAssign::AExt: 2559 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2560 break; 2561 default: 2562 llvm_unreachable("Unknown loc info!"); 2563 } 2564 2565 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2566 Flag = Chain.getValue(1); 2567 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2568 } 2569 2570 // FIXME: Does sret work properly? 2571 if (!Info->isEntryFunction()) { 2572 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2573 const MCPhysReg *I = 2574 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2575 if (I) { 2576 for (; *I; ++I) { 2577 if (AMDGPU::SReg_64RegClass.contains(*I)) 2578 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2579 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2580 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2581 else 2582 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2583 } 2584 } 2585 } 2586 2587 // Update chain and glue. 2588 RetOps[0] = Chain; 2589 if (Flag.getNode()) 2590 RetOps.push_back(Flag); 2591 2592 unsigned Opc = AMDGPUISD::ENDPGM; 2593 if (!IsWaveEnd) 2594 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2595 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2596 } 2597 2598 SDValue SITargetLowering::LowerCallResult( 2599 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2600 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2601 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2602 SDValue ThisVal) const { 2603 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2604 2605 // Assign locations to each value returned by this call. 2606 SmallVector<CCValAssign, 16> RVLocs; 2607 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2608 *DAG.getContext()); 2609 CCInfo.AnalyzeCallResult(Ins, RetCC); 2610 2611 // Copy all of the result registers out of their specified physreg. 2612 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2613 CCValAssign VA = RVLocs[i]; 2614 SDValue Val; 2615 2616 if (VA.isRegLoc()) { 2617 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2618 Chain = Val.getValue(1); 2619 InFlag = Val.getValue(2); 2620 } else if (VA.isMemLoc()) { 2621 report_fatal_error("TODO: return values in memory"); 2622 } else 2623 llvm_unreachable("unknown argument location type"); 2624 2625 switch (VA.getLocInfo()) { 2626 case CCValAssign::Full: 2627 break; 2628 case CCValAssign::BCvt: 2629 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2630 break; 2631 case CCValAssign::ZExt: 2632 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2633 DAG.getValueType(VA.getValVT())); 2634 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2635 break; 2636 case CCValAssign::SExt: 2637 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2638 DAG.getValueType(VA.getValVT())); 2639 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2640 break; 2641 case CCValAssign::AExt: 2642 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2643 break; 2644 default: 2645 llvm_unreachable("Unknown loc info!"); 2646 } 2647 2648 InVals.push_back(Val); 2649 } 2650 2651 return Chain; 2652 } 2653 2654 // Add code to pass special inputs required depending on used features separate 2655 // from the explicit user arguments present in the IR. 2656 void SITargetLowering::passSpecialInputs( 2657 CallLoweringInfo &CLI, 2658 CCState &CCInfo, 2659 const SIMachineFunctionInfo &Info, 2660 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2661 SmallVectorImpl<SDValue> &MemOpChains, 2662 SDValue Chain) const { 2663 // If we don't have a call site, this was a call inserted by 2664 // legalization. These can never use special inputs. 2665 if (!CLI.CB) 2666 return; 2667 2668 SelectionDAG &DAG = CLI.DAG; 2669 const SDLoc &DL = CLI.DL; 2670 2671 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2672 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2673 2674 const AMDGPUFunctionArgInfo *CalleeArgInfo 2675 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2676 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2677 auto &ArgUsageInfo = 2678 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2679 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2680 } 2681 2682 // TODO: Unify with private memory register handling. This is complicated by 2683 // the fact that at least in kernels, the input argument is not necessarily 2684 // in the same location as the input. 2685 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2686 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2687 AMDGPUFunctionArgInfo::QUEUE_PTR, 2688 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2689 AMDGPUFunctionArgInfo::DISPATCH_ID, 2690 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2691 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2692 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2693 }; 2694 2695 for (auto InputID : InputRegs) { 2696 const ArgDescriptor *OutgoingArg; 2697 const TargetRegisterClass *ArgRC; 2698 LLT ArgTy; 2699 2700 std::tie(OutgoingArg, ArgRC, ArgTy) = 2701 CalleeArgInfo->getPreloadedValue(InputID); 2702 if (!OutgoingArg) 2703 continue; 2704 2705 const ArgDescriptor *IncomingArg; 2706 const TargetRegisterClass *IncomingArgRC; 2707 LLT Ty; 2708 std::tie(IncomingArg, IncomingArgRC, Ty) = 2709 CallerArgInfo.getPreloadedValue(InputID); 2710 assert(IncomingArgRC == ArgRC); 2711 2712 // All special arguments are ints for now. 2713 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2714 SDValue InputReg; 2715 2716 if (IncomingArg) { 2717 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2718 } else { 2719 // The implicit arg ptr is special because it doesn't have a corresponding 2720 // input for kernels, and is computed from the kernarg segment pointer. 2721 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2722 InputReg = getImplicitArgPtr(DAG, DL); 2723 } 2724 2725 if (OutgoingArg->isRegister()) { 2726 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2727 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2728 report_fatal_error("failed to allocate implicit input argument"); 2729 } else { 2730 unsigned SpecialArgOffset = 2731 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2732 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2733 SpecialArgOffset); 2734 MemOpChains.push_back(ArgStore); 2735 } 2736 } 2737 2738 // Pack workitem IDs into a single register or pass it as is if already 2739 // packed. 2740 const ArgDescriptor *OutgoingArg; 2741 const TargetRegisterClass *ArgRC; 2742 LLT Ty; 2743 2744 std::tie(OutgoingArg, ArgRC, Ty) = 2745 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2746 if (!OutgoingArg) 2747 std::tie(OutgoingArg, ArgRC, Ty) = 2748 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2749 if (!OutgoingArg) 2750 std::tie(OutgoingArg, ArgRC, Ty) = 2751 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2752 if (!OutgoingArg) 2753 return; 2754 2755 const ArgDescriptor *IncomingArgX = std::get<0>( 2756 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2757 const ArgDescriptor *IncomingArgY = std::get<0>( 2758 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2759 const ArgDescriptor *IncomingArgZ = std::get<0>( 2760 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2761 2762 SDValue InputReg; 2763 SDLoc SL; 2764 2765 // If incoming ids are not packed we need to pack them. 2766 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2767 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2768 2769 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2770 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2771 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2772 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2773 InputReg = InputReg.getNode() ? 2774 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2775 } 2776 2777 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2778 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2779 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2780 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2781 InputReg = InputReg.getNode() ? 2782 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2783 } 2784 2785 if (!InputReg.getNode()) { 2786 // Workitem ids are already packed, any of present incoming arguments 2787 // will carry all required fields. 2788 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2789 IncomingArgX ? *IncomingArgX : 2790 IncomingArgY ? *IncomingArgY : 2791 *IncomingArgZ, ~0u); 2792 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2793 } 2794 2795 if (OutgoingArg->isRegister()) { 2796 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2797 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2798 } else { 2799 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2800 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2801 SpecialArgOffset); 2802 MemOpChains.push_back(ArgStore); 2803 } 2804 } 2805 2806 static bool canGuaranteeTCO(CallingConv::ID CC) { 2807 return CC == CallingConv::Fast; 2808 } 2809 2810 /// Return true if we might ever do TCO for calls with this calling convention. 2811 static bool mayTailCallThisCC(CallingConv::ID CC) { 2812 switch (CC) { 2813 case CallingConv::C: 2814 return true; 2815 default: 2816 return canGuaranteeTCO(CC); 2817 } 2818 } 2819 2820 bool SITargetLowering::isEligibleForTailCallOptimization( 2821 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2822 const SmallVectorImpl<ISD::OutputArg> &Outs, 2823 const SmallVectorImpl<SDValue> &OutVals, 2824 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2825 if (!mayTailCallThisCC(CalleeCC)) 2826 return false; 2827 2828 MachineFunction &MF = DAG.getMachineFunction(); 2829 const Function &CallerF = MF.getFunction(); 2830 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2831 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2832 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2833 2834 // Kernels aren't callable, and don't have a live in return address so it 2835 // doesn't make sense to do a tail call with entry functions. 2836 if (!CallerPreserved) 2837 return false; 2838 2839 bool CCMatch = CallerCC == CalleeCC; 2840 2841 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2842 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2843 return true; 2844 return false; 2845 } 2846 2847 // TODO: Can we handle var args? 2848 if (IsVarArg) 2849 return false; 2850 2851 for (const Argument &Arg : CallerF.args()) { 2852 if (Arg.hasByValAttr()) 2853 return false; 2854 } 2855 2856 LLVMContext &Ctx = *DAG.getContext(); 2857 2858 // Check that the call results are passed in the same way. 2859 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2860 CCAssignFnForCall(CalleeCC, IsVarArg), 2861 CCAssignFnForCall(CallerCC, IsVarArg))) 2862 return false; 2863 2864 // The callee has to preserve all registers the caller needs to preserve. 2865 if (!CCMatch) { 2866 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2867 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2868 return false; 2869 } 2870 2871 // Nothing more to check if the callee is taking no arguments. 2872 if (Outs.empty()) 2873 return true; 2874 2875 SmallVector<CCValAssign, 16> ArgLocs; 2876 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2877 2878 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2879 2880 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2881 // If the stack arguments for this call do not fit into our own save area then 2882 // the call cannot be made tail. 2883 // TODO: Is this really necessary? 2884 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2885 return false; 2886 2887 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2888 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2889 } 2890 2891 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2892 if (!CI->isTailCall()) 2893 return false; 2894 2895 const Function *ParentFn = CI->getParent()->getParent(); 2896 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2897 return false; 2898 return true; 2899 } 2900 2901 // The wave scratch offset register is used as the global base pointer. 2902 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2903 SmallVectorImpl<SDValue> &InVals) const { 2904 SelectionDAG &DAG = CLI.DAG; 2905 const SDLoc &DL = CLI.DL; 2906 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2907 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2908 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2909 SDValue Chain = CLI.Chain; 2910 SDValue Callee = CLI.Callee; 2911 bool &IsTailCall = CLI.IsTailCall; 2912 CallingConv::ID CallConv = CLI.CallConv; 2913 bool IsVarArg = CLI.IsVarArg; 2914 bool IsSibCall = false; 2915 bool IsThisReturn = false; 2916 MachineFunction &MF = DAG.getMachineFunction(); 2917 2918 if (Callee.isUndef() || isNullConstant(Callee)) { 2919 if (!CLI.IsTailCall) { 2920 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2921 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2922 } 2923 2924 return Chain; 2925 } 2926 2927 if (IsVarArg) { 2928 return lowerUnhandledCall(CLI, InVals, 2929 "unsupported call to variadic function "); 2930 } 2931 2932 if (!CLI.CB) 2933 report_fatal_error("unsupported libcall legalization"); 2934 2935 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2936 !CLI.CB->getCalledFunction()) { 2937 return lowerUnhandledCall(CLI, InVals, 2938 "unsupported indirect call to function "); 2939 } 2940 2941 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2942 return lowerUnhandledCall(CLI, InVals, 2943 "unsupported required tail call to function "); 2944 } 2945 2946 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2947 // Note the issue is with the CC of the calling function, not of the call 2948 // itself. 2949 return lowerUnhandledCall(CLI, InVals, 2950 "unsupported call from graphics shader of function "); 2951 } 2952 2953 if (IsTailCall) { 2954 IsTailCall = isEligibleForTailCallOptimization( 2955 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2956 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2957 report_fatal_error("failed to perform tail call elimination on a call " 2958 "site marked musttail"); 2959 } 2960 2961 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2962 2963 // A sibling call is one where we're under the usual C ABI and not planning 2964 // to change that but can still do a tail call: 2965 if (!TailCallOpt && IsTailCall) 2966 IsSibCall = true; 2967 2968 if (IsTailCall) 2969 ++NumTailCalls; 2970 } 2971 2972 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2973 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2974 SmallVector<SDValue, 8> MemOpChains; 2975 2976 // Analyze operands of the call, assigning locations to each operand. 2977 SmallVector<CCValAssign, 16> ArgLocs; 2978 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2979 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2980 2981 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2982 // With a fixed ABI, allocate fixed registers before user arguments. 2983 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2984 } 2985 2986 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2987 2988 // Get a count of how many bytes are to be pushed on the stack. 2989 unsigned NumBytes = CCInfo.getNextStackOffset(); 2990 2991 if (IsSibCall) { 2992 // Since we're not changing the ABI to make this a tail call, the memory 2993 // operands are already available in the caller's incoming argument space. 2994 NumBytes = 0; 2995 } 2996 2997 // FPDiff is the byte offset of the call's argument area from the callee's. 2998 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2999 // by this amount for a tail call. In a sibling call it must be 0 because the 3000 // caller will deallocate the entire stack and the callee still expects its 3001 // arguments to begin at SP+0. Completely unused for non-tail calls. 3002 int32_t FPDiff = 0; 3003 MachineFrameInfo &MFI = MF.getFrameInfo(); 3004 3005 // Adjust the stack pointer for the new arguments... 3006 // These operations are automatically eliminated by the prolog/epilog pass 3007 if (!IsSibCall) { 3008 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3009 3010 SmallVector<SDValue, 4> CopyFromChains; 3011 3012 // In the HSA case, this should be an identity copy. 3013 SDValue ScratchRSrcReg 3014 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3015 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3016 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3017 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3018 } 3019 3020 MVT PtrVT = MVT::i32; 3021 3022 // Walk the register/memloc assignments, inserting copies/loads. 3023 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3024 CCValAssign &VA = ArgLocs[i]; 3025 SDValue Arg = OutVals[i]; 3026 3027 // Promote the value if needed. 3028 switch (VA.getLocInfo()) { 3029 case CCValAssign::Full: 3030 break; 3031 case CCValAssign::BCvt: 3032 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3033 break; 3034 case CCValAssign::ZExt: 3035 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3036 break; 3037 case CCValAssign::SExt: 3038 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3039 break; 3040 case CCValAssign::AExt: 3041 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3042 break; 3043 case CCValAssign::FPExt: 3044 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3045 break; 3046 default: 3047 llvm_unreachable("Unknown loc info!"); 3048 } 3049 3050 if (VA.isRegLoc()) { 3051 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3052 } else { 3053 assert(VA.isMemLoc()); 3054 3055 SDValue DstAddr; 3056 MachinePointerInfo DstInfo; 3057 3058 unsigned LocMemOffset = VA.getLocMemOffset(); 3059 int32_t Offset = LocMemOffset; 3060 3061 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3062 MaybeAlign Alignment; 3063 3064 if (IsTailCall) { 3065 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3066 unsigned OpSize = Flags.isByVal() ? 3067 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3068 3069 // FIXME: We can have better than the minimum byval required alignment. 3070 Alignment = 3071 Flags.isByVal() 3072 ? Flags.getNonZeroByValAlign() 3073 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3074 3075 Offset = Offset + FPDiff; 3076 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3077 3078 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3079 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3080 3081 // Make sure any stack arguments overlapping with where we're storing 3082 // are loaded before this eventual operation. Otherwise they'll be 3083 // clobbered. 3084 3085 // FIXME: Why is this really necessary? This seems to just result in a 3086 // lot of code to copy the stack and write them back to the same 3087 // locations, which are supposed to be immutable? 3088 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3089 } else { 3090 DstAddr = PtrOff; 3091 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3092 Alignment = 3093 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3094 } 3095 3096 if (Outs[i].Flags.isByVal()) { 3097 SDValue SizeNode = 3098 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3099 SDValue Cpy = 3100 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3101 Outs[i].Flags.getNonZeroByValAlign(), 3102 /*isVol = */ false, /*AlwaysInline = */ true, 3103 /*isTailCall = */ false, DstInfo, 3104 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3105 3106 MemOpChains.push_back(Cpy); 3107 } else { 3108 SDValue Store = 3109 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3110 MemOpChains.push_back(Store); 3111 } 3112 } 3113 } 3114 3115 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3116 // Copy special input registers after user input arguments. 3117 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3118 } 3119 3120 if (!MemOpChains.empty()) 3121 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3122 3123 // Build a sequence of copy-to-reg nodes chained together with token chain 3124 // and flag operands which copy the outgoing args into the appropriate regs. 3125 SDValue InFlag; 3126 for (auto &RegToPass : RegsToPass) { 3127 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3128 RegToPass.second, InFlag); 3129 InFlag = Chain.getValue(1); 3130 } 3131 3132 3133 SDValue PhysReturnAddrReg; 3134 if (IsTailCall) { 3135 // Since the return is being combined with the call, we need to pass on the 3136 // return address. 3137 3138 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3139 SDValue ReturnAddrReg = CreateLiveInRegister( 3140 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3141 3142 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3143 MVT::i64); 3144 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3145 InFlag = Chain.getValue(1); 3146 } 3147 3148 // We don't usually want to end the call-sequence here because we would tidy 3149 // the frame up *after* the call, however in the ABI-changing tail-call case 3150 // we've carefully laid out the parameters so that when sp is reset they'll be 3151 // in the correct location. 3152 if (IsTailCall && !IsSibCall) { 3153 Chain = DAG.getCALLSEQ_END(Chain, 3154 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3155 DAG.getTargetConstant(0, DL, MVT::i32), 3156 InFlag, DL); 3157 InFlag = Chain.getValue(1); 3158 } 3159 3160 std::vector<SDValue> Ops; 3161 Ops.push_back(Chain); 3162 Ops.push_back(Callee); 3163 // Add a redundant copy of the callee global which will not be legalized, as 3164 // we need direct access to the callee later. 3165 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3166 const GlobalValue *GV = GSD->getGlobal(); 3167 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3168 } else { 3169 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3170 } 3171 3172 if (IsTailCall) { 3173 // Each tail call may have to adjust the stack by a different amount, so 3174 // this information must travel along with the operation for eventual 3175 // consumption by emitEpilogue. 3176 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3177 3178 Ops.push_back(PhysReturnAddrReg); 3179 } 3180 3181 // Add argument registers to the end of the list so that they are known live 3182 // into the call. 3183 for (auto &RegToPass : RegsToPass) { 3184 Ops.push_back(DAG.getRegister(RegToPass.first, 3185 RegToPass.second.getValueType())); 3186 } 3187 3188 // Add a register mask operand representing the call-preserved registers. 3189 3190 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3191 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3192 assert(Mask && "Missing call preserved mask for calling convention"); 3193 Ops.push_back(DAG.getRegisterMask(Mask)); 3194 3195 if (InFlag.getNode()) 3196 Ops.push_back(InFlag); 3197 3198 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3199 3200 // If we're doing a tall call, use a TC_RETURN here rather than an 3201 // actual call instruction. 3202 if (IsTailCall) { 3203 MFI.setHasTailCall(); 3204 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3205 } 3206 3207 // Returns a chain and a flag for retval copy to use. 3208 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3209 Chain = Call.getValue(0); 3210 InFlag = Call.getValue(1); 3211 3212 uint64_t CalleePopBytes = NumBytes; 3213 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3214 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3215 InFlag, DL); 3216 if (!Ins.empty()) 3217 InFlag = Chain.getValue(1); 3218 3219 // Handle result values, copying them out of physregs into vregs that we 3220 // return. 3221 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3222 InVals, IsThisReturn, 3223 IsThisReturn ? OutVals[0] : SDValue()); 3224 } 3225 3226 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3227 // except for applying the wave size scale to the increment amount. 3228 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3229 SDValue Op, SelectionDAG &DAG) const { 3230 const MachineFunction &MF = DAG.getMachineFunction(); 3231 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3232 3233 SDLoc dl(Op); 3234 EVT VT = Op.getValueType(); 3235 SDValue Tmp1 = Op; 3236 SDValue Tmp2 = Op.getValue(1); 3237 SDValue Tmp3 = Op.getOperand(2); 3238 SDValue Chain = Tmp1.getOperand(0); 3239 3240 Register SPReg = Info->getStackPtrOffsetReg(); 3241 3242 // Chain the dynamic stack allocation so that it doesn't modify the stack 3243 // pointer when other instructions are using the stack. 3244 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3245 3246 SDValue Size = Tmp2.getOperand(1); 3247 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3248 Chain = SP.getValue(1); 3249 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3250 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3251 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3252 unsigned Opc = 3253 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3254 ISD::ADD : ISD::SUB; 3255 3256 SDValue ScaledSize = DAG.getNode( 3257 ISD::SHL, dl, VT, Size, 3258 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3259 3260 Align StackAlign = TFL->getStackAlign(); 3261 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3262 if (Alignment && *Alignment > StackAlign) { 3263 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3264 DAG.getConstant(-(uint64_t)Alignment->value() 3265 << ST.getWavefrontSizeLog2(), 3266 dl, VT)); 3267 } 3268 3269 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3270 Tmp2 = DAG.getCALLSEQ_END( 3271 Chain, DAG.getIntPtrConstant(0, dl, true), 3272 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3273 3274 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3275 } 3276 3277 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3278 SelectionDAG &DAG) const { 3279 // We only handle constant sizes here to allow non-entry block, static sized 3280 // allocas. A truly dynamic value is more difficult to support because we 3281 // don't know if the size value is uniform or not. If the size isn't uniform, 3282 // we would need to do a wave reduction to get the maximum size to know how 3283 // much to increment the uniform stack pointer. 3284 SDValue Size = Op.getOperand(1); 3285 if (isa<ConstantSDNode>(Size)) 3286 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3287 3288 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3289 } 3290 3291 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3292 const MachineFunction &MF) const { 3293 Register Reg = StringSwitch<Register>(RegName) 3294 .Case("m0", AMDGPU::M0) 3295 .Case("exec", AMDGPU::EXEC) 3296 .Case("exec_lo", AMDGPU::EXEC_LO) 3297 .Case("exec_hi", AMDGPU::EXEC_HI) 3298 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3299 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3300 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3301 .Default(Register()); 3302 3303 if (Reg == AMDGPU::NoRegister) { 3304 report_fatal_error(Twine("invalid register name \"" 3305 + StringRef(RegName) + "\".")); 3306 3307 } 3308 3309 if (!Subtarget->hasFlatScrRegister() && 3310 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3311 report_fatal_error(Twine("invalid register \"" 3312 + StringRef(RegName) + "\" for subtarget.")); 3313 } 3314 3315 switch (Reg) { 3316 case AMDGPU::M0: 3317 case AMDGPU::EXEC_LO: 3318 case AMDGPU::EXEC_HI: 3319 case AMDGPU::FLAT_SCR_LO: 3320 case AMDGPU::FLAT_SCR_HI: 3321 if (VT.getSizeInBits() == 32) 3322 return Reg; 3323 break; 3324 case AMDGPU::EXEC: 3325 case AMDGPU::FLAT_SCR: 3326 if (VT.getSizeInBits() == 64) 3327 return Reg; 3328 break; 3329 default: 3330 llvm_unreachable("missing register type checking"); 3331 } 3332 3333 report_fatal_error(Twine("invalid type for register \"" 3334 + StringRef(RegName) + "\".")); 3335 } 3336 3337 // If kill is not the last instruction, split the block so kill is always a 3338 // proper terminator. 3339 MachineBasicBlock * 3340 SITargetLowering::splitKillBlock(MachineInstr &MI, 3341 MachineBasicBlock *BB) const { 3342 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3343 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3344 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3345 return SplitBB; 3346 } 3347 3348 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3349 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3350 // be the first instruction in the remainder block. 3351 // 3352 /// \returns { LoopBody, Remainder } 3353 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3354 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3355 MachineFunction *MF = MBB.getParent(); 3356 MachineBasicBlock::iterator I(&MI); 3357 3358 // To insert the loop we need to split the block. Move everything after this 3359 // point to a new block, and insert a new empty block between the two. 3360 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3361 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3362 MachineFunction::iterator MBBI(MBB); 3363 ++MBBI; 3364 3365 MF->insert(MBBI, LoopBB); 3366 MF->insert(MBBI, RemainderBB); 3367 3368 LoopBB->addSuccessor(LoopBB); 3369 LoopBB->addSuccessor(RemainderBB); 3370 3371 // Move the rest of the block into a new block. 3372 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3373 3374 if (InstInLoop) { 3375 auto Next = std::next(I); 3376 3377 // Move instruction to loop body. 3378 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3379 3380 // Move the rest of the block. 3381 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3382 } else { 3383 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3384 } 3385 3386 MBB.addSuccessor(LoopBB); 3387 3388 return std::make_pair(LoopBB, RemainderBB); 3389 } 3390 3391 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3392 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3393 MachineBasicBlock *MBB = MI.getParent(); 3394 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3395 auto I = MI.getIterator(); 3396 auto E = std::next(I); 3397 3398 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3399 .addImm(0); 3400 3401 MIBundleBuilder Bundler(*MBB, I, E); 3402 finalizeBundle(*MBB, Bundler.begin()); 3403 } 3404 3405 MachineBasicBlock * 3406 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3407 MachineBasicBlock *BB) const { 3408 const DebugLoc &DL = MI.getDebugLoc(); 3409 3410 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3411 3412 MachineBasicBlock *LoopBB; 3413 MachineBasicBlock *RemainderBB; 3414 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3415 3416 // Apparently kill flags are only valid if the def is in the same block? 3417 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3418 Src->setIsKill(false); 3419 3420 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3421 3422 MachineBasicBlock::iterator I = LoopBB->end(); 3423 3424 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3425 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3426 3427 // Clear TRAP_STS.MEM_VIOL 3428 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3429 .addImm(0) 3430 .addImm(EncodedReg); 3431 3432 bundleInstWithWaitcnt(MI); 3433 3434 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3435 3436 // Load and check TRAP_STS.MEM_VIOL 3437 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3438 .addImm(EncodedReg); 3439 3440 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3441 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3442 .addReg(Reg, RegState::Kill) 3443 .addImm(0); 3444 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3445 .addMBB(LoopBB); 3446 3447 return RemainderBB; 3448 } 3449 3450 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3451 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3452 // will only do one iteration. In the worst case, this will loop 64 times. 3453 // 3454 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3455 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3456 const SIInstrInfo *TII, 3457 MachineRegisterInfo &MRI, 3458 MachineBasicBlock &OrigBB, 3459 MachineBasicBlock &LoopBB, 3460 const DebugLoc &DL, 3461 const MachineOperand &IdxReg, 3462 unsigned InitReg, 3463 unsigned ResultReg, 3464 unsigned PhiReg, 3465 unsigned InitSaveExecReg, 3466 int Offset, 3467 bool UseGPRIdxMode, 3468 bool IsIndirectSrc) { 3469 MachineFunction *MF = OrigBB.getParent(); 3470 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3471 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3472 MachineBasicBlock::iterator I = LoopBB.begin(); 3473 3474 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3475 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3476 Register NewExec = MRI.createVirtualRegister(BoolRC); 3477 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3478 Register CondReg = MRI.createVirtualRegister(BoolRC); 3479 3480 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3481 .addReg(InitReg) 3482 .addMBB(&OrigBB) 3483 .addReg(ResultReg) 3484 .addMBB(&LoopBB); 3485 3486 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3487 .addReg(InitSaveExecReg) 3488 .addMBB(&OrigBB) 3489 .addReg(NewExec) 3490 .addMBB(&LoopBB); 3491 3492 // Read the next variant <- also loop target. 3493 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3494 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3495 3496 // Compare the just read M0 value to all possible Idx values. 3497 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3498 .addReg(CurrentIdxReg) 3499 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3500 3501 // Update EXEC, save the original EXEC value to VCC. 3502 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3503 : AMDGPU::S_AND_SAVEEXEC_B64), 3504 NewExec) 3505 .addReg(CondReg, RegState::Kill); 3506 3507 MRI.setSimpleHint(NewExec, CondReg); 3508 3509 if (UseGPRIdxMode) { 3510 unsigned IdxReg; 3511 if (Offset == 0) { 3512 IdxReg = CurrentIdxReg; 3513 } else { 3514 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3515 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3516 .addReg(CurrentIdxReg, RegState::Kill) 3517 .addImm(Offset); 3518 } 3519 unsigned IdxMode = IsIndirectSrc ? 3520 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3521 MachineInstr *SetOn = 3522 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3523 .addReg(IdxReg, RegState::Kill) 3524 .addImm(IdxMode); 3525 SetOn->getOperand(3).setIsUndef(); 3526 } else { 3527 // Move index from VCC into M0 3528 if (Offset == 0) { 3529 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3530 .addReg(CurrentIdxReg, RegState::Kill); 3531 } else { 3532 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3533 .addReg(CurrentIdxReg, RegState::Kill) 3534 .addImm(Offset); 3535 } 3536 } 3537 3538 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3539 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3540 MachineInstr *InsertPt = 3541 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3542 : AMDGPU::S_XOR_B64_term), Exec) 3543 .addReg(Exec) 3544 .addReg(NewExec); 3545 3546 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3547 // s_cbranch_scc0? 3548 3549 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3550 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3551 .addMBB(&LoopBB); 3552 3553 return InsertPt->getIterator(); 3554 } 3555 3556 // This has slightly sub-optimal regalloc when the source vector is killed by 3557 // the read. The register allocator does not understand that the kill is 3558 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3559 // subregister from it, using 1 more VGPR than necessary. This was saved when 3560 // this was expanded after register allocation. 3561 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3562 MachineBasicBlock &MBB, 3563 MachineInstr &MI, 3564 unsigned InitResultReg, 3565 unsigned PhiReg, 3566 int Offset, 3567 bool UseGPRIdxMode, 3568 bool IsIndirectSrc) { 3569 MachineFunction *MF = MBB.getParent(); 3570 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3571 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3572 MachineRegisterInfo &MRI = MF->getRegInfo(); 3573 const DebugLoc &DL = MI.getDebugLoc(); 3574 MachineBasicBlock::iterator I(&MI); 3575 3576 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3577 Register DstReg = MI.getOperand(0).getReg(); 3578 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3579 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3580 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3581 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3582 3583 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3584 3585 // Save the EXEC mask 3586 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3587 .addReg(Exec); 3588 3589 MachineBasicBlock *LoopBB; 3590 MachineBasicBlock *RemainderBB; 3591 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3592 3593 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3594 3595 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3596 InitResultReg, DstReg, PhiReg, TmpExec, 3597 Offset, UseGPRIdxMode, IsIndirectSrc); 3598 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3599 MachineFunction::iterator MBBI(LoopBB); 3600 ++MBBI; 3601 MF->insert(MBBI, LandingPad); 3602 LoopBB->removeSuccessor(RemainderBB); 3603 LandingPad->addSuccessor(RemainderBB); 3604 LoopBB->addSuccessor(LandingPad); 3605 MachineBasicBlock::iterator First = LandingPad->begin(); 3606 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3607 .addReg(SaveExec); 3608 3609 return InsPt; 3610 } 3611 3612 // Returns subreg index, offset 3613 static std::pair<unsigned, int> 3614 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3615 const TargetRegisterClass *SuperRC, 3616 unsigned VecReg, 3617 int Offset) { 3618 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3619 3620 // Skip out of bounds offsets, or else we would end up using an undefined 3621 // register. 3622 if (Offset >= NumElts || Offset < 0) 3623 return std::make_pair(AMDGPU::sub0, Offset); 3624 3625 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3626 } 3627 3628 // Return true if the index is an SGPR and was set. 3629 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3630 MachineRegisterInfo &MRI, 3631 MachineInstr &MI, 3632 int Offset, 3633 bool UseGPRIdxMode, 3634 bool IsIndirectSrc) { 3635 MachineBasicBlock *MBB = MI.getParent(); 3636 const DebugLoc &DL = MI.getDebugLoc(); 3637 MachineBasicBlock::iterator I(&MI); 3638 3639 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3640 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3641 3642 assert(Idx->getReg() != AMDGPU::NoRegister); 3643 3644 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3645 return false; 3646 3647 if (UseGPRIdxMode) { 3648 unsigned IdxMode = IsIndirectSrc ? 3649 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3650 if (Offset == 0) { 3651 MachineInstr *SetOn = 3652 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3653 .add(*Idx) 3654 .addImm(IdxMode); 3655 3656 SetOn->getOperand(3).setIsUndef(); 3657 } else { 3658 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3659 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3660 .add(*Idx) 3661 .addImm(Offset); 3662 MachineInstr *SetOn = 3663 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3664 .addReg(Tmp, RegState::Kill) 3665 .addImm(IdxMode); 3666 3667 SetOn->getOperand(3).setIsUndef(); 3668 } 3669 3670 return true; 3671 } 3672 3673 if (Offset == 0) { 3674 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3675 .add(*Idx); 3676 } else { 3677 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3678 .add(*Idx) 3679 .addImm(Offset); 3680 } 3681 3682 return true; 3683 } 3684 3685 // Control flow needs to be inserted if indexing with a VGPR. 3686 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3687 MachineBasicBlock &MBB, 3688 const GCNSubtarget &ST) { 3689 const SIInstrInfo *TII = ST.getInstrInfo(); 3690 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3691 MachineFunction *MF = MBB.getParent(); 3692 MachineRegisterInfo &MRI = MF->getRegInfo(); 3693 3694 Register Dst = MI.getOperand(0).getReg(); 3695 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3696 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3697 3698 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3699 3700 unsigned SubReg; 3701 std::tie(SubReg, Offset) 3702 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3703 3704 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3705 3706 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3707 MachineBasicBlock::iterator I(&MI); 3708 const DebugLoc &DL = MI.getDebugLoc(); 3709 3710 if (UseGPRIdxMode) { 3711 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3712 // to avoid interfering with other uses, so probably requires a new 3713 // optimization pass. 3714 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3715 .addReg(SrcReg, 0, SubReg) 3716 .addReg(SrcReg, RegState::Implicit) 3717 .addReg(AMDGPU::M0, RegState::Implicit); 3718 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3719 } else { 3720 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3721 .addReg(SrcReg, 0, SubReg) 3722 .addReg(SrcReg, RegState::Implicit); 3723 } 3724 3725 MI.eraseFromParent(); 3726 3727 return &MBB; 3728 } 3729 3730 const DebugLoc &DL = MI.getDebugLoc(); 3731 MachineBasicBlock::iterator I(&MI); 3732 3733 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3734 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3735 3736 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3737 3738 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3739 Offset, UseGPRIdxMode, true); 3740 MachineBasicBlock *LoopBB = InsPt->getParent(); 3741 3742 if (UseGPRIdxMode) { 3743 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3744 .addReg(SrcReg, 0, SubReg) 3745 .addReg(SrcReg, RegState::Implicit) 3746 .addReg(AMDGPU::M0, RegState::Implicit); 3747 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3748 } else { 3749 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3750 .addReg(SrcReg, 0, SubReg) 3751 .addReg(SrcReg, RegState::Implicit); 3752 } 3753 3754 MI.eraseFromParent(); 3755 3756 return LoopBB; 3757 } 3758 3759 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3760 MachineBasicBlock &MBB, 3761 const GCNSubtarget &ST) { 3762 const SIInstrInfo *TII = ST.getInstrInfo(); 3763 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3764 MachineFunction *MF = MBB.getParent(); 3765 MachineRegisterInfo &MRI = MF->getRegInfo(); 3766 3767 Register Dst = MI.getOperand(0).getReg(); 3768 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3769 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3770 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3771 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3772 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3773 3774 // This can be an immediate, but will be folded later. 3775 assert(Val->getReg()); 3776 3777 unsigned SubReg; 3778 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3779 SrcVec->getReg(), 3780 Offset); 3781 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3782 3783 if (Idx->getReg() == AMDGPU::NoRegister) { 3784 MachineBasicBlock::iterator I(&MI); 3785 const DebugLoc &DL = MI.getDebugLoc(); 3786 3787 assert(Offset == 0); 3788 3789 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3790 .add(*SrcVec) 3791 .add(*Val) 3792 .addImm(SubReg); 3793 3794 MI.eraseFromParent(); 3795 return &MBB; 3796 } 3797 3798 const MCInstrDesc &MovRelDesc 3799 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3800 3801 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3802 MachineBasicBlock::iterator I(&MI); 3803 const DebugLoc &DL = MI.getDebugLoc(); 3804 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3805 .addReg(SrcVec->getReg()) 3806 .add(*Val) 3807 .addImm(SubReg); 3808 if (UseGPRIdxMode) 3809 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3810 3811 MI.eraseFromParent(); 3812 return &MBB; 3813 } 3814 3815 if (Val->isReg()) 3816 MRI.clearKillFlags(Val->getReg()); 3817 3818 const DebugLoc &DL = MI.getDebugLoc(); 3819 3820 Register PhiReg = MRI.createVirtualRegister(VecRC); 3821 3822 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3823 Offset, UseGPRIdxMode, false); 3824 MachineBasicBlock *LoopBB = InsPt->getParent(); 3825 3826 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3827 .addReg(PhiReg) 3828 .add(*Val) 3829 .addImm(AMDGPU::sub0); 3830 if (UseGPRIdxMode) 3831 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3832 3833 MI.eraseFromParent(); 3834 return LoopBB; 3835 } 3836 3837 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3838 MachineInstr &MI, MachineBasicBlock *BB) const { 3839 3840 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3841 MachineFunction *MF = BB->getParent(); 3842 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3843 3844 switch (MI.getOpcode()) { 3845 case AMDGPU::S_UADDO_PSEUDO: 3846 case AMDGPU::S_USUBO_PSEUDO: { 3847 const DebugLoc &DL = MI.getDebugLoc(); 3848 MachineOperand &Dest0 = MI.getOperand(0); 3849 MachineOperand &Dest1 = MI.getOperand(1); 3850 MachineOperand &Src0 = MI.getOperand(2); 3851 MachineOperand &Src1 = MI.getOperand(3); 3852 3853 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3854 ? AMDGPU::S_ADD_I32 3855 : AMDGPU::S_SUB_I32; 3856 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3857 3858 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3859 .addImm(1) 3860 .addImm(0); 3861 3862 MI.eraseFromParent(); 3863 return BB; 3864 } 3865 case AMDGPU::S_ADD_U64_PSEUDO: 3866 case AMDGPU::S_SUB_U64_PSEUDO: { 3867 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3868 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3869 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3870 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3871 const DebugLoc &DL = MI.getDebugLoc(); 3872 3873 MachineOperand &Dest = MI.getOperand(0); 3874 MachineOperand &Src0 = MI.getOperand(1); 3875 MachineOperand &Src1 = MI.getOperand(2); 3876 3877 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3878 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3879 3880 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3881 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3882 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3883 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3884 3885 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3886 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3887 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3888 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3889 3890 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3891 3892 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3893 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3894 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3895 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3896 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3897 .addReg(DestSub0) 3898 .addImm(AMDGPU::sub0) 3899 .addReg(DestSub1) 3900 .addImm(AMDGPU::sub1); 3901 MI.eraseFromParent(); 3902 return BB; 3903 } 3904 case AMDGPU::V_ADD_U64_PSEUDO: 3905 case AMDGPU::V_SUB_U64_PSEUDO: { 3906 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3907 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3908 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3909 const DebugLoc &DL = MI.getDebugLoc(); 3910 3911 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3912 3913 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3914 3915 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3916 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3917 3918 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3919 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3920 3921 MachineOperand &Dest = MI.getOperand(0); 3922 MachineOperand &Src0 = MI.getOperand(1); 3923 MachineOperand &Src1 = MI.getOperand(2); 3924 3925 const TargetRegisterClass *Src0RC = Src0.isReg() 3926 ? MRI.getRegClass(Src0.getReg()) 3927 : &AMDGPU::VReg_64RegClass; 3928 const TargetRegisterClass *Src1RC = Src1.isReg() 3929 ? MRI.getRegClass(Src1.getReg()) 3930 : &AMDGPU::VReg_64RegClass; 3931 3932 const TargetRegisterClass *Src0SubRC = 3933 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3934 const TargetRegisterClass *Src1SubRC = 3935 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3936 3937 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3938 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3939 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3940 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3941 3942 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3943 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3944 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3945 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3946 3947 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3948 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3949 .addReg(CarryReg, RegState::Define) 3950 .add(SrcReg0Sub0) 3951 .add(SrcReg1Sub0) 3952 .addImm(0); // clamp bit 3953 3954 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3955 MachineInstr *HiHalf = 3956 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3957 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3958 .add(SrcReg0Sub1) 3959 .add(SrcReg1Sub1) 3960 .addReg(CarryReg, RegState::Kill) 3961 .addImm(0); // clamp bit 3962 3963 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3964 .addReg(DestSub0) 3965 .addImm(AMDGPU::sub0) 3966 .addReg(DestSub1) 3967 .addImm(AMDGPU::sub1); 3968 TII->legalizeOperands(*LoHalf); 3969 TII->legalizeOperands(*HiHalf); 3970 MI.eraseFromParent(); 3971 return BB; 3972 } 3973 case AMDGPU::S_ADD_CO_PSEUDO: 3974 case AMDGPU::S_SUB_CO_PSEUDO: { 3975 // This pseudo has a chance to be selected 3976 // only from uniform add/subcarry node. All the VGPR operands 3977 // therefore assumed to be splat vectors. 3978 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3979 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3980 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3981 MachineBasicBlock::iterator MII = MI; 3982 const DebugLoc &DL = MI.getDebugLoc(); 3983 MachineOperand &Dest = MI.getOperand(0); 3984 MachineOperand &CarryDest = MI.getOperand(1); 3985 MachineOperand &Src0 = MI.getOperand(2); 3986 MachineOperand &Src1 = MI.getOperand(3); 3987 MachineOperand &Src2 = MI.getOperand(4); 3988 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3989 ? AMDGPU::S_ADDC_U32 3990 : AMDGPU::S_SUBB_U32; 3991 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3992 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3993 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3994 .addReg(Src0.getReg()); 3995 Src0.setReg(RegOp0); 3996 } 3997 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3998 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3999 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4000 .addReg(Src1.getReg()); 4001 Src1.setReg(RegOp1); 4002 } 4003 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4004 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4005 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4006 .addReg(Src2.getReg()); 4007 Src2.setReg(RegOp2); 4008 } 4009 4010 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4011 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4012 if (ST.hasScalarCompareEq64()) { 4013 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4014 .addReg(Src2.getReg()) 4015 .addImm(0); 4016 } else { 4017 const TargetRegisterClass *SubRC = 4018 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4019 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4020 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4021 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4022 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4023 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4024 4025 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4026 .add(Src2Sub0) 4027 .add(Src2Sub1); 4028 4029 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4030 .addReg(Src2_32, RegState::Kill) 4031 .addImm(0); 4032 } 4033 } else { 4034 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4035 .addReg(Src2.getReg()) 4036 .addImm(0); 4037 } 4038 4039 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4040 4041 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4042 .addReg(AMDGPU::SCC); 4043 MI.eraseFromParent(); 4044 return BB; 4045 } 4046 case AMDGPU::SI_INIT_M0: { 4047 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4048 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4049 .add(MI.getOperand(0)); 4050 MI.eraseFromParent(); 4051 return BB; 4052 } 4053 case AMDGPU::SI_INIT_EXEC: 4054 // This should be before all vector instructions. 4055 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4056 AMDGPU::EXEC) 4057 .addImm(MI.getOperand(0).getImm()); 4058 MI.eraseFromParent(); 4059 return BB; 4060 4061 case AMDGPU::SI_INIT_EXEC_LO: 4062 // This should be before all vector instructions. 4063 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4064 AMDGPU::EXEC_LO) 4065 .addImm(MI.getOperand(0).getImm()); 4066 MI.eraseFromParent(); 4067 return BB; 4068 4069 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4070 // Extract the thread count from an SGPR input and set EXEC accordingly. 4071 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4072 // 4073 // S_BFE_U32 count, input, {shift, 7} 4074 // S_BFM_B64 exec, count, 0 4075 // S_CMP_EQ_U32 count, 64 4076 // S_CMOV_B64 exec, -1 4077 MachineInstr *FirstMI = &*BB->begin(); 4078 MachineRegisterInfo &MRI = MF->getRegInfo(); 4079 Register InputReg = MI.getOperand(0).getReg(); 4080 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4081 bool Found = false; 4082 4083 // Move the COPY of the input reg to the beginning, so that we can use it. 4084 for (auto I = BB->begin(); I != &MI; I++) { 4085 if (I->getOpcode() != TargetOpcode::COPY || 4086 I->getOperand(0).getReg() != InputReg) 4087 continue; 4088 4089 if (I == FirstMI) { 4090 FirstMI = &*++BB->begin(); 4091 } else { 4092 I->removeFromParent(); 4093 BB->insert(FirstMI, &*I); 4094 } 4095 Found = true; 4096 break; 4097 } 4098 assert(Found); 4099 (void)Found; 4100 4101 // This should be before all vector instructions. 4102 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4103 bool isWave32 = getSubtarget()->isWave32(); 4104 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4105 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4106 .addReg(InputReg) 4107 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4108 BuildMI(*BB, FirstMI, DebugLoc(), 4109 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4110 Exec) 4111 .addReg(CountReg) 4112 .addImm(0); 4113 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4114 .addReg(CountReg, RegState::Kill) 4115 .addImm(getSubtarget()->getWavefrontSize()); 4116 BuildMI(*BB, FirstMI, DebugLoc(), 4117 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4118 Exec) 4119 .addImm(-1); 4120 MI.eraseFromParent(); 4121 return BB; 4122 } 4123 4124 case AMDGPU::GET_GROUPSTATICSIZE: { 4125 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4126 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4127 DebugLoc DL = MI.getDebugLoc(); 4128 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4129 .add(MI.getOperand(0)) 4130 .addImm(MFI->getLDSSize()); 4131 MI.eraseFromParent(); 4132 return BB; 4133 } 4134 case AMDGPU::SI_INDIRECT_SRC_V1: 4135 case AMDGPU::SI_INDIRECT_SRC_V2: 4136 case AMDGPU::SI_INDIRECT_SRC_V4: 4137 case AMDGPU::SI_INDIRECT_SRC_V8: 4138 case AMDGPU::SI_INDIRECT_SRC_V16: 4139 case AMDGPU::SI_INDIRECT_SRC_V32: 4140 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4141 case AMDGPU::SI_INDIRECT_DST_V1: 4142 case AMDGPU::SI_INDIRECT_DST_V2: 4143 case AMDGPU::SI_INDIRECT_DST_V4: 4144 case AMDGPU::SI_INDIRECT_DST_V8: 4145 case AMDGPU::SI_INDIRECT_DST_V16: 4146 case AMDGPU::SI_INDIRECT_DST_V32: 4147 return emitIndirectDst(MI, *BB, *getSubtarget()); 4148 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4149 case AMDGPU::SI_KILL_I1_PSEUDO: 4150 return splitKillBlock(MI, BB); 4151 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4152 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4153 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4154 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4155 4156 Register Dst = MI.getOperand(0).getReg(); 4157 Register Src0 = MI.getOperand(1).getReg(); 4158 Register Src1 = MI.getOperand(2).getReg(); 4159 const DebugLoc &DL = MI.getDebugLoc(); 4160 Register SrcCond = MI.getOperand(3).getReg(); 4161 4162 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4163 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4164 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4165 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4166 4167 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4168 .addReg(SrcCond); 4169 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4170 .addImm(0) 4171 .addReg(Src0, 0, AMDGPU::sub0) 4172 .addImm(0) 4173 .addReg(Src1, 0, AMDGPU::sub0) 4174 .addReg(SrcCondCopy); 4175 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4176 .addImm(0) 4177 .addReg(Src0, 0, AMDGPU::sub1) 4178 .addImm(0) 4179 .addReg(Src1, 0, AMDGPU::sub1) 4180 .addReg(SrcCondCopy); 4181 4182 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4183 .addReg(DstLo) 4184 .addImm(AMDGPU::sub0) 4185 .addReg(DstHi) 4186 .addImm(AMDGPU::sub1); 4187 MI.eraseFromParent(); 4188 return BB; 4189 } 4190 case AMDGPU::SI_BR_UNDEF: { 4191 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4192 const DebugLoc &DL = MI.getDebugLoc(); 4193 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4194 .add(MI.getOperand(0)); 4195 Br->getOperand(1).setIsUndef(true); // read undef SCC 4196 MI.eraseFromParent(); 4197 return BB; 4198 } 4199 case AMDGPU::ADJCALLSTACKUP: 4200 case AMDGPU::ADJCALLSTACKDOWN: { 4201 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4202 MachineInstrBuilder MIB(*MF, &MI); 4203 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4204 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4205 return BB; 4206 } 4207 case AMDGPU::SI_CALL_ISEL: { 4208 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4209 const DebugLoc &DL = MI.getDebugLoc(); 4210 4211 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4212 4213 MachineInstrBuilder MIB; 4214 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4215 4216 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4217 MIB.add(MI.getOperand(I)); 4218 4219 MIB.cloneMemRefs(MI); 4220 MI.eraseFromParent(); 4221 return BB; 4222 } 4223 case AMDGPU::V_ADD_CO_U32_e32: 4224 case AMDGPU::V_SUB_CO_U32_e32: 4225 case AMDGPU::V_SUBREV_CO_U32_e32: { 4226 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4227 const DebugLoc &DL = MI.getDebugLoc(); 4228 unsigned Opc = MI.getOpcode(); 4229 4230 bool NeedClampOperand = false; 4231 if (TII->pseudoToMCOpcode(Opc) == -1) { 4232 Opc = AMDGPU::getVOPe64(Opc); 4233 NeedClampOperand = true; 4234 } 4235 4236 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4237 if (TII->isVOP3(*I)) { 4238 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4239 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4240 I.addReg(TRI->getVCC(), RegState::Define); 4241 } 4242 I.add(MI.getOperand(1)) 4243 .add(MI.getOperand(2)); 4244 if (NeedClampOperand) 4245 I.addImm(0); // clamp bit for e64 encoding 4246 4247 TII->legalizeOperands(*I); 4248 4249 MI.eraseFromParent(); 4250 return BB; 4251 } 4252 case AMDGPU::DS_GWS_INIT: 4253 case AMDGPU::DS_GWS_SEMA_V: 4254 case AMDGPU::DS_GWS_SEMA_BR: 4255 case AMDGPU::DS_GWS_SEMA_P: 4256 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4257 case AMDGPU::DS_GWS_BARRIER: 4258 // A s_waitcnt 0 is required to be the instruction immediately following. 4259 if (getSubtarget()->hasGWSAutoReplay()) { 4260 bundleInstWithWaitcnt(MI); 4261 return BB; 4262 } 4263 4264 return emitGWSMemViolTestLoop(MI, BB); 4265 case AMDGPU::S_SETREG_B32: { 4266 // Try to optimize cases that only set the denormal mode or rounding mode. 4267 // 4268 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4269 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4270 // instead. 4271 // 4272 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4273 // allow you to have a no side effect instruction in the output of a 4274 // sideeffecting pattern. 4275 unsigned ID, Offset, Width; 4276 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4277 if (ID != AMDGPU::Hwreg::ID_MODE) 4278 return BB; 4279 4280 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4281 const unsigned SetMask = WidthMask << Offset; 4282 4283 if (getSubtarget()->hasDenormModeInst()) { 4284 unsigned SetDenormOp = 0; 4285 unsigned SetRoundOp = 0; 4286 4287 // The dedicated instructions can only set the whole denorm or round mode 4288 // at once, not a subset of bits in either. 4289 if (SetMask == 4290 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4291 // If this fully sets both the round and denorm mode, emit the two 4292 // dedicated instructions for these. 4293 SetRoundOp = AMDGPU::S_ROUND_MODE; 4294 SetDenormOp = AMDGPU::S_DENORM_MODE; 4295 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4296 SetRoundOp = AMDGPU::S_ROUND_MODE; 4297 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4298 SetDenormOp = AMDGPU::S_DENORM_MODE; 4299 } 4300 4301 if (SetRoundOp || SetDenormOp) { 4302 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4303 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4304 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4305 unsigned ImmVal = Def->getOperand(1).getImm(); 4306 if (SetRoundOp) { 4307 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4308 .addImm(ImmVal & 0xf); 4309 4310 // If we also have the denorm mode, get just the denorm mode bits. 4311 ImmVal >>= 4; 4312 } 4313 4314 if (SetDenormOp) { 4315 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4316 .addImm(ImmVal & 0xf); 4317 } 4318 4319 MI.eraseFromParent(); 4320 return BB; 4321 } 4322 } 4323 } 4324 4325 // If only FP bits are touched, used the no side effects pseudo. 4326 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4327 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4328 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4329 4330 return BB; 4331 } 4332 default: 4333 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4334 } 4335 } 4336 4337 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4338 return isTypeLegal(VT.getScalarType()); 4339 } 4340 4341 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4342 // This currently forces unfolding various combinations of fsub into fma with 4343 // free fneg'd operands. As long as we have fast FMA (controlled by 4344 // isFMAFasterThanFMulAndFAdd), we should perform these. 4345 4346 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4347 // most of these combines appear to be cycle neutral but save on instruction 4348 // count / code size. 4349 return true; 4350 } 4351 4352 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4353 EVT VT) const { 4354 if (!VT.isVector()) { 4355 return MVT::i1; 4356 } 4357 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4358 } 4359 4360 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4361 // TODO: Should i16 be used always if legal? For now it would force VALU 4362 // shifts. 4363 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4364 } 4365 4366 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4367 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4368 ? Ty.changeElementSize(16) 4369 : Ty.changeElementSize(32); 4370 } 4371 4372 // Answering this is somewhat tricky and depends on the specific device which 4373 // have different rates for fma or all f64 operations. 4374 // 4375 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4376 // regardless of which device (although the number of cycles differs between 4377 // devices), so it is always profitable for f64. 4378 // 4379 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4380 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4381 // which we can always do even without fused FP ops since it returns the same 4382 // result as the separate operations and since it is always full 4383 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4384 // however does not support denormals, so we do report fma as faster if we have 4385 // a fast fma device and require denormals. 4386 // 4387 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4388 EVT VT) const { 4389 VT = VT.getScalarType(); 4390 4391 switch (VT.getSimpleVT().SimpleTy) { 4392 case MVT::f32: { 4393 // If mad is not available this depends only on if f32 fma is full rate. 4394 if (!Subtarget->hasMadMacF32Insts()) 4395 return Subtarget->hasFastFMAF32(); 4396 4397 // Otherwise f32 mad is always full rate and returns the same result as 4398 // the separate operations so should be preferred over fma. 4399 // However does not support denomals. 4400 if (hasFP32Denormals(MF)) 4401 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4402 4403 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4404 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4405 } 4406 case MVT::f64: 4407 return true; 4408 case MVT::f16: 4409 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4410 default: 4411 break; 4412 } 4413 4414 return false; 4415 } 4416 4417 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4418 const SDNode *N) const { 4419 // TODO: Check future ftz flag 4420 // v_mad_f32/v_mac_f32 do not support denormals. 4421 EVT VT = N->getValueType(0); 4422 if (VT == MVT::f32) 4423 return Subtarget->hasMadMacF32Insts() && 4424 !hasFP32Denormals(DAG.getMachineFunction()); 4425 if (VT == MVT::f16) { 4426 return Subtarget->hasMadF16() && 4427 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4428 } 4429 4430 return false; 4431 } 4432 4433 //===----------------------------------------------------------------------===// 4434 // Custom DAG Lowering Operations 4435 //===----------------------------------------------------------------------===// 4436 4437 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4438 // wider vector type is legal. 4439 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4440 SelectionDAG &DAG) const { 4441 unsigned Opc = Op.getOpcode(); 4442 EVT VT = Op.getValueType(); 4443 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4444 4445 SDValue Lo, Hi; 4446 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4447 4448 SDLoc SL(Op); 4449 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4450 Op->getFlags()); 4451 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4452 Op->getFlags()); 4453 4454 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4455 } 4456 4457 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4458 // wider vector type is legal. 4459 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4460 SelectionDAG &DAG) const { 4461 unsigned Opc = Op.getOpcode(); 4462 EVT VT = Op.getValueType(); 4463 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4464 4465 SDValue Lo0, Hi0; 4466 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4467 SDValue Lo1, Hi1; 4468 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4469 4470 SDLoc SL(Op); 4471 4472 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4473 Op->getFlags()); 4474 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4475 Op->getFlags()); 4476 4477 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4478 } 4479 4480 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4481 SelectionDAG &DAG) const { 4482 unsigned Opc = Op.getOpcode(); 4483 EVT VT = Op.getValueType(); 4484 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4485 4486 SDValue Lo0, Hi0; 4487 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4488 SDValue Lo1, Hi1; 4489 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4490 SDValue Lo2, Hi2; 4491 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4492 4493 SDLoc SL(Op); 4494 4495 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4496 Op->getFlags()); 4497 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4498 Op->getFlags()); 4499 4500 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4501 } 4502 4503 4504 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4505 switch (Op.getOpcode()) { 4506 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4507 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4508 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4509 case ISD::LOAD: { 4510 SDValue Result = LowerLOAD(Op, DAG); 4511 assert((!Result.getNode() || 4512 Result.getNode()->getNumValues() == 2) && 4513 "Load should return a value and a chain"); 4514 return Result; 4515 } 4516 4517 case ISD::FSIN: 4518 case ISD::FCOS: 4519 return LowerTrig(Op, DAG); 4520 case ISD::SELECT: return LowerSELECT(Op, DAG); 4521 case ISD::FDIV: return LowerFDIV(Op, DAG); 4522 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4523 case ISD::STORE: return LowerSTORE(Op, DAG); 4524 case ISD::GlobalAddress: { 4525 MachineFunction &MF = DAG.getMachineFunction(); 4526 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4527 return LowerGlobalAddress(MFI, Op, DAG); 4528 } 4529 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4530 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4531 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4532 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4533 case ISD::INSERT_SUBVECTOR: 4534 return lowerINSERT_SUBVECTOR(Op, DAG); 4535 case ISD::INSERT_VECTOR_ELT: 4536 return lowerINSERT_VECTOR_ELT(Op, DAG); 4537 case ISD::EXTRACT_VECTOR_ELT: 4538 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4539 case ISD::VECTOR_SHUFFLE: 4540 return lowerVECTOR_SHUFFLE(Op, DAG); 4541 case ISD::BUILD_VECTOR: 4542 return lowerBUILD_VECTOR(Op, DAG); 4543 case ISD::FP_ROUND: 4544 return lowerFP_ROUND(Op, DAG); 4545 case ISD::TRAP: 4546 return lowerTRAP(Op, DAG); 4547 case ISD::DEBUGTRAP: 4548 return lowerDEBUGTRAP(Op, DAG); 4549 case ISD::FABS: 4550 case ISD::FNEG: 4551 case ISD::FCANONICALIZE: 4552 case ISD::BSWAP: 4553 return splitUnaryVectorOp(Op, DAG); 4554 case ISD::FMINNUM: 4555 case ISD::FMAXNUM: 4556 return lowerFMINNUM_FMAXNUM(Op, DAG); 4557 case ISD::FMA: 4558 return splitTernaryVectorOp(Op, DAG); 4559 case ISD::SHL: 4560 case ISD::SRA: 4561 case ISD::SRL: 4562 case ISD::ADD: 4563 case ISD::SUB: 4564 case ISD::MUL: 4565 case ISD::SMIN: 4566 case ISD::SMAX: 4567 case ISD::UMIN: 4568 case ISD::UMAX: 4569 case ISD::FADD: 4570 case ISD::FMUL: 4571 case ISD::FMINNUM_IEEE: 4572 case ISD::FMAXNUM_IEEE: 4573 case ISD::UADDSAT: 4574 case ISD::USUBSAT: 4575 case ISD::SADDSAT: 4576 case ISD::SSUBSAT: 4577 return splitBinaryVectorOp(Op, DAG); 4578 case ISD::SMULO: 4579 case ISD::UMULO: 4580 return lowerXMULO(Op, DAG); 4581 case ISD::DYNAMIC_STACKALLOC: 4582 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4583 } 4584 return SDValue(); 4585 } 4586 4587 // Used for D16: Casts the result of an instruction into the right vector, 4588 // packs values if loads return unpacked values. 4589 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4590 const SDLoc &DL, 4591 SelectionDAG &DAG, bool Unpacked) { 4592 if (!LoadVT.isVector()) 4593 return Result; 4594 4595 // Cast back to the original packed type or to a larger type that is a 4596 // multiple of 32 bit for D16. Widening the return type is a required for 4597 // legalization. 4598 EVT FittingLoadVT = LoadVT; 4599 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4600 FittingLoadVT = 4601 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4602 LoadVT.getVectorNumElements() + 1); 4603 } 4604 4605 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4606 // Truncate to v2i16/v4i16. 4607 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4608 4609 // Workaround legalizer not scalarizing truncate after vector op 4610 // legalization but not creating intermediate vector trunc. 4611 SmallVector<SDValue, 4> Elts; 4612 DAG.ExtractVectorElements(Result, Elts); 4613 for (SDValue &Elt : Elts) 4614 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4615 4616 // Pad illegal v1i16/v3fi6 to v4i16 4617 if ((LoadVT.getVectorNumElements() % 2) == 1) 4618 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4619 4620 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4621 4622 // Bitcast to original type (v2f16/v4f16). 4623 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4624 } 4625 4626 // Cast back to the original packed type. 4627 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4628 } 4629 4630 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4631 MemSDNode *M, 4632 SelectionDAG &DAG, 4633 ArrayRef<SDValue> Ops, 4634 bool IsIntrinsic) const { 4635 SDLoc DL(M); 4636 4637 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4638 EVT LoadVT = M->getValueType(0); 4639 4640 EVT EquivLoadVT = LoadVT; 4641 if (LoadVT.isVector()) { 4642 if (Unpacked) { 4643 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4644 LoadVT.getVectorNumElements()); 4645 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4646 // Widen v3f16 to legal type 4647 EquivLoadVT = 4648 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4649 LoadVT.getVectorNumElements() + 1); 4650 } 4651 } 4652 4653 // Change from v4f16/v2f16 to EquivLoadVT. 4654 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4655 4656 SDValue Load 4657 = DAG.getMemIntrinsicNode( 4658 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4659 VTList, Ops, M->getMemoryVT(), 4660 M->getMemOperand()); 4661 4662 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4663 4664 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4665 } 4666 4667 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4668 SelectionDAG &DAG, 4669 ArrayRef<SDValue> Ops) const { 4670 SDLoc DL(M); 4671 EVT LoadVT = M->getValueType(0); 4672 EVT EltType = LoadVT.getScalarType(); 4673 EVT IntVT = LoadVT.changeTypeToInteger(); 4674 4675 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4676 4677 unsigned Opc = 4678 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4679 4680 if (IsD16) { 4681 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4682 } 4683 4684 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4685 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4686 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4687 4688 if (isTypeLegal(LoadVT)) { 4689 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4690 M->getMemOperand(), DAG); 4691 } 4692 4693 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4694 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4695 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4696 M->getMemOperand(), DAG); 4697 return DAG.getMergeValues( 4698 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4699 DL); 4700 } 4701 4702 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4703 SDNode *N, SelectionDAG &DAG) { 4704 EVT VT = N->getValueType(0); 4705 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4706 unsigned CondCode = CD->getZExtValue(); 4707 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4708 return DAG.getUNDEF(VT); 4709 4710 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4711 4712 SDValue LHS = N->getOperand(1); 4713 SDValue RHS = N->getOperand(2); 4714 4715 SDLoc DL(N); 4716 4717 EVT CmpVT = LHS.getValueType(); 4718 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4719 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4720 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4721 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4722 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4723 } 4724 4725 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4726 4727 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4728 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4729 4730 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4731 DAG.getCondCode(CCOpcode)); 4732 if (VT.bitsEq(CCVT)) 4733 return SetCC; 4734 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4735 } 4736 4737 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4738 SDNode *N, SelectionDAG &DAG) { 4739 EVT VT = N->getValueType(0); 4740 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4741 4742 unsigned CondCode = CD->getZExtValue(); 4743 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4744 return DAG.getUNDEF(VT); 4745 4746 SDValue Src0 = N->getOperand(1); 4747 SDValue Src1 = N->getOperand(2); 4748 EVT CmpVT = Src0.getValueType(); 4749 SDLoc SL(N); 4750 4751 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4752 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4753 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4754 } 4755 4756 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4757 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4758 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4759 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4760 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4761 Src1, DAG.getCondCode(CCOpcode)); 4762 if (VT.bitsEq(CCVT)) 4763 return SetCC; 4764 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4765 } 4766 4767 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4768 SelectionDAG &DAG) { 4769 EVT VT = N->getValueType(0); 4770 SDValue Src = N->getOperand(1); 4771 SDLoc SL(N); 4772 4773 if (Src.getOpcode() == ISD::SETCC) { 4774 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4775 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4776 Src.getOperand(1), Src.getOperand(2)); 4777 } 4778 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4779 // (ballot 0) -> 0 4780 if (Arg->isNullValue()) 4781 return DAG.getConstant(0, SL, VT); 4782 4783 // (ballot 1) -> EXEC/EXEC_LO 4784 if (Arg->isOne()) { 4785 Register Exec; 4786 if (VT.getScalarSizeInBits() == 32) 4787 Exec = AMDGPU::EXEC_LO; 4788 else if (VT.getScalarSizeInBits() == 64) 4789 Exec = AMDGPU::EXEC; 4790 else 4791 return SDValue(); 4792 4793 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4794 } 4795 } 4796 4797 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4798 // ISD::SETNE) 4799 return DAG.getNode( 4800 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4801 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4802 } 4803 4804 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4805 SmallVectorImpl<SDValue> &Results, 4806 SelectionDAG &DAG) const { 4807 switch (N->getOpcode()) { 4808 case ISD::INSERT_VECTOR_ELT: { 4809 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4810 Results.push_back(Res); 4811 return; 4812 } 4813 case ISD::EXTRACT_VECTOR_ELT: { 4814 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4815 Results.push_back(Res); 4816 return; 4817 } 4818 case ISD::INTRINSIC_WO_CHAIN: { 4819 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4820 switch (IID) { 4821 case Intrinsic::amdgcn_cvt_pkrtz: { 4822 SDValue Src0 = N->getOperand(1); 4823 SDValue Src1 = N->getOperand(2); 4824 SDLoc SL(N); 4825 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4826 Src0, Src1); 4827 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4828 return; 4829 } 4830 case Intrinsic::amdgcn_cvt_pknorm_i16: 4831 case Intrinsic::amdgcn_cvt_pknorm_u16: 4832 case Intrinsic::amdgcn_cvt_pk_i16: 4833 case Intrinsic::amdgcn_cvt_pk_u16: { 4834 SDValue Src0 = N->getOperand(1); 4835 SDValue Src1 = N->getOperand(2); 4836 SDLoc SL(N); 4837 unsigned Opcode; 4838 4839 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4840 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4841 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4842 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4843 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4844 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4845 else 4846 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4847 4848 EVT VT = N->getValueType(0); 4849 if (isTypeLegal(VT)) 4850 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4851 else { 4852 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4853 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4854 } 4855 return; 4856 } 4857 } 4858 break; 4859 } 4860 case ISD::INTRINSIC_W_CHAIN: { 4861 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4862 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4863 // FIXME: Hacky 4864 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4865 Results.push_back(Res.getOperand(I)); 4866 } 4867 } else { 4868 Results.push_back(Res); 4869 Results.push_back(Res.getValue(1)); 4870 } 4871 return; 4872 } 4873 4874 break; 4875 } 4876 case ISD::SELECT: { 4877 SDLoc SL(N); 4878 EVT VT = N->getValueType(0); 4879 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4880 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4881 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4882 4883 EVT SelectVT = NewVT; 4884 if (NewVT.bitsLT(MVT::i32)) { 4885 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4886 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4887 SelectVT = MVT::i32; 4888 } 4889 4890 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4891 N->getOperand(0), LHS, RHS); 4892 4893 if (NewVT != SelectVT) 4894 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4895 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4896 return; 4897 } 4898 case ISD::FNEG: { 4899 if (N->getValueType(0) != MVT::v2f16) 4900 break; 4901 4902 SDLoc SL(N); 4903 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4904 4905 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4906 BC, 4907 DAG.getConstant(0x80008000, SL, MVT::i32)); 4908 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4909 return; 4910 } 4911 case ISD::FABS: { 4912 if (N->getValueType(0) != MVT::v2f16) 4913 break; 4914 4915 SDLoc SL(N); 4916 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4917 4918 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4919 BC, 4920 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4921 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4922 return; 4923 } 4924 default: 4925 break; 4926 } 4927 } 4928 4929 /// Helper function for LowerBRCOND 4930 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4931 4932 SDNode *Parent = Value.getNode(); 4933 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4934 I != E; ++I) { 4935 4936 if (I.getUse().get() != Value) 4937 continue; 4938 4939 if (I->getOpcode() == Opcode) 4940 return *I; 4941 } 4942 return nullptr; 4943 } 4944 4945 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4946 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4947 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4948 case Intrinsic::amdgcn_if: 4949 return AMDGPUISD::IF; 4950 case Intrinsic::amdgcn_else: 4951 return AMDGPUISD::ELSE; 4952 case Intrinsic::amdgcn_loop: 4953 return AMDGPUISD::LOOP; 4954 case Intrinsic::amdgcn_end_cf: 4955 llvm_unreachable("should not occur"); 4956 default: 4957 return 0; 4958 } 4959 } 4960 4961 // break, if_break, else_break are all only used as inputs to loop, not 4962 // directly as branch conditions. 4963 return 0; 4964 } 4965 4966 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4967 const Triple &TT = getTargetMachine().getTargetTriple(); 4968 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4969 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4970 AMDGPU::shouldEmitConstantsToTextSection(TT); 4971 } 4972 4973 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4974 // FIXME: Either avoid relying on address space here or change the default 4975 // address space for functions to avoid the explicit check. 4976 return (GV->getValueType()->isFunctionTy() || 4977 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4978 !shouldEmitFixup(GV) && 4979 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4980 } 4981 4982 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4983 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4984 } 4985 4986 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4987 if (!GV->hasExternalLinkage()) 4988 return true; 4989 4990 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4991 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4992 } 4993 4994 /// This transforms the control flow intrinsics to get the branch destination as 4995 /// last parameter, also switches branch target with BR if the need arise 4996 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4997 SelectionDAG &DAG) const { 4998 SDLoc DL(BRCOND); 4999 5000 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5001 SDValue Target = BRCOND.getOperand(2); 5002 SDNode *BR = nullptr; 5003 SDNode *SetCC = nullptr; 5004 5005 if (Intr->getOpcode() == ISD::SETCC) { 5006 // As long as we negate the condition everything is fine 5007 SetCC = Intr; 5008 Intr = SetCC->getOperand(0).getNode(); 5009 5010 } else { 5011 // Get the target from BR if we don't negate the condition 5012 BR = findUser(BRCOND, ISD::BR); 5013 assert(BR && "brcond missing unconditional branch user"); 5014 Target = BR->getOperand(1); 5015 } 5016 5017 unsigned CFNode = isCFIntrinsic(Intr); 5018 if (CFNode == 0) { 5019 // This is a uniform branch so we don't need to legalize. 5020 return BRCOND; 5021 } 5022 5023 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5024 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5025 5026 assert(!SetCC || 5027 (SetCC->getConstantOperandVal(1) == 1 && 5028 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5029 ISD::SETNE)); 5030 5031 // operands of the new intrinsic call 5032 SmallVector<SDValue, 4> Ops; 5033 if (HaveChain) 5034 Ops.push_back(BRCOND.getOperand(0)); 5035 5036 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5037 Ops.push_back(Target); 5038 5039 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5040 5041 // build the new intrinsic call 5042 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5043 5044 if (!HaveChain) { 5045 SDValue Ops[] = { 5046 SDValue(Result, 0), 5047 BRCOND.getOperand(0) 5048 }; 5049 5050 Result = DAG.getMergeValues(Ops, DL).getNode(); 5051 } 5052 5053 if (BR) { 5054 // Give the branch instruction our target 5055 SDValue Ops[] = { 5056 BR->getOperand(0), 5057 BRCOND.getOperand(2) 5058 }; 5059 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5060 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5061 } 5062 5063 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5064 5065 // Copy the intrinsic results to registers 5066 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5067 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5068 if (!CopyToReg) 5069 continue; 5070 5071 Chain = DAG.getCopyToReg( 5072 Chain, DL, 5073 CopyToReg->getOperand(1), 5074 SDValue(Result, i - 1), 5075 SDValue()); 5076 5077 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5078 } 5079 5080 // Remove the old intrinsic from the chain 5081 DAG.ReplaceAllUsesOfValueWith( 5082 SDValue(Intr, Intr->getNumValues() - 1), 5083 Intr->getOperand(0)); 5084 5085 return Chain; 5086 } 5087 5088 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5089 SelectionDAG &DAG) const { 5090 MVT VT = Op.getSimpleValueType(); 5091 SDLoc DL(Op); 5092 // Checking the depth 5093 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5094 return DAG.getConstant(0, DL, VT); 5095 5096 MachineFunction &MF = DAG.getMachineFunction(); 5097 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5098 // Check for kernel and shader functions 5099 if (Info->isEntryFunction()) 5100 return DAG.getConstant(0, DL, VT); 5101 5102 MachineFrameInfo &MFI = MF.getFrameInfo(); 5103 // There is a call to @llvm.returnaddress in this function 5104 MFI.setReturnAddressIsTaken(true); 5105 5106 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5107 // Get the return address reg and mark it as an implicit live-in 5108 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5109 5110 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5111 } 5112 5113 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5114 SDValue Op, 5115 const SDLoc &DL, 5116 EVT VT) const { 5117 return Op.getValueType().bitsLE(VT) ? 5118 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5119 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5120 DAG.getTargetConstant(0, DL, MVT::i32)); 5121 } 5122 5123 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5124 assert(Op.getValueType() == MVT::f16 && 5125 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5126 5127 SDValue Src = Op.getOperand(0); 5128 EVT SrcVT = Src.getValueType(); 5129 if (SrcVT != MVT::f64) 5130 return Op; 5131 5132 SDLoc DL(Op); 5133 5134 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5135 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5136 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5137 } 5138 5139 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5140 SelectionDAG &DAG) const { 5141 EVT VT = Op.getValueType(); 5142 const MachineFunction &MF = DAG.getMachineFunction(); 5143 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5144 bool IsIEEEMode = Info->getMode().IEEE; 5145 5146 // FIXME: Assert during selection that this is only selected for 5147 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5148 // mode functions, but this happens to be OK since it's only done in cases 5149 // where there is known no sNaN. 5150 if (IsIEEEMode) 5151 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5152 5153 if (VT == MVT::v4f16) 5154 return splitBinaryVectorOp(Op, DAG); 5155 return Op; 5156 } 5157 5158 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5159 EVT VT = Op.getValueType(); 5160 SDLoc SL(Op); 5161 SDValue LHS = Op.getOperand(0); 5162 SDValue RHS = Op.getOperand(1); 5163 bool isSigned = Op.getOpcode() == ISD::SMULO; 5164 5165 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5166 const APInt &C = RHSC->getAPIntValue(); 5167 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5168 if (C.isPowerOf2()) { 5169 // smulo(x, signed_min) is same as umulo(x, signed_min). 5170 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5171 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5172 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5173 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5174 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5175 SL, VT, Result, ShiftAmt), 5176 LHS, ISD::SETNE); 5177 return DAG.getMergeValues({ Result, Overflow }, SL); 5178 } 5179 } 5180 5181 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5182 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5183 SL, VT, LHS, RHS); 5184 5185 SDValue Sign = isSigned 5186 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5187 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5188 : DAG.getConstant(0, SL, VT); 5189 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5190 5191 return DAG.getMergeValues({ Result, Overflow }, SL); 5192 } 5193 5194 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5195 SDLoc SL(Op); 5196 SDValue Chain = Op.getOperand(0); 5197 5198 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5199 !Subtarget->isTrapHandlerEnabled()) 5200 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5201 5202 MachineFunction &MF = DAG.getMachineFunction(); 5203 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5204 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5205 assert(UserSGPR != AMDGPU::NoRegister); 5206 SDValue QueuePtr = CreateLiveInRegister( 5207 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5208 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5209 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5210 QueuePtr, SDValue()); 5211 SDValue Ops[] = { 5212 ToReg, 5213 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5214 SGPR01, 5215 ToReg.getValue(1) 5216 }; 5217 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5218 } 5219 5220 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5221 SDLoc SL(Op); 5222 SDValue Chain = Op.getOperand(0); 5223 MachineFunction &MF = DAG.getMachineFunction(); 5224 5225 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5226 !Subtarget->isTrapHandlerEnabled()) { 5227 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5228 "debugtrap handler not supported", 5229 Op.getDebugLoc(), 5230 DS_Warning); 5231 LLVMContext &Ctx = MF.getFunction().getContext(); 5232 Ctx.diagnose(NoTrap); 5233 return Chain; 5234 } 5235 5236 SDValue Ops[] = { 5237 Chain, 5238 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5239 }; 5240 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5241 } 5242 5243 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5244 SelectionDAG &DAG) const { 5245 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5246 if (Subtarget->hasApertureRegs()) { 5247 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5248 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5249 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5250 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5251 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5252 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5253 unsigned Encoding = 5254 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5255 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5256 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5257 5258 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5259 SDValue ApertureReg = SDValue( 5260 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5261 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5262 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5263 } 5264 5265 MachineFunction &MF = DAG.getMachineFunction(); 5266 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5267 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5268 assert(UserSGPR != AMDGPU::NoRegister); 5269 5270 SDValue QueuePtr = CreateLiveInRegister( 5271 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5272 5273 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5274 // private_segment_aperture_base_hi. 5275 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5276 5277 SDValue Ptr = 5278 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5279 5280 // TODO: Use custom target PseudoSourceValue. 5281 // TODO: We should use the value from the IR intrinsic call, but it might not 5282 // be available and how do we get it? 5283 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5284 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5285 commonAlignment(Align(64), StructOffset), 5286 MachineMemOperand::MODereferenceable | 5287 MachineMemOperand::MOInvariant); 5288 } 5289 5290 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5291 SelectionDAG &DAG) const { 5292 SDLoc SL(Op); 5293 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5294 5295 SDValue Src = ASC->getOperand(0); 5296 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5297 5298 const AMDGPUTargetMachine &TM = 5299 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5300 5301 // flat -> local/private 5302 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5303 unsigned DestAS = ASC->getDestAddressSpace(); 5304 5305 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5306 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5307 unsigned NullVal = TM.getNullPointerValue(DestAS); 5308 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5309 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5310 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5311 5312 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5313 NonNull, Ptr, SegmentNullPtr); 5314 } 5315 } 5316 5317 // local/private -> flat 5318 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5319 unsigned SrcAS = ASC->getSrcAddressSpace(); 5320 5321 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5322 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5323 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5324 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5325 5326 SDValue NonNull 5327 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5328 5329 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5330 SDValue CvtPtr 5331 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5332 5333 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5334 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5335 FlatNullPtr); 5336 } 5337 } 5338 5339 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5340 Src.getValueType() == MVT::i64) 5341 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5342 5343 // global <-> flat are no-ops and never emitted. 5344 5345 const MachineFunction &MF = DAG.getMachineFunction(); 5346 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5347 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5348 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5349 5350 return DAG.getUNDEF(ASC->getValueType(0)); 5351 } 5352 5353 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5354 // the small vector and inserting them into the big vector. That is better than 5355 // the default expansion of doing it via a stack slot. Even though the use of 5356 // the stack slot would be optimized away afterwards, the stack slot itself 5357 // remains. 5358 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5359 SelectionDAG &DAG) const { 5360 SDValue Vec = Op.getOperand(0); 5361 SDValue Ins = Op.getOperand(1); 5362 SDValue Idx = Op.getOperand(2); 5363 EVT VecVT = Vec.getValueType(); 5364 EVT InsVT = Ins.getValueType(); 5365 EVT EltVT = VecVT.getVectorElementType(); 5366 unsigned InsNumElts = InsVT.getVectorNumElements(); 5367 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5368 SDLoc SL(Op); 5369 5370 for (unsigned I = 0; I != InsNumElts; ++I) { 5371 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5372 DAG.getConstant(I, SL, MVT::i32)); 5373 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5374 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5375 } 5376 return Vec; 5377 } 5378 5379 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5380 SelectionDAG &DAG) const { 5381 SDValue Vec = Op.getOperand(0); 5382 SDValue InsVal = Op.getOperand(1); 5383 SDValue Idx = Op.getOperand(2); 5384 EVT VecVT = Vec.getValueType(); 5385 EVT EltVT = VecVT.getVectorElementType(); 5386 unsigned VecSize = VecVT.getSizeInBits(); 5387 unsigned EltSize = EltVT.getSizeInBits(); 5388 5389 5390 assert(VecSize <= 64); 5391 5392 unsigned NumElts = VecVT.getVectorNumElements(); 5393 SDLoc SL(Op); 5394 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5395 5396 if (NumElts == 4 && EltSize == 16 && KIdx) { 5397 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5398 5399 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5400 DAG.getConstant(0, SL, MVT::i32)); 5401 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5402 DAG.getConstant(1, SL, MVT::i32)); 5403 5404 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5405 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5406 5407 unsigned Idx = KIdx->getZExtValue(); 5408 bool InsertLo = Idx < 2; 5409 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5410 InsertLo ? LoVec : HiVec, 5411 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5412 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5413 5414 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5415 5416 SDValue Concat = InsertLo ? 5417 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5418 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5419 5420 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5421 } 5422 5423 if (isa<ConstantSDNode>(Idx)) 5424 return SDValue(); 5425 5426 MVT IntVT = MVT::getIntegerVT(VecSize); 5427 5428 // Avoid stack access for dynamic indexing. 5429 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5430 5431 // Create a congruent vector with the target value in each element so that 5432 // the required element can be masked and ORed into the target vector. 5433 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5434 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5435 5436 assert(isPowerOf2_32(EltSize)); 5437 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5438 5439 // Convert vector index to bit-index. 5440 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5441 5442 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5443 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5444 DAG.getConstant(0xffff, SL, IntVT), 5445 ScaledIdx); 5446 5447 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5448 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5449 DAG.getNOT(SL, BFM, IntVT), BCVec); 5450 5451 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5452 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5453 } 5454 5455 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5456 SelectionDAG &DAG) const { 5457 SDLoc SL(Op); 5458 5459 EVT ResultVT = Op.getValueType(); 5460 SDValue Vec = Op.getOperand(0); 5461 SDValue Idx = Op.getOperand(1); 5462 EVT VecVT = Vec.getValueType(); 5463 unsigned VecSize = VecVT.getSizeInBits(); 5464 EVT EltVT = VecVT.getVectorElementType(); 5465 assert(VecSize <= 64); 5466 5467 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5468 5469 // Make sure we do any optimizations that will make it easier to fold 5470 // source modifiers before obscuring it with bit operations. 5471 5472 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5473 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5474 return Combined; 5475 5476 unsigned EltSize = EltVT.getSizeInBits(); 5477 assert(isPowerOf2_32(EltSize)); 5478 5479 MVT IntVT = MVT::getIntegerVT(VecSize); 5480 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5481 5482 // Convert vector index to bit-index (* EltSize) 5483 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5484 5485 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5486 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5487 5488 if (ResultVT == MVT::f16) { 5489 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5490 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5491 } 5492 5493 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5494 } 5495 5496 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5497 assert(Elt % 2 == 0); 5498 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5499 } 5500 5501 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5502 SelectionDAG &DAG) const { 5503 SDLoc SL(Op); 5504 EVT ResultVT = Op.getValueType(); 5505 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5506 5507 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5508 EVT EltVT = PackVT.getVectorElementType(); 5509 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5510 5511 // vector_shuffle <0,1,6,7> lhs, rhs 5512 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5513 // 5514 // vector_shuffle <6,7,2,3> lhs, rhs 5515 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5516 // 5517 // vector_shuffle <6,7,0,1> lhs, rhs 5518 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5519 5520 // Avoid scalarizing when both halves are reading from consecutive elements. 5521 SmallVector<SDValue, 4> Pieces; 5522 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5523 if (elementPairIsContiguous(SVN->getMask(), I)) { 5524 const int Idx = SVN->getMaskElt(I); 5525 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5526 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5527 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5528 PackVT, SVN->getOperand(VecIdx), 5529 DAG.getConstant(EltIdx, SL, MVT::i32)); 5530 Pieces.push_back(SubVec); 5531 } else { 5532 const int Idx0 = SVN->getMaskElt(I); 5533 const int Idx1 = SVN->getMaskElt(I + 1); 5534 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5535 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5536 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5537 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5538 5539 SDValue Vec0 = SVN->getOperand(VecIdx0); 5540 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5541 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5542 5543 SDValue Vec1 = SVN->getOperand(VecIdx1); 5544 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5545 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5546 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5547 } 5548 } 5549 5550 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5551 } 5552 5553 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5554 SelectionDAG &DAG) const { 5555 SDLoc SL(Op); 5556 EVT VT = Op.getValueType(); 5557 5558 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5559 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5560 5561 // Turn into pair of packed build_vectors. 5562 // TODO: Special case for constants that can be materialized with s_mov_b64. 5563 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5564 { Op.getOperand(0), Op.getOperand(1) }); 5565 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5566 { Op.getOperand(2), Op.getOperand(3) }); 5567 5568 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5569 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5570 5571 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5572 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5573 } 5574 5575 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5576 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5577 5578 SDValue Lo = Op.getOperand(0); 5579 SDValue Hi = Op.getOperand(1); 5580 5581 // Avoid adding defined bits with the zero_extend. 5582 if (Hi.isUndef()) { 5583 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5584 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5585 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5586 } 5587 5588 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5589 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5590 5591 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5592 DAG.getConstant(16, SL, MVT::i32)); 5593 if (Lo.isUndef()) 5594 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5595 5596 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5597 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5598 5599 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5600 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5601 } 5602 5603 bool 5604 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5605 // We can fold offsets for anything that doesn't require a GOT relocation. 5606 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5607 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5608 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5609 !shouldEmitGOTReloc(GA->getGlobal()); 5610 } 5611 5612 static SDValue 5613 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5614 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5615 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5616 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5617 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5618 // lowered to the following code sequence: 5619 // 5620 // For constant address space: 5621 // s_getpc_b64 s[0:1] 5622 // s_add_u32 s0, s0, $symbol 5623 // s_addc_u32 s1, s1, 0 5624 // 5625 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5626 // a fixup or relocation is emitted to replace $symbol with a literal 5627 // constant, which is a pc-relative offset from the encoding of the $symbol 5628 // operand to the global variable. 5629 // 5630 // For global address space: 5631 // s_getpc_b64 s[0:1] 5632 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5633 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5634 // 5635 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5636 // fixups or relocations are emitted to replace $symbol@*@lo and 5637 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5638 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5639 // operand to the global variable. 5640 // 5641 // What we want here is an offset from the value returned by s_getpc 5642 // (which is the address of the s_add_u32 instruction) to the global 5643 // variable, but since the encoding of $symbol starts 4 bytes after the start 5644 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5645 // small. This requires us to add 4 to the global variable offset in order to 5646 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5647 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5648 // instruction. 5649 SDValue PtrLo = 5650 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5651 SDValue PtrHi; 5652 if (GAFlags == SIInstrInfo::MO_NONE) { 5653 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5654 } else { 5655 PtrHi = 5656 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5657 } 5658 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5659 } 5660 5661 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5662 SDValue Op, 5663 SelectionDAG &DAG) const { 5664 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5665 SDLoc DL(GSD); 5666 EVT PtrVT = Op.getValueType(); 5667 5668 const GlobalValue *GV = GSD->getGlobal(); 5669 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5670 shouldUseLDSConstAddress(GV)) || 5671 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5672 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5673 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5674 GV->hasExternalLinkage()) { 5675 Type *Ty = GV->getValueType(); 5676 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5677 // zero-sized type in other languages to declare the dynamic shared 5678 // memory which size is not known at the compile time. They will be 5679 // allocated by the runtime and placed directly after the static 5680 // allocated ones. They all share the same offset. 5681 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5682 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5683 // Adjust alignment for that dynamic shared memory array. 5684 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5685 return SDValue( 5686 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5687 } 5688 } 5689 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5690 } 5691 5692 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5693 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5694 SIInstrInfo::MO_ABS32_LO); 5695 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5696 } 5697 5698 if (shouldEmitFixup(GV)) 5699 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5700 else if (shouldEmitPCReloc(GV)) 5701 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5702 SIInstrInfo::MO_REL32); 5703 5704 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5705 SIInstrInfo::MO_GOTPCREL32); 5706 5707 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5708 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5709 const DataLayout &DataLayout = DAG.getDataLayout(); 5710 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5711 MachinePointerInfo PtrInfo 5712 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5713 5714 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5715 MachineMemOperand::MODereferenceable | 5716 MachineMemOperand::MOInvariant); 5717 } 5718 5719 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5720 const SDLoc &DL, SDValue V) const { 5721 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5722 // the destination register. 5723 // 5724 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5725 // so we will end up with redundant moves to m0. 5726 // 5727 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5728 5729 // A Null SDValue creates a glue result. 5730 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5731 V, Chain); 5732 return SDValue(M0, 0); 5733 } 5734 5735 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5736 SDValue Op, 5737 MVT VT, 5738 unsigned Offset) const { 5739 SDLoc SL(Op); 5740 SDValue Param = lowerKernargMemParameter( 5741 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5742 // The local size values will have the hi 16-bits as zero. 5743 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5744 DAG.getValueType(VT)); 5745 } 5746 5747 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5748 EVT VT) { 5749 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5750 "non-hsa intrinsic with hsa target", 5751 DL.getDebugLoc()); 5752 DAG.getContext()->diagnose(BadIntrin); 5753 return DAG.getUNDEF(VT); 5754 } 5755 5756 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5757 EVT VT) { 5758 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5759 "intrinsic not supported on subtarget", 5760 DL.getDebugLoc()); 5761 DAG.getContext()->diagnose(BadIntrin); 5762 return DAG.getUNDEF(VT); 5763 } 5764 5765 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5766 ArrayRef<SDValue> Elts) { 5767 assert(!Elts.empty()); 5768 MVT Type; 5769 unsigned NumElts; 5770 5771 if (Elts.size() == 1) { 5772 Type = MVT::f32; 5773 NumElts = 1; 5774 } else if (Elts.size() == 2) { 5775 Type = MVT::v2f32; 5776 NumElts = 2; 5777 } else if (Elts.size() == 3) { 5778 Type = MVT::v3f32; 5779 NumElts = 3; 5780 } else if (Elts.size() <= 4) { 5781 Type = MVT::v4f32; 5782 NumElts = 4; 5783 } else if (Elts.size() <= 8) { 5784 Type = MVT::v8f32; 5785 NumElts = 8; 5786 } else { 5787 assert(Elts.size() <= 16); 5788 Type = MVT::v16f32; 5789 NumElts = 16; 5790 } 5791 5792 SmallVector<SDValue, 16> VecElts(NumElts); 5793 for (unsigned i = 0; i < Elts.size(); ++i) { 5794 SDValue Elt = Elts[i]; 5795 if (Elt.getValueType() != MVT::f32) 5796 Elt = DAG.getBitcast(MVT::f32, Elt); 5797 VecElts[i] = Elt; 5798 } 5799 for (unsigned i = Elts.size(); i < NumElts; ++i) 5800 VecElts[i] = DAG.getUNDEF(MVT::f32); 5801 5802 if (NumElts == 1) 5803 return VecElts[0]; 5804 return DAG.getBuildVector(Type, DL, VecElts); 5805 } 5806 5807 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5808 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5809 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5810 5811 uint64_t Value = CachePolicyConst->getZExtValue(); 5812 SDLoc DL(CachePolicy); 5813 if (GLC) { 5814 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5815 Value &= ~(uint64_t)0x1; 5816 } 5817 if (SLC) { 5818 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5819 Value &= ~(uint64_t)0x2; 5820 } 5821 if (DLC) { 5822 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5823 Value &= ~(uint64_t)0x4; 5824 } 5825 5826 return Value == 0; 5827 } 5828 5829 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5830 SDValue Src, int ExtraElts) { 5831 EVT SrcVT = Src.getValueType(); 5832 5833 SmallVector<SDValue, 8> Elts; 5834 5835 if (SrcVT.isVector()) 5836 DAG.ExtractVectorElements(Src, Elts); 5837 else 5838 Elts.push_back(Src); 5839 5840 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5841 while (ExtraElts--) 5842 Elts.push_back(Undef); 5843 5844 return DAG.getBuildVector(CastVT, DL, Elts); 5845 } 5846 5847 // Re-construct the required return value for a image load intrinsic. 5848 // This is more complicated due to the optional use TexFailCtrl which means the required 5849 // return type is an aggregate 5850 static SDValue constructRetValue(SelectionDAG &DAG, 5851 MachineSDNode *Result, 5852 ArrayRef<EVT> ResultTypes, 5853 bool IsTexFail, bool Unpacked, bool IsD16, 5854 int DMaskPop, int NumVDataDwords, 5855 const SDLoc &DL, LLVMContext &Context) { 5856 // Determine the required return type. This is the same regardless of IsTexFail flag 5857 EVT ReqRetVT = ResultTypes[0]; 5858 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5859 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5860 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5861 5862 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5863 DMaskPop : (DMaskPop + 1) / 2; 5864 5865 MVT DataDwordVT = NumDataDwords == 1 ? 5866 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5867 5868 MVT MaskPopVT = MaskPopDwords == 1 ? 5869 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5870 5871 SDValue Data(Result, 0); 5872 SDValue TexFail; 5873 5874 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5875 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5876 if (MaskPopVT.isVector()) { 5877 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5878 SDValue(Result, 0), ZeroIdx); 5879 } else { 5880 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5881 SDValue(Result, 0), ZeroIdx); 5882 } 5883 } 5884 5885 if (DataDwordVT.isVector()) 5886 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5887 NumDataDwords - MaskPopDwords); 5888 5889 if (IsD16) 5890 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5891 5892 EVT LegalReqRetVT = ReqRetVT; 5893 if (!ReqRetVT.isVector()) { 5894 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5895 } else { 5896 // We need to widen the return vector to a legal type 5897 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5898 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5899 LegalReqRetVT = 5900 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5901 ReqRetVT.getVectorNumElements() + 1); 5902 } 5903 } 5904 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5905 5906 if (IsTexFail) { 5907 TexFail = 5908 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5909 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5910 5911 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5912 } 5913 5914 if (Result->getNumValues() == 1) 5915 return Data; 5916 5917 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5918 } 5919 5920 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5921 SDValue *LWE, bool &IsTexFail) { 5922 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5923 5924 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5925 if (Value) { 5926 IsTexFail = true; 5927 } 5928 5929 SDLoc DL(TexFailCtrlConst); 5930 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5931 Value &= ~(uint64_t)0x1; 5932 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5933 Value &= ~(uint64_t)0x2; 5934 5935 return Value == 0; 5936 } 5937 5938 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5939 MVT PackVectorVT, 5940 SmallVectorImpl<SDValue> &PackedAddrs, 5941 unsigned DimIdx, unsigned EndIdx, 5942 unsigned NumGradients) { 5943 SDLoc DL(Op); 5944 for (unsigned I = DimIdx; I < EndIdx; I++) { 5945 SDValue Addr = Op.getOperand(I); 5946 5947 // Gradients are packed with undef for each coordinate. 5948 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5949 // 1D: undef,dx/dh; undef,dx/dv 5950 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5951 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5952 if (((I + 1) >= EndIdx) || 5953 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5954 I == DimIdx + NumGradients - 1))) { 5955 if (Addr.getValueType() != MVT::i16) 5956 Addr = DAG.getBitcast(MVT::i16, Addr); 5957 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5958 } else { 5959 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5960 I++; 5961 } 5962 Addr = DAG.getBitcast(MVT::f32, Addr); 5963 PackedAddrs.push_back(Addr); 5964 } 5965 } 5966 5967 SDValue SITargetLowering::lowerImage(SDValue Op, 5968 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5969 SelectionDAG &DAG, bool WithChain) const { 5970 SDLoc DL(Op); 5971 MachineFunction &MF = DAG.getMachineFunction(); 5972 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5973 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5974 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5975 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5976 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5977 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5978 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5979 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5980 unsigned IntrOpcode = Intr->BaseOpcode; 5981 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5982 5983 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5984 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5985 bool IsD16 = false; 5986 bool IsG16 = false; 5987 bool IsA16 = false; 5988 SDValue VData; 5989 int NumVDataDwords; 5990 bool AdjustRetType = false; 5991 5992 // Offset of intrinsic arguments 5993 const unsigned ArgOffset = WithChain ? 2 : 1; 5994 5995 unsigned DMask; 5996 unsigned DMaskLanes = 0; 5997 5998 if (BaseOpcode->Atomic) { 5999 VData = Op.getOperand(2); 6000 6001 bool Is64Bit = VData.getValueType() == MVT::i64; 6002 if (BaseOpcode->AtomicX2) { 6003 SDValue VData2 = Op.getOperand(3); 6004 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6005 {VData, VData2}); 6006 if (Is64Bit) 6007 VData = DAG.getBitcast(MVT::v4i32, VData); 6008 6009 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6010 DMask = Is64Bit ? 0xf : 0x3; 6011 NumVDataDwords = Is64Bit ? 4 : 2; 6012 } else { 6013 DMask = Is64Bit ? 0x3 : 0x1; 6014 NumVDataDwords = Is64Bit ? 2 : 1; 6015 } 6016 } else { 6017 auto *DMaskConst = 6018 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6019 DMask = DMaskConst->getZExtValue(); 6020 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6021 6022 if (BaseOpcode->Store) { 6023 VData = Op.getOperand(2); 6024 6025 MVT StoreVT = VData.getSimpleValueType(); 6026 if (StoreVT.getScalarType() == MVT::f16) { 6027 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6028 return Op; // D16 is unsupported for this instruction 6029 6030 IsD16 = true; 6031 VData = handleD16VData(VData, DAG, true); 6032 } 6033 6034 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6035 } else { 6036 // Work out the num dwords based on the dmask popcount and underlying type 6037 // and whether packing is supported. 6038 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6039 if (LoadVT.getScalarType() == MVT::f16) { 6040 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6041 return Op; // D16 is unsupported for this instruction 6042 6043 IsD16 = true; 6044 } 6045 6046 // Confirm that the return type is large enough for the dmask specified 6047 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6048 (!LoadVT.isVector() && DMaskLanes > 1)) 6049 return Op; 6050 6051 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6052 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6053 // instructions. 6054 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6055 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6056 NumVDataDwords = (DMaskLanes + 1) / 2; 6057 else 6058 NumVDataDwords = DMaskLanes; 6059 6060 AdjustRetType = true; 6061 } 6062 } 6063 6064 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6065 SmallVector<SDValue, 4> VAddrs; 6066 6067 // Optimize _L to _LZ when _L is zero 6068 if (LZMappingInfo) { 6069 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6070 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6071 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6072 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6073 VAddrEnd--; // remove 'lod' 6074 } 6075 } 6076 } 6077 6078 // Optimize _mip away, when 'lod' is zero 6079 if (MIPMappingInfo) { 6080 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6081 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6082 if (ConstantLod->isNullValue()) { 6083 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6084 VAddrEnd--; // remove 'mip' 6085 } 6086 } 6087 } 6088 6089 // Push back extra arguments. 6090 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6091 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6092 6093 // Check for 16 bit addresses or derivatives and pack if true. 6094 MVT VAddrVT = 6095 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6096 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6097 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6098 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6099 6100 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6101 VAddrScalarVT = VAddrVT.getScalarType(); 6102 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6103 if (IsA16 || IsG16) { 6104 if (IsA16) { 6105 if (!ST->hasA16()) { 6106 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6107 "support 16 bit addresses\n"); 6108 return Op; 6109 } 6110 if (!IsG16) { 6111 LLVM_DEBUG( 6112 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6113 "need 16 bit derivatives but got 32 bit derivatives\n"); 6114 return Op; 6115 } 6116 } else if (!ST->hasG16()) { 6117 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6118 "support 16 bit derivatives\n"); 6119 return Op; 6120 } 6121 6122 if (BaseOpcode->Gradients && !IsA16) { 6123 if (!ST->hasG16()) { 6124 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6125 "support 16 bit derivatives\n"); 6126 return Op; 6127 } 6128 // Activate g16 6129 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6130 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6131 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6132 } 6133 6134 // Don't compress addresses for G16 6135 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6136 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6137 ArgOffset + Intr->GradientStart, PackEndIdx, 6138 Intr->NumGradients); 6139 6140 if (!IsA16) { 6141 // Add uncompressed address 6142 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6143 VAddrs.push_back(Op.getOperand(I)); 6144 } 6145 } else { 6146 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6147 VAddrs.push_back(Op.getOperand(I)); 6148 } 6149 6150 // If the register allocator cannot place the address registers contiguously 6151 // without introducing moves, then using the non-sequential address encoding 6152 // is always preferable, since it saves VALU instructions and is usually a 6153 // wash in terms of code size or even better. 6154 // 6155 // However, we currently have no way of hinting to the register allocator that 6156 // MIMG addresses should be placed contiguously when it is possible to do so, 6157 // so force non-NSA for the common 2-address case as a heuristic. 6158 // 6159 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6160 // allocation when possible. 6161 bool UseNSA = 6162 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6163 SDValue VAddr; 6164 if (!UseNSA) 6165 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6166 6167 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6168 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6169 SDValue Unorm; 6170 if (!BaseOpcode->Sampler) { 6171 Unorm = True; 6172 } else { 6173 auto UnormConst = 6174 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6175 6176 Unorm = UnormConst->getZExtValue() ? True : False; 6177 } 6178 6179 SDValue TFE; 6180 SDValue LWE; 6181 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6182 bool IsTexFail = false; 6183 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6184 return Op; 6185 6186 if (IsTexFail) { 6187 if (!DMaskLanes) { 6188 // Expecting to get an error flag since TFC is on - and dmask is 0 6189 // Force dmask to be at least 1 otherwise the instruction will fail 6190 DMask = 0x1; 6191 DMaskLanes = 1; 6192 NumVDataDwords = 1; 6193 } 6194 NumVDataDwords += 1; 6195 AdjustRetType = true; 6196 } 6197 6198 // Has something earlier tagged that the return type needs adjusting 6199 // This happens if the instruction is a load or has set TexFailCtrl flags 6200 if (AdjustRetType) { 6201 // NumVDataDwords reflects the true number of dwords required in the return type 6202 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6203 // This is a no-op load. This can be eliminated 6204 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6205 if (isa<MemSDNode>(Op)) 6206 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6207 return Undef; 6208 } 6209 6210 EVT NewVT = NumVDataDwords > 1 ? 6211 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6212 : MVT::i32; 6213 6214 ResultTypes[0] = NewVT; 6215 if (ResultTypes.size() == 3) { 6216 // Original result was aggregate type used for TexFailCtrl results 6217 // The actual instruction returns as a vector type which has now been 6218 // created. Remove the aggregate result. 6219 ResultTypes.erase(&ResultTypes[1]); 6220 } 6221 } 6222 6223 SDValue GLC; 6224 SDValue SLC; 6225 SDValue DLC; 6226 if (BaseOpcode->Atomic) { 6227 GLC = True; // TODO no-return optimization 6228 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6229 DAG, nullptr, &SLC, IsGFX10 ? &DLC : nullptr)) 6230 return Op; 6231 } else { 6232 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6233 DAG, &GLC, &SLC, IsGFX10 ? &DLC : nullptr)) 6234 return Op; 6235 } 6236 6237 SmallVector<SDValue, 26> Ops; 6238 if (BaseOpcode->Store || BaseOpcode->Atomic) 6239 Ops.push_back(VData); // vdata 6240 if (UseNSA) { 6241 for (const SDValue &Addr : VAddrs) 6242 Ops.push_back(Addr); 6243 } else { 6244 Ops.push_back(VAddr); 6245 } 6246 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6247 if (BaseOpcode->Sampler) 6248 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6249 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6250 if (IsGFX10) 6251 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6252 Ops.push_back(Unorm); 6253 if (IsGFX10) 6254 Ops.push_back(DLC); 6255 Ops.push_back(GLC); 6256 Ops.push_back(SLC); 6257 Ops.push_back(IsA16 && // r128, a16 for gfx9 6258 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6259 if (IsGFX10) 6260 Ops.push_back(IsA16 ? True : False); 6261 Ops.push_back(TFE); 6262 Ops.push_back(LWE); 6263 if (!IsGFX10) 6264 Ops.push_back(DimInfo->DA ? True : False); 6265 if (BaseOpcode->HasD16) 6266 Ops.push_back(IsD16 ? True : False); 6267 if (isa<MemSDNode>(Op)) 6268 Ops.push_back(Op.getOperand(0)); // chain 6269 6270 int NumVAddrDwords = 6271 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6272 int Opcode = -1; 6273 6274 if (IsGFX10) { 6275 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6276 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6277 : AMDGPU::MIMGEncGfx10Default, 6278 NumVDataDwords, NumVAddrDwords); 6279 } else { 6280 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6281 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6282 NumVDataDwords, NumVAddrDwords); 6283 if (Opcode == -1) 6284 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6285 NumVDataDwords, NumVAddrDwords); 6286 } 6287 assert(Opcode != -1); 6288 6289 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6290 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6291 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6292 DAG.setNodeMemRefs(NewNode, {MemRef}); 6293 } 6294 6295 if (BaseOpcode->AtomicX2) { 6296 SmallVector<SDValue, 1> Elt; 6297 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6298 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6299 } else if (!BaseOpcode->Store) { 6300 return constructRetValue(DAG, NewNode, 6301 OrigResultTypes, IsTexFail, 6302 Subtarget->hasUnpackedD16VMem(), IsD16, 6303 DMaskLanes, NumVDataDwords, DL, 6304 *DAG.getContext()); 6305 } 6306 6307 return SDValue(NewNode, 0); 6308 } 6309 6310 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6311 SDValue Offset, SDValue CachePolicy, 6312 SelectionDAG &DAG) const { 6313 MachineFunction &MF = DAG.getMachineFunction(); 6314 6315 const DataLayout &DataLayout = DAG.getDataLayout(); 6316 Align Alignment = 6317 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6318 6319 MachineMemOperand *MMO = MF.getMachineMemOperand( 6320 MachinePointerInfo(), 6321 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6322 MachineMemOperand::MOInvariant, 6323 VT.getStoreSize(), Alignment); 6324 6325 if (!Offset->isDivergent()) { 6326 SDValue Ops[] = { 6327 Rsrc, 6328 Offset, // Offset 6329 CachePolicy 6330 }; 6331 6332 // Widen vec3 load to vec4. 6333 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6334 EVT WidenedVT = 6335 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6336 auto WidenedOp = DAG.getMemIntrinsicNode( 6337 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6338 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6339 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6340 DAG.getVectorIdxConstant(0, DL)); 6341 return Subvector; 6342 } 6343 6344 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6345 DAG.getVTList(VT), Ops, VT, MMO); 6346 } 6347 6348 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6349 // assume that the buffer is unswizzled. 6350 SmallVector<SDValue, 4> Loads; 6351 unsigned NumLoads = 1; 6352 MVT LoadVT = VT.getSimpleVT(); 6353 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6354 assert((LoadVT.getScalarType() == MVT::i32 || 6355 LoadVT.getScalarType() == MVT::f32)); 6356 6357 if (NumElts == 8 || NumElts == 16) { 6358 NumLoads = NumElts / 4; 6359 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6360 } 6361 6362 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6363 SDValue Ops[] = { 6364 DAG.getEntryNode(), // Chain 6365 Rsrc, // rsrc 6366 DAG.getConstant(0, DL, MVT::i32), // vindex 6367 {}, // voffset 6368 {}, // soffset 6369 {}, // offset 6370 CachePolicy, // cachepolicy 6371 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6372 }; 6373 6374 // Use the alignment to ensure that the required offsets will fit into the 6375 // immediate offsets. 6376 setBufferOffsets(Offset, DAG, &Ops[3], 6377 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6378 6379 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6380 for (unsigned i = 0; i < NumLoads; ++i) { 6381 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6382 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6383 LoadVT, MMO, DAG)); 6384 } 6385 6386 if (NumElts == 8 || NumElts == 16) 6387 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6388 6389 return Loads[0]; 6390 } 6391 6392 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6393 SelectionDAG &DAG) const { 6394 MachineFunction &MF = DAG.getMachineFunction(); 6395 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6396 6397 EVT VT = Op.getValueType(); 6398 SDLoc DL(Op); 6399 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6400 6401 // TODO: Should this propagate fast-math-flags? 6402 6403 switch (IntrinsicID) { 6404 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6405 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6406 return emitNonHSAIntrinsicError(DAG, DL, VT); 6407 return getPreloadedValue(DAG, *MFI, VT, 6408 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6409 } 6410 case Intrinsic::amdgcn_dispatch_ptr: 6411 case Intrinsic::amdgcn_queue_ptr: { 6412 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6413 DiagnosticInfoUnsupported BadIntrin( 6414 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6415 DL.getDebugLoc()); 6416 DAG.getContext()->diagnose(BadIntrin); 6417 return DAG.getUNDEF(VT); 6418 } 6419 6420 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6421 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6422 return getPreloadedValue(DAG, *MFI, VT, RegID); 6423 } 6424 case Intrinsic::amdgcn_implicitarg_ptr: { 6425 if (MFI->isEntryFunction()) 6426 return getImplicitArgPtr(DAG, DL); 6427 return getPreloadedValue(DAG, *MFI, VT, 6428 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6429 } 6430 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6431 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6432 // This only makes sense to call in a kernel, so just lower to null. 6433 return DAG.getConstant(0, DL, VT); 6434 } 6435 6436 return getPreloadedValue(DAG, *MFI, VT, 6437 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6438 } 6439 case Intrinsic::amdgcn_dispatch_id: { 6440 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6441 } 6442 case Intrinsic::amdgcn_rcp: 6443 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6444 case Intrinsic::amdgcn_rsq: 6445 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6446 case Intrinsic::amdgcn_rsq_legacy: 6447 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6448 return emitRemovedIntrinsicError(DAG, DL, VT); 6449 return SDValue(); 6450 case Intrinsic::amdgcn_rcp_legacy: 6451 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6452 return emitRemovedIntrinsicError(DAG, DL, VT); 6453 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6454 case Intrinsic::amdgcn_rsq_clamp: { 6455 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6456 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6457 6458 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6459 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6460 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6461 6462 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6463 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6464 DAG.getConstantFP(Max, DL, VT)); 6465 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6466 DAG.getConstantFP(Min, DL, VT)); 6467 } 6468 case Intrinsic::r600_read_ngroups_x: 6469 if (Subtarget->isAmdHsaOS()) 6470 return emitNonHSAIntrinsicError(DAG, DL, VT); 6471 6472 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6473 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6474 false); 6475 case Intrinsic::r600_read_ngroups_y: 6476 if (Subtarget->isAmdHsaOS()) 6477 return emitNonHSAIntrinsicError(DAG, DL, VT); 6478 6479 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6480 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6481 false); 6482 case Intrinsic::r600_read_ngroups_z: 6483 if (Subtarget->isAmdHsaOS()) 6484 return emitNonHSAIntrinsicError(DAG, DL, VT); 6485 6486 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6487 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6488 false); 6489 case Intrinsic::r600_read_global_size_x: 6490 if (Subtarget->isAmdHsaOS()) 6491 return emitNonHSAIntrinsicError(DAG, DL, VT); 6492 6493 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6494 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6495 Align(4), false); 6496 case Intrinsic::r600_read_global_size_y: 6497 if (Subtarget->isAmdHsaOS()) 6498 return emitNonHSAIntrinsicError(DAG, DL, VT); 6499 6500 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6501 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6502 Align(4), false); 6503 case Intrinsic::r600_read_global_size_z: 6504 if (Subtarget->isAmdHsaOS()) 6505 return emitNonHSAIntrinsicError(DAG, DL, VT); 6506 6507 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6508 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6509 Align(4), false); 6510 case Intrinsic::r600_read_local_size_x: 6511 if (Subtarget->isAmdHsaOS()) 6512 return emitNonHSAIntrinsicError(DAG, DL, VT); 6513 6514 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6515 SI::KernelInputOffsets::LOCAL_SIZE_X); 6516 case Intrinsic::r600_read_local_size_y: 6517 if (Subtarget->isAmdHsaOS()) 6518 return emitNonHSAIntrinsicError(DAG, DL, VT); 6519 6520 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6521 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6522 case Intrinsic::r600_read_local_size_z: 6523 if (Subtarget->isAmdHsaOS()) 6524 return emitNonHSAIntrinsicError(DAG, DL, VT); 6525 6526 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6527 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6528 case Intrinsic::amdgcn_workgroup_id_x: 6529 return getPreloadedValue(DAG, *MFI, VT, 6530 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6531 case Intrinsic::amdgcn_workgroup_id_y: 6532 return getPreloadedValue(DAG, *MFI, VT, 6533 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6534 case Intrinsic::amdgcn_workgroup_id_z: 6535 return getPreloadedValue(DAG, *MFI, VT, 6536 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6537 case Intrinsic::amdgcn_workitem_id_x: 6538 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6539 SDLoc(DAG.getEntryNode()), 6540 MFI->getArgInfo().WorkItemIDX); 6541 case Intrinsic::amdgcn_workitem_id_y: 6542 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6543 SDLoc(DAG.getEntryNode()), 6544 MFI->getArgInfo().WorkItemIDY); 6545 case Intrinsic::amdgcn_workitem_id_z: 6546 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6547 SDLoc(DAG.getEntryNode()), 6548 MFI->getArgInfo().WorkItemIDZ); 6549 case Intrinsic::amdgcn_wavefrontsize: 6550 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6551 SDLoc(Op), MVT::i32); 6552 case Intrinsic::amdgcn_s_buffer_load: { 6553 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6554 SDValue GLC; 6555 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6556 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6557 IsGFX10 ? &DLC : nullptr)) 6558 return Op; 6559 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6560 DAG); 6561 } 6562 case Intrinsic::amdgcn_fdiv_fast: 6563 return lowerFDIV_FAST(Op, DAG); 6564 case Intrinsic::amdgcn_sin: 6565 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6566 6567 case Intrinsic::amdgcn_cos: 6568 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6569 6570 case Intrinsic::amdgcn_mul_u24: 6571 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6572 case Intrinsic::amdgcn_mul_i24: 6573 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6574 6575 case Intrinsic::amdgcn_log_clamp: { 6576 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6577 return SDValue(); 6578 6579 DiagnosticInfoUnsupported BadIntrin( 6580 MF.getFunction(), "intrinsic not supported on subtarget", 6581 DL.getDebugLoc()); 6582 DAG.getContext()->diagnose(BadIntrin); 6583 return DAG.getUNDEF(VT); 6584 } 6585 case Intrinsic::amdgcn_ldexp: 6586 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6587 Op.getOperand(1), Op.getOperand(2)); 6588 6589 case Intrinsic::amdgcn_fract: 6590 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6591 6592 case Intrinsic::amdgcn_class: 6593 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6594 Op.getOperand(1), Op.getOperand(2)); 6595 case Intrinsic::amdgcn_div_fmas: 6596 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6597 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6598 Op.getOperand(4)); 6599 6600 case Intrinsic::amdgcn_div_fixup: 6601 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6602 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6603 6604 case Intrinsic::amdgcn_div_scale: { 6605 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6606 6607 // Translate to the operands expected by the machine instruction. The 6608 // first parameter must be the same as the first instruction. 6609 SDValue Numerator = Op.getOperand(1); 6610 SDValue Denominator = Op.getOperand(2); 6611 6612 // Note this order is opposite of the machine instruction's operations, 6613 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6614 // intrinsic has the numerator as the first operand to match a normal 6615 // division operation. 6616 6617 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6618 6619 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6620 Denominator, Numerator); 6621 } 6622 case Intrinsic::amdgcn_icmp: { 6623 // There is a Pat that handles this variant, so return it as-is. 6624 if (Op.getOperand(1).getValueType() == MVT::i1 && 6625 Op.getConstantOperandVal(2) == 0 && 6626 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6627 return Op; 6628 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6629 } 6630 case Intrinsic::amdgcn_fcmp: { 6631 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6632 } 6633 case Intrinsic::amdgcn_ballot: 6634 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6635 case Intrinsic::amdgcn_fmed3: 6636 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6637 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6638 case Intrinsic::amdgcn_fdot2: 6639 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6640 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6641 Op.getOperand(4)); 6642 case Intrinsic::amdgcn_fmul_legacy: 6643 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6644 Op.getOperand(1), Op.getOperand(2)); 6645 case Intrinsic::amdgcn_sffbh: 6646 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6647 case Intrinsic::amdgcn_sbfe: 6648 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6649 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6650 case Intrinsic::amdgcn_ubfe: 6651 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6652 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6653 case Intrinsic::amdgcn_cvt_pkrtz: 6654 case Intrinsic::amdgcn_cvt_pknorm_i16: 6655 case Intrinsic::amdgcn_cvt_pknorm_u16: 6656 case Intrinsic::amdgcn_cvt_pk_i16: 6657 case Intrinsic::amdgcn_cvt_pk_u16: { 6658 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6659 EVT VT = Op.getValueType(); 6660 unsigned Opcode; 6661 6662 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6663 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6664 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6665 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6666 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6667 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6668 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6669 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6670 else 6671 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6672 6673 if (isTypeLegal(VT)) 6674 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6675 6676 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6677 Op.getOperand(1), Op.getOperand(2)); 6678 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6679 } 6680 case Intrinsic::amdgcn_fmad_ftz: 6681 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6682 Op.getOperand(2), Op.getOperand(3)); 6683 6684 case Intrinsic::amdgcn_if_break: 6685 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6686 Op->getOperand(1), Op->getOperand(2)), 0); 6687 6688 case Intrinsic::amdgcn_groupstaticsize: { 6689 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6690 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6691 return Op; 6692 6693 const Module *M = MF.getFunction().getParent(); 6694 const GlobalValue *GV = 6695 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6696 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6697 SIInstrInfo::MO_ABS32_LO); 6698 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6699 } 6700 case Intrinsic::amdgcn_is_shared: 6701 case Intrinsic::amdgcn_is_private: { 6702 SDLoc SL(Op); 6703 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6704 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6705 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6706 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6707 Op.getOperand(1)); 6708 6709 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6710 DAG.getConstant(1, SL, MVT::i32)); 6711 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6712 } 6713 case Intrinsic::amdgcn_alignbit: 6714 return DAG.getNode(ISD::FSHR, DL, VT, 6715 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6716 case Intrinsic::amdgcn_reloc_constant: { 6717 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6718 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6719 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6720 auto RelocSymbol = cast<GlobalVariable>( 6721 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6722 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6723 SIInstrInfo::MO_ABS32_LO); 6724 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6725 } 6726 default: 6727 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6728 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6729 return lowerImage(Op, ImageDimIntr, DAG, false); 6730 6731 return Op; 6732 } 6733 } 6734 6735 // This function computes an appropriate offset to pass to 6736 // MachineMemOperand::setOffset() based on the offset inputs to 6737 // an intrinsic. If any of the offsets are non-contstant or 6738 // if VIndex is non-zero then this function returns 0. Otherwise, 6739 // it returns the sum of VOffset, SOffset, and Offset. 6740 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6741 SDValue SOffset, 6742 SDValue Offset, 6743 SDValue VIndex = SDValue()) { 6744 6745 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6746 !isa<ConstantSDNode>(Offset)) 6747 return 0; 6748 6749 if (VIndex) { 6750 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6751 return 0; 6752 } 6753 6754 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6755 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6756 cast<ConstantSDNode>(Offset)->getSExtValue(); 6757 } 6758 6759 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6760 SelectionDAG &DAG, 6761 unsigned NewOpcode) const { 6762 SDLoc DL(Op); 6763 6764 SDValue VData = Op.getOperand(2); 6765 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6766 SDValue Ops[] = { 6767 Op.getOperand(0), // Chain 6768 VData, // vdata 6769 Op.getOperand(3), // rsrc 6770 DAG.getConstant(0, DL, MVT::i32), // vindex 6771 Offsets.first, // voffset 6772 Op.getOperand(5), // soffset 6773 Offsets.second, // offset 6774 Op.getOperand(6), // cachepolicy 6775 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6776 }; 6777 6778 auto *M = cast<MemSDNode>(Op); 6779 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6780 6781 EVT MemVT = VData.getValueType(); 6782 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6783 M->getMemOperand()); 6784 } 6785 6786 SDValue 6787 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6788 unsigned NewOpcode) const { 6789 SDLoc DL(Op); 6790 6791 SDValue VData = Op.getOperand(2); 6792 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6793 SDValue Ops[] = { 6794 Op.getOperand(0), // Chain 6795 VData, // vdata 6796 Op.getOperand(3), // rsrc 6797 Op.getOperand(4), // vindex 6798 Offsets.first, // voffset 6799 Op.getOperand(6), // soffset 6800 Offsets.second, // offset 6801 Op.getOperand(7), // cachepolicy 6802 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6803 }; 6804 6805 auto *M = cast<MemSDNode>(Op); 6806 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6807 Ops[3])); 6808 6809 EVT MemVT = VData.getValueType(); 6810 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6811 M->getMemOperand()); 6812 } 6813 6814 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6815 SelectionDAG &DAG) const { 6816 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6817 SDLoc DL(Op); 6818 6819 switch (IntrID) { 6820 case Intrinsic::amdgcn_ds_ordered_add: 6821 case Intrinsic::amdgcn_ds_ordered_swap: { 6822 MemSDNode *M = cast<MemSDNode>(Op); 6823 SDValue Chain = M->getOperand(0); 6824 SDValue M0 = M->getOperand(2); 6825 SDValue Value = M->getOperand(3); 6826 unsigned IndexOperand = M->getConstantOperandVal(7); 6827 unsigned WaveRelease = M->getConstantOperandVal(8); 6828 unsigned WaveDone = M->getConstantOperandVal(9); 6829 6830 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6831 IndexOperand &= ~0x3f; 6832 unsigned CountDw = 0; 6833 6834 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6835 CountDw = (IndexOperand >> 24) & 0xf; 6836 IndexOperand &= ~(0xf << 24); 6837 6838 if (CountDw < 1 || CountDw > 4) { 6839 report_fatal_error( 6840 "ds_ordered_count: dword count must be between 1 and 4"); 6841 } 6842 } 6843 6844 if (IndexOperand) 6845 report_fatal_error("ds_ordered_count: bad index operand"); 6846 6847 if (WaveDone && !WaveRelease) 6848 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6849 6850 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6851 unsigned ShaderType = 6852 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6853 unsigned Offset0 = OrderedCountIndex << 2; 6854 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6855 (Instruction << 4); 6856 6857 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6858 Offset1 |= (CountDw - 1) << 6; 6859 6860 unsigned Offset = Offset0 | (Offset1 << 8); 6861 6862 SDValue Ops[] = { 6863 Chain, 6864 Value, 6865 DAG.getTargetConstant(Offset, DL, MVT::i16), 6866 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6867 }; 6868 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6869 M->getVTList(), Ops, M->getMemoryVT(), 6870 M->getMemOperand()); 6871 } 6872 case Intrinsic::amdgcn_ds_fadd: { 6873 MemSDNode *M = cast<MemSDNode>(Op); 6874 unsigned Opc; 6875 switch (IntrID) { 6876 case Intrinsic::amdgcn_ds_fadd: 6877 Opc = ISD::ATOMIC_LOAD_FADD; 6878 break; 6879 } 6880 6881 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6882 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6883 M->getMemOperand()); 6884 } 6885 case Intrinsic::amdgcn_atomic_inc: 6886 case Intrinsic::amdgcn_atomic_dec: 6887 case Intrinsic::amdgcn_ds_fmin: 6888 case Intrinsic::amdgcn_ds_fmax: { 6889 MemSDNode *M = cast<MemSDNode>(Op); 6890 unsigned Opc; 6891 switch (IntrID) { 6892 case Intrinsic::amdgcn_atomic_inc: 6893 Opc = AMDGPUISD::ATOMIC_INC; 6894 break; 6895 case Intrinsic::amdgcn_atomic_dec: 6896 Opc = AMDGPUISD::ATOMIC_DEC; 6897 break; 6898 case Intrinsic::amdgcn_ds_fmin: 6899 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6900 break; 6901 case Intrinsic::amdgcn_ds_fmax: 6902 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6903 break; 6904 default: 6905 llvm_unreachable("Unknown intrinsic!"); 6906 } 6907 SDValue Ops[] = { 6908 M->getOperand(0), // Chain 6909 M->getOperand(2), // Ptr 6910 M->getOperand(3) // Value 6911 }; 6912 6913 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6914 M->getMemoryVT(), M->getMemOperand()); 6915 } 6916 case Intrinsic::amdgcn_buffer_load: 6917 case Intrinsic::amdgcn_buffer_load_format: { 6918 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6919 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6920 unsigned IdxEn = 1; 6921 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6922 IdxEn = Idx->getZExtValue() != 0; 6923 SDValue Ops[] = { 6924 Op.getOperand(0), // Chain 6925 Op.getOperand(2), // rsrc 6926 Op.getOperand(3), // vindex 6927 SDValue(), // voffset -- will be set by setBufferOffsets 6928 SDValue(), // soffset -- will be set by setBufferOffsets 6929 SDValue(), // offset -- will be set by setBufferOffsets 6930 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6931 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6932 }; 6933 6934 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6935 // We don't know the offset if vindex is non-zero, so clear it. 6936 if (IdxEn) 6937 Offset = 0; 6938 6939 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6940 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6941 6942 EVT VT = Op.getValueType(); 6943 EVT IntVT = VT.changeTypeToInteger(); 6944 auto *M = cast<MemSDNode>(Op); 6945 M->getMemOperand()->setOffset(Offset); 6946 EVT LoadVT = Op.getValueType(); 6947 6948 if (LoadVT.getScalarType() == MVT::f16) 6949 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6950 M, DAG, Ops); 6951 6952 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6953 if (LoadVT.getScalarType() == MVT::i8 || 6954 LoadVT.getScalarType() == MVT::i16) 6955 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6956 6957 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6958 M->getMemOperand(), DAG); 6959 } 6960 case Intrinsic::amdgcn_raw_buffer_load: 6961 case Intrinsic::amdgcn_raw_buffer_load_format: { 6962 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6963 6964 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6965 SDValue Ops[] = { 6966 Op.getOperand(0), // Chain 6967 Op.getOperand(2), // rsrc 6968 DAG.getConstant(0, DL, MVT::i32), // vindex 6969 Offsets.first, // voffset 6970 Op.getOperand(4), // soffset 6971 Offsets.second, // offset 6972 Op.getOperand(5), // cachepolicy, swizzled buffer 6973 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6974 }; 6975 6976 auto *M = cast<MemSDNode>(Op); 6977 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6978 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6979 } 6980 case Intrinsic::amdgcn_struct_buffer_load: 6981 case Intrinsic::amdgcn_struct_buffer_load_format: { 6982 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6983 6984 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6985 SDValue Ops[] = { 6986 Op.getOperand(0), // Chain 6987 Op.getOperand(2), // rsrc 6988 Op.getOperand(3), // vindex 6989 Offsets.first, // voffset 6990 Op.getOperand(5), // soffset 6991 Offsets.second, // offset 6992 Op.getOperand(6), // cachepolicy, swizzled buffer 6993 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6994 }; 6995 6996 auto *M = cast<MemSDNode>(Op); 6997 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6998 Ops[2])); 6999 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7000 } 7001 case Intrinsic::amdgcn_tbuffer_load: { 7002 MemSDNode *M = cast<MemSDNode>(Op); 7003 EVT LoadVT = Op.getValueType(); 7004 7005 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7006 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7007 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7008 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7009 unsigned IdxEn = 1; 7010 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 7011 IdxEn = Idx->getZExtValue() != 0; 7012 SDValue Ops[] = { 7013 Op.getOperand(0), // Chain 7014 Op.getOperand(2), // rsrc 7015 Op.getOperand(3), // vindex 7016 Op.getOperand(4), // voffset 7017 Op.getOperand(5), // soffset 7018 Op.getOperand(6), // offset 7019 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7020 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7021 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7022 }; 7023 7024 if (LoadVT.getScalarType() == MVT::f16) 7025 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7026 M, DAG, Ops); 7027 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7028 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7029 DAG); 7030 } 7031 case Intrinsic::amdgcn_raw_tbuffer_load: { 7032 MemSDNode *M = cast<MemSDNode>(Op); 7033 EVT LoadVT = Op.getValueType(); 7034 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7035 7036 SDValue Ops[] = { 7037 Op.getOperand(0), // Chain 7038 Op.getOperand(2), // rsrc 7039 DAG.getConstant(0, DL, MVT::i32), // vindex 7040 Offsets.first, // voffset 7041 Op.getOperand(4), // soffset 7042 Offsets.second, // offset 7043 Op.getOperand(5), // format 7044 Op.getOperand(6), // cachepolicy, swizzled buffer 7045 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7046 }; 7047 7048 if (LoadVT.getScalarType() == MVT::f16) 7049 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7050 M, DAG, Ops); 7051 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7052 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7053 DAG); 7054 } 7055 case Intrinsic::amdgcn_struct_tbuffer_load: { 7056 MemSDNode *M = cast<MemSDNode>(Op); 7057 EVT LoadVT = Op.getValueType(); 7058 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7059 7060 SDValue Ops[] = { 7061 Op.getOperand(0), // Chain 7062 Op.getOperand(2), // rsrc 7063 Op.getOperand(3), // vindex 7064 Offsets.first, // voffset 7065 Op.getOperand(5), // soffset 7066 Offsets.second, // offset 7067 Op.getOperand(6), // format 7068 Op.getOperand(7), // cachepolicy, swizzled buffer 7069 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7070 }; 7071 7072 if (LoadVT.getScalarType() == MVT::f16) 7073 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7074 M, DAG, Ops); 7075 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7076 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7077 DAG); 7078 } 7079 case Intrinsic::amdgcn_buffer_atomic_swap: 7080 case Intrinsic::amdgcn_buffer_atomic_add: 7081 case Intrinsic::amdgcn_buffer_atomic_sub: 7082 case Intrinsic::amdgcn_buffer_atomic_csub: 7083 case Intrinsic::amdgcn_buffer_atomic_smin: 7084 case Intrinsic::amdgcn_buffer_atomic_umin: 7085 case Intrinsic::amdgcn_buffer_atomic_smax: 7086 case Intrinsic::amdgcn_buffer_atomic_umax: 7087 case Intrinsic::amdgcn_buffer_atomic_and: 7088 case Intrinsic::amdgcn_buffer_atomic_or: 7089 case Intrinsic::amdgcn_buffer_atomic_xor: 7090 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7091 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7092 unsigned IdxEn = 1; 7093 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7094 IdxEn = Idx->getZExtValue() != 0; 7095 SDValue Ops[] = { 7096 Op.getOperand(0), // Chain 7097 Op.getOperand(2), // vdata 7098 Op.getOperand(3), // rsrc 7099 Op.getOperand(4), // vindex 7100 SDValue(), // voffset -- will be set by setBufferOffsets 7101 SDValue(), // soffset -- will be set by setBufferOffsets 7102 SDValue(), // offset -- will be set by setBufferOffsets 7103 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7104 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7105 }; 7106 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7107 // We don't know the offset if vindex is non-zero, so clear it. 7108 if (IdxEn) 7109 Offset = 0; 7110 EVT VT = Op.getValueType(); 7111 7112 auto *M = cast<MemSDNode>(Op); 7113 M->getMemOperand()->setOffset(Offset); 7114 unsigned Opcode = 0; 7115 7116 switch (IntrID) { 7117 case Intrinsic::amdgcn_buffer_atomic_swap: 7118 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7119 break; 7120 case Intrinsic::amdgcn_buffer_atomic_add: 7121 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7122 break; 7123 case Intrinsic::amdgcn_buffer_atomic_sub: 7124 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7125 break; 7126 case Intrinsic::amdgcn_buffer_atomic_csub: 7127 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7128 break; 7129 case Intrinsic::amdgcn_buffer_atomic_smin: 7130 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7131 break; 7132 case Intrinsic::amdgcn_buffer_atomic_umin: 7133 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7134 break; 7135 case Intrinsic::amdgcn_buffer_atomic_smax: 7136 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7137 break; 7138 case Intrinsic::amdgcn_buffer_atomic_umax: 7139 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7140 break; 7141 case Intrinsic::amdgcn_buffer_atomic_and: 7142 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7143 break; 7144 case Intrinsic::amdgcn_buffer_atomic_or: 7145 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7146 break; 7147 case Intrinsic::amdgcn_buffer_atomic_xor: 7148 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7149 break; 7150 case Intrinsic::amdgcn_buffer_atomic_fadd: 7151 if (!Op.getValue(0).use_empty()) { 7152 DiagnosticInfoUnsupported 7153 NoFpRet(DAG.getMachineFunction().getFunction(), 7154 "return versions of fp atomics not supported", 7155 DL.getDebugLoc(), DS_Error); 7156 DAG.getContext()->diagnose(NoFpRet); 7157 return SDValue(); 7158 } 7159 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7160 break; 7161 default: 7162 llvm_unreachable("unhandled atomic opcode"); 7163 } 7164 7165 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7166 M->getMemOperand()); 7167 } 7168 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7169 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7170 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7171 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7172 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7173 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7174 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7175 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7176 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7177 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7178 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7179 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7180 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7181 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7182 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7183 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7184 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7185 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7186 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7187 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7188 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7189 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7190 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7191 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7192 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7193 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7194 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7195 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7196 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7197 return lowerStructBufferAtomicIntrin(Op, DAG, 7198 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7199 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7200 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7201 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7202 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7203 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7204 return lowerStructBufferAtomicIntrin(Op, DAG, 7205 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7206 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7207 return lowerStructBufferAtomicIntrin(Op, DAG, 7208 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7209 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7210 return lowerStructBufferAtomicIntrin(Op, DAG, 7211 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7212 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7213 return lowerStructBufferAtomicIntrin(Op, DAG, 7214 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7215 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7216 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7217 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7218 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7219 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7220 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7221 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7222 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7223 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7224 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7225 7226 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7227 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7228 unsigned IdxEn = 1; 7229 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7230 IdxEn = Idx->getZExtValue() != 0; 7231 SDValue Ops[] = { 7232 Op.getOperand(0), // Chain 7233 Op.getOperand(2), // src 7234 Op.getOperand(3), // cmp 7235 Op.getOperand(4), // rsrc 7236 Op.getOperand(5), // vindex 7237 SDValue(), // voffset -- will be set by setBufferOffsets 7238 SDValue(), // soffset -- will be set by setBufferOffsets 7239 SDValue(), // offset -- will be set by setBufferOffsets 7240 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7241 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7242 }; 7243 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7244 // We don't know the offset if vindex is non-zero, so clear it. 7245 if (IdxEn) 7246 Offset = 0; 7247 EVT VT = Op.getValueType(); 7248 auto *M = cast<MemSDNode>(Op); 7249 M->getMemOperand()->setOffset(Offset); 7250 7251 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7252 Op->getVTList(), Ops, VT, M->getMemOperand()); 7253 } 7254 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7255 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7256 SDValue Ops[] = { 7257 Op.getOperand(0), // Chain 7258 Op.getOperand(2), // src 7259 Op.getOperand(3), // cmp 7260 Op.getOperand(4), // rsrc 7261 DAG.getConstant(0, DL, MVT::i32), // vindex 7262 Offsets.first, // voffset 7263 Op.getOperand(6), // soffset 7264 Offsets.second, // offset 7265 Op.getOperand(7), // cachepolicy 7266 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7267 }; 7268 EVT VT = Op.getValueType(); 7269 auto *M = cast<MemSDNode>(Op); 7270 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7271 7272 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7273 Op->getVTList(), Ops, VT, M->getMemOperand()); 7274 } 7275 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7276 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7277 SDValue Ops[] = { 7278 Op.getOperand(0), // Chain 7279 Op.getOperand(2), // src 7280 Op.getOperand(3), // cmp 7281 Op.getOperand(4), // rsrc 7282 Op.getOperand(5), // vindex 7283 Offsets.first, // voffset 7284 Op.getOperand(7), // soffset 7285 Offsets.second, // offset 7286 Op.getOperand(8), // cachepolicy 7287 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7288 }; 7289 EVT VT = Op.getValueType(); 7290 auto *M = cast<MemSDNode>(Op); 7291 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7292 Ops[4])); 7293 7294 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7295 Op->getVTList(), Ops, VT, M->getMemOperand()); 7296 } 7297 case Intrinsic::amdgcn_global_atomic_fadd: { 7298 if (!Op.getValue(0).use_empty()) { 7299 DiagnosticInfoUnsupported 7300 NoFpRet(DAG.getMachineFunction().getFunction(), 7301 "return versions of fp atomics not supported", 7302 DL.getDebugLoc(), DS_Error); 7303 DAG.getContext()->diagnose(NoFpRet); 7304 return SDValue(); 7305 } 7306 MemSDNode *M = cast<MemSDNode>(Op); 7307 SDValue Ops[] = { 7308 M->getOperand(0), // Chain 7309 M->getOperand(2), // Ptr 7310 M->getOperand(3) // Value 7311 }; 7312 7313 EVT VT = Op.getOperand(3).getValueType(); 7314 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7315 DAG.getVTList(VT, MVT::Other), Ops, 7316 M->getMemOperand()); 7317 } 7318 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7319 SDLoc DL(Op); 7320 MemSDNode *M = cast<MemSDNode>(Op); 7321 SDValue NodePtr = M->getOperand(2); 7322 SDValue RayExtent = M->getOperand(3); 7323 SDValue RayOrigin = M->getOperand(4); 7324 SDValue RayDir = M->getOperand(5); 7325 SDValue RayInvDir = M->getOperand(6); 7326 SDValue TDescr = M->getOperand(7); 7327 7328 assert(NodePtr.getValueType() == MVT::i32 || 7329 NodePtr.getValueType() == MVT::i64); 7330 assert(RayDir.getValueType() == MVT::v4f16 || 7331 RayDir.getValueType() == MVT::v4f32); 7332 7333 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7334 bool Is64 = NodePtr.getValueType() == MVT::i64; 7335 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7336 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7337 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7338 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7339 7340 SmallVector<SDValue, 16> Ops; 7341 7342 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7343 SmallVector<SDValue, 3> Lanes; 7344 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7345 if (Lanes[0].getValueSizeInBits() == 32) { 7346 for (unsigned I = 0; I < 3; ++I) 7347 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7348 } else { 7349 if (IsAligned) { 7350 Ops.push_back( 7351 DAG.getBitcast(MVT::i32, 7352 DAG.getBuildVector(MVT::v2f16, DL, 7353 { Lanes[0], Lanes[1] }))); 7354 Ops.push_back(Lanes[2]); 7355 } else { 7356 SDValue Elt0 = Ops.pop_back_val(); 7357 Ops.push_back( 7358 DAG.getBitcast(MVT::i32, 7359 DAG.getBuildVector(MVT::v2f16, DL, 7360 { Elt0, Lanes[0] }))); 7361 Ops.push_back( 7362 DAG.getBitcast(MVT::i32, 7363 DAG.getBuildVector(MVT::v2f16, DL, 7364 { Lanes[1], Lanes[2] }))); 7365 } 7366 } 7367 }; 7368 7369 if (Is64) 7370 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7371 else 7372 Ops.push_back(NodePtr); 7373 7374 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7375 packLanes(RayOrigin, true); 7376 packLanes(RayDir, true); 7377 packLanes(RayInvDir, false); 7378 Ops.push_back(TDescr); 7379 if (IsA16) 7380 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7381 Ops.push_back(M->getChain()); 7382 7383 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7384 MachineMemOperand *MemRef = M->getMemOperand(); 7385 DAG.setNodeMemRefs(NewNode, {MemRef}); 7386 return SDValue(NewNode, 0); 7387 } 7388 default: 7389 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7390 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7391 return lowerImage(Op, ImageDimIntr, DAG, true); 7392 7393 return SDValue(); 7394 } 7395 } 7396 7397 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7398 // dwordx4 if on SI. 7399 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7400 SDVTList VTList, 7401 ArrayRef<SDValue> Ops, EVT MemVT, 7402 MachineMemOperand *MMO, 7403 SelectionDAG &DAG) const { 7404 EVT VT = VTList.VTs[0]; 7405 EVT WidenedVT = VT; 7406 EVT WidenedMemVT = MemVT; 7407 if (!Subtarget->hasDwordx3LoadStores() && 7408 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7409 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7410 WidenedVT.getVectorElementType(), 4); 7411 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7412 WidenedMemVT.getVectorElementType(), 4); 7413 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7414 } 7415 7416 assert(VTList.NumVTs == 2); 7417 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7418 7419 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7420 WidenedMemVT, MMO); 7421 if (WidenedVT != VT) { 7422 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7423 DAG.getVectorIdxConstant(0, DL)); 7424 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7425 } 7426 return NewOp; 7427 } 7428 7429 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7430 bool ImageStore) const { 7431 EVT StoreVT = VData.getValueType(); 7432 7433 // No change for f16 and legal vector D16 types. 7434 if (!StoreVT.isVector()) 7435 return VData; 7436 7437 SDLoc DL(VData); 7438 unsigned NumElements = StoreVT.getVectorNumElements(); 7439 7440 if (Subtarget->hasUnpackedD16VMem()) { 7441 // We need to unpack the packed data to store. 7442 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7443 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7444 7445 EVT EquivStoreVT = 7446 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7447 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7448 return DAG.UnrollVectorOp(ZExt.getNode()); 7449 } else if (NumElements == 3) { 7450 EVT IntStoreVT = 7451 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7452 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7453 7454 EVT WidenedStoreVT = EVT::getVectorVT( 7455 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7456 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7457 WidenedStoreVT.getStoreSizeInBits()); 7458 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7459 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7460 } 7461 7462 // The sq block of gfx8.1 does not estimate register use correctly for d16 7463 // image store instructions. The data operand is computed as if it were not a 7464 // d16 image instruction. 7465 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7466 // Bitcast to i16 7467 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7468 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7469 7470 // Decompose into scalars 7471 SmallVector<SDValue, 4> Elts; 7472 DAG.ExtractVectorElements(IntVData, Elts); 7473 7474 // Group pairs of i16 into v2i16 and bitcast to i32 7475 SmallVector<SDValue, 4> PackedElts; 7476 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7477 SDValue Pair = 7478 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7479 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7480 PackedElts.push_back(IntPair); 7481 } 7482 7483 // Pad using UNDEF 7484 PackedElts.resize(PackedElts.size() * 2, DAG.getUNDEF(MVT::i32)); 7485 7486 // Build final vector 7487 EVT VecVT = 7488 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7489 return DAG.getBuildVector(VecVT, DL, PackedElts); 7490 } 7491 7492 assert(isTypeLegal(StoreVT)); 7493 return VData; 7494 } 7495 7496 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7497 SelectionDAG &DAG) const { 7498 SDLoc DL(Op); 7499 SDValue Chain = Op.getOperand(0); 7500 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7501 MachineFunction &MF = DAG.getMachineFunction(); 7502 7503 switch (IntrinsicID) { 7504 case Intrinsic::amdgcn_exp_compr: { 7505 SDValue Src0 = Op.getOperand(4); 7506 SDValue Src1 = Op.getOperand(5); 7507 // Hack around illegal type on SI by directly selecting it. 7508 if (isTypeLegal(Src0.getValueType())) 7509 return SDValue(); 7510 7511 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7512 SDValue Undef = DAG.getUNDEF(MVT::f32); 7513 const SDValue Ops[] = { 7514 Op.getOperand(2), // tgt 7515 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7516 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7517 Undef, // src2 7518 Undef, // src3 7519 Op.getOperand(7), // vm 7520 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7521 Op.getOperand(3), // en 7522 Op.getOperand(0) // Chain 7523 }; 7524 7525 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7526 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7527 } 7528 case Intrinsic::amdgcn_s_barrier: { 7529 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7530 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7531 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7532 if (WGSize <= ST.getWavefrontSize()) 7533 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7534 Op.getOperand(0)), 0); 7535 } 7536 return SDValue(); 7537 }; 7538 case Intrinsic::amdgcn_tbuffer_store: { 7539 SDValue VData = Op.getOperand(2); 7540 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7541 if (IsD16) 7542 VData = handleD16VData(VData, DAG); 7543 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7544 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7545 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7546 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7547 unsigned IdxEn = 1; 7548 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7549 IdxEn = Idx->getZExtValue() != 0; 7550 SDValue Ops[] = { 7551 Chain, 7552 VData, // vdata 7553 Op.getOperand(3), // rsrc 7554 Op.getOperand(4), // vindex 7555 Op.getOperand(5), // voffset 7556 Op.getOperand(6), // soffset 7557 Op.getOperand(7), // offset 7558 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7559 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7560 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7561 }; 7562 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7563 AMDGPUISD::TBUFFER_STORE_FORMAT; 7564 MemSDNode *M = cast<MemSDNode>(Op); 7565 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7566 M->getMemoryVT(), M->getMemOperand()); 7567 } 7568 7569 case Intrinsic::amdgcn_struct_tbuffer_store: { 7570 SDValue VData = Op.getOperand(2); 7571 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7572 if (IsD16) 7573 VData = handleD16VData(VData, DAG); 7574 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7575 SDValue Ops[] = { 7576 Chain, 7577 VData, // vdata 7578 Op.getOperand(3), // rsrc 7579 Op.getOperand(4), // vindex 7580 Offsets.first, // voffset 7581 Op.getOperand(6), // soffset 7582 Offsets.second, // offset 7583 Op.getOperand(7), // format 7584 Op.getOperand(8), // cachepolicy, swizzled buffer 7585 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7586 }; 7587 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7588 AMDGPUISD::TBUFFER_STORE_FORMAT; 7589 MemSDNode *M = cast<MemSDNode>(Op); 7590 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7591 M->getMemoryVT(), M->getMemOperand()); 7592 } 7593 7594 case Intrinsic::amdgcn_raw_tbuffer_store: { 7595 SDValue VData = Op.getOperand(2); 7596 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7597 if (IsD16) 7598 VData = handleD16VData(VData, DAG); 7599 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7600 SDValue Ops[] = { 7601 Chain, 7602 VData, // vdata 7603 Op.getOperand(3), // rsrc 7604 DAG.getConstant(0, DL, MVT::i32), // vindex 7605 Offsets.first, // voffset 7606 Op.getOperand(5), // soffset 7607 Offsets.second, // offset 7608 Op.getOperand(6), // format 7609 Op.getOperand(7), // cachepolicy, swizzled buffer 7610 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7611 }; 7612 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7613 AMDGPUISD::TBUFFER_STORE_FORMAT; 7614 MemSDNode *M = cast<MemSDNode>(Op); 7615 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7616 M->getMemoryVT(), M->getMemOperand()); 7617 } 7618 7619 case Intrinsic::amdgcn_buffer_store: 7620 case Intrinsic::amdgcn_buffer_store_format: { 7621 SDValue VData = Op.getOperand(2); 7622 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7623 if (IsD16) 7624 VData = handleD16VData(VData, DAG); 7625 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7626 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7627 unsigned IdxEn = 1; 7628 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7629 IdxEn = Idx->getZExtValue() != 0; 7630 SDValue Ops[] = { 7631 Chain, 7632 VData, 7633 Op.getOperand(3), // rsrc 7634 Op.getOperand(4), // vindex 7635 SDValue(), // voffset -- will be set by setBufferOffsets 7636 SDValue(), // soffset -- will be set by setBufferOffsets 7637 SDValue(), // offset -- will be set by setBufferOffsets 7638 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7639 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7640 }; 7641 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7642 // We don't know the offset if vindex is non-zero, so clear it. 7643 if (IdxEn) 7644 Offset = 0; 7645 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7646 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7647 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7648 MemSDNode *M = cast<MemSDNode>(Op); 7649 M->getMemOperand()->setOffset(Offset); 7650 7651 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7652 EVT VDataType = VData.getValueType().getScalarType(); 7653 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7654 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7655 7656 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7657 M->getMemoryVT(), M->getMemOperand()); 7658 } 7659 7660 case Intrinsic::amdgcn_raw_buffer_store: 7661 case Intrinsic::amdgcn_raw_buffer_store_format: { 7662 const bool IsFormat = 7663 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7664 7665 SDValue VData = Op.getOperand(2); 7666 EVT VDataVT = VData.getValueType(); 7667 EVT EltType = VDataVT.getScalarType(); 7668 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7669 if (IsD16) { 7670 VData = handleD16VData(VData, DAG); 7671 VDataVT = VData.getValueType(); 7672 } 7673 7674 if (!isTypeLegal(VDataVT)) { 7675 VData = 7676 DAG.getNode(ISD::BITCAST, DL, 7677 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7678 } 7679 7680 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7681 SDValue Ops[] = { 7682 Chain, 7683 VData, 7684 Op.getOperand(3), // rsrc 7685 DAG.getConstant(0, DL, MVT::i32), // vindex 7686 Offsets.first, // voffset 7687 Op.getOperand(5), // soffset 7688 Offsets.second, // offset 7689 Op.getOperand(6), // cachepolicy, swizzled buffer 7690 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7691 }; 7692 unsigned Opc = 7693 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7694 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7695 MemSDNode *M = cast<MemSDNode>(Op); 7696 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7697 7698 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7699 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7700 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7701 7702 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7703 M->getMemoryVT(), M->getMemOperand()); 7704 } 7705 7706 case Intrinsic::amdgcn_struct_buffer_store: 7707 case Intrinsic::amdgcn_struct_buffer_store_format: { 7708 const bool IsFormat = 7709 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7710 7711 SDValue VData = Op.getOperand(2); 7712 EVT VDataVT = VData.getValueType(); 7713 EVT EltType = VDataVT.getScalarType(); 7714 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7715 7716 if (IsD16) { 7717 VData = handleD16VData(VData, DAG); 7718 VDataVT = VData.getValueType(); 7719 } 7720 7721 if (!isTypeLegal(VDataVT)) { 7722 VData = 7723 DAG.getNode(ISD::BITCAST, DL, 7724 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7725 } 7726 7727 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7728 SDValue Ops[] = { 7729 Chain, 7730 VData, 7731 Op.getOperand(3), // rsrc 7732 Op.getOperand(4), // vindex 7733 Offsets.first, // voffset 7734 Op.getOperand(6), // soffset 7735 Offsets.second, // offset 7736 Op.getOperand(7), // cachepolicy, swizzled buffer 7737 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7738 }; 7739 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7740 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7741 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7742 MemSDNode *M = cast<MemSDNode>(Op); 7743 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7744 Ops[3])); 7745 7746 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7747 EVT VDataType = VData.getValueType().getScalarType(); 7748 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7749 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7750 7751 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7752 M->getMemoryVT(), M->getMemOperand()); 7753 } 7754 case Intrinsic::amdgcn_end_cf: 7755 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7756 Op->getOperand(2), Chain), 0); 7757 7758 default: { 7759 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7760 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7761 return lowerImage(Op, ImageDimIntr, DAG, true); 7762 7763 return Op; 7764 } 7765 } 7766 } 7767 7768 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7769 // offset (the offset that is included in bounds checking and swizzling, to be 7770 // split between the instruction's voffset and immoffset fields) and soffset 7771 // (the offset that is excluded from bounds checking and swizzling, to go in 7772 // the instruction's soffset field). This function takes the first kind of 7773 // offset and figures out how to split it between voffset and immoffset. 7774 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7775 SDValue Offset, SelectionDAG &DAG) const { 7776 SDLoc DL(Offset); 7777 const unsigned MaxImm = 4095; 7778 SDValue N0 = Offset; 7779 ConstantSDNode *C1 = nullptr; 7780 7781 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7782 N0 = SDValue(); 7783 else if (DAG.isBaseWithConstantOffset(N0)) { 7784 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7785 N0 = N0.getOperand(0); 7786 } 7787 7788 if (C1) { 7789 unsigned ImmOffset = C1->getZExtValue(); 7790 // If the immediate value is too big for the immoffset field, put the value 7791 // and -4096 into the immoffset field so that the value that is copied/added 7792 // for the voffset field is a multiple of 4096, and it stands more chance 7793 // of being CSEd with the copy/add for another similar load/store. 7794 // However, do not do that rounding down to a multiple of 4096 if that is a 7795 // negative number, as it appears to be illegal to have a negative offset 7796 // in the vgpr, even if adding the immediate offset makes it positive. 7797 unsigned Overflow = ImmOffset & ~MaxImm; 7798 ImmOffset -= Overflow; 7799 if ((int32_t)Overflow < 0) { 7800 Overflow += ImmOffset; 7801 ImmOffset = 0; 7802 } 7803 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7804 if (Overflow) { 7805 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7806 if (!N0) 7807 N0 = OverflowVal; 7808 else { 7809 SDValue Ops[] = { N0, OverflowVal }; 7810 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7811 } 7812 } 7813 } 7814 if (!N0) 7815 N0 = DAG.getConstant(0, DL, MVT::i32); 7816 if (!C1) 7817 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7818 return {N0, SDValue(C1, 0)}; 7819 } 7820 7821 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7822 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7823 // pointed to by Offsets. 7824 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7825 SelectionDAG &DAG, SDValue *Offsets, 7826 Align Alignment) const { 7827 SDLoc DL(CombinedOffset); 7828 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7829 uint32_t Imm = C->getZExtValue(); 7830 uint32_t SOffset, ImmOffset; 7831 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7832 Alignment)) { 7833 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7834 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7835 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7836 return SOffset + ImmOffset; 7837 } 7838 } 7839 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7840 SDValue N0 = CombinedOffset.getOperand(0); 7841 SDValue N1 = CombinedOffset.getOperand(1); 7842 uint32_t SOffset, ImmOffset; 7843 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7844 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7845 Subtarget, Alignment)) { 7846 Offsets[0] = N0; 7847 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7848 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7849 return 0; 7850 } 7851 } 7852 Offsets[0] = CombinedOffset; 7853 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7854 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7855 return 0; 7856 } 7857 7858 // Handle 8 bit and 16 bit buffer loads 7859 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7860 EVT LoadVT, SDLoc DL, 7861 ArrayRef<SDValue> Ops, 7862 MemSDNode *M) const { 7863 EVT IntVT = LoadVT.changeTypeToInteger(); 7864 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7865 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7866 7867 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7868 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7869 Ops, IntVT, 7870 M->getMemOperand()); 7871 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7872 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7873 7874 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7875 } 7876 7877 // Handle 8 bit and 16 bit buffer stores 7878 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7879 EVT VDataType, SDLoc DL, 7880 SDValue Ops[], 7881 MemSDNode *M) const { 7882 if (VDataType == MVT::f16) 7883 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7884 7885 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7886 Ops[1] = BufferStoreExt; 7887 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7888 AMDGPUISD::BUFFER_STORE_SHORT; 7889 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7890 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7891 M->getMemOperand()); 7892 } 7893 7894 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7895 ISD::LoadExtType ExtType, SDValue Op, 7896 const SDLoc &SL, EVT VT) { 7897 if (VT.bitsLT(Op.getValueType())) 7898 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7899 7900 switch (ExtType) { 7901 case ISD::SEXTLOAD: 7902 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7903 case ISD::ZEXTLOAD: 7904 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7905 case ISD::EXTLOAD: 7906 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7907 case ISD::NON_EXTLOAD: 7908 return Op; 7909 } 7910 7911 llvm_unreachable("invalid ext type"); 7912 } 7913 7914 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7915 SelectionDAG &DAG = DCI.DAG; 7916 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7917 return SDValue(); 7918 7919 // FIXME: Constant loads should all be marked invariant. 7920 unsigned AS = Ld->getAddressSpace(); 7921 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7922 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7923 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7924 return SDValue(); 7925 7926 // Don't do this early, since it may interfere with adjacent load merging for 7927 // illegal types. We can avoid losing alignment information for exotic types 7928 // pre-legalize. 7929 EVT MemVT = Ld->getMemoryVT(); 7930 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7931 MemVT.getSizeInBits() >= 32) 7932 return SDValue(); 7933 7934 SDLoc SL(Ld); 7935 7936 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7937 "unexpected vector extload"); 7938 7939 // TODO: Drop only high part of range. 7940 SDValue Ptr = Ld->getBasePtr(); 7941 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7942 MVT::i32, SL, Ld->getChain(), Ptr, 7943 Ld->getOffset(), 7944 Ld->getPointerInfo(), MVT::i32, 7945 Ld->getAlignment(), 7946 Ld->getMemOperand()->getFlags(), 7947 Ld->getAAInfo(), 7948 nullptr); // Drop ranges 7949 7950 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7951 if (MemVT.isFloatingPoint()) { 7952 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7953 "unexpected fp extload"); 7954 TruncVT = MemVT.changeTypeToInteger(); 7955 } 7956 7957 SDValue Cvt = NewLoad; 7958 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7959 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7960 DAG.getValueType(TruncVT)); 7961 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7962 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7963 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7964 } else { 7965 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7966 } 7967 7968 EVT VT = Ld->getValueType(0); 7969 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7970 7971 DCI.AddToWorklist(Cvt.getNode()); 7972 7973 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7974 // the appropriate extension from the 32-bit load. 7975 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7976 DCI.AddToWorklist(Cvt.getNode()); 7977 7978 // Handle conversion back to floating point if necessary. 7979 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7980 7981 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7982 } 7983 7984 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7985 SDLoc DL(Op); 7986 LoadSDNode *Load = cast<LoadSDNode>(Op); 7987 ISD::LoadExtType ExtType = Load->getExtensionType(); 7988 EVT MemVT = Load->getMemoryVT(); 7989 7990 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7991 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7992 return SDValue(); 7993 7994 // FIXME: Copied from PPC 7995 // First, load into 32 bits, then truncate to 1 bit. 7996 7997 SDValue Chain = Load->getChain(); 7998 SDValue BasePtr = Load->getBasePtr(); 7999 MachineMemOperand *MMO = Load->getMemOperand(); 8000 8001 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8002 8003 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8004 BasePtr, RealMemVT, MMO); 8005 8006 if (!MemVT.isVector()) { 8007 SDValue Ops[] = { 8008 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8009 NewLD.getValue(1) 8010 }; 8011 8012 return DAG.getMergeValues(Ops, DL); 8013 } 8014 8015 SmallVector<SDValue, 3> Elts; 8016 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8017 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8018 DAG.getConstant(I, DL, MVT::i32)); 8019 8020 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8021 } 8022 8023 SDValue Ops[] = { 8024 DAG.getBuildVector(MemVT, DL, Elts), 8025 NewLD.getValue(1) 8026 }; 8027 8028 return DAG.getMergeValues(Ops, DL); 8029 } 8030 8031 if (!MemVT.isVector()) 8032 return SDValue(); 8033 8034 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8035 "Custom lowering for non-i32 vectors hasn't been implemented."); 8036 8037 unsigned Alignment = Load->getAlignment(); 8038 unsigned AS = Load->getAddressSpace(); 8039 if (Subtarget->hasLDSMisalignedBug() && 8040 AS == AMDGPUAS::FLAT_ADDRESS && 8041 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8042 return SplitVectorLoad(Op, DAG); 8043 } 8044 8045 MachineFunction &MF = DAG.getMachineFunction(); 8046 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8047 // If there is a possibilty that flat instruction access scratch memory 8048 // then we need to use the same legalization rules we use for private. 8049 if (AS == AMDGPUAS::FLAT_ADDRESS && 8050 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8051 AS = MFI->hasFlatScratchInit() ? 8052 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8053 8054 unsigned NumElements = MemVT.getVectorNumElements(); 8055 8056 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8057 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8058 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8059 if (MemVT.isPow2VectorType()) 8060 return SDValue(); 8061 return WidenOrSplitVectorLoad(Op, DAG); 8062 } 8063 // Non-uniform loads will be selected to MUBUF instructions, so they 8064 // have the same legalization requirements as global and private 8065 // loads. 8066 // 8067 } 8068 8069 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8070 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8071 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8072 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8073 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8074 Alignment >= 4 && NumElements < 32) { 8075 if (MemVT.isPow2VectorType()) 8076 return SDValue(); 8077 return WidenOrSplitVectorLoad(Op, DAG); 8078 } 8079 // Non-uniform loads will be selected to MUBUF instructions, so they 8080 // have the same legalization requirements as global and private 8081 // loads. 8082 // 8083 } 8084 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8085 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8086 AS == AMDGPUAS::GLOBAL_ADDRESS || 8087 AS == AMDGPUAS::FLAT_ADDRESS) { 8088 if (NumElements > 4) 8089 return SplitVectorLoad(Op, DAG); 8090 // v3 loads not supported on SI. 8091 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8092 return WidenOrSplitVectorLoad(Op, DAG); 8093 8094 // v3 and v4 loads are supported for private and global memory. 8095 return SDValue(); 8096 } 8097 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8098 // Depending on the setting of the private_element_size field in the 8099 // resource descriptor, we can only make private accesses up to a certain 8100 // size. 8101 switch (Subtarget->getMaxPrivateElementSize()) { 8102 case 4: { 8103 SDValue Ops[2]; 8104 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8105 return DAG.getMergeValues(Ops, DL); 8106 } 8107 case 8: 8108 if (NumElements > 2) 8109 return SplitVectorLoad(Op, DAG); 8110 return SDValue(); 8111 case 16: 8112 // Same as global/flat 8113 if (NumElements > 4) 8114 return SplitVectorLoad(Op, DAG); 8115 // v3 loads not supported on SI. 8116 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8117 return WidenOrSplitVectorLoad(Op, DAG); 8118 8119 return SDValue(); 8120 default: 8121 llvm_unreachable("unsupported private_element_size"); 8122 } 8123 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8124 // Use ds_read_b128 or ds_read_b96 when possible. 8125 if (Subtarget->hasDS96AndDS128() && 8126 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8127 MemVT.getStoreSize() == 12) && 8128 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8129 Load->getAlign())) 8130 return SDValue(); 8131 8132 if (NumElements > 2) 8133 return SplitVectorLoad(Op, DAG); 8134 8135 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8136 // address is negative, then the instruction is incorrectly treated as 8137 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8138 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8139 // load later in the SILoadStoreOptimizer. 8140 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8141 NumElements == 2 && MemVT.getStoreSize() == 8 && 8142 Load->getAlignment() < 8) { 8143 return SplitVectorLoad(Op, DAG); 8144 } 8145 } 8146 8147 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8148 MemVT, *Load->getMemOperand())) { 8149 SDValue Ops[2]; 8150 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8151 return DAG.getMergeValues(Ops, DL); 8152 } 8153 8154 return SDValue(); 8155 } 8156 8157 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8158 EVT VT = Op.getValueType(); 8159 assert(VT.getSizeInBits() == 64); 8160 8161 SDLoc DL(Op); 8162 SDValue Cond = Op.getOperand(0); 8163 8164 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8165 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8166 8167 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8168 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8169 8170 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8171 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8172 8173 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8174 8175 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8176 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8177 8178 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8179 8180 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8181 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8182 } 8183 8184 // Catch division cases where we can use shortcuts with rcp and rsq 8185 // instructions. 8186 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8187 SelectionDAG &DAG) const { 8188 SDLoc SL(Op); 8189 SDValue LHS = Op.getOperand(0); 8190 SDValue RHS = Op.getOperand(1); 8191 EVT VT = Op.getValueType(); 8192 const SDNodeFlags Flags = Op->getFlags(); 8193 8194 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8195 Flags.hasApproximateFuncs(); 8196 8197 // Without !fpmath accuracy information, we can't do more because we don't 8198 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8199 if (!AllowInaccurateRcp) 8200 return SDValue(); 8201 8202 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8203 if (CLHS->isExactlyValue(1.0)) { 8204 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8205 // the CI documentation has a worst case error of 1 ulp. 8206 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8207 // use it as long as we aren't trying to use denormals. 8208 // 8209 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8210 8211 // 1.0 / sqrt(x) -> rsq(x) 8212 8213 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8214 // error seems really high at 2^29 ULP. 8215 if (RHS.getOpcode() == ISD::FSQRT) 8216 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8217 8218 // 1.0 / x -> rcp(x) 8219 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8220 } 8221 8222 // Same as for 1.0, but expand the sign out of the constant. 8223 if (CLHS->isExactlyValue(-1.0)) { 8224 // -1.0 / x -> rcp (fneg x) 8225 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8226 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8227 } 8228 } 8229 8230 // Turn into multiply by the reciprocal. 8231 // x / y -> x * (1.0 / y) 8232 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8233 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8234 } 8235 8236 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8237 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8238 SDNodeFlags Flags) { 8239 if (GlueChain->getNumValues() <= 1) { 8240 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8241 } 8242 8243 assert(GlueChain->getNumValues() == 3); 8244 8245 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8246 switch (Opcode) { 8247 default: llvm_unreachable("no chain equivalent for opcode"); 8248 case ISD::FMUL: 8249 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8250 break; 8251 } 8252 8253 return DAG.getNode(Opcode, SL, VTList, 8254 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8255 Flags); 8256 } 8257 8258 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8259 EVT VT, SDValue A, SDValue B, SDValue C, 8260 SDValue GlueChain, SDNodeFlags Flags) { 8261 if (GlueChain->getNumValues() <= 1) { 8262 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8263 } 8264 8265 assert(GlueChain->getNumValues() == 3); 8266 8267 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8268 switch (Opcode) { 8269 default: llvm_unreachable("no chain equivalent for opcode"); 8270 case ISD::FMA: 8271 Opcode = AMDGPUISD::FMA_W_CHAIN; 8272 break; 8273 } 8274 8275 return DAG.getNode(Opcode, SL, VTList, 8276 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8277 Flags); 8278 } 8279 8280 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8281 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8282 return FastLowered; 8283 8284 SDLoc SL(Op); 8285 SDValue Src0 = Op.getOperand(0); 8286 SDValue Src1 = Op.getOperand(1); 8287 8288 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8289 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8290 8291 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8292 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8293 8294 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8295 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8296 8297 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8298 } 8299 8300 // Faster 2.5 ULP division that does not support denormals. 8301 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8302 SDLoc SL(Op); 8303 SDValue LHS = Op.getOperand(1); 8304 SDValue RHS = Op.getOperand(2); 8305 8306 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8307 8308 const APFloat K0Val(BitsToFloat(0x6f800000)); 8309 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8310 8311 const APFloat K1Val(BitsToFloat(0x2f800000)); 8312 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8313 8314 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8315 8316 EVT SetCCVT = 8317 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8318 8319 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8320 8321 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8322 8323 // TODO: Should this propagate fast-math-flags? 8324 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8325 8326 // rcp does not support denormals. 8327 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8328 8329 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8330 8331 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8332 } 8333 8334 // Returns immediate value for setting the F32 denorm mode when using the 8335 // S_DENORM_MODE instruction. 8336 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8337 const SDLoc &SL, const GCNSubtarget *ST) { 8338 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8339 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8340 ? FP_DENORM_FLUSH_NONE 8341 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8342 8343 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8344 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8345 } 8346 8347 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8348 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8349 return FastLowered; 8350 8351 // The selection matcher assumes anything with a chain selecting to a 8352 // mayRaiseFPException machine instruction. Since we're introducing a chain 8353 // here, we need to explicitly report nofpexcept for the regular fdiv 8354 // lowering. 8355 SDNodeFlags Flags = Op->getFlags(); 8356 Flags.setNoFPExcept(true); 8357 8358 SDLoc SL(Op); 8359 SDValue LHS = Op.getOperand(0); 8360 SDValue RHS = Op.getOperand(1); 8361 8362 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8363 8364 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8365 8366 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8367 {RHS, RHS, LHS}, Flags); 8368 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8369 {LHS, RHS, LHS}, Flags); 8370 8371 // Denominator is scaled to not be denormal, so using rcp is ok. 8372 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8373 DenominatorScaled, Flags); 8374 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8375 DenominatorScaled, Flags); 8376 8377 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8378 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8379 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8380 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8381 8382 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8383 8384 if (!HasFP32Denormals) { 8385 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8386 // lowering. The chain dependence is insufficient, and we need glue. We do 8387 // not need the glue variants in a strictfp function. 8388 8389 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8390 8391 SDNode *EnableDenorm; 8392 if (Subtarget->hasDenormModeInst()) { 8393 const SDValue EnableDenormValue = 8394 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8395 8396 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8397 DAG.getEntryNode(), EnableDenormValue).getNode(); 8398 } else { 8399 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8400 SL, MVT::i32); 8401 EnableDenorm = 8402 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8403 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8404 } 8405 8406 SDValue Ops[3] = { 8407 NegDivScale0, 8408 SDValue(EnableDenorm, 0), 8409 SDValue(EnableDenorm, 1) 8410 }; 8411 8412 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8413 } 8414 8415 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8416 ApproxRcp, One, NegDivScale0, Flags); 8417 8418 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8419 ApproxRcp, Fma0, Flags); 8420 8421 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8422 Fma1, Fma1, Flags); 8423 8424 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8425 NumeratorScaled, Mul, Flags); 8426 8427 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8428 Fma2, Fma1, Mul, Fma2, Flags); 8429 8430 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8431 NumeratorScaled, Fma3, Flags); 8432 8433 if (!HasFP32Denormals) { 8434 SDNode *DisableDenorm; 8435 if (Subtarget->hasDenormModeInst()) { 8436 const SDValue DisableDenormValue = 8437 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8438 8439 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8440 Fma4.getValue(1), DisableDenormValue, 8441 Fma4.getValue(2)).getNode(); 8442 } else { 8443 const SDValue DisableDenormValue = 8444 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8445 8446 DisableDenorm = DAG.getMachineNode( 8447 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8448 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8449 } 8450 8451 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8452 SDValue(DisableDenorm, 0), DAG.getRoot()); 8453 DAG.setRoot(OutputChain); 8454 } 8455 8456 SDValue Scale = NumeratorScaled.getValue(1); 8457 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8458 {Fma4, Fma1, Fma3, Scale}, Flags); 8459 8460 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8461 } 8462 8463 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8464 if (DAG.getTarget().Options.UnsafeFPMath) 8465 return lowerFastUnsafeFDIV(Op, DAG); 8466 8467 SDLoc SL(Op); 8468 SDValue X = Op.getOperand(0); 8469 SDValue Y = Op.getOperand(1); 8470 8471 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8472 8473 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8474 8475 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8476 8477 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8478 8479 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8480 8481 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8482 8483 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8484 8485 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8486 8487 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8488 8489 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8490 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8491 8492 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8493 NegDivScale0, Mul, DivScale1); 8494 8495 SDValue Scale; 8496 8497 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8498 // Workaround a hardware bug on SI where the condition output from div_scale 8499 // is not usable. 8500 8501 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8502 8503 // Figure out if the scale to use for div_fmas. 8504 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8505 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8506 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8507 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8508 8509 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8510 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8511 8512 SDValue Scale0Hi 8513 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8514 SDValue Scale1Hi 8515 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8516 8517 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8518 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8519 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8520 } else { 8521 Scale = DivScale1.getValue(1); 8522 } 8523 8524 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8525 Fma4, Fma3, Mul, Scale); 8526 8527 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8528 } 8529 8530 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8531 EVT VT = Op.getValueType(); 8532 8533 if (VT == MVT::f32) 8534 return LowerFDIV32(Op, DAG); 8535 8536 if (VT == MVT::f64) 8537 return LowerFDIV64(Op, DAG); 8538 8539 if (VT == MVT::f16) 8540 return LowerFDIV16(Op, DAG); 8541 8542 llvm_unreachable("Unexpected type for fdiv"); 8543 } 8544 8545 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8546 SDLoc DL(Op); 8547 StoreSDNode *Store = cast<StoreSDNode>(Op); 8548 EVT VT = Store->getMemoryVT(); 8549 8550 if (VT == MVT::i1) { 8551 return DAG.getTruncStore(Store->getChain(), DL, 8552 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8553 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8554 } 8555 8556 assert(VT.isVector() && 8557 Store->getValue().getValueType().getScalarType() == MVT::i32); 8558 8559 unsigned AS = Store->getAddressSpace(); 8560 if (Subtarget->hasLDSMisalignedBug() && 8561 AS == AMDGPUAS::FLAT_ADDRESS && 8562 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8563 return SplitVectorStore(Op, DAG); 8564 } 8565 8566 MachineFunction &MF = DAG.getMachineFunction(); 8567 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8568 // If there is a possibilty that flat instruction access scratch memory 8569 // then we need to use the same legalization rules we use for private. 8570 if (AS == AMDGPUAS::FLAT_ADDRESS && 8571 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8572 AS = MFI->hasFlatScratchInit() ? 8573 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8574 8575 unsigned NumElements = VT.getVectorNumElements(); 8576 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8577 AS == AMDGPUAS::FLAT_ADDRESS) { 8578 if (NumElements > 4) 8579 return SplitVectorStore(Op, DAG); 8580 // v3 stores not supported on SI. 8581 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8582 return SplitVectorStore(Op, DAG); 8583 8584 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8585 VT, *Store->getMemOperand())) 8586 return expandUnalignedStore(Store, DAG); 8587 8588 return SDValue(); 8589 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8590 switch (Subtarget->getMaxPrivateElementSize()) { 8591 case 4: 8592 return scalarizeVectorStore(Store, DAG); 8593 case 8: 8594 if (NumElements > 2) 8595 return SplitVectorStore(Op, DAG); 8596 return SDValue(); 8597 case 16: 8598 if (NumElements > 4 || NumElements == 3) 8599 return SplitVectorStore(Op, DAG); 8600 return SDValue(); 8601 default: 8602 llvm_unreachable("unsupported private_element_size"); 8603 } 8604 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8605 // Use ds_write_b128 or ds_write_b96 when possible. 8606 if (Subtarget->hasDS96AndDS128() && 8607 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8608 (VT.getStoreSize() == 12)) && 8609 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8610 Store->getAlign())) 8611 return SDValue(); 8612 8613 if (NumElements > 2) 8614 return SplitVectorStore(Op, DAG); 8615 8616 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8617 // address is negative, then the instruction is incorrectly treated as 8618 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8619 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8620 // store later in the SILoadStoreOptimizer. 8621 if (!Subtarget->hasUsableDSOffset() && 8622 NumElements == 2 && VT.getStoreSize() == 8 && 8623 Store->getAlignment() < 8) { 8624 return SplitVectorStore(Op, DAG); 8625 } 8626 8627 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8628 VT, *Store->getMemOperand())) { 8629 if (VT.isVector()) 8630 return SplitVectorStore(Op, DAG); 8631 return expandUnalignedStore(Store, DAG); 8632 } 8633 8634 return SDValue(); 8635 } else { 8636 llvm_unreachable("unhandled address space"); 8637 } 8638 } 8639 8640 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8641 SDLoc DL(Op); 8642 EVT VT = Op.getValueType(); 8643 SDValue Arg = Op.getOperand(0); 8644 SDValue TrigVal; 8645 8646 // Propagate fast-math flags so that the multiply we introduce can be folded 8647 // if Arg is already the result of a multiply by constant. 8648 auto Flags = Op->getFlags(); 8649 8650 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8651 8652 if (Subtarget->hasTrigReducedRange()) { 8653 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8654 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8655 } else { 8656 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8657 } 8658 8659 switch (Op.getOpcode()) { 8660 case ISD::FCOS: 8661 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8662 case ISD::FSIN: 8663 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8664 default: 8665 llvm_unreachable("Wrong trig opcode"); 8666 } 8667 } 8668 8669 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8670 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8671 assert(AtomicNode->isCompareAndSwap()); 8672 unsigned AS = AtomicNode->getAddressSpace(); 8673 8674 // No custom lowering required for local address space 8675 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8676 return Op; 8677 8678 // Non-local address space requires custom lowering for atomic compare 8679 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8680 SDLoc DL(Op); 8681 SDValue ChainIn = Op.getOperand(0); 8682 SDValue Addr = Op.getOperand(1); 8683 SDValue Old = Op.getOperand(2); 8684 SDValue New = Op.getOperand(3); 8685 EVT VT = Op.getValueType(); 8686 MVT SimpleVT = VT.getSimpleVT(); 8687 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8688 8689 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8690 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8691 8692 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8693 Ops, VT, AtomicNode->getMemOperand()); 8694 } 8695 8696 //===----------------------------------------------------------------------===// 8697 // Custom DAG optimizations 8698 //===----------------------------------------------------------------------===// 8699 8700 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8701 DAGCombinerInfo &DCI) const { 8702 EVT VT = N->getValueType(0); 8703 EVT ScalarVT = VT.getScalarType(); 8704 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8705 return SDValue(); 8706 8707 SelectionDAG &DAG = DCI.DAG; 8708 SDLoc DL(N); 8709 8710 SDValue Src = N->getOperand(0); 8711 EVT SrcVT = Src.getValueType(); 8712 8713 // TODO: We could try to match extracting the higher bytes, which would be 8714 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8715 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8716 // about in practice. 8717 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8718 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8719 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8720 DCI.AddToWorklist(Cvt.getNode()); 8721 8722 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8723 if (ScalarVT != MVT::f32) { 8724 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8725 DAG.getTargetConstant(0, DL, MVT::i32)); 8726 } 8727 return Cvt; 8728 } 8729 } 8730 8731 return SDValue(); 8732 } 8733 8734 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8735 8736 // This is a variant of 8737 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8738 // 8739 // The normal DAG combiner will do this, but only if the add has one use since 8740 // that would increase the number of instructions. 8741 // 8742 // This prevents us from seeing a constant offset that can be folded into a 8743 // memory instruction's addressing mode. If we know the resulting add offset of 8744 // a pointer can be folded into an addressing offset, we can replace the pointer 8745 // operand with the add of new constant offset. This eliminates one of the uses, 8746 // and may allow the remaining use to also be simplified. 8747 // 8748 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8749 unsigned AddrSpace, 8750 EVT MemVT, 8751 DAGCombinerInfo &DCI) const { 8752 SDValue N0 = N->getOperand(0); 8753 SDValue N1 = N->getOperand(1); 8754 8755 // We only do this to handle cases where it's profitable when there are 8756 // multiple uses of the add, so defer to the standard combine. 8757 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8758 N0->hasOneUse()) 8759 return SDValue(); 8760 8761 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8762 if (!CN1) 8763 return SDValue(); 8764 8765 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8766 if (!CAdd) 8767 return SDValue(); 8768 8769 // If the resulting offset is too large, we can't fold it into the addressing 8770 // mode offset. 8771 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8772 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8773 8774 AddrMode AM; 8775 AM.HasBaseReg = true; 8776 AM.BaseOffs = Offset.getSExtValue(); 8777 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8778 return SDValue(); 8779 8780 SelectionDAG &DAG = DCI.DAG; 8781 SDLoc SL(N); 8782 EVT VT = N->getValueType(0); 8783 8784 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8785 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8786 8787 SDNodeFlags Flags; 8788 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8789 (N0.getOpcode() == ISD::OR || 8790 N0->getFlags().hasNoUnsignedWrap())); 8791 8792 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8793 } 8794 8795 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8796 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8797 /// specific intrinsic, but they all place the pointer operand first. 8798 static unsigned getBasePtrIndex(const MemSDNode *N) { 8799 switch (N->getOpcode()) { 8800 case ISD::STORE: 8801 case ISD::INTRINSIC_W_CHAIN: 8802 case ISD::INTRINSIC_VOID: 8803 return 2; 8804 default: 8805 return 1; 8806 } 8807 } 8808 8809 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8810 DAGCombinerInfo &DCI) const { 8811 SelectionDAG &DAG = DCI.DAG; 8812 SDLoc SL(N); 8813 8814 unsigned PtrIdx = getBasePtrIndex(N); 8815 SDValue Ptr = N->getOperand(PtrIdx); 8816 8817 // TODO: We could also do this for multiplies. 8818 if (Ptr.getOpcode() == ISD::SHL) { 8819 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8820 N->getMemoryVT(), DCI); 8821 if (NewPtr) { 8822 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8823 8824 NewOps[PtrIdx] = NewPtr; 8825 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8826 } 8827 } 8828 8829 return SDValue(); 8830 } 8831 8832 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8833 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8834 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8835 (Opc == ISD::XOR && Val == 0); 8836 } 8837 8838 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8839 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8840 // integer combine opportunities since most 64-bit operations are decomposed 8841 // this way. TODO: We won't want this for SALU especially if it is an inline 8842 // immediate. 8843 SDValue SITargetLowering::splitBinaryBitConstantOp( 8844 DAGCombinerInfo &DCI, 8845 const SDLoc &SL, 8846 unsigned Opc, SDValue LHS, 8847 const ConstantSDNode *CRHS) const { 8848 uint64_t Val = CRHS->getZExtValue(); 8849 uint32_t ValLo = Lo_32(Val); 8850 uint32_t ValHi = Hi_32(Val); 8851 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8852 8853 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8854 bitOpWithConstantIsReducible(Opc, ValHi)) || 8855 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8856 // If we need to materialize a 64-bit immediate, it will be split up later 8857 // anyway. Avoid creating the harder to understand 64-bit immediate 8858 // materialization. 8859 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8860 } 8861 8862 return SDValue(); 8863 } 8864 8865 // Returns true if argument is a boolean value which is not serialized into 8866 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8867 static bool isBoolSGPR(SDValue V) { 8868 if (V.getValueType() != MVT::i1) 8869 return false; 8870 switch (V.getOpcode()) { 8871 default: break; 8872 case ISD::SETCC: 8873 case ISD::AND: 8874 case ISD::OR: 8875 case ISD::XOR: 8876 case AMDGPUISD::FP_CLASS: 8877 return true; 8878 } 8879 return false; 8880 } 8881 8882 // If a constant has all zeroes or all ones within each byte return it. 8883 // Otherwise return 0. 8884 static uint32_t getConstantPermuteMask(uint32_t C) { 8885 // 0xff for any zero byte in the mask 8886 uint32_t ZeroByteMask = 0; 8887 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8888 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8889 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8890 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8891 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8892 if ((NonZeroByteMask & C) != NonZeroByteMask) 8893 return 0; // Partial bytes selected. 8894 return C; 8895 } 8896 8897 // Check if a node selects whole bytes from its operand 0 starting at a byte 8898 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8899 // or -1 if not succeeded. 8900 // Note byte select encoding: 8901 // value 0-3 selects corresponding source byte; 8902 // value 0xc selects zero; 8903 // value 0xff selects 0xff. 8904 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8905 assert(V.getValueSizeInBits() == 32); 8906 8907 if (V.getNumOperands() != 2) 8908 return ~0; 8909 8910 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8911 if (!N1) 8912 return ~0; 8913 8914 uint32_t C = N1->getZExtValue(); 8915 8916 switch (V.getOpcode()) { 8917 default: 8918 break; 8919 case ISD::AND: 8920 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8921 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8922 } 8923 break; 8924 8925 case ISD::OR: 8926 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8927 return (0x03020100 & ~ConstMask) | ConstMask; 8928 } 8929 break; 8930 8931 case ISD::SHL: 8932 if (C % 8) 8933 return ~0; 8934 8935 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8936 8937 case ISD::SRL: 8938 if (C % 8) 8939 return ~0; 8940 8941 return uint32_t(0x0c0c0c0c03020100ull >> C); 8942 } 8943 8944 return ~0; 8945 } 8946 8947 SDValue SITargetLowering::performAndCombine(SDNode *N, 8948 DAGCombinerInfo &DCI) const { 8949 if (DCI.isBeforeLegalize()) 8950 return SDValue(); 8951 8952 SelectionDAG &DAG = DCI.DAG; 8953 EVT VT = N->getValueType(0); 8954 SDValue LHS = N->getOperand(0); 8955 SDValue RHS = N->getOperand(1); 8956 8957 8958 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8959 if (VT == MVT::i64 && CRHS) { 8960 if (SDValue Split 8961 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8962 return Split; 8963 } 8964 8965 if (CRHS && VT == MVT::i32) { 8966 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8967 // nb = number of trailing zeroes in mask 8968 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8969 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8970 uint64_t Mask = CRHS->getZExtValue(); 8971 unsigned Bits = countPopulation(Mask); 8972 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8973 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8974 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8975 unsigned Shift = CShift->getZExtValue(); 8976 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8977 unsigned Offset = NB + Shift; 8978 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8979 SDLoc SL(N); 8980 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8981 LHS->getOperand(0), 8982 DAG.getConstant(Offset, SL, MVT::i32), 8983 DAG.getConstant(Bits, SL, MVT::i32)); 8984 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8985 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8986 DAG.getValueType(NarrowVT)); 8987 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8988 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8989 return Shl; 8990 } 8991 } 8992 } 8993 8994 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8995 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8996 isa<ConstantSDNode>(LHS.getOperand(2))) { 8997 uint32_t Sel = getConstantPermuteMask(Mask); 8998 if (!Sel) 8999 return SDValue(); 9000 9001 // Select 0xc for all zero bytes 9002 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9003 SDLoc DL(N); 9004 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9005 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9006 } 9007 } 9008 9009 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9010 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9011 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9012 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9013 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9014 9015 SDValue X = LHS.getOperand(0); 9016 SDValue Y = RHS.getOperand(0); 9017 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9018 return SDValue(); 9019 9020 if (LCC == ISD::SETO) { 9021 if (X != LHS.getOperand(1)) 9022 return SDValue(); 9023 9024 if (RCC == ISD::SETUNE) { 9025 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9026 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9027 return SDValue(); 9028 9029 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9030 SIInstrFlags::N_SUBNORMAL | 9031 SIInstrFlags::N_ZERO | 9032 SIInstrFlags::P_ZERO | 9033 SIInstrFlags::P_SUBNORMAL | 9034 SIInstrFlags::P_NORMAL; 9035 9036 static_assert(((~(SIInstrFlags::S_NAN | 9037 SIInstrFlags::Q_NAN | 9038 SIInstrFlags::N_INFINITY | 9039 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9040 "mask not equal"); 9041 9042 SDLoc DL(N); 9043 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9044 X, DAG.getConstant(Mask, DL, MVT::i32)); 9045 } 9046 } 9047 } 9048 9049 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9050 std::swap(LHS, RHS); 9051 9052 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9053 RHS.hasOneUse()) { 9054 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9055 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9056 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9057 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9058 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9059 (RHS.getOperand(0) == LHS.getOperand(0) && 9060 LHS.getOperand(0) == LHS.getOperand(1))) { 9061 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9062 unsigned NewMask = LCC == ISD::SETO ? 9063 Mask->getZExtValue() & ~OrdMask : 9064 Mask->getZExtValue() & OrdMask; 9065 9066 SDLoc DL(N); 9067 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9068 DAG.getConstant(NewMask, DL, MVT::i32)); 9069 } 9070 } 9071 9072 if (VT == MVT::i32 && 9073 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9074 // and x, (sext cc from i1) => select cc, x, 0 9075 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9076 std::swap(LHS, RHS); 9077 if (isBoolSGPR(RHS.getOperand(0))) 9078 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9079 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9080 } 9081 9082 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9083 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9084 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9085 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9086 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9087 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9088 if (LHSMask != ~0u && RHSMask != ~0u) { 9089 // Canonicalize the expression in an attempt to have fewer unique masks 9090 // and therefore fewer registers used to hold the masks. 9091 if (LHSMask > RHSMask) { 9092 std::swap(LHSMask, RHSMask); 9093 std::swap(LHS, RHS); 9094 } 9095 9096 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9097 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9098 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9099 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9100 9101 // Check of we need to combine values from two sources within a byte. 9102 if (!(LHSUsedLanes & RHSUsedLanes) && 9103 // If we select high and lower word keep it for SDWA. 9104 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9105 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9106 // Each byte in each mask is either selector mask 0-3, or has higher 9107 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9108 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9109 // mask which is not 0xff wins. By anding both masks we have a correct 9110 // result except that 0x0c shall be corrected to give 0x0c only. 9111 uint32_t Mask = LHSMask & RHSMask; 9112 for (unsigned I = 0; I < 32; I += 8) { 9113 uint32_t ByteSel = 0xff << I; 9114 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9115 Mask &= (0x0c << I) & 0xffffffff; 9116 } 9117 9118 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9119 // or 0x0c. 9120 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9121 SDLoc DL(N); 9122 9123 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9124 LHS.getOperand(0), RHS.getOperand(0), 9125 DAG.getConstant(Sel, DL, MVT::i32)); 9126 } 9127 } 9128 } 9129 9130 return SDValue(); 9131 } 9132 9133 SDValue SITargetLowering::performOrCombine(SDNode *N, 9134 DAGCombinerInfo &DCI) const { 9135 SelectionDAG &DAG = DCI.DAG; 9136 SDValue LHS = N->getOperand(0); 9137 SDValue RHS = N->getOperand(1); 9138 9139 EVT VT = N->getValueType(0); 9140 if (VT == MVT::i1) { 9141 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9142 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9143 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9144 SDValue Src = LHS.getOperand(0); 9145 if (Src != RHS.getOperand(0)) 9146 return SDValue(); 9147 9148 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9149 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9150 if (!CLHS || !CRHS) 9151 return SDValue(); 9152 9153 // Only 10 bits are used. 9154 static const uint32_t MaxMask = 0x3ff; 9155 9156 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9157 SDLoc DL(N); 9158 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9159 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9160 } 9161 9162 return SDValue(); 9163 } 9164 9165 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9166 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9167 LHS.getOpcode() == AMDGPUISD::PERM && 9168 isa<ConstantSDNode>(LHS.getOperand(2))) { 9169 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9170 if (!Sel) 9171 return SDValue(); 9172 9173 Sel |= LHS.getConstantOperandVal(2); 9174 SDLoc DL(N); 9175 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9176 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9177 } 9178 9179 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9180 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9181 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9182 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9183 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9184 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9185 if (LHSMask != ~0u && RHSMask != ~0u) { 9186 // Canonicalize the expression in an attempt to have fewer unique masks 9187 // and therefore fewer registers used to hold the masks. 9188 if (LHSMask > RHSMask) { 9189 std::swap(LHSMask, RHSMask); 9190 std::swap(LHS, RHS); 9191 } 9192 9193 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9194 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9195 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9196 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9197 9198 // Check of we need to combine values from two sources within a byte. 9199 if (!(LHSUsedLanes & RHSUsedLanes) && 9200 // If we select high and lower word keep it for SDWA. 9201 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9202 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9203 // Kill zero bytes selected by other mask. Zero value is 0xc. 9204 LHSMask &= ~RHSUsedLanes; 9205 RHSMask &= ~LHSUsedLanes; 9206 // Add 4 to each active LHS lane 9207 LHSMask |= LHSUsedLanes & 0x04040404; 9208 // Combine masks 9209 uint32_t Sel = LHSMask | RHSMask; 9210 SDLoc DL(N); 9211 9212 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9213 LHS.getOperand(0), RHS.getOperand(0), 9214 DAG.getConstant(Sel, DL, MVT::i32)); 9215 } 9216 } 9217 } 9218 9219 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9220 return SDValue(); 9221 9222 // TODO: This could be a generic combine with a predicate for extracting the 9223 // high half of an integer being free. 9224 9225 // (or i64:x, (zero_extend i32:y)) -> 9226 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9227 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9228 RHS.getOpcode() != ISD::ZERO_EXTEND) 9229 std::swap(LHS, RHS); 9230 9231 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9232 SDValue ExtSrc = RHS.getOperand(0); 9233 EVT SrcVT = ExtSrc.getValueType(); 9234 if (SrcVT == MVT::i32) { 9235 SDLoc SL(N); 9236 SDValue LowLHS, HiBits; 9237 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9238 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9239 9240 DCI.AddToWorklist(LowOr.getNode()); 9241 DCI.AddToWorklist(HiBits.getNode()); 9242 9243 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9244 LowOr, HiBits); 9245 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9246 } 9247 } 9248 9249 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9250 if (CRHS) { 9251 if (SDValue Split 9252 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9253 return Split; 9254 } 9255 9256 return SDValue(); 9257 } 9258 9259 SDValue SITargetLowering::performXorCombine(SDNode *N, 9260 DAGCombinerInfo &DCI) const { 9261 EVT VT = N->getValueType(0); 9262 if (VT != MVT::i64) 9263 return SDValue(); 9264 9265 SDValue LHS = N->getOperand(0); 9266 SDValue RHS = N->getOperand(1); 9267 9268 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9269 if (CRHS) { 9270 if (SDValue Split 9271 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9272 return Split; 9273 } 9274 9275 return SDValue(); 9276 } 9277 9278 // Instructions that will be lowered with a final instruction that zeros the 9279 // high result bits. 9280 // XXX - probably only need to list legal operations. 9281 static bool fp16SrcZerosHighBits(unsigned Opc) { 9282 switch (Opc) { 9283 case ISD::FADD: 9284 case ISD::FSUB: 9285 case ISD::FMUL: 9286 case ISD::FDIV: 9287 case ISD::FREM: 9288 case ISD::FMA: 9289 case ISD::FMAD: 9290 case ISD::FCANONICALIZE: 9291 case ISD::FP_ROUND: 9292 case ISD::UINT_TO_FP: 9293 case ISD::SINT_TO_FP: 9294 case ISD::FABS: 9295 // Fabs is lowered to a bit operation, but it's an and which will clear the 9296 // high bits anyway. 9297 case ISD::FSQRT: 9298 case ISD::FSIN: 9299 case ISD::FCOS: 9300 case ISD::FPOWI: 9301 case ISD::FPOW: 9302 case ISD::FLOG: 9303 case ISD::FLOG2: 9304 case ISD::FLOG10: 9305 case ISD::FEXP: 9306 case ISD::FEXP2: 9307 case ISD::FCEIL: 9308 case ISD::FTRUNC: 9309 case ISD::FRINT: 9310 case ISD::FNEARBYINT: 9311 case ISD::FROUND: 9312 case ISD::FFLOOR: 9313 case ISD::FMINNUM: 9314 case ISD::FMAXNUM: 9315 case AMDGPUISD::FRACT: 9316 case AMDGPUISD::CLAMP: 9317 case AMDGPUISD::COS_HW: 9318 case AMDGPUISD::SIN_HW: 9319 case AMDGPUISD::FMIN3: 9320 case AMDGPUISD::FMAX3: 9321 case AMDGPUISD::FMED3: 9322 case AMDGPUISD::FMAD_FTZ: 9323 case AMDGPUISD::RCP: 9324 case AMDGPUISD::RSQ: 9325 case AMDGPUISD::RCP_IFLAG: 9326 case AMDGPUISD::LDEXP: 9327 return true; 9328 default: 9329 // fcopysign, select and others may be lowered to 32-bit bit operations 9330 // which don't zero the high bits. 9331 return false; 9332 } 9333 } 9334 9335 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9336 DAGCombinerInfo &DCI) const { 9337 if (!Subtarget->has16BitInsts() || 9338 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9339 return SDValue(); 9340 9341 EVT VT = N->getValueType(0); 9342 if (VT != MVT::i32) 9343 return SDValue(); 9344 9345 SDValue Src = N->getOperand(0); 9346 if (Src.getValueType() != MVT::i16) 9347 return SDValue(); 9348 9349 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9350 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9351 if (Src.getOpcode() == ISD::BITCAST) { 9352 SDValue BCSrc = Src.getOperand(0); 9353 if (BCSrc.getValueType() == MVT::f16 && 9354 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9355 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9356 } 9357 9358 return SDValue(); 9359 } 9360 9361 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9362 DAGCombinerInfo &DCI) 9363 const { 9364 SDValue Src = N->getOperand(0); 9365 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9366 9367 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9368 VTSign->getVT() == MVT::i8) || 9369 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9370 VTSign->getVT() == MVT::i16)) && 9371 Src.hasOneUse()) { 9372 auto *M = cast<MemSDNode>(Src); 9373 SDValue Ops[] = { 9374 Src.getOperand(0), // Chain 9375 Src.getOperand(1), // rsrc 9376 Src.getOperand(2), // vindex 9377 Src.getOperand(3), // voffset 9378 Src.getOperand(4), // soffset 9379 Src.getOperand(5), // offset 9380 Src.getOperand(6), 9381 Src.getOperand(7) 9382 }; 9383 // replace with BUFFER_LOAD_BYTE/SHORT 9384 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9385 Src.getOperand(0).getValueType()); 9386 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9387 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9388 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9389 ResList, 9390 Ops, M->getMemoryVT(), 9391 M->getMemOperand()); 9392 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9393 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9394 } 9395 return SDValue(); 9396 } 9397 9398 SDValue SITargetLowering::performClassCombine(SDNode *N, 9399 DAGCombinerInfo &DCI) const { 9400 SelectionDAG &DAG = DCI.DAG; 9401 SDValue Mask = N->getOperand(1); 9402 9403 // fp_class x, 0 -> false 9404 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9405 if (CMask->isNullValue()) 9406 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9407 } 9408 9409 if (N->getOperand(0).isUndef()) 9410 return DAG.getUNDEF(MVT::i1); 9411 9412 return SDValue(); 9413 } 9414 9415 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9416 DAGCombinerInfo &DCI) const { 9417 EVT VT = N->getValueType(0); 9418 SDValue N0 = N->getOperand(0); 9419 9420 if (N0.isUndef()) 9421 return N0; 9422 9423 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9424 N0.getOpcode() == ISD::SINT_TO_FP)) { 9425 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9426 N->getFlags()); 9427 } 9428 9429 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9430 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9431 N0.getOperand(0), N->getFlags()); 9432 } 9433 9434 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9435 } 9436 9437 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9438 unsigned MaxDepth) const { 9439 unsigned Opcode = Op.getOpcode(); 9440 if (Opcode == ISD::FCANONICALIZE) 9441 return true; 9442 9443 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9444 auto F = CFP->getValueAPF(); 9445 if (F.isNaN() && F.isSignaling()) 9446 return false; 9447 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9448 } 9449 9450 // If source is a result of another standard FP operation it is already in 9451 // canonical form. 9452 if (MaxDepth == 0) 9453 return false; 9454 9455 switch (Opcode) { 9456 // These will flush denorms if required. 9457 case ISD::FADD: 9458 case ISD::FSUB: 9459 case ISD::FMUL: 9460 case ISD::FCEIL: 9461 case ISD::FFLOOR: 9462 case ISD::FMA: 9463 case ISD::FMAD: 9464 case ISD::FSQRT: 9465 case ISD::FDIV: 9466 case ISD::FREM: 9467 case ISD::FP_ROUND: 9468 case ISD::FP_EXTEND: 9469 case AMDGPUISD::FMUL_LEGACY: 9470 case AMDGPUISD::FMAD_FTZ: 9471 case AMDGPUISD::RCP: 9472 case AMDGPUISD::RSQ: 9473 case AMDGPUISD::RSQ_CLAMP: 9474 case AMDGPUISD::RCP_LEGACY: 9475 case AMDGPUISD::RCP_IFLAG: 9476 case AMDGPUISD::DIV_SCALE: 9477 case AMDGPUISD::DIV_FMAS: 9478 case AMDGPUISD::DIV_FIXUP: 9479 case AMDGPUISD::FRACT: 9480 case AMDGPUISD::LDEXP: 9481 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9482 case AMDGPUISD::CVT_F32_UBYTE0: 9483 case AMDGPUISD::CVT_F32_UBYTE1: 9484 case AMDGPUISD::CVT_F32_UBYTE2: 9485 case AMDGPUISD::CVT_F32_UBYTE3: 9486 return true; 9487 9488 // It can/will be lowered or combined as a bit operation. 9489 // Need to check their input recursively to handle. 9490 case ISD::FNEG: 9491 case ISD::FABS: 9492 case ISD::FCOPYSIGN: 9493 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9494 9495 case ISD::FSIN: 9496 case ISD::FCOS: 9497 case ISD::FSINCOS: 9498 return Op.getValueType().getScalarType() != MVT::f16; 9499 9500 case ISD::FMINNUM: 9501 case ISD::FMAXNUM: 9502 case ISD::FMINNUM_IEEE: 9503 case ISD::FMAXNUM_IEEE: 9504 case AMDGPUISD::CLAMP: 9505 case AMDGPUISD::FMED3: 9506 case AMDGPUISD::FMAX3: 9507 case AMDGPUISD::FMIN3: { 9508 // FIXME: Shouldn't treat the generic operations different based these. 9509 // However, we aren't really required to flush the result from 9510 // minnum/maxnum.. 9511 9512 // snans will be quieted, so we only need to worry about denormals. 9513 if (Subtarget->supportsMinMaxDenormModes() || 9514 denormalsEnabledForType(DAG, Op.getValueType())) 9515 return true; 9516 9517 // Flushing may be required. 9518 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9519 // targets need to check their input recursively. 9520 9521 // FIXME: Does this apply with clamp? It's implemented with max. 9522 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9523 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9524 return false; 9525 } 9526 9527 return true; 9528 } 9529 case ISD::SELECT: { 9530 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9531 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9532 } 9533 case ISD::BUILD_VECTOR: { 9534 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9535 SDValue SrcOp = Op.getOperand(i); 9536 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9537 return false; 9538 } 9539 9540 return true; 9541 } 9542 case ISD::EXTRACT_VECTOR_ELT: 9543 case ISD::EXTRACT_SUBVECTOR: { 9544 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9545 } 9546 case ISD::INSERT_VECTOR_ELT: { 9547 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9548 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9549 } 9550 case ISD::UNDEF: 9551 // Could be anything. 9552 return false; 9553 9554 case ISD::BITCAST: { 9555 // Hack round the mess we make when legalizing extract_vector_elt 9556 SDValue Src = Op.getOperand(0); 9557 if (Src.getValueType() == MVT::i16 && 9558 Src.getOpcode() == ISD::TRUNCATE) { 9559 SDValue TruncSrc = Src.getOperand(0); 9560 if (TruncSrc.getValueType() == MVT::i32 && 9561 TruncSrc.getOpcode() == ISD::BITCAST && 9562 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9563 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9564 } 9565 } 9566 9567 return false; 9568 } 9569 case ISD::INTRINSIC_WO_CHAIN: { 9570 unsigned IntrinsicID 9571 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9572 // TODO: Handle more intrinsics 9573 switch (IntrinsicID) { 9574 case Intrinsic::amdgcn_cvt_pkrtz: 9575 case Intrinsic::amdgcn_cubeid: 9576 case Intrinsic::amdgcn_frexp_mant: 9577 case Intrinsic::amdgcn_fdot2: 9578 case Intrinsic::amdgcn_rcp: 9579 case Intrinsic::amdgcn_rsq: 9580 case Intrinsic::amdgcn_rsq_clamp: 9581 case Intrinsic::amdgcn_rcp_legacy: 9582 case Intrinsic::amdgcn_rsq_legacy: 9583 case Intrinsic::amdgcn_trig_preop: 9584 return true; 9585 default: 9586 break; 9587 } 9588 9589 LLVM_FALLTHROUGH; 9590 } 9591 default: 9592 return denormalsEnabledForType(DAG, Op.getValueType()) && 9593 DAG.isKnownNeverSNaN(Op); 9594 } 9595 9596 llvm_unreachable("invalid operation"); 9597 } 9598 9599 // Constant fold canonicalize. 9600 SDValue SITargetLowering::getCanonicalConstantFP( 9601 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9602 // Flush denormals to 0 if not enabled. 9603 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9604 return DAG.getConstantFP(0.0, SL, VT); 9605 9606 if (C.isNaN()) { 9607 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9608 if (C.isSignaling()) { 9609 // Quiet a signaling NaN. 9610 // FIXME: Is this supposed to preserve payload bits? 9611 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9612 } 9613 9614 // Make sure it is the canonical NaN bitpattern. 9615 // 9616 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9617 // immediate? 9618 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9619 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9620 } 9621 9622 // Already canonical. 9623 return DAG.getConstantFP(C, SL, VT); 9624 } 9625 9626 static bool vectorEltWillFoldAway(SDValue Op) { 9627 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9628 } 9629 9630 SDValue SITargetLowering::performFCanonicalizeCombine( 9631 SDNode *N, 9632 DAGCombinerInfo &DCI) const { 9633 SelectionDAG &DAG = DCI.DAG; 9634 SDValue N0 = N->getOperand(0); 9635 EVT VT = N->getValueType(0); 9636 9637 // fcanonicalize undef -> qnan 9638 if (N0.isUndef()) { 9639 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9640 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9641 } 9642 9643 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9644 EVT VT = N->getValueType(0); 9645 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9646 } 9647 9648 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9649 // (fcanonicalize k) 9650 // 9651 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9652 9653 // TODO: This could be better with wider vectors that will be split to v2f16, 9654 // and to consider uses since there aren't that many packed operations. 9655 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9656 isTypeLegal(MVT::v2f16)) { 9657 SDLoc SL(N); 9658 SDValue NewElts[2]; 9659 SDValue Lo = N0.getOperand(0); 9660 SDValue Hi = N0.getOperand(1); 9661 EVT EltVT = Lo.getValueType(); 9662 9663 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9664 for (unsigned I = 0; I != 2; ++I) { 9665 SDValue Op = N0.getOperand(I); 9666 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9667 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9668 CFP->getValueAPF()); 9669 } else if (Op.isUndef()) { 9670 // Handled below based on what the other operand is. 9671 NewElts[I] = Op; 9672 } else { 9673 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9674 } 9675 } 9676 9677 // If one half is undef, and one is constant, perfer a splat vector rather 9678 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9679 // cheaper to use and may be free with a packed operation. 9680 if (NewElts[0].isUndef()) { 9681 if (isa<ConstantFPSDNode>(NewElts[1])) 9682 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9683 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9684 } 9685 9686 if (NewElts[1].isUndef()) { 9687 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9688 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9689 } 9690 9691 return DAG.getBuildVector(VT, SL, NewElts); 9692 } 9693 } 9694 9695 unsigned SrcOpc = N0.getOpcode(); 9696 9697 // If it's free to do so, push canonicalizes further up the source, which may 9698 // find a canonical source. 9699 // 9700 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9701 // sNaNs. 9702 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9703 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9704 if (CRHS && N0.hasOneUse()) { 9705 SDLoc SL(N); 9706 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9707 N0.getOperand(0)); 9708 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9709 DCI.AddToWorklist(Canon0.getNode()); 9710 9711 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9712 } 9713 } 9714 9715 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9716 } 9717 9718 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9719 switch (Opc) { 9720 case ISD::FMAXNUM: 9721 case ISD::FMAXNUM_IEEE: 9722 return AMDGPUISD::FMAX3; 9723 case ISD::SMAX: 9724 return AMDGPUISD::SMAX3; 9725 case ISD::UMAX: 9726 return AMDGPUISD::UMAX3; 9727 case ISD::FMINNUM: 9728 case ISD::FMINNUM_IEEE: 9729 return AMDGPUISD::FMIN3; 9730 case ISD::SMIN: 9731 return AMDGPUISD::SMIN3; 9732 case ISD::UMIN: 9733 return AMDGPUISD::UMIN3; 9734 default: 9735 llvm_unreachable("Not a min/max opcode"); 9736 } 9737 } 9738 9739 SDValue SITargetLowering::performIntMed3ImmCombine( 9740 SelectionDAG &DAG, const SDLoc &SL, 9741 SDValue Op0, SDValue Op1, bool Signed) const { 9742 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9743 if (!K1) 9744 return SDValue(); 9745 9746 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9747 if (!K0) 9748 return SDValue(); 9749 9750 if (Signed) { 9751 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9752 return SDValue(); 9753 } else { 9754 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9755 return SDValue(); 9756 } 9757 9758 EVT VT = K0->getValueType(0); 9759 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9760 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9761 return DAG.getNode(Med3Opc, SL, VT, 9762 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9763 } 9764 9765 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9766 MVT NVT = MVT::i32; 9767 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9768 9769 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9770 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9771 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9772 9773 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9774 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9775 } 9776 9777 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9778 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9779 return C; 9780 9781 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9782 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9783 return C; 9784 } 9785 9786 return nullptr; 9787 } 9788 9789 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9790 const SDLoc &SL, 9791 SDValue Op0, 9792 SDValue Op1) const { 9793 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9794 if (!K1) 9795 return SDValue(); 9796 9797 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9798 if (!K0) 9799 return SDValue(); 9800 9801 // Ordered >= (although NaN inputs should have folded away by now). 9802 if (K0->getValueAPF() > K1->getValueAPF()) 9803 return SDValue(); 9804 9805 const MachineFunction &MF = DAG.getMachineFunction(); 9806 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9807 9808 // TODO: Check IEEE bit enabled? 9809 EVT VT = Op0.getValueType(); 9810 if (Info->getMode().DX10Clamp) { 9811 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9812 // hardware fmed3 behavior converting to a min. 9813 // FIXME: Should this be allowing -0.0? 9814 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9815 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9816 } 9817 9818 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9819 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9820 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9821 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9822 // then give the other result, which is different from med3 with a NaN 9823 // input. 9824 SDValue Var = Op0.getOperand(0); 9825 if (!DAG.isKnownNeverSNaN(Var)) 9826 return SDValue(); 9827 9828 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9829 9830 if ((!K0->hasOneUse() || 9831 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9832 (!K1->hasOneUse() || 9833 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9834 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9835 Var, SDValue(K0, 0), SDValue(K1, 0)); 9836 } 9837 } 9838 9839 return SDValue(); 9840 } 9841 9842 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9843 DAGCombinerInfo &DCI) const { 9844 SelectionDAG &DAG = DCI.DAG; 9845 9846 EVT VT = N->getValueType(0); 9847 unsigned Opc = N->getOpcode(); 9848 SDValue Op0 = N->getOperand(0); 9849 SDValue Op1 = N->getOperand(1); 9850 9851 // Only do this if the inner op has one use since this will just increases 9852 // register pressure for no benefit. 9853 9854 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9855 !VT.isVector() && 9856 (VT == MVT::i32 || VT == MVT::f32 || 9857 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9858 // max(max(a, b), c) -> max3(a, b, c) 9859 // min(min(a, b), c) -> min3(a, b, c) 9860 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9861 SDLoc DL(N); 9862 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9863 DL, 9864 N->getValueType(0), 9865 Op0.getOperand(0), 9866 Op0.getOperand(1), 9867 Op1); 9868 } 9869 9870 // Try commuted. 9871 // max(a, max(b, c)) -> max3(a, b, c) 9872 // min(a, min(b, c)) -> min3(a, b, c) 9873 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9874 SDLoc DL(N); 9875 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9876 DL, 9877 N->getValueType(0), 9878 Op0, 9879 Op1.getOperand(0), 9880 Op1.getOperand(1)); 9881 } 9882 } 9883 9884 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9885 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9886 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9887 return Med3; 9888 } 9889 9890 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9891 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9892 return Med3; 9893 } 9894 9895 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9896 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9897 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9898 (Opc == AMDGPUISD::FMIN_LEGACY && 9899 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9900 (VT == MVT::f32 || VT == MVT::f64 || 9901 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9902 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9903 Op0.hasOneUse()) { 9904 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9905 return Res; 9906 } 9907 9908 return SDValue(); 9909 } 9910 9911 static bool isClampZeroToOne(SDValue A, SDValue B) { 9912 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9913 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9914 // FIXME: Should this be allowing -0.0? 9915 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9916 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9917 } 9918 } 9919 9920 return false; 9921 } 9922 9923 // FIXME: Should only worry about snans for version with chain. 9924 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9925 DAGCombinerInfo &DCI) const { 9926 EVT VT = N->getValueType(0); 9927 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9928 // NaNs. With a NaN input, the order of the operands may change the result. 9929 9930 SelectionDAG &DAG = DCI.DAG; 9931 SDLoc SL(N); 9932 9933 SDValue Src0 = N->getOperand(0); 9934 SDValue Src1 = N->getOperand(1); 9935 SDValue Src2 = N->getOperand(2); 9936 9937 if (isClampZeroToOne(Src0, Src1)) { 9938 // const_a, const_b, x -> clamp is safe in all cases including signaling 9939 // nans. 9940 // FIXME: Should this be allowing -0.0? 9941 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9942 } 9943 9944 const MachineFunction &MF = DAG.getMachineFunction(); 9945 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9946 9947 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9948 // handling no dx10-clamp? 9949 if (Info->getMode().DX10Clamp) { 9950 // If NaNs is clamped to 0, we are free to reorder the inputs. 9951 9952 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9953 std::swap(Src0, Src1); 9954 9955 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9956 std::swap(Src1, Src2); 9957 9958 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9959 std::swap(Src0, Src1); 9960 9961 if (isClampZeroToOne(Src1, Src2)) 9962 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9963 } 9964 9965 return SDValue(); 9966 } 9967 9968 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9969 DAGCombinerInfo &DCI) const { 9970 SDValue Src0 = N->getOperand(0); 9971 SDValue Src1 = N->getOperand(1); 9972 if (Src0.isUndef() && Src1.isUndef()) 9973 return DCI.DAG.getUNDEF(N->getValueType(0)); 9974 return SDValue(); 9975 } 9976 9977 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9978 // expanded into a set of cmp/select instructions. 9979 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9980 unsigned NumElem, 9981 bool IsDivergentIdx) { 9982 if (UseDivergentRegisterIndexing) 9983 return false; 9984 9985 unsigned VecSize = EltSize * NumElem; 9986 9987 // Sub-dword vectors of size 2 dword or less have better implementation. 9988 if (VecSize <= 64 && EltSize < 32) 9989 return false; 9990 9991 // Always expand the rest of sub-dword instructions, otherwise it will be 9992 // lowered via memory. 9993 if (EltSize < 32) 9994 return true; 9995 9996 // Always do this if var-idx is divergent, otherwise it will become a loop. 9997 if (IsDivergentIdx) 9998 return true; 9999 10000 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10001 unsigned NumInsts = NumElem /* Number of compares */ + 10002 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10003 return NumInsts <= 16; 10004 } 10005 10006 static bool shouldExpandVectorDynExt(SDNode *N) { 10007 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10008 if (isa<ConstantSDNode>(Idx)) 10009 return false; 10010 10011 SDValue Vec = N->getOperand(0); 10012 EVT VecVT = Vec.getValueType(); 10013 EVT EltVT = VecVT.getVectorElementType(); 10014 unsigned EltSize = EltVT.getSizeInBits(); 10015 unsigned NumElem = VecVT.getVectorNumElements(); 10016 10017 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10018 Idx->isDivergent()); 10019 } 10020 10021 SDValue SITargetLowering::performExtractVectorEltCombine( 10022 SDNode *N, DAGCombinerInfo &DCI) const { 10023 SDValue Vec = N->getOperand(0); 10024 SelectionDAG &DAG = DCI.DAG; 10025 10026 EVT VecVT = Vec.getValueType(); 10027 EVT EltVT = VecVT.getVectorElementType(); 10028 10029 if ((Vec.getOpcode() == ISD::FNEG || 10030 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10031 SDLoc SL(N); 10032 EVT EltVT = N->getValueType(0); 10033 SDValue Idx = N->getOperand(1); 10034 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10035 Vec.getOperand(0), Idx); 10036 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10037 } 10038 10039 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10040 // => 10041 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10042 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10043 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10044 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10045 SDLoc SL(N); 10046 EVT EltVT = N->getValueType(0); 10047 SDValue Idx = N->getOperand(1); 10048 unsigned Opc = Vec.getOpcode(); 10049 10050 switch(Opc) { 10051 default: 10052 break; 10053 // TODO: Support other binary operations. 10054 case ISD::FADD: 10055 case ISD::FSUB: 10056 case ISD::FMUL: 10057 case ISD::ADD: 10058 case ISD::UMIN: 10059 case ISD::UMAX: 10060 case ISD::SMIN: 10061 case ISD::SMAX: 10062 case ISD::FMAXNUM: 10063 case ISD::FMINNUM: 10064 case ISD::FMAXNUM_IEEE: 10065 case ISD::FMINNUM_IEEE: { 10066 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10067 Vec.getOperand(0), Idx); 10068 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10069 Vec.getOperand(1), Idx); 10070 10071 DCI.AddToWorklist(Elt0.getNode()); 10072 DCI.AddToWorklist(Elt1.getNode()); 10073 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10074 } 10075 } 10076 } 10077 10078 unsigned VecSize = VecVT.getSizeInBits(); 10079 unsigned EltSize = EltVT.getSizeInBits(); 10080 10081 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10082 if (::shouldExpandVectorDynExt(N)) { 10083 SDLoc SL(N); 10084 SDValue Idx = N->getOperand(1); 10085 SDValue V; 10086 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10087 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10088 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10089 if (I == 0) 10090 V = Elt; 10091 else 10092 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10093 } 10094 return V; 10095 } 10096 10097 if (!DCI.isBeforeLegalize()) 10098 return SDValue(); 10099 10100 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10101 // elements. This exposes more load reduction opportunities by replacing 10102 // multiple small extract_vector_elements with a single 32-bit extract. 10103 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10104 if (isa<MemSDNode>(Vec) && 10105 EltSize <= 16 && 10106 EltVT.isByteSized() && 10107 VecSize > 32 && 10108 VecSize % 32 == 0 && 10109 Idx) { 10110 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10111 10112 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10113 unsigned EltIdx = BitIndex / 32; 10114 unsigned LeftoverBitIdx = BitIndex % 32; 10115 SDLoc SL(N); 10116 10117 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10118 DCI.AddToWorklist(Cast.getNode()); 10119 10120 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10121 DAG.getConstant(EltIdx, SL, MVT::i32)); 10122 DCI.AddToWorklist(Elt.getNode()); 10123 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10124 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10125 DCI.AddToWorklist(Srl.getNode()); 10126 10127 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10128 DCI.AddToWorklist(Trunc.getNode()); 10129 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10130 } 10131 10132 return SDValue(); 10133 } 10134 10135 SDValue 10136 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10137 DAGCombinerInfo &DCI) const { 10138 SDValue Vec = N->getOperand(0); 10139 SDValue Idx = N->getOperand(2); 10140 EVT VecVT = Vec.getValueType(); 10141 EVT EltVT = VecVT.getVectorElementType(); 10142 10143 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10144 // => BUILD_VECTOR n x select (e, const-idx) 10145 if (!::shouldExpandVectorDynExt(N)) 10146 return SDValue(); 10147 10148 SelectionDAG &DAG = DCI.DAG; 10149 SDLoc SL(N); 10150 SDValue Ins = N->getOperand(1); 10151 EVT IdxVT = Idx.getValueType(); 10152 10153 SmallVector<SDValue, 16> Ops; 10154 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10155 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10156 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10157 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10158 Ops.push_back(V); 10159 } 10160 10161 return DAG.getBuildVector(VecVT, SL, Ops); 10162 } 10163 10164 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10165 const SDNode *N0, 10166 const SDNode *N1) const { 10167 EVT VT = N0->getValueType(0); 10168 10169 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10170 // support denormals ever. 10171 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10172 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10173 getSubtarget()->hasMadF16())) && 10174 isOperationLegal(ISD::FMAD, VT)) 10175 return ISD::FMAD; 10176 10177 const TargetOptions &Options = DAG.getTarget().Options; 10178 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10179 (N0->getFlags().hasAllowContract() && 10180 N1->getFlags().hasAllowContract())) && 10181 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10182 return ISD::FMA; 10183 } 10184 10185 return 0; 10186 } 10187 10188 // For a reassociatable opcode perform: 10189 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10190 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10191 SelectionDAG &DAG) const { 10192 EVT VT = N->getValueType(0); 10193 if (VT != MVT::i32 && VT != MVT::i64) 10194 return SDValue(); 10195 10196 unsigned Opc = N->getOpcode(); 10197 SDValue Op0 = N->getOperand(0); 10198 SDValue Op1 = N->getOperand(1); 10199 10200 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10201 return SDValue(); 10202 10203 if (Op0->isDivergent()) 10204 std::swap(Op0, Op1); 10205 10206 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10207 return SDValue(); 10208 10209 SDValue Op2 = Op1.getOperand(1); 10210 Op1 = Op1.getOperand(0); 10211 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10212 return SDValue(); 10213 10214 if (Op1->isDivergent()) 10215 std::swap(Op1, Op2); 10216 10217 // If either operand is constant this will conflict with 10218 // DAGCombiner::ReassociateOps(). 10219 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10220 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10221 return SDValue(); 10222 10223 SDLoc SL(N); 10224 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10225 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10226 } 10227 10228 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10229 EVT VT, 10230 SDValue N0, SDValue N1, SDValue N2, 10231 bool Signed) { 10232 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10233 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10234 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10235 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10236 } 10237 10238 SDValue SITargetLowering::performAddCombine(SDNode *N, 10239 DAGCombinerInfo &DCI) const { 10240 SelectionDAG &DAG = DCI.DAG; 10241 EVT VT = N->getValueType(0); 10242 SDLoc SL(N); 10243 SDValue LHS = N->getOperand(0); 10244 SDValue RHS = N->getOperand(1); 10245 10246 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10247 && Subtarget->hasMad64_32() && 10248 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10249 VT.getScalarSizeInBits() <= 64) { 10250 if (LHS.getOpcode() != ISD::MUL) 10251 std::swap(LHS, RHS); 10252 10253 SDValue MulLHS = LHS.getOperand(0); 10254 SDValue MulRHS = LHS.getOperand(1); 10255 SDValue AddRHS = RHS; 10256 10257 // TODO: Maybe restrict if SGPR inputs. 10258 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10259 numBitsUnsigned(MulRHS, DAG) <= 32) { 10260 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10261 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10262 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10263 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10264 } 10265 10266 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10267 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10268 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10269 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10270 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10271 } 10272 10273 return SDValue(); 10274 } 10275 10276 if (SDValue V = reassociateScalarOps(N, DAG)) { 10277 return V; 10278 } 10279 10280 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10281 return SDValue(); 10282 10283 // add x, zext (setcc) => addcarry x, 0, setcc 10284 // add x, sext (setcc) => subcarry x, 0, setcc 10285 unsigned Opc = LHS.getOpcode(); 10286 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10287 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10288 std::swap(RHS, LHS); 10289 10290 Opc = RHS.getOpcode(); 10291 switch (Opc) { 10292 default: break; 10293 case ISD::ZERO_EXTEND: 10294 case ISD::SIGN_EXTEND: 10295 case ISD::ANY_EXTEND: { 10296 auto Cond = RHS.getOperand(0); 10297 // If this won't be a real VOPC output, we would still need to insert an 10298 // extra instruction anyway. 10299 if (!isBoolSGPR(Cond)) 10300 break; 10301 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10302 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10303 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10304 return DAG.getNode(Opc, SL, VTList, Args); 10305 } 10306 case ISD::ADDCARRY: { 10307 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10308 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10309 if (!C || C->getZExtValue() != 0) break; 10310 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10311 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10312 } 10313 } 10314 return SDValue(); 10315 } 10316 10317 SDValue SITargetLowering::performSubCombine(SDNode *N, 10318 DAGCombinerInfo &DCI) const { 10319 SelectionDAG &DAG = DCI.DAG; 10320 EVT VT = N->getValueType(0); 10321 10322 if (VT != MVT::i32) 10323 return SDValue(); 10324 10325 SDLoc SL(N); 10326 SDValue LHS = N->getOperand(0); 10327 SDValue RHS = N->getOperand(1); 10328 10329 // sub x, zext (setcc) => subcarry x, 0, setcc 10330 // sub x, sext (setcc) => addcarry x, 0, setcc 10331 unsigned Opc = RHS.getOpcode(); 10332 switch (Opc) { 10333 default: break; 10334 case ISD::ZERO_EXTEND: 10335 case ISD::SIGN_EXTEND: 10336 case ISD::ANY_EXTEND: { 10337 auto Cond = RHS.getOperand(0); 10338 // If this won't be a real VOPC output, we would still need to insert an 10339 // extra instruction anyway. 10340 if (!isBoolSGPR(Cond)) 10341 break; 10342 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10343 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10344 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10345 return DAG.getNode(Opc, SL, VTList, Args); 10346 } 10347 } 10348 10349 if (LHS.getOpcode() == ISD::SUBCARRY) { 10350 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10351 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10352 if (!C || !C->isNullValue()) 10353 return SDValue(); 10354 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10355 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10356 } 10357 return SDValue(); 10358 } 10359 10360 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10361 DAGCombinerInfo &DCI) const { 10362 10363 if (N->getValueType(0) != MVT::i32) 10364 return SDValue(); 10365 10366 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10367 if (!C || C->getZExtValue() != 0) 10368 return SDValue(); 10369 10370 SelectionDAG &DAG = DCI.DAG; 10371 SDValue LHS = N->getOperand(0); 10372 10373 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10374 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10375 unsigned LHSOpc = LHS.getOpcode(); 10376 unsigned Opc = N->getOpcode(); 10377 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10378 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10379 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10380 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10381 } 10382 return SDValue(); 10383 } 10384 10385 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10386 DAGCombinerInfo &DCI) const { 10387 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10388 return SDValue(); 10389 10390 SelectionDAG &DAG = DCI.DAG; 10391 EVT VT = N->getValueType(0); 10392 10393 SDLoc SL(N); 10394 SDValue LHS = N->getOperand(0); 10395 SDValue RHS = N->getOperand(1); 10396 10397 // These should really be instruction patterns, but writing patterns with 10398 // source modiifiers is a pain. 10399 10400 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10401 if (LHS.getOpcode() == ISD::FADD) { 10402 SDValue A = LHS.getOperand(0); 10403 if (A == LHS.getOperand(1)) { 10404 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10405 if (FusedOp != 0) { 10406 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10407 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10408 } 10409 } 10410 } 10411 10412 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10413 if (RHS.getOpcode() == ISD::FADD) { 10414 SDValue A = RHS.getOperand(0); 10415 if (A == RHS.getOperand(1)) { 10416 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10417 if (FusedOp != 0) { 10418 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10419 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10420 } 10421 } 10422 } 10423 10424 return SDValue(); 10425 } 10426 10427 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10428 DAGCombinerInfo &DCI) const { 10429 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10430 return SDValue(); 10431 10432 SelectionDAG &DAG = DCI.DAG; 10433 SDLoc SL(N); 10434 EVT VT = N->getValueType(0); 10435 assert(!VT.isVector()); 10436 10437 // Try to get the fneg to fold into the source modifier. This undoes generic 10438 // DAG combines and folds them into the mad. 10439 // 10440 // Only do this if we are not trying to support denormals. v_mad_f32 does 10441 // not support denormals ever. 10442 SDValue LHS = N->getOperand(0); 10443 SDValue RHS = N->getOperand(1); 10444 if (LHS.getOpcode() == ISD::FADD) { 10445 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10446 SDValue A = LHS.getOperand(0); 10447 if (A == LHS.getOperand(1)) { 10448 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10449 if (FusedOp != 0){ 10450 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10451 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10452 10453 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10454 } 10455 } 10456 } 10457 10458 if (RHS.getOpcode() == ISD::FADD) { 10459 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10460 10461 SDValue A = RHS.getOperand(0); 10462 if (A == RHS.getOperand(1)) { 10463 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10464 if (FusedOp != 0){ 10465 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10466 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10467 } 10468 } 10469 } 10470 10471 return SDValue(); 10472 } 10473 10474 SDValue SITargetLowering::performFMACombine(SDNode *N, 10475 DAGCombinerInfo &DCI) const { 10476 SelectionDAG &DAG = DCI.DAG; 10477 EVT VT = N->getValueType(0); 10478 SDLoc SL(N); 10479 10480 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10481 return SDValue(); 10482 10483 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10484 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10485 SDValue Op1 = N->getOperand(0); 10486 SDValue Op2 = N->getOperand(1); 10487 SDValue FMA = N->getOperand(2); 10488 10489 if (FMA.getOpcode() != ISD::FMA || 10490 Op1.getOpcode() != ISD::FP_EXTEND || 10491 Op2.getOpcode() != ISD::FP_EXTEND) 10492 return SDValue(); 10493 10494 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10495 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10496 // is sufficient to allow generaing fdot2. 10497 const TargetOptions &Options = DAG.getTarget().Options; 10498 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10499 (N->getFlags().hasAllowContract() && 10500 FMA->getFlags().hasAllowContract())) { 10501 Op1 = Op1.getOperand(0); 10502 Op2 = Op2.getOperand(0); 10503 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10504 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10505 return SDValue(); 10506 10507 SDValue Vec1 = Op1.getOperand(0); 10508 SDValue Idx1 = Op1.getOperand(1); 10509 SDValue Vec2 = Op2.getOperand(0); 10510 10511 SDValue FMAOp1 = FMA.getOperand(0); 10512 SDValue FMAOp2 = FMA.getOperand(1); 10513 SDValue FMAAcc = FMA.getOperand(2); 10514 10515 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10516 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10517 return SDValue(); 10518 10519 FMAOp1 = FMAOp1.getOperand(0); 10520 FMAOp2 = FMAOp2.getOperand(0); 10521 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10522 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10523 return SDValue(); 10524 10525 SDValue Vec3 = FMAOp1.getOperand(0); 10526 SDValue Vec4 = FMAOp2.getOperand(0); 10527 SDValue Idx2 = FMAOp1.getOperand(1); 10528 10529 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10530 // Idx1 and Idx2 cannot be the same. 10531 Idx1 == Idx2) 10532 return SDValue(); 10533 10534 if (Vec1 == Vec2 || Vec3 == Vec4) 10535 return SDValue(); 10536 10537 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10538 return SDValue(); 10539 10540 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10541 (Vec1 == Vec4 && Vec2 == Vec3)) { 10542 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10543 DAG.getTargetConstant(0, SL, MVT::i1)); 10544 } 10545 } 10546 return SDValue(); 10547 } 10548 10549 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10550 DAGCombinerInfo &DCI) const { 10551 SelectionDAG &DAG = DCI.DAG; 10552 SDLoc SL(N); 10553 10554 SDValue LHS = N->getOperand(0); 10555 SDValue RHS = N->getOperand(1); 10556 EVT VT = LHS.getValueType(); 10557 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10558 10559 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10560 if (!CRHS) { 10561 CRHS = dyn_cast<ConstantSDNode>(LHS); 10562 if (CRHS) { 10563 std::swap(LHS, RHS); 10564 CC = getSetCCSwappedOperands(CC); 10565 } 10566 } 10567 10568 if (CRHS) { 10569 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10570 isBoolSGPR(LHS.getOperand(0))) { 10571 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10572 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10573 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10574 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10575 if ((CRHS->isAllOnesValue() && 10576 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10577 (CRHS->isNullValue() && 10578 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10579 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10580 DAG.getConstant(-1, SL, MVT::i1)); 10581 if ((CRHS->isAllOnesValue() && 10582 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10583 (CRHS->isNullValue() && 10584 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10585 return LHS.getOperand(0); 10586 } 10587 10588 uint64_t CRHSVal = CRHS->getZExtValue(); 10589 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10590 LHS.getOpcode() == ISD::SELECT && 10591 isa<ConstantSDNode>(LHS.getOperand(1)) && 10592 isa<ConstantSDNode>(LHS.getOperand(2)) && 10593 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10594 isBoolSGPR(LHS.getOperand(0))) { 10595 // Given CT != FT: 10596 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10597 // setcc (select cc, CT, CF), CF, ne => cc 10598 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10599 // setcc (select cc, CT, CF), CT, eq => cc 10600 uint64_t CT = LHS.getConstantOperandVal(1); 10601 uint64_t CF = LHS.getConstantOperandVal(2); 10602 10603 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10604 (CT == CRHSVal && CC == ISD::SETNE)) 10605 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10606 DAG.getConstant(-1, SL, MVT::i1)); 10607 if ((CF == CRHSVal && CC == ISD::SETNE) || 10608 (CT == CRHSVal && CC == ISD::SETEQ)) 10609 return LHS.getOperand(0); 10610 } 10611 } 10612 10613 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10614 VT != MVT::f16)) 10615 return SDValue(); 10616 10617 // Match isinf/isfinite pattern 10618 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10619 // (fcmp one (fabs x), inf) -> (fp_class x, 10620 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10621 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10622 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10623 if (!CRHS) 10624 return SDValue(); 10625 10626 const APFloat &APF = CRHS->getValueAPF(); 10627 if (APF.isInfinity() && !APF.isNegative()) { 10628 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10629 SIInstrFlags::N_INFINITY; 10630 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10631 SIInstrFlags::P_ZERO | 10632 SIInstrFlags::N_NORMAL | 10633 SIInstrFlags::P_NORMAL | 10634 SIInstrFlags::N_SUBNORMAL | 10635 SIInstrFlags::P_SUBNORMAL; 10636 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10637 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10638 DAG.getConstant(Mask, SL, MVT::i32)); 10639 } 10640 } 10641 10642 return SDValue(); 10643 } 10644 10645 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10646 DAGCombinerInfo &DCI) const { 10647 SelectionDAG &DAG = DCI.DAG; 10648 SDLoc SL(N); 10649 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10650 10651 SDValue Src = N->getOperand(0); 10652 SDValue Shift = N->getOperand(0); 10653 10654 // TODO: Extend type shouldn't matter (assuming legal types). 10655 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10656 Shift = Shift.getOperand(0); 10657 10658 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10659 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10660 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10661 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10662 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10663 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10664 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10665 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10666 SDLoc(Shift.getOperand(0)), MVT::i32); 10667 10668 unsigned ShiftOffset = 8 * Offset; 10669 if (Shift.getOpcode() == ISD::SHL) 10670 ShiftOffset -= C->getZExtValue(); 10671 else 10672 ShiftOffset += C->getZExtValue(); 10673 10674 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10675 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10676 MVT::f32, Shift); 10677 } 10678 } 10679 } 10680 10681 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10682 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10683 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10684 // We simplified Src. If this node is not dead, visit it again so it is 10685 // folded properly. 10686 if (N->getOpcode() != ISD::DELETED_NODE) 10687 DCI.AddToWorklist(N); 10688 return SDValue(N, 0); 10689 } 10690 10691 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10692 if (SDValue DemandedSrc = 10693 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10694 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10695 10696 return SDValue(); 10697 } 10698 10699 SDValue SITargetLowering::performClampCombine(SDNode *N, 10700 DAGCombinerInfo &DCI) const { 10701 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10702 if (!CSrc) 10703 return SDValue(); 10704 10705 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10706 const APFloat &F = CSrc->getValueAPF(); 10707 APFloat Zero = APFloat::getZero(F.getSemantics()); 10708 if (F < Zero || 10709 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10710 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10711 } 10712 10713 APFloat One(F.getSemantics(), "1.0"); 10714 if (F > One) 10715 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10716 10717 return SDValue(CSrc, 0); 10718 } 10719 10720 10721 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10722 DAGCombinerInfo &DCI) const { 10723 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10724 return SDValue(); 10725 switch (N->getOpcode()) { 10726 case ISD::ADD: 10727 return performAddCombine(N, DCI); 10728 case ISD::SUB: 10729 return performSubCombine(N, DCI); 10730 case ISD::ADDCARRY: 10731 case ISD::SUBCARRY: 10732 return performAddCarrySubCarryCombine(N, DCI); 10733 case ISD::FADD: 10734 return performFAddCombine(N, DCI); 10735 case ISD::FSUB: 10736 return performFSubCombine(N, DCI); 10737 case ISD::SETCC: 10738 return performSetCCCombine(N, DCI); 10739 case ISD::FMAXNUM: 10740 case ISD::FMINNUM: 10741 case ISD::FMAXNUM_IEEE: 10742 case ISD::FMINNUM_IEEE: 10743 case ISD::SMAX: 10744 case ISD::SMIN: 10745 case ISD::UMAX: 10746 case ISD::UMIN: 10747 case AMDGPUISD::FMIN_LEGACY: 10748 case AMDGPUISD::FMAX_LEGACY: 10749 return performMinMaxCombine(N, DCI); 10750 case ISD::FMA: 10751 return performFMACombine(N, DCI); 10752 case ISD::AND: 10753 return performAndCombine(N, DCI); 10754 case ISD::OR: 10755 return performOrCombine(N, DCI); 10756 case ISD::XOR: 10757 return performXorCombine(N, DCI); 10758 case ISD::ZERO_EXTEND: 10759 return performZeroExtendCombine(N, DCI); 10760 case ISD::SIGN_EXTEND_INREG: 10761 return performSignExtendInRegCombine(N , DCI); 10762 case AMDGPUISD::FP_CLASS: 10763 return performClassCombine(N, DCI); 10764 case ISD::FCANONICALIZE: 10765 return performFCanonicalizeCombine(N, DCI); 10766 case AMDGPUISD::RCP: 10767 return performRcpCombine(N, DCI); 10768 case AMDGPUISD::FRACT: 10769 case AMDGPUISD::RSQ: 10770 case AMDGPUISD::RCP_LEGACY: 10771 case AMDGPUISD::RCP_IFLAG: 10772 case AMDGPUISD::RSQ_CLAMP: 10773 case AMDGPUISD::LDEXP: { 10774 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10775 SDValue Src = N->getOperand(0); 10776 if (Src.isUndef()) 10777 return Src; 10778 break; 10779 } 10780 case ISD::SINT_TO_FP: 10781 case ISD::UINT_TO_FP: 10782 return performUCharToFloatCombine(N, DCI); 10783 case AMDGPUISD::CVT_F32_UBYTE0: 10784 case AMDGPUISD::CVT_F32_UBYTE1: 10785 case AMDGPUISD::CVT_F32_UBYTE2: 10786 case AMDGPUISD::CVT_F32_UBYTE3: 10787 return performCvtF32UByteNCombine(N, DCI); 10788 case AMDGPUISD::FMED3: 10789 return performFMed3Combine(N, DCI); 10790 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10791 return performCvtPkRTZCombine(N, DCI); 10792 case AMDGPUISD::CLAMP: 10793 return performClampCombine(N, DCI); 10794 case ISD::SCALAR_TO_VECTOR: { 10795 SelectionDAG &DAG = DCI.DAG; 10796 EVT VT = N->getValueType(0); 10797 10798 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10799 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10800 SDLoc SL(N); 10801 SDValue Src = N->getOperand(0); 10802 EVT EltVT = Src.getValueType(); 10803 if (EltVT == MVT::f16) 10804 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10805 10806 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10807 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10808 } 10809 10810 break; 10811 } 10812 case ISD::EXTRACT_VECTOR_ELT: 10813 return performExtractVectorEltCombine(N, DCI); 10814 case ISD::INSERT_VECTOR_ELT: 10815 return performInsertVectorEltCombine(N, DCI); 10816 case ISD::LOAD: { 10817 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10818 return Widended; 10819 LLVM_FALLTHROUGH; 10820 } 10821 default: { 10822 if (!DCI.isBeforeLegalize()) { 10823 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10824 return performMemSDNodeCombine(MemNode, DCI); 10825 } 10826 10827 break; 10828 } 10829 } 10830 10831 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10832 } 10833 10834 /// Helper function for adjustWritemask 10835 static unsigned SubIdx2Lane(unsigned Idx) { 10836 switch (Idx) { 10837 default: return 0; 10838 case AMDGPU::sub0: return 0; 10839 case AMDGPU::sub1: return 1; 10840 case AMDGPU::sub2: return 2; 10841 case AMDGPU::sub3: return 3; 10842 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10843 } 10844 } 10845 10846 /// Adjust the writemask of MIMG instructions 10847 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10848 SelectionDAG &DAG) const { 10849 unsigned Opcode = Node->getMachineOpcode(); 10850 10851 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10852 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10853 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10854 return Node; // not implemented for D16 10855 10856 SDNode *Users[5] = { nullptr }; 10857 unsigned Lane = 0; 10858 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10859 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10860 unsigned NewDmask = 0; 10861 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10862 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10863 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10864 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10865 unsigned TFCLane = 0; 10866 bool HasChain = Node->getNumValues() > 1; 10867 10868 if (OldDmask == 0) { 10869 // These are folded out, but on the chance it happens don't assert. 10870 return Node; 10871 } 10872 10873 unsigned OldBitsSet = countPopulation(OldDmask); 10874 // Work out which is the TFE/LWE lane if that is enabled. 10875 if (UsesTFC) { 10876 TFCLane = OldBitsSet; 10877 } 10878 10879 // Try to figure out the used register components 10880 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10881 I != E; ++I) { 10882 10883 // Don't look at users of the chain. 10884 if (I.getUse().getResNo() != 0) 10885 continue; 10886 10887 // Abort if we can't understand the usage 10888 if (!I->isMachineOpcode() || 10889 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10890 return Node; 10891 10892 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10893 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10894 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10895 // set, etc. 10896 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10897 10898 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10899 if (UsesTFC && Lane == TFCLane) { 10900 Users[Lane] = *I; 10901 } else { 10902 // Set which texture component corresponds to the lane. 10903 unsigned Comp; 10904 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10905 Comp = countTrailingZeros(Dmask); 10906 Dmask &= ~(1 << Comp); 10907 } 10908 10909 // Abort if we have more than one user per component. 10910 if (Users[Lane]) 10911 return Node; 10912 10913 Users[Lane] = *I; 10914 NewDmask |= 1 << Comp; 10915 } 10916 } 10917 10918 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10919 bool NoChannels = !NewDmask; 10920 if (NoChannels) { 10921 if (!UsesTFC) { 10922 // No uses of the result and not using TFC. Then do nothing. 10923 return Node; 10924 } 10925 // If the original dmask has one channel - then nothing to do 10926 if (OldBitsSet == 1) 10927 return Node; 10928 // Use an arbitrary dmask - required for the instruction to work 10929 NewDmask = 1; 10930 } 10931 // Abort if there's no change 10932 if (NewDmask == OldDmask) 10933 return Node; 10934 10935 unsigned BitsSet = countPopulation(NewDmask); 10936 10937 // Check for TFE or LWE - increase the number of channels by one to account 10938 // for the extra return value 10939 // This will need adjustment for D16 if this is also included in 10940 // adjustWriteMask (this function) but at present D16 are excluded. 10941 unsigned NewChannels = BitsSet + UsesTFC; 10942 10943 int NewOpcode = 10944 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10945 assert(NewOpcode != -1 && 10946 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10947 "failed to find equivalent MIMG op"); 10948 10949 // Adjust the writemask in the node 10950 SmallVector<SDValue, 12> Ops; 10951 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10952 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10953 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10954 10955 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10956 10957 MVT ResultVT = NewChannels == 1 ? 10958 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10959 NewChannels == 5 ? 8 : NewChannels); 10960 SDVTList NewVTList = HasChain ? 10961 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10962 10963 10964 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10965 NewVTList, Ops); 10966 10967 if (HasChain) { 10968 // Update chain. 10969 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10970 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10971 } 10972 10973 if (NewChannels == 1) { 10974 assert(Node->hasNUsesOfValue(1, 0)); 10975 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10976 SDLoc(Node), Users[Lane]->getValueType(0), 10977 SDValue(NewNode, 0)); 10978 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10979 return nullptr; 10980 } 10981 10982 // Update the users of the node with the new indices 10983 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10984 SDNode *User = Users[i]; 10985 if (!User) { 10986 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10987 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10988 if (i || !NoChannels) 10989 continue; 10990 } else { 10991 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10992 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10993 } 10994 10995 switch (Idx) { 10996 default: break; 10997 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10998 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10999 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11000 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11001 } 11002 } 11003 11004 DAG.RemoveDeadNode(Node); 11005 return nullptr; 11006 } 11007 11008 static bool isFrameIndexOp(SDValue Op) { 11009 if (Op.getOpcode() == ISD::AssertZext) 11010 Op = Op.getOperand(0); 11011 11012 return isa<FrameIndexSDNode>(Op); 11013 } 11014 11015 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11016 /// with frame index operands. 11017 /// LLVM assumes that inputs are to these instructions are registers. 11018 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11019 SelectionDAG &DAG) const { 11020 if (Node->getOpcode() == ISD::CopyToReg) { 11021 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11022 SDValue SrcVal = Node->getOperand(2); 11023 11024 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11025 // to try understanding copies to physical registers. 11026 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11027 SDLoc SL(Node); 11028 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11029 SDValue VReg = DAG.getRegister( 11030 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11031 11032 SDNode *Glued = Node->getGluedNode(); 11033 SDValue ToVReg 11034 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11035 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11036 SDValue ToResultReg 11037 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11038 VReg, ToVReg.getValue(1)); 11039 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11040 DAG.RemoveDeadNode(Node); 11041 return ToResultReg.getNode(); 11042 } 11043 } 11044 11045 SmallVector<SDValue, 8> Ops; 11046 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11047 if (!isFrameIndexOp(Node->getOperand(i))) { 11048 Ops.push_back(Node->getOperand(i)); 11049 continue; 11050 } 11051 11052 SDLoc DL(Node); 11053 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11054 Node->getOperand(i).getValueType(), 11055 Node->getOperand(i)), 0)); 11056 } 11057 11058 return DAG.UpdateNodeOperands(Node, Ops); 11059 } 11060 11061 /// Fold the instructions after selecting them. 11062 /// Returns null if users were already updated. 11063 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11064 SelectionDAG &DAG) const { 11065 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11066 unsigned Opcode = Node->getMachineOpcode(); 11067 11068 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11069 !TII->isGather4(Opcode) && 11070 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11071 return adjustWritemask(Node, DAG); 11072 } 11073 11074 if (Opcode == AMDGPU::INSERT_SUBREG || 11075 Opcode == AMDGPU::REG_SEQUENCE) { 11076 legalizeTargetIndependentNode(Node, DAG); 11077 return Node; 11078 } 11079 11080 switch (Opcode) { 11081 case AMDGPU::V_DIV_SCALE_F32: 11082 case AMDGPU::V_DIV_SCALE_F64: { 11083 // Satisfy the operand register constraint when one of the inputs is 11084 // undefined. Ordinarily each undef value will have its own implicit_def of 11085 // a vreg, so force these to use a single register. 11086 SDValue Src0 = Node->getOperand(1); 11087 SDValue Src1 = Node->getOperand(3); 11088 SDValue Src2 = Node->getOperand(5); 11089 11090 if ((Src0.isMachineOpcode() && 11091 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11092 (Src0 == Src1 || Src0 == Src2)) 11093 break; 11094 11095 MVT VT = Src0.getValueType().getSimpleVT(); 11096 const TargetRegisterClass *RC = 11097 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11098 11099 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11100 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11101 11102 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11103 UndefReg, Src0, SDValue()); 11104 11105 // src0 must be the same register as src1 or src2, even if the value is 11106 // undefined, so make sure we don't violate this constraint. 11107 if (Src0.isMachineOpcode() && 11108 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11109 if (Src1.isMachineOpcode() && 11110 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11111 Src0 = Src1; 11112 else if (Src2.isMachineOpcode() && 11113 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11114 Src0 = Src2; 11115 else { 11116 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11117 Src0 = UndefReg; 11118 Src1 = UndefReg; 11119 } 11120 } else 11121 break; 11122 11123 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11124 Ops[1] = Src0; 11125 Ops[3] = Src1; 11126 Ops[5] = Src2; 11127 Ops.push_back(ImpDef.getValue(1)); 11128 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11129 } 11130 default: 11131 break; 11132 } 11133 11134 return Node; 11135 } 11136 11137 /// Assign the register class depending on the number of 11138 /// bits set in the writemask 11139 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11140 SDNode *Node) const { 11141 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11142 11143 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11144 11145 if (TII->isVOP3(MI.getOpcode())) { 11146 // Make sure constant bus requirements are respected. 11147 TII->legalizeOperandsVOP3(MRI, MI); 11148 11149 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11150 // This saves a chain-copy of registers and better ballance register 11151 // use between vgpr and agpr as agpr tuples tend to be big. 11152 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11153 unsigned Opc = MI.getOpcode(); 11154 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11155 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11156 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11157 if (I == -1) 11158 break; 11159 MachineOperand &Op = MI.getOperand(I); 11160 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11161 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11162 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11163 continue; 11164 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11165 if (!Src || !Src->isCopy() || 11166 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11167 continue; 11168 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11169 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11170 // All uses of agpr64 and agpr32 can also accept vgpr except for 11171 // v_accvgpr_read, but we do not produce agpr reads during selection, 11172 // so no use checks are needed. 11173 MRI.setRegClass(Op.getReg(), NewRC); 11174 } 11175 } 11176 11177 return; 11178 } 11179 11180 // Replace unused atomics with the no return version. 11181 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11182 if (NoRetAtomicOp != -1) { 11183 if (!Node->hasAnyUseOfValue(0)) { 11184 int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11185 AMDGPU::OpName::glc1); 11186 if (Glc1Idx != -1) 11187 MI.RemoveOperand(Glc1Idx); 11188 MI.RemoveOperand(0); 11189 MI.setDesc(TII->get(NoRetAtomicOp)); 11190 return; 11191 } 11192 11193 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11194 // instruction, because the return type of these instructions is a vec2 of 11195 // the memory type, so it can be tied to the input operand. 11196 // This means these instructions always have a use, so we need to add a 11197 // special case to check if the atomic has only one extract_subreg use, 11198 // which itself has no uses. 11199 if ((Node->hasNUsesOfValue(1, 0) && 11200 Node->use_begin()->isMachineOpcode() && 11201 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11202 !Node->use_begin()->hasAnyUseOfValue(0))) { 11203 Register Def = MI.getOperand(0).getReg(); 11204 11205 // Change this into a noret atomic. 11206 MI.setDesc(TII->get(NoRetAtomicOp)); 11207 MI.RemoveOperand(0); 11208 11209 // If we only remove the def operand from the atomic instruction, the 11210 // extract_subreg will be left with a use of a vreg without a def. 11211 // So we need to insert an implicit_def to avoid machine verifier 11212 // errors. 11213 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11214 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11215 } 11216 return; 11217 } 11218 } 11219 11220 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11221 uint64_t Val) { 11222 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11223 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11224 } 11225 11226 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11227 const SDLoc &DL, 11228 SDValue Ptr) const { 11229 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11230 11231 // Build the half of the subregister with the constants before building the 11232 // full 128-bit register. If we are building multiple resource descriptors, 11233 // this will allow CSEing of the 2-component register. 11234 const SDValue Ops0[] = { 11235 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11236 buildSMovImm32(DAG, DL, 0), 11237 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11238 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11239 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11240 }; 11241 11242 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11243 MVT::v2i32, Ops0), 0); 11244 11245 // Combine the constants and the pointer. 11246 const SDValue Ops1[] = { 11247 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11248 Ptr, 11249 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11250 SubRegHi, 11251 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11252 }; 11253 11254 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11255 } 11256 11257 /// Return a resource descriptor with the 'Add TID' bit enabled 11258 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11259 /// of the resource descriptor) to create an offset, which is added to 11260 /// the resource pointer. 11261 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11262 SDValue Ptr, uint32_t RsrcDword1, 11263 uint64_t RsrcDword2And3) const { 11264 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11265 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11266 if (RsrcDword1) { 11267 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11268 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11269 0); 11270 } 11271 11272 SDValue DataLo = buildSMovImm32(DAG, DL, 11273 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11274 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11275 11276 const SDValue Ops[] = { 11277 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11278 PtrLo, 11279 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11280 PtrHi, 11281 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11282 DataLo, 11283 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11284 DataHi, 11285 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11286 }; 11287 11288 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11289 } 11290 11291 //===----------------------------------------------------------------------===// 11292 // SI Inline Assembly Support 11293 //===----------------------------------------------------------------------===// 11294 11295 std::pair<unsigned, const TargetRegisterClass *> 11296 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11297 StringRef Constraint, 11298 MVT VT) const { 11299 const TargetRegisterClass *RC = nullptr; 11300 if (Constraint.size() == 1) { 11301 const unsigned BitWidth = VT.getSizeInBits(); 11302 switch (Constraint[0]) { 11303 default: 11304 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11305 case 's': 11306 case 'r': 11307 switch (BitWidth) { 11308 case 16: 11309 RC = &AMDGPU::SReg_32RegClass; 11310 break; 11311 case 64: 11312 RC = &AMDGPU::SGPR_64RegClass; 11313 break; 11314 default: 11315 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11316 if (!RC) 11317 return std::make_pair(0U, nullptr); 11318 break; 11319 } 11320 break; 11321 case 'v': 11322 switch (BitWidth) { 11323 case 16: 11324 RC = &AMDGPU::VGPR_32RegClass; 11325 break; 11326 default: 11327 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11328 if (!RC) 11329 return std::make_pair(0U, nullptr); 11330 break; 11331 } 11332 break; 11333 case 'a': 11334 if (!Subtarget->hasMAIInsts()) 11335 break; 11336 switch (BitWidth) { 11337 case 16: 11338 RC = &AMDGPU::AGPR_32RegClass; 11339 break; 11340 default: 11341 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11342 if (!RC) 11343 return std::make_pair(0U, nullptr); 11344 break; 11345 } 11346 break; 11347 } 11348 // We actually support i128, i16 and f16 as inline parameters 11349 // even if they are not reported as legal 11350 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11351 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11352 return std::make_pair(0U, RC); 11353 } 11354 11355 if (Constraint.size() > 1) { 11356 if (Constraint[1] == 'v') { 11357 RC = &AMDGPU::VGPR_32RegClass; 11358 } else if (Constraint[1] == 's') { 11359 RC = &AMDGPU::SGPR_32RegClass; 11360 } else if (Constraint[1] == 'a') { 11361 RC = &AMDGPU::AGPR_32RegClass; 11362 } 11363 11364 if (RC) { 11365 uint32_t Idx; 11366 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11367 if (!Failed && Idx < RC->getNumRegs()) 11368 return std::make_pair(RC->getRegister(Idx), RC); 11369 } 11370 } 11371 11372 // FIXME: Returns VS_32 for physical SGPR constraints 11373 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11374 } 11375 11376 static bool isImmConstraint(StringRef Constraint) { 11377 if (Constraint.size() == 1) { 11378 switch (Constraint[0]) { 11379 default: break; 11380 case 'I': 11381 case 'J': 11382 case 'A': 11383 case 'B': 11384 case 'C': 11385 return true; 11386 } 11387 } else if (Constraint == "DA" || 11388 Constraint == "DB") { 11389 return true; 11390 } 11391 return false; 11392 } 11393 11394 SITargetLowering::ConstraintType 11395 SITargetLowering::getConstraintType(StringRef Constraint) const { 11396 if (Constraint.size() == 1) { 11397 switch (Constraint[0]) { 11398 default: break; 11399 case 's': 11400 case 'v': 11401 case 'a': 11402 return C_RegisterClass; 11403 } 11404 } 11405 if (isImmConstraint(Constraint)) { 11406 return C_Other; 11407 } 11408 return TargetLowering::getConstraintType(Constraint); 11409 } 11410 11411 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11412 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11413 Val = Val & maskTrailingOnes<uint64_t>(Size); 11414 } 11415 return Val; 11416 } 11417 11418 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11419 std::string &Constraint, 11420 std::vector<SDValue> &Ops, 11421 SelectionDAG &DAG) const { 11422 if (isImmConstraint(Constraint)) { 11423 uint64_t Val; 11424 if (getAsmOperandConstVal(Op, Val) && 11425 checkAsmConstraintVal(Op, Constraint, Val)) { 11426 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11427 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11428 } 11429 } else { 11430 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11431 } 11432 } 11433 11434 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11435 unsigned Size = Op.getScalarValueSizeInBits(); 11436 if (Size > 64) 11437 return false; 11438 11439 if (Size == 16 && !Subtarget->has16BitInsts()) 11440 return false; 11441 11442 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11443 Val = C->getSExtValue(); 11444 return true; 11445 } 11446 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11447 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11448 return true; 11449 } 11450 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11451 if (Size != 16 || Op.getNumOperands() != 2) 11452 return false; 11453 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11454 return false; 11455 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11456 Val = C->getSExtValue(); 11457 return true; 11458 } 11459 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11460 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11461 return true; 11462 } 11463 } 11464 11465 return false; 11466 } 11467 11468 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11469 const std::string &Constraint, 11470 uint64_t Val) const { 11471 if (Constraint.size() == 1) { 11472 switch (Constraint[0]) { 11473 case 'I': 11474 return AMDGPU::isInlinableIntLiteral(Val); 11475 case 'J': 11476 return isInt<16>(Val); 11477 case 'A': 11478 return checkAsmConstraintValA(Op, Val); 11479 case 'B': 11480 return isInt<32>(Val); 11481 case 'C': 11482 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11483 AMDGPU::isInlinableIntLiteral(Val); 11484 default: 11485 break; 11486 } 11487 } else if (Constraint.size() == 2) { 11488 if (Constraint == "DA") { 11489 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11490 int64_t LoBits = static_cast<int32_t>(Val); 11491 return checkAsmConstraintValA(Op, HiBits, 32) && 11492 checkAsmConstraintValA(Op, LoBits, 32); 11493 } 11494 if (Constraint == "DB") { 11495 return true; 11496 } 11497 } 11498 llvm_unreachable("Invalid asm constraint"); 11499 } 11500 11501 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11502 uint64_t Val, 11503 unsigned MaxSize) const { 11504 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11505 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11506 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11507 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11508 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11509 return true; 11510 } 11511 return false; 11512 } 11513 11514 // Figure out which registers should be reserved for stack access. Only after 11515 // the function is legalized do we know all of the non-spill stack objects or if 11516 // calls are present. 11517 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11518 MachineRegisterInfo &MRI = MF.getRegInfo(); 11519 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11520 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11521 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11522 11523 if (Info->isEntryFunction()) { 11524 // Callable functions have fixed registers used for stack access. 11525 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11526 } 11527 11528 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11529 Info->getStackPtrOffsetReg())); 11530 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11531 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11532 11533 // We need to worry about replacing the default register with itself in case 11534 // of MIR testcases missing the MFI. 11535 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11536 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11537 11538 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11539 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11540 11541 Info->limitOccupancy(MF); 11542 11543 if (ST.isWave32() && !MF.empty()) { 11544 // Add VCC_HI def because many instructions marked as imp-use VCC where 11545 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11546 // having a use of undef. 11547 11548 const SIInstrInfo *TII = ST.getInstrInfo(); 11549 DebugLoc DL; 11550 11551 MachineBasicBlock &MBB = MF.front(); 11552 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11553 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11554 11555 for (auto &MBB : MF) { 11556 for (auto &MI : MBB) { 11557 TII->fixImplicitOperands(MI); 11558 } 11559 } 11560 } 11561 11562 TargetLoweringBase::finalizeLowering(MF); 11563 11564 // Allocate a VGPR for future SGPR Spill if 11565 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11566 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11567 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11568 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11569 Info->reserveVGPRforSGPRSpills(MF); 11570 } 11571 11572 void SITargetLowering::computeKnownBitsForFrameIndex( 11573 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11574 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11575 11576 // Set the high bits to zero based on the maximum allowed scratch size per 11577 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11578 // calculation won't overflow, so assume the sign bit is never set. 11579 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11580 } 11581 11582 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11583 KnownBits &Known, unsigned Dim) { 11584 unsigned MaxValue = 11585 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11586 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11587 } 11588 11589 void SITargetLowering::computeKnownBitsForTargetInstr( 11590 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11591 const MachineRegisterInfo &MRI, unsigned Depth) const { 11592 const MachineInstr *MI = MRI.getVRegDef(R); 11593 switch (MI->getOpcode()) { 11594 case AMDGPU::G_INTRINSIC: { 11595 switch (MI->getIntrinsicID()) { 11596 case Intrinsic::amdgcn_workitem_id_x: 11597 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11598 break; 11599 case Intrinsic::amdgcn_workitem_id_y: 11600 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11601 break; 11602 case Intrinsic::amdgcn_workitem_id_z: 11603 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11604 break; 11605 case Intrinsic::amdgcn_mbcnt_lo: 11606 case Intrinsic::amdgcn_mbcnt_hi: { 11607 // These return at most the wavefront size - 1. 11608 unsigned Size = MRI.getType(R).getSizeInBits(); 11609 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11610 break; 11611 } 11612 case Intrinsic::amdgcn_groupstaticsize: { 11613 // We can report everything over the maximum size as 0. We can't report 11614 // based on the actual size because we don't know if it's accurate or not 11615 // at any given point. 11616 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11617 break; 11618 } 11619 } 11620 break; 11621 } 11622 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11623 Known.Zero.setHighBits(24); 11624 break; 11625 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11626 Known.Zero.setHighBits(16); 11627 break; 11628 } 11629 } 11630 11631 Align SITargetLowering::computeKnownAlignForTargetInstr( 11632 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11633 unsigned Depth) const { 11634 const MachineInstr *MI = MRI.getVRegDef(R); 11635 switch (MI->getOpcode()) { 11636 case AMDGPU::G_INTRINSIC: 11637 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11638 // FIXME: Can this move to generic code? What about the case where the call 11639 // site specifies a lower alignment? 11640 Intrinsic::ID IID = MI->getIntrinsicID(); 11641 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11642 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11643 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11644 return *RetAlign; 11645 return Align(1); 11646 } 11647 default: 11648 return Align(1); 11649 } 11650 } 11651 11652 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11653 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11654 const Align CacheLineAlign = Align(64); 11655 11656 // Pre-GFX10 target did not benefit from loop alignment 11657 if (!ML || DisableLoopAlignment || 11658 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11659 getSubtarget()->hasInstFwdPrefetchBug()) 11660 return PrefAlign; 11661 11662 // On GFX10 I$ is 4 x 64 bytes cache lines. 11663 // By default prefetcher keeps one cache line behind and reads two ahead. 11664 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11665 // behind and one ahead. 11666 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11667 // If loop fits 64 bytes it always spans no more than two cache lines and 11668 // does not need an alignment. 11669 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11670 // Else if loop is less or equal 192 bytes we need two lines behind. 11671 11672 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11673 const MachineBasicBlock *Header = ML->getHeader(); 11674 if (Header->getAlignment() != PrefAlign) 11675 return Header->getAlignment(); // Already processed. 11676 11677 unsigned LoopSize = 0; 11678 for (const MachineBasicBlock *MBB : ML->blocks()) { 11679 // If inner loop block is aligned assume in average half of the alignment 11680 // size to be added as nops. 11681 if (MBB != Header) 11682 LoopSize += MBB->getAlignment().value() / 2; 11683 11684 for (const MachineInstr &MI : *MBB) { 11685 LoopSize += TII->getInstSizeInBytes(MI); 11686 if (LoopSize > 192) 11687 return PrefAlign; 11688 } 11689 } 11690 11691 if (LoopSize <= 64) 11692 return PrefAlign; 11693 11694 if (LoopSize <= 128) 11695 return CacheLineAlign; 11696 11697 // If any of parent loops is surrounded by prefetch instructions do not 11698 // insert new for inner loop, which would reset parent's settings. 11699 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11700 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11701 auto I = Exit->getFirstNonDebugInstr(); 11702 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11703 return CacheLineAlign; 11704 } 11705 } 11706 11707 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11708 MachineBasicBlock *Exit = ML->getExitBlock(); 11709 11710 if (Pre && Exit) { 11711 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11712 TII->get(AMDGPU::S_INST_PREFETCH)) 11713 .addImm(1); // prefetch 2 lines behind PC 11714 11715 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11716 TII->get(AMDGPU::S_INST_PREFETCH)) 11717 .addImm(2); // prefetch 1 line behind PC 11718 } 11719 11720 return CacheLineAlign; 11721 } 11722 11723 LLVM_ATTRIBUTE_UNUSED 11724 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11725 assert(N->getOpcode() == ISD::CopyFromReg); 11726 do { 11727 // Follow the chain until we find an INLINEASM node. 11728 N = N->getOperand(0).getNode(); 11729 if (N->getOpcode() == ISD::INLINEASM || 11730 N->getOpcode() == ISD::INLINEASM_BR) 11731 return true; 11732 } while (N->getOpcode() == ISD::CopyFromReg); 11733 return false; 11734 } 11735 11736 bool SITargetLowering::isSDNodeSourceOfDivergence( 11737 const SDNode *N, FunctionLoweringInfo *FLI, 11738 LegacyDivergenceAnalysis *KDA) const { 11739 switch (N->getOpcode()) { 11740 case ISD::CopyFromReg: { 11741 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11742 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11743 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11744 Register Reg = R->getReg(); 11745 11746 // FIXME: Why does this need to consider isLiveIn? 11747 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11748 return !TRI->isSGPRReg(MRI, Reg); 11749 11750 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11751 return KDA->isDivergent(V); 11752 11753 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11754 return !TRI->isSGPRReg(MRI, Reg); 11755 } 11756 case ISD::LOAD: { 11757 const LoadSDNode *L = cast<LoadSDNode>(N); 11758 unsigned AS = L->getAddressSpace(); 11759 // A flat load may access private memory. 11760 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11761 } 11762 case ISD::CALLSEQ_END: 11763 return true; 11764 case ISD::INTRINSIC_WO_CHAIN: 11765 return AMDGPU::isIntrinsicSourceOfDivergence( 11766 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11767 case ISD::INTRINSIC_W_CHAIN: 11768 return AMDGPU::isIntrinsicSourceOfDivergence( 11769 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11770 } 11771 return false; 11772 } 11773 11774 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11775 EVT VT) const { 11776 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11777 case MVT::f32: 11778 return hasFP32Denormals(DAG.getMachineFunction()); 11779 case MVT::f64: 11780 case MVT::f16: 11781 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11782 default: 11783 return false; 11784 } 11785 } 11786 11787 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11788 const SelectionDAG &DAG, 11789 bool SNaN, 11790 unsigned Depth) const { 11791 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11792 const MachineFunction &MF = DAG.getMachineFunction(); 11793 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11794 11795 if (Info->getMode().DX10Clamp) 11796 return true; // Clamped to 0. 11797 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11798 } 11799 11800 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11801 SNaN, Depth); 11802 } 11803 11804 // Global FP atomic instructions have a hardcoded FP mode and do not support 11805 // FP32 denormals, and only support v2f16 denormals. 11806 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11807 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11808 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11809 if (&Flt == &APFloat::IEEEsingle()) 11810 return DenormMode == DenormalMode::getPreserveSign(); 11811 return DenormMode == DenormalMode::getIEEE(); 11812 } 11813 11814 TargetLowering::AtomicExpansionKind 11815 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11816 switch (RMW->getOperation()) { 11817 case AtomicRMWInst::FAdd: { 11818 Type *Ty = RMW->getType(); 11819 11820 // We don't have a way to support 16-bit atomics now, so just leave them 11821 // as-is. 11822 if (Ty->isHalfTy()) 11823 return AtomicExpansionKind::None; 11824 11825 if (!Ty->isFloatTy()) 11826 return AtomicExpansionKind::CmpXChg; 11827 11828 // TODO: Do have these for flat. Older targets also had them for buffers. 11829 unsigned AS = RMW->getPointerAddressSpace(); 11830 11831 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11832 if (!fpModeMatchesGlobalFPAtomicMode(RMW)) 11833 return AtomicExpansionKind::CmpXChg; 11834 11835 return RMW->use_empty() ? AtomicExpansionKind::None : 11836 AtomicExpansionKind::CmpXChg; 11837 } 11838 11839 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11840 // to round-to-nearest-even. 11841 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11842 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11843 } 11844 default: 11845 break; 11846 } 11847 11848 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11849 } 11850 11851 const TargetRegisterClass * 11852 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11853 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11854 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11855 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11856 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11857 : &AMDGPU::SReg_32RegClass; 11858 if (!TRI->isSGPRClass(RC) && !isDivergent) 11859 return TRI->getEquivalentSGPRClass(RC); 11860 else if (TRI->isSGPRClass(RC) && isDivergent) 11861 return TRI->getEquivalentVGPRClass(RC); 11862 11863 return RC; 11864 } 11865 11866 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11867 // uniform values (as produced by the mask results of control flow intrinsics) 11868 // used outside of divergent blocks. The phi users need to also be treated as 11869 // always uniform. 11870 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11871 unsigned WaveSize) { 11872 // FIXME: We asssume we never cast the mask results of a control flow 11873 // intrinsic. 11874 // Early exit if the type won't be consistent as a compile time hack. 11875 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11876 if (!IT || IT->getBitWidth() != WaveSize) 11877 return false; 11878 11879 if (!isa<Instruction>(V)) 11880 return false; 11881 if (!Visited.insert(V).second) 11882 return false; 11883 bool Result = false; 11884 for (auto U : V->users()) { 11885 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11886 if (V == U->getOperand(1)) { 11887 switch (Intrinsic->getIntrinsicID()) { 11888 default: 11889 Result = false; 11890 break; 11891 case Intrinsic::amdgcn_if_break: 11892 case Intrinsic::amdgcn_if: 11893 case Intrinsic::amdgcn_else: 11894 Result = true; 11895 break; 11896 } 11897 } 11898 if (V == U->getOperand(0)) { 11899 switch (Intrinsic->getIntrinsicID()) { 11900 default: 11901 Result = false; 11902 break; 11903 case Intrinsic::amdgcn_end_cf: 11904 case Intrinsic::amdgcn_loop: 11905 Result = true; 11906 break; 11907 } 11908 } 11909 } else { 11910 Result = hasCFUser(U, Visited, WaveSize); 11911 } 11912 if (Result) 11913 break; 11914 } 11915 return Result; 11916 } 11917 11918 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11919 const Value *V) const { 11920 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11921 if (CI->isInlineAsm()) { 11922 // FIXME: This cannot give a correct answer. This should only trigger in 11923 // the case where inline asm returns mixed SGPR and VGPR results, used 11924 // outside the defining block. We don't have a specific result to 11925 // consider, so this assumes if any value is SGPR, the overall register 11926 // also needs to be SGPR. 11927 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11928 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11929 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11930 for (auto &TC : TargetConstraints) { 11931 if (TC.Type == InlineAsm::isOutput) { 11932 ComputeConstraintToUse(TC, SDValue()); 11933 unsigned AssignedReg; 11934 const TargetRegisterClass *RC; 11935 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11936 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11937 if (RC) { 11938 MachineRegisterInfo &MRI = MF.getRegInfo(); 11939 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11940 return true; 11941 else if (SIRI->isSGPRClass(RC)) 11942 return true; 11943 } 11944 } 11945 } 11946 } 11947 } 11948 SmallPtrSet<const Value *, 16> Visited; 11949 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11950 } 11951 11952 std::pair<int, MVT> 11953 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11954 Type *Ty) const { 11955 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11956 auto Size = DL.getTypeSizeInBits(Ty); 11957 // Maximum load or store can handle 8 dwords for scalar and 4 for 11958 // vector ALU. Let's assume anything above 8 dwords is expensive 11959 // even if legal. 11960 if (Size <= 256) 11961 return Cost; 11962 11963 Cost.first = (Size + 255) / 256; 11964 return Cost; 11965 } 11966