1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUSubtarget.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 19 #include "SIDefines.h" 20 #include "SIInstrInfo.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "SIRegisterInfo.h" 23 #include "Utils/AMDGPUBaseInfo.h" 24 #include "llvm/ADT/APFloat.h" 25 #include "llvm/ADT/APInt.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/BitVector.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/ADT/StringSwitch.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CallingConvLower.h" 36 #include "llvm/CodeGen/DAGCombine.h" 37 #include "llvm/CodeGen/FunctionLoweringInfo.h" 38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetCallingConv.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/ValueTypes.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugLoc.h" 58 #include "llvm/IR/DerivedTypes.h" 59 #include "llvm/IR/DiagnosticInfo.h" 60 #include "llvm/IR/Function.h" 61 #include "llvm/IR/GlobalValue.h" 62 #include "llvm/IR/InstrTypes.h" 63 #include "llvm/IR/Instruction.h" 64 #include "llvm/IR/Instructions.h" 65 #include "llvm/IR/IntrinsicInst.h" 66 #include "llvm/IR/Type.h" 67 #include "llvm/Support/Casting.h" 68 #include "llvm/Support/CodeGen.h" 69 #include "llvm/Support/CommandLine.h" 70 #include "llvm/Support/Compiler.h" 71 #include "llvm/Support/ErrorHandling.h" 72 #include "llvm/Support/KnownBits.h" 73 #include "llvm/Support/MachineValueType.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Target/TargetOptions.h" 76 #include <cassert> 77 #include <cmath> 78 #include <cstdint> 79 #include <iterator> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 86 #define DEBUG_TYPE "si-lower" 87 88 STATISTIC(NumTailCalls, "Number of tail calls"); 89 90 static cl::opt<bool> DisableLoopAlignment( 91 "amdgpu-disable-loop-alignment", 92 cl::desc("Do not align and prefetch loops"), 93 cl::init(false)); 94 95 static cl::opt<bool> VGPRReserveforSGPRSpill( 96 "amdgpu-reserve-vgpr-for-sgpr-spill", 97 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 98 99 static cl::opt<bool> UseDivergentRegisterIndexing( 100 "amdgpu-use-divergent-register-indexing", 101 cl::Hidden, 102 cl::desc("Use indirect register addressing for divergent indexes"), 103 cl::init(false)); 104 105 static bool hasFP32Denormals(const MachineFunction &MF) { 106 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 107 return Info->getMode().allFP32Denormals(); 108 } 109 110 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 111 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 112 return Info->getMode().allFP64FP16Denormals(); 113 } 114 115 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 116 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 117 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 118 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 119 return AMDGPU::SGPR0 + Reg; 120 } 121 } 122 llvm_unreachable("Cannot allocate sgpr"); 123 } 124 125 SITargetLowering::SITargetLowering(const TargetMachine &TM, 126 const GCNSubtarget &STI) 127 : AMDGPUTargetLowering(TM, STI), 128 Subtarget(&STI) { 129 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 130 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 131 132 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 133 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 134 135 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 136 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 137 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 138 139 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 140 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 141 142 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 143 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 144 145 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 146 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 147 148 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 149 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 150 151 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 152 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 153 154 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 155 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 156 157 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 158 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 159 160 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 161 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 162 163 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 164 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 165 166 if (Subtarget->has16BitInsts()) { 167 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 168 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 169 170 // Unless there are also VOP3P operations, not operations are really legal. 171 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 172 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 173 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 174 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 175 } 176 177 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 178 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 179 180 computeRegisterProperties(Subtarget->getRegisterInfo()); 181 182 // The boolean content concept here is too inflexible. Compares only ever 183 // really produce a 1-bit result. Any copy/extend from these will turn into a 184 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 185 // it's what most targets use. 186 setBooleanContents(ZeroOrOneBooleanContent); 187 setBooleanVectorContents(ZeroOrOneBooleanContent); 188 189 // We need to custom lower vector stores from local memory 190 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 196 setOperationAction(ISD::LOAD, MVT::i1, Custom); 197 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 198 199 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 204 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 205 setOperationAction(ISD::STORE, MVT::i1, Custom); 206 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 207 208 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 209 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 210 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 211 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 212 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 213 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 214 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 215 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 216 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 217 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 218 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 219 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 220 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 221 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 222 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 223 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 224 225 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 227 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 228 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 229 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 230 231 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 232 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 233 234 setOperationAction(ISD::SELECT, MVT::i1, Promote); 235 setOperationAction(ISD::SELECT, MVT::i64, Custom); 236 setOperationAction(ISD::SELECT, MVT::f64, Promote); 237 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 238 239 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 242 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 243 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 244 245 setOperationAction(ISD::SETCC, MVT::i1, Promote); 246 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 247 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 248 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 249 250 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 251 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 252 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 253 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 254 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 255 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 256 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 257 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 258 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 267 268 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 269 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 270 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 271 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 272 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 273 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 274 275 setOperationAction(ISD::UADDO, MVT::i32, Legal); 276 setOperationAction(ISD::USUBO, MVT::i32, Legal); 277 278 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 279 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 280 281 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 282 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 283 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 284 285 #if 0 286 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 287 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 288 #endif 289 290 // We only support LOAD/STORE and vector manipulation ops for vectors 291 // with > 4 elements. 292 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 293 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 294 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 295 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 296 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 297 switch (Op) { 298 case ISD::LOAD: 299 case ISD::STORE: 300 case ISD::BUILD_VECTOR: 301 case ISD::BITCAST: 302 case ISD::EXTRACT_VECTOR_ELT: 303 case ISD::INSERT_VECTOR_ELT: 304 case ISD::INSERT_SUBVECTOR: 305 case ISD::EXTRACT_SUBVECTOR: 306 case ISD::SCALAR_TO_VECTOR: 307 break; 308 case ISD::CONCAT_VECTORS: 309 setOperationAction(Op, VT, Custom); 310 break; 311 default: 312 setOperationAction(Op, VT, Expand); 313 break; 314 } 315 } 316 } 317 318 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 319 320 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 321 // is expanded to avoid having two separate loops in case the index is a VGPR. 322 323 // Most operations are naturally 32-bit vector operations. We only support 324 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 325 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 326 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 327 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 328 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 330 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 331 332 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 333 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 334 335 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 336 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 337 } 338 339 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 340 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 341 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 344 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 345 346 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 347 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 348 349 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 350 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 351 } 352 353 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 354 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 355 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 358 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 359 360 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 361 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 362 363 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 364 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 365 } 366 367 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 368 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 369 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 372 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 373 374 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 375 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 376 377 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 378 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 379 } 380 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 383 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 384 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 385 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 387 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 388 389 // Avoid stack access for these. 390 // TODO: Generalize to more vector types. 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 395 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 401 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 404 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 405 406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 409 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 410 411 // Deal with vec3 vector operations when widened to vec4. 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 416 417 // Deal with vec5 vector operations when widened to vec8. 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 420 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 421 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 422 423 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 424 // and output demarshalling 425 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 426 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 427 428 // We can't return success/failure, only the old value, 429 // let LLVM add the comparison 430 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 431 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 432 433 if (Subtarget->hasFlatAddressSpace()) { 434 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 435 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 436 } 437 438 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 439 440 // FIXME: This should be narrowed to i32, but that only happens if i64 is 441 // illegal. 442 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 443 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 444 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 445 446 // On SI this is s_memtime and s_memrealtime on VI. 447 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 448 setOperationAction(ISD::TRAP, MVT::Other, Custom); 449 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 450 451 if (Subtarget->has16BitInsts()) { 452 setOperationAction(ISD::FPOW, MVT::f16, Promote); 453 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 454 setOperationAction(ISD::FLOG, MVT::f16, Custom); 455 setOperationAction(ISD::FEXP, MVT::f16, Custom); 456 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 457 } 458 459 if (Subtarget->hasMadMacF32Insts()) 460 setOperationAction(ISD::FMAD, MVT::f32, Legal); 461 462 if (!Subtarget->hasBFI()) { 463 // fcopysign can be done in a single instruction with BFI. 464 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 465 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 466 } 467 468 if (!Subtarget->hasBCNT(32)) 469 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 470 471 if (!Subtarget->hasBCNT(64)) 472 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 473 474 if (Subtarget->hasFFBH()) 475 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 476 477 if (Subtarget->hasFFBL()) 478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 479 480 // We only really have 32-bit BFE instructions (and 16-bit on VI). 481 // 482 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 483 // effort to match them now. We want this to be false for i64 cases when the 484 // extraction isn't restricted to the upper or lower half. Ideally we would 485 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 486 // span the midpoint are probably relatively rare, so don't worry about them 487 // for now. 488 if (Subtarget->hasBFE()) 489 setHasExtractBitsInsn(true); 490 491 // Clamp modifier on add/sub 492 if (Subtarget->hasIntClamp()) { 493 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 494 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 495 } 496 497 if (Subtarget->hasAddNoCarry()) { 498 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 502 } 503 504 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 508 509 510 // These are really only legal for ieee_mode functions. We should be avoiding 511 // them for functions that don't have ieee_mode enabled, so just say they are 512 // legal. 513 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 517 518 519 if (Subtarget->haveRoundOpsF64()) { 520 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 521 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 522 setOperationAction(ISD::FRINT, MVT::f64, Legal); 523 } else { 524 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 525 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 526 setOperationAction(ISD::FRINT, MVT::f64, Custom); 527 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 528 } 529 530 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 531 532 setOperationAction(ISD::FSIN, MVT::f32, Custom); 533 setOperationAction(ISD::FCOS, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f64, Custom); 536 537 if (Subtarget->has16BitInsts()) { 538 setOperationAction(ISD::Constant, MVT::i16, Legal); 539 540 setOperationAction(ISD::SMIN, MVT::i16, Legal); 541 setOperationAction(ISD::SMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::UMIN, MVT::i16, Legal); 544 setOperationAction(ISD::UMAX, MVT::i16, Legal); 545 546 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 547 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 548 549 setOperationAction(ISD::ROTR, MVT::i16, Promote); 550 setOperationAction(ISD::ROTL, MVT::i16, Promote); 551 552 setOperationAction(ISD::SDIV, MVT::i16, Promote); 553 setOperationAction(ISD::UDIV, MVT::i16, Promote); 554 setOperationAction(ISD::SREM, MVT::i16, Promote); 555 setOperationAction(ISD::UREM, MVT::i16, Promote); 556 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 557 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 558 559 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 560 561 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 566 567 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 568 569 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::LOAD, MVT::i16, Custom); 572 573 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 574 575 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 576 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 577 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 579 580 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 582 583 // F16 - Constant Actions. 584 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 585 586 // F16 - Load/Store Actions. 587 setOperationAction(ISD::LOAD, MVT::f16, Promote); 588 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 589 setOperationAction(ISD::STORE, MVT::f16, Promote); 590 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 591 592 // F16 - VOP1 Actions. 593 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 594 setOperationAction(ISD::FCOS, MVT::f16, Custom); 595 setOperationAction(ISD::FSIN, MVT::f16, Custom); 596 597 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 598 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 599 600 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 601 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 602 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 604 setOperationAction(ISD::FROUND, MVT::f16, Custom); 605 606 // F16 - VOP2 Actions. 607 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 608 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 609 610 setOperationAction(ISD::FDIV, MVT::f16, Custom); 611 612 // F16 - VOP3 Actions. 613 setOperationAction(ISD::FMA, MVT::f16, Legal); 614 if (STI.hasMadF16()) 615 setOperationAction(ISD::FMAD, MVT::f16, Legal); 616 617 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 618 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 619 switch (Op) { 620 case ISD::LOAD: 621 case ISD::STORE: 622 case ISD::BUILD_VECTOR: 623 case ISD::BITCAST: 624 case ISD::EXTRACT_VECTOR_ELT: 625 case ISD::INSERT_VECTOR_ELT: 626 case ISD::INSERT_SUBVECTOR: 627 case ISD::EXTRACT_SUBVECTOR: 628 case ISD::SCALAR_TO_VECTOR: 629 break; 630 case ISD::CONCAT_VECTORS: 631 setOperationAction(Op, VT, Custom); 632 break; 633 default: 634 setOperationAction(Op, VT, Expand); 635 break; 636 } 637 } 638 } 639 640 // v_perm_b32 can handle either of these. 641 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 643 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 644 645 // XXX - Do these do anything? Vector constants turn into build_vector. 646 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 647 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 648 649 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 650 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 653 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 654 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 655 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 656 657 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 658 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 659 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 660 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 661 662 setOperationAction(ISD::AND, MVT::v2i16, Promote); 663 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 664 setOperationAction(ISD::OR, MVT::v2i16, Promote); 665 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 666 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 668 669 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 670 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 671 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 672 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 673 674 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 675 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 676 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 677 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 678 679 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 682 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 683 684 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 686 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 687 688 if (!Subtarget->hasVOP3PInsts()) { 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 690 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 691 } 692 693 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 694 // This isn't really legal, but this avoids the legalizer unrolling it (and 695 // allows matching fneg (fabs x) patterns) 696 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 697 698 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 700 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 701 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 702 703 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 704 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 705 706 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 707 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 708 } 709 710 if (Subtarget->hasVOP3PInsts()) { 711 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 712 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 713 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 716 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 717 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 719 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 720 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 721 722 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 725 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 726 727 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 730 731 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 732 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 733 734 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 735 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 741 742 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 744 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 745 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 746 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 747 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 748 749 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 750 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 752 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 753 754 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 757 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 758 759 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 762 763 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 764 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 765 766 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 768 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 769 770 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 772 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 773 } 774 775 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 776 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 777 778 if (Subtarget->has16BitInsts()) { 779 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 780 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 781 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 782 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 783 } else { 784 // Legalization hack. 785 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 786 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 787 788 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 789 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 790 } 791 792 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 793 setOperationAction(ISD::SELECT, VT, Custom); 794 } 795 796 setOperationAction(ISD::SMULO, MVT::i64, Custom); 797 setOperationAction(ISD::UMULO, MVT::i64, Custom); 798 799 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 801 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 802 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 803 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 805 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 806 807 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 808 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 809 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 810 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 811 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 812 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 813 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 815 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 816 817 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 818 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 819 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 820 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 821 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 822 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 823 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 824 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 825 826 setTargetDAGCombine(ISD::ADD); 827 setTargetDAGCombine(ISD::ADDCARRY); 828 setTargetDAGCombine(ISD::SUB); 829 setTargetDAGCombine(ISD::SUBCARRY); 830 setTargetDAGCombine(ISD::FADD); 831 setTargetDAGCombine(ISD::FSUB); 832 setTargetDAGCombine(ISD::FMINNUM); 833 setTargetDAGCombine(ISD::FMAXNUM); 834 setTargetDAGCombine(ISD::FMINNUM_IEEE); 835 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 836 setTargetDAGCombine(ISD::FMA); 837 setTargetDAGCombine(ISD::SMIN); 838 setTargetDAGCombine(ISD::SMAX); 839 setTargetDAGCombine(ISD::UMIN); 840 setTargetDAGCombine(ISD::UMAX); 841 setTargetDAGCombine(ISD::SETCC); 842 setTargetDAGCombine(ISD::AND); 843 setTargetDAGCombine(ISD::OR); 844 setTargetDAGCombine(ISD::XOR); 845 setTargetDAGCombine(ISD::SINT_TO_FP); 846 setTargetDAGCombine(ISD::UINT_TO_FP); 847 setTargetDAGCombine(ISD::FCANONICALIZE); 848 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 849 setTargetDAGCombine(ISD::ZERO_EXTEND); 850 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 851 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 852 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 853 854 // All memory operations. Some folding on the pointer operand is done to help 855 // matching the constant offsets in the addressing modes. 856 setTargetDAGCombine(ISD::LOAD); 857 setTargetDAGCombine(ISD::STORE); 858 setTargetDAGCombine(ISD::ATOMIC_LOAD); 859 setTargetDAGCombine(ISD::ATOMIC_STORE); 860 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 861 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 862 setTargetDAGCombine(ISD::ATOMIC_SWAP); 863 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 864 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 865 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 866 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 867 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 868 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 870 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 871 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 872 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 873 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 874 setTargetDAGCombine(ISD::INTRINSIC_VOID); 875 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 876 877 // FIXME: In other contexts we pretend this is a per-function property. 878 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 879 880 setSchedulingPreference(Sched::RegPressure); 881 } 882 883 const GCNSubtarget *SITargetLowering::getSubtarget() const { 884 return Subtarget; 885 } 886 887 //===----------------------------------------------------------------------===// 888 // TargetLowering queries 889 //===----------------------------------------------------------------------===// 890 891 // v_mad_mix* support a conversion from f16 to f32. 892 // 893 // There is only one special case when denormals are enabled we don't currently, 894 // where this is OK to use. 895 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 896 EVT DestVT, EVT SrcVT) const { 897 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 898 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 899 DestVT.getScalarType() == MVT::f32 && 900 SrcVT.getScalarType() == MVT::f16 && 901 // TODO: This probably only requires no input flushing? 902 !hasFP32Denormals(DAG.getMachineFunction()); 903 } 904 905 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 906 // SI has some legal vector types, but no legal vector operations. Say no 907 // shuffles are legal in order to prefer scalarizing some vector operations. 908 return false; 909 } 910 911 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 912 CallingConv::ID CC, 913 EVT VT) const { 914 if (CC == CallingConv::AMDGPU_KERNEL) 915 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 916 917 if (VT.isVector()) { 918 EVT ScalarVT = VT.getScalarType(); 919 unsigned Size = ScalarVT.getSizeInBits(); 920 if (Size == 32) 921 return ScalarVT.getSimpleVT(); 922 923 if (Size > 32) 924 return MVT::i32; 925 926 if (Size == 16 && Subtarget->has16BitInsts()) 927 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 928 } else if (VT.getSizeInBits() > 32) 929 return MVT::i32; 930 931 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 932 } 933 934 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 935 CallingConv::ID CC, 936 EVT VT) const { 937 if (CC == CallingConv::AMDGPU_KERNEL) 938 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 939 940 if (VT.isVector()) { 941 unsigned NumElts = VT.getVectorNumElements(); 942 EVT ScalarVT = VT.getScalarType(); 943 unsigned Size = ScalarVT.getSizeInBits(); 944 945 if (Size == 32) 946 return NumElts; 947 948 if (Size > 32) 949 return NumElts * ((Size + 31) / 32); 950 951 if (Size == 16 && Subtarget->has16BitInsts()) 952 return (NumElts + 1) / 2; 953 } else if (VT.getSizeInBits() > 32) 954 return (VT.getSizeInBits() + 31) / 32; 955 956 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 957 } 958 959 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 960 LLVMContext &Context, CallingConv::ID CC, 961 EVT VT, EVT &IntermediateVT, 962 unsigned &NumIntermediates, MVT &RegisterVT) const { 963 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 964 unsigned NumElts = VT.getVectorNumElements(); 965 EVT ScalarVT = VT.getScalarType(); 966 unsigned Size = ScalarVT.getSizeInBits(); 967 if (Size == 32) { 968 RegisterVT = ScalarVT.getSimpleVT(); 969 IntermediateVT = RegisterVT; 970 NumIntermediates = NumElts; 971 return NumIntermediates; 972 } 973 974 if (Size > 32) { 975 RegisterVT = MVT::i32; 976 IntermediateVT = RegisterVT; 977 NumIntermediates = NumElts * ((Size + 31) / 32); 978 return NumIntermediates; 979 } 980 981 // FIXME: We should fix the ABI to be the same on targets without 16-bit 982 // support, but unless we can properly handle 3-vectors, it will be still be 983 // inconsistent. 984 if (Size == 16 && Subtarget->has16BitInsts()) { 985 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 986 IntermediateVT = RegisterVT; 987 NumIntermediates = (NumElts + 1) / 2; 988 return NumIntermediates; 989 } 990 } 991 992 return TargetLowering::getVectorTypeBreakdownForCallingConv( 993 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 994 } 995 996 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 997 assert(DMaskLanes != 0); 998 999 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1000 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1001 return EVT::getVectorVT(Ty->getContext(), 1002 EVT::getEVT(VT->getElementType()), 1003 NumElts); 1004 } 1005 1006 return EVT::getEVT(Ty); 1007 } 1008 1009 // Peek through TFE struct returns to only use the data size. 1010 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1011 auto *ST = dyn_cast<StructType>(Ty); 1012 if (!ST) 1013 return memVTFromImageData(Ty, DMaskLanes); 1014 1015 // Some intrinsics return an aggregate type - special case to work out the 1016 // correct memVT. 1017 // 1018 // Only limited forms of aggregate type currently expected. 1019 if (ST->getNumContainedTypes() != 2 || 1020 !ST->getContainedType(1)->isIntegerTy(32)) 1021 return EVT(); 1022 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1023 } 1024 1025 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1026 const CallInst &CI, 1027 MachineFunction &MF, 1028 unsigned IntrID) const { 1029 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1030 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1031 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1032 (Intrinsic::ID)IntrID); 1033 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1034 return false; 1035 1036 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1037 1038 if (RsrcIntr->IsImage) { 1039 Info.ptrVal = MFI->getImagePSV( 1040 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1041 CI.getArgOperand(RsrcIntr->RsrcArg)); 1042 Info.align.reset(); 1043 } else { 1044 Info.ptrVal = MFI->getBufferPSV( 1045 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1046 CI.getArgOperand(RsrcIntr->RsrcArg)); 1047 } 1048 1049 Info.flags = MachineMemOperand::MODereferenceable; 1050 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1051 unsigned DMaskLanes = 4; 1052 1053 if (RsrcIntr->IsImage) { 1054 const AMDGPU::ImageDimIntrinsicInfo *Intr 1055 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1056 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1057 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1058 1059 if (!BaseOpcode->Gather4) { 1060 // If this isn't a gather, we may have excess loaded elements in the 1061 // IR type. Check the dmask for the real number of elements loaded. 1062 unsigned DMask 1063 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1064 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1065 } 1066 1067 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1068 } else 1069 Info.memVT = EVT::getEVT(CI.getType()); 1070 1071 // FIXME: What does alignment mean for an image? 1072 Info.opc = ISD::INTRINSIC_W_CHAIN; 1073 Info.flags |= MachineMemOperand::MOLoad; 1074 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1075 Info.opc = ISD::INTRINSIC_VOID; 1076 1077 Type *DataTy = CI.getArgOperand(0)->getType(); 1078 if (RsrcIntr->IsImage) { 1079 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1080 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1081 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1082 } else 1083 Info.memVT = EVT::getEVT(DataTy); 1084 1085 Info.flags |= MachineMemOperand::MOStore; 1086 } else { 1087 // Atomic 1088 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1089 ISD::INTRINSIC_W_CHAIN; 1090 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1091 Info.flags = MachineMemOperand::MOLoad | 1092 MachineMemOperand::MOStore | 1093 MachineMemOperand::MODereferenceable; 1094 1095 // XXX - Should this be volatile without known ordering? 1096 Info.flags |= MachineMemOperand::MOVolatile; 1097 } 1098 return true; 1099 } 1100 1101 switch (IntrID) { 1102 case Intrinsic::amdgcn_atomic_inc: 1103 case Intrinsic::amdgcn_atomic_dec: 1104 case Intrinsic::amdgcn_ds_ordered_add: 1105 case Intrinsic::amdgcn_ds_ordered_swap: 1106 case Intrinsic::amdgcn_ds_fadd: 1107 case Intrinsic::amdgcn_ds_fmin: 1108 case Intrinsic::amdgcn_ds_fmax: { 1109 Info.opc = ISD::INTRINSIC_W_CHAIN; 1110 Info.memVT = MVT::getVT(CI.getType()); 1111 Info.ptrVal = CI.getOperand(0); 1112 Info.align.reset(); 1113 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1114 1115 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1116 if (!Vol->isZero()) 1117 Info.flags |= MachineMemOperand::MOVolatile; 1118 1119 return true; 1120 } 1121 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1122 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1123 1124 Info.opc = ISD::INTRINSIC_W_CHAIN; 1125 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1126 Info.ptrVal = MFI->getBufferPSV( 1127 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1128 CI.getArgOperand(1)); 1129 Info.align.reset(); 1130 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1131 1132 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1133 if (!Vol || !Vol->isZero()) 1134 Info.flags |= MachineMemOperand::MOVolatile; 1135 1136 return true; 1137 } 1138 case Intrinsic::amdgcn_ds_append: 1139 case Intrinsic::amdgcn_ds_consume: { 1140 Info.opc = ISD::INTRINSIC_W_CHAIN; 1141 Info.memVT = MVT::getVT(CI.getType()); 1142 Info.ptrVal = CI.getOperand(0); 1143 Info.align.reset(); 1144 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1145 1146 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1147 if (!Vol->isZero()) 1148 Info.flags |= MachineMemOperand::MOVolatile; 1149 1150 return true; 1151 } 1152 case Intrinsic::amdgcn_global_atomic_csub: { 1153 Info.opc = ISD::INTRINSIC_W_CHAIN; 1154 Info.memVT = MVT::getVT(CI.getType()); 1155 Info.ptrVal = CI.getOperand(0); 1156 Info.align.reset(); 1157 Info.flags = MachineMemOperand::MOLoad | 1158 MachineMemOperand::MOStore | 1159 MachineMemOperand::MOVolatile; 1160 return true; 1161 } 1162 case Intrinsic::amdgcn_global_atomic_fadd: { 1163 Info.opc = ISD::INTRINSIC_W_CHAIN; 1164 Info.memVT = MVT::getVT(CI.getType()); 1165 Info.ptrVal = CI.getOperand(0); 1166 Info.align.reset(); 1167 Info.flags = MachineMemOperand::MOLoad | 1168 MachineMemOperand::MOStore | 1169 MachineMemOperand::MODereferenceable | 1170 MachineMemOperand::MOVolatile; 1171 return true; 1172 } 1173 case Intrinsic::amdgcn_ds_gws_init: 1174 case Intrinsic::amdgcn_ds_gws_barrier: 1175 case Intrinsic::amdgcn_ds_gws_sema_v: 1176 case Intrinsic::amdgcn_ds_gws_sema_br: 1177 case Intrinsic::amdgcn_ds_gws_sema_p: 1178 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1179 Info.opc = ISD::INTRINSIC_VOID; 1180 1181 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1182 Info.ptrVal = 1183 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1184 1185 // This is an abstract access, but we need to specify a type and size. 1186 Info.memVT = MVT::i32; 1187 Info.size = 4; 1188 Info.align = Align(4); 1189 1190 Info.flags = MachineMemOperand::MOStore; 1191 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1192 Info.flags = MachineMemOperand::MOLoad; 1193 return true; 1194 } 1195 default: 1196 return false; 1197 } 1198 } 1199 1200 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1201 SmallVectorImpl<Value*> &Ops, 1202 Type *&AccessTy) const { 1203 switch (II->getIntrinsicID()) { 1204 case Intrinsic::amdgcn_atomic_inc: 1205 case Intrinsic::amdgcn_atomic_dec: 1206 case Intrinsic::amdgcn_ds_ordered_add: 1207 case Intrinsic::amdgcn_ds_ordered_swap: 1208 case Intrinsic::amdgcn_ds_append: 1209 case Intrinsic::amdgcn_ds_consume: 1210 case Intrinsic::amdgcn_ds_fadd: 1211 case Intrinsic::amdgcn_ds_fmin: 1212 case Intrinsic::amdgcn_ds_fmax: 1213 case Intrinsic::amdgcn_global_atomic_fadd: 1214 case Intrinsic::amdgcn_global_atomic_csub: { 1215 Value *Ptr = II->getArgOperand(0); 1216 AccessTy = II->getType(); 1217 Ops.push_back(Ptr); 1218 return true; 1219 } 1220 default: 1221 return false; 1222 } 1223 } 1224 1225 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1226 if (!Subtarget->hasFlatInstOffsets()) { 1227 // Flat instructions do not have offsets, and only have the register 1228 // address. 1229 return AM.BaseOffs == 0 && AM.Scale == 0; 1230 } 1231 1232 return AM.Scale == 0 && 1233 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1234 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1235 /*Signed=*/false)); 1236 } 1237 1238 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1239 if (Subtarget->hasFlatGlobalInsts()) 1240 return AM.Scale == 0 && 1241 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1242 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1243 /*Signed=*/true)); 1244 1245 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1246 // Assume the we will use FLAT for all global memory accesses 1247 // on VI. 1248 // FIXME: This assumption is currently wrong. On VI we still use 1249 // MUBUF instructions for the r + i addressing mode. As currently 1250 // implemented, the MUBUF instructions only work on buffer < 4GB. 1251 // It may be possible to support > 4GB buffers with MUBUF instructions, 1252 // by setting the stride value in the resource descriptor which would 1253 // increase the size limit to (stride * 4GB). However, this is risky, 1254 // because it has never been validated. 1255 return isLegalFlatAddressingMode(AM); 1256 } 1257 1258 return isLegalMUBUFAddressingMode(AM); 1259 } 1260 1261 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1262 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1263 // additionally can do r + r + i with addr64. 32-bit has more addressing 1264 // mode options. Depending on the resource constant, it can also do 1265 // (i64 r0) + (i32 r1) * (i14 i). 1266 // 1267 // Private arrays end up using a scratch buffer most of the time, so also 1268 // assume those use MUBUF instructions. Scratch loads / stores are currently 1269 // implemented as mubuf instructions with offen bit set, so slightly 1270 // different than the normal addr64. 1271 if (!isUInt<12>(AM.BaseOffs)) 1272 return false; 1273 1274 // FIXME: Since we can split immediate into soffset and immediate offset, 1275 // would it make sense to allow any immediate? 1276 1277 switch (AM.Scale) { 1278 case 0: // r + i or just i, depending on HasBaseReg. 1279 return true; 1280 case 1: 1281 return true; // We have r + r or r + i. 1282 case 2: 1283 if (AM.HasBaseReg) { 1284 // Reject 2 * r + r. 1285 return false; 1286 } 1287 1288 // Allow 2 * r as r + r 1289 // Or 2 * r + i is allowed as r + r + i. 1290 return true; 1291 default: // Don't allow n * r 1292 return false; 1293 } 1294 } 1295 1296 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1297 const AddrMode &AM, Type *Ty, 1298 unsigned AS, Instruction *I) const { 1299 // No global is ever allowed as a base. 1300 if (AM.BaseGV) 1301 return false; 1302 1303 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1304 return isLegalGlobalAddressingMode(AM); 1305 1306 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1307 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1308 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1309 // If the offset isn't a multiple of 4, it probably isn't going to be 1310 // correctly aligned. 1311 // FIXME: Can we get the real alignment here? 1312 if (AM.BaseOffs % 4 != 0) 1313 return isLegalMUBUFAddressingMode(AM); 1314 1315 // There are no SMRD extloads, so if we have to do a small type access we 1316 // will use a MUBUF load. 1317 // FIXME?: We also need to do this if unaligned, but we don't know the 1318 // alignment here. 1319 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1320 return isLegalGlobalAddressingMode(AM); 1321 1322 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1323 // SMRD instructions have an 8-bit, dword offset on SI. 1324 if (!isUInt<8>(AM.BaseOffs / 4)) 1325 return false; 1326 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1327 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1328 // in 8-bits, it can use a smaller encoding. 1329 if (!isUInt<32>(AM.BaseOffs / 4)) 1330 return false; 1331 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1332 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1333 if (!isUInt<20>(AM.BaseOffs)) 1334 return false; 1335 } else 1336 llvm_unreachable("unhandled generation"); 1337 1338 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1339 return true; 1340 1341 if (AM.Scale == 1 && AM.HasBaseReg) 1342 return true; 1343 1344 return false; 1345 1346 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1347 return isLegalMUBUFAddressingMode(AM); 1348 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1349 AS == AMDGPUAS::REGION_ADDRESS) { 1350 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1351 // field. 1352 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1353 // an 8-bit dword offset but we don't know the alignment here. 1354 if (!isUInt<16>(AM.BaseOffs)) 1355 return false; 1356 1357 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1358 return true; 1359 1360 if (AM.Scale == 1 && AM.HasBaseReg) 1361 return true; 1362 1363 return false; 1364 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1365 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1366 // For an unknown address space, this usually means that this is for some 1367 // reason being used for pure arithmetic, and not based on some addressing 1368 // computation. We don't have instructions that compute pointers with any 1369 // addressing modes, so treat them as having no offset like flat 1370 // instructions. 1371 return isLegalFlatAddressingMode(AM); 1372 } 1373 1374 // Assume a user alias of global for unknown address spaces. 1375 return isLegalGlobalAddressingMode(AM); 1376 } 1377 1378 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1379 const SelectionDAG &DAG) const { 1380 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1381 return (MemVT.getSizeInBits() <= 4 * 32); 1382 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1383 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1384 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1385 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1386 return (MemVT.getSizeInBits() <= 2 * 32); 1387 } 1388 return true; 1389 } 1390 1391 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1392 unsigned Size, unsigned AddrSpace, Align Alignment, 1393 MachineMemOperand::Flags Flags, bool *IsFast) const { 1394 if (IsFast) 1395 *IsFast = false; 1396 1397 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1398 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1399 // Check if alignment requirements for ds_read/write instructions are 1400 // disabled. 1401 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1402 if (IsFast) 1403 *IsFast = true; 1404 return true; 1405 } 1406 1407 if (Size == 64) { 1408 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1409 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1410 // with adjacent offsets. 1411 bool AlignedBy4 = Alignment >= Align(4); 1412 if (IsFast) 1413 *IsFast = AlignedBy4; 1414 1415 return AlignedBy4; 1416 } 1417 if (Size == 96) { 1418 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1419 bool Aligned = Alignment >= Align((Subtarget->hasUnalignedDSAccess() && 1420 !Subtarget->hasLDSMisalignedBug()) 1421 ? 4 1422 : 16); 1423 if (IsFast) 1424 *IsFast = Aligned; 1425 1426 return Aligned; 1427 } 1428 if (Size == 128) { 1429 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1430 // can do a 8 byte aligned, 16 byte access in a single operation using 1431 // ds_read2/write2_b64. 1432 bool Aligned = Alignment >= Align((Subtarget->hasUnalignedDSAccess() && 1433 !Subtarget->hasLDSMisalignedBug()) 1434 ? 4 1435 : 8); 1436 if (IsFast) 1437 *IsFast = Aligned; 1438 1439 return Aligned; 1440 } 1441 } 1442 1443 // FIXME: We have to be conservative here and assume that flat operations 1444 // will access scratch. If we had access to the IR function, then we 1445 // could determine if any private memory was used in the function. 1446 if (!Subtarget->hasUnalignedScratchAccess() && 1447 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1448 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1449 bool AlignedBy4 = Alignment >= Align(4); 1450 if (IsFast) 1451 *IsFast = AlignedBy4; 1452 1453 return AlignedBy4; 1454 } 1455 1456 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1457 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1458 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1459 // If we have an uniform constant load, it still requires using a slow 1460 // buffer instruction if unaligned. 1461 if (IsFast) { 1462 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1463 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1464 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1465 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1466 Alignment >= Align(4) : Alignment != Align(2); 1467 } 1468 1469 return true; 1470 } 1471 1472 // Smaller than dword value must be aligned. 1473 if (Size < 32) 1474 return false; 1475 1476 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1477 // byte-address are ignored, thus forcing Dword alignment. 1478 // This applies to private, global, and constant memory. 1479 if (IsFast) 1480 *IsFast = true; 1481 1482 return Size >= 32 && Alignment >= Align(4); 1483 } 1484 1485 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1486 EVT VT, unsigned AddrSpace, unsigned Alignment, 1487 MachineMemOperand::Flags Flags, bool *IsFast) const { 1488 if (IsFast) 1489 *IsFast = false; 1490 1491 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1492 // which isn't a simple VT. 1493 // Until MVT is extended to handle this, simply check for the size and 1494 // rely on the condition below: allow accesses if the size is a multiple of 4. 1495 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1496 VT.getStoreSize() > 16)) { 1497 return false; 1498 } 1499 1500 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1501 Align(Alignment), Flags, IsFast); 1502 } 1503 1504 EVT SITargetLowering::getOptimalMemOpType( 1505 const MemOp &Op, const AttributeList &FuncAttributes) const { 1506 // FIXME: Should account for address space here. 1507 1508 // The default fallback uses the private pointer size as a guess for a type to 1509 // use. Make sure we switch these to 64-bit accesses. 1510 1511 if (Op.size() >= 16 && 1512 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1513 return MVT::v4i32; 1514 1515 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1516 return MVT::v2i32; 1517 1518 // Use the default. 1519 return MVT::Other; 1520 } 1521 1522 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1523 const MemSDNode *MemNode = cast<MemSDNode>(N); 1524 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1525 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1526 return I && I->getMetadata("amdgpu.noclobber"); 1527 } 1528 1529 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1530 unsigned DestAS) const { 1531 // Flat -> private/local is a simple truncate. 1532 // Flat -> global is no-op 1533 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1534 return true; 1535 1536 const GCNTargetMachine &TM = 1537 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1538 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1539 } 1540 1541 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1542 const MemSDNode *MemNode = cast<MemSDNode>(N); 1543 1544 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1545 } 1546 1547 TargetLoweringBase::LegalizeTypeAction 1548 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1549 int NumElts = VT.getVectorNumElements(); 1550 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1551 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1552 return TargetLoweringBase::getPreferredVectorAction(VT); 1553 } 1554 1555 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1556 Type *Ty) const { 1557 // FIXME: Could be smarter if called for vector constants. 1558 return true; 1559 } 1560 1561 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1562 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1563 switch (Op) { 1564 case ISD::LOAD: 1565 case ISD::STORE: 1566 1567 // These operations are done with 32-bit instructions anyway. 1568 case ISD::AND: 1569 case ISD::OR: 1570 case ISD::XOR: 1571 case ISD::SELECT: 1572 // TODO: Extensions? 1573 return true; 1574 default: 1575 return false; 1576 } 1577 } 1578 1579 // SimplifySetCC uses this function to determine whether or not it should 1580 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1581 if (VT == MVT::i1 && Op == ISD::SETCC) 1582 return false; 1583 1584 return TargetLowering::isTypeDesirableForOp(Op, VT); 1585 } 1586 1587 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1588 const SDLoc &SL, 1589 SDValue Chain, 1590 uint64_t Offset) const { 1591 const DataLayout &DL = DAG.getDataLayout(); 1592 MachineFunction &MF = DAG.getMachineFunction(); 1593 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1594 1595 const ArgDescriptor *InputPtrReg; 1596 const TargetRegisterClass *RC; 1597 LLT ArgTy; 1598 1599 std::tie(InputPtrReg, RC, ArgTy) = 1600 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1601 1602 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1603 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1604 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1605 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1606 1607 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1608 } 1609 1610 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1611 const SDLoc &SL) const { 1612 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1613 FIRST_IMPLICIT); 1614 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1615 } 1616 1617 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1618 const SDLoc &SL, SDValue Val, 1619 bool Signed, 1620 const ISD::InputArg *Arg) const { 1621 // First, if it is a widened vector, narrow it. 1622 if (VT.isVector() && 1623 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1624 EVT NarrowedVT = 1625 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1626 VT.getVectorNumElements()); 1627 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1628 DAG.getConstant(0, SL, MVT::i32)); 1629 } 1630 1631 // Then convert the vector elements or scalar value. 1632 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1633 VT.bitsLT(MemVT)) { 1634 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1635 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1636 } 1637 1638 if (MemVT.isFloatingPoint()) 1639 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1640 else if (Signed) 1641 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1642 else 1643 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1644 1645 return Val; 1646 } 1647 1648 SDValue SITargetLowering::lowerKernargMemParameter( 1649 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1650 uint64_t Offset, Align Alignment, bool Signed, 1651 const ISD::InputArg *Arg) const { 1652 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1653 1654 // Try to avoid using an extload by loading earlier than the argument address, 1655 // and extracting the relevant bits. The load should hopefully be merged with 1656 // the previous argument. 1657 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1658 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1659 int64_t AlignDownOffset = alignDown(Offset, 4); 1660 int64_t OffsetDiff = Offset - AlignDownOffset; 1661 1662 EVT IntVT = MemVT.changeTypeToInteger(); 1663 1664 // TODO: If we passed in the base kernel offset we could have a better 1665 // alignment than 4, but we don't really need it. 1666 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1667 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1668 MachineMemOperand::MODereferenceable | 1669 MachineMemOperand::MOInvariant); 1670 1671 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1672 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1673 1674 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1675 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1676 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1677 1678 1679 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1680 } 1681 1682 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1683 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1684 MachineMemOperand::MODereferenceable | 1685 MachineMemOperand::MOInvariant); 1686 1687 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1688 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1689 } 1690 1691 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1692 const SDLoc &SL, SDValue Chain, 1693 const ISD::InputArg &Arg) const { 1694 MachineFunction &MF = DAG.getMachineFunction(); 1695 MachineFrameInfo &MFI = MF.getFrameInfo(); 1696 1697 if (Arg.Flags.isByVal()) { 1698 unsigned Size = Arg.Flags.getByValSize(); 1699 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1700 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1701 } 1702 1703 unsigned ArgOffset = VA.getLocMemOffset(); 1704 unsigned ArgSize = VA.getValVT().getStoreSize(); 1705 1706 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1707 1708 // Create load nodes to retrieve arguments from the stack. 1709 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1710 SDValue ArgValue; 1711 1712 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1713 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1714 MVT MemVT = VA.getValVT(); 1715 1716 switch (VA.getLocInfo()) { 1717 default: 1718 break; 1719 case CCValAssign::BCvt: 1720 MemVT = VA.getLocVT(); 1721 break; 1722 case CCValAssign::SExt: 1723 ExtType = ISD::SEXTLOAD; 1724 break; 1725 case CCValAssign::ZExt: 1726 ExtType = ISD::ZEXTLOAD; 1727 break; 1728 case CCValAssign::AExt: 1729 ExtType = ISD::EXTLOAD; 1730 break; 1731 } 1732 1733 ArgValue = DAG.getExtLoad( 1734 ExtType, SL, VA.getLocVT(), Chain, FIN, 1735 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1736 MemVT); 1737 return ArgValue; 1738 } 1739 1740 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1741 const SIMachineFunctionInfo &MFI, 1742 EVT VT, 1743 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1744 const ArgDescriptor *Reg; 1745 const TargetRegisterClass *RC; 1746 LLT Ty; 1747 1748 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1749 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1750 } 1751 1752 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1753 CallingConv::ID CallConv, 1754 ArrayRef<ISD::InputArg> Ins, 1755 BitVector &Skipped, 1756 FunctionType *FType, 1757 SIMachineFunctionInfo *Info) { 1758 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1759 const ISD::InputArg *Arg = &Ins[I]; 1760 1761 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1762 "vector type argument should have been split"); 1763 1764 // First check if it's a PS input addr. 1765 if (CallConv == CallingConv::AMDGPU_PS && 1766 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1767 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1768 1769 // Inconveniently only the first part of the split is marked as isSplit, 1770 // so skip to the end. We only want to increment PSInputNum once for the 1771 // entire split argument. 1772 if (Arg->Flags.isSplit()) { 1773 while (!Arg->Flags.isSplitEnd()) { 1774 assert((!Arg->VT.isVector() || 1775 Arg->VT.getScalarSizeInBits() == 16) && 1776 "unexpected vector split in ps argument type"); 1777 if (!SkipArg) 1778 Splits.push_back(*Arg); 1779 Arg = &Ins[++I]; 1780 } 1781 } 1782 1783 if (SkipArg) { 1784 // We can safely skip PS inputs. 1785 Skipped.set(Arg->getOrigArgIndex()); 1786 ++PSInputNum; 1787 continue; 1788 } 1789 1790 Info->markPSInputAllocated(PSInputNum); 1791 if (Arg->Used) 1792 Info->markPSInputEnabled(PSInputNum); 1793 1794 ++PSInputNum; 1795 } 1796 1797 Splits.push_back(*Arg); 1798 } 1799 } 1800 1801 // Allocate special inputs passed in VGPRs. 1802 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1803 MachineFunction &MF, 1804 const SIRegisterInfo &TRI, 1805 SIMachineFunctionInfo &Info) const { 1806 const LLT S32 = LLT::scalar(32); 1807 MachineRegisterInfo &MRI = MF.getRegInfo(); 1808 1809 if (Info.hasWorkItemIDX()) { 1810 Register Reg = AMDGPU::VGPR0; 1811 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1812 1813 CCInfo.AllocateReg(Reg); 1814 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1815 } 1816 1817 if (Info.hasWorkItemIDY()) { 1818 Register Reg = AMDGPU::VGPR1; 1819 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1820 1821 CCInfo.AllocateReg(Reg); 1822 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1823 } 1824 1825 if (Info.hasWorkItemIDZ()) { 1826 Register Reg = AMDGPU::VGPR2; 1827 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1828 1829 CCInfo.AllocateReg(Reg); 1830 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1831 } 1832 } 1833 1834 // Try to allocate a VGPR at the end of the argument list, or if no argument 1835 // VGPRs are left allocating a stack slot. 1836 // If \p Mask is is given it indicates bitfield position in the register. 1837 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1838 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1839 ArgDescriptor Arg = ArgDescriptor()) { 1840 if (Arg.isSet()) 1841 return ArgDescriptor::createArg(Arg, Mask); 1842 1843 ArrayRef<MCPhysReg> ArgVGPRs 1844 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1845 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1846 if (RegIdx == ArgVGPRs.size()) { 1847 // Spill to stack required. 1848 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1849 1850 return ArgDescriptor::createStack(Offset, Mask); 1851 } 1852 1853 unsigned Reg = ArgVGPRs[RegIdx]; 1854 Reg = CCInfo.AllocateReg(Reg); 1855 assert(Reg != AMDGPU::NoRegister); 1856 1857 MachineFunction &MF = CCInfo.getMachineFunction(); 1858 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1859 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1860 return ArgDescriptor::createRegister(Reg, Mask); 1861 } 1862 1863 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1864 const TargetRegisterClass *RC, 1865 unsigned NumArgRegs) { 1866 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1867 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1868 if (RegIdx == ArgSGPRs.size()) 1869 report_fatal_error("ran out of SGPRs for arguments"); 1870 1871 unsigned Reg = ArgSGPRs[RegIdx]; 1872 Reg = CCInfo.AllocateReg(Reg); 1873 assert(Reg != AMDGPU::NoRegister); 1874 1875 MachineFunction &MF = CCInfo.getMachineFunction(); 1876 MF.addLiveIn(Reg, RC); 1877 return ArgDescriptor::createRegister(Reg); 1878 } 1879 1880 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1881 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1882 } 1883 1884 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1885 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1886 } 1887 1888 /// Allocate implicit function VGPR arguments at the end of allocated user 1889 /// arguments. 1890 void SITargetLowering::allocateSpecialInputVGPRs( 1891 CCState &CCInfo, MachineFunction &MF, 1892 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1893 const unsigned Mask = 0x3ff; 1894 ArgDescriptor Arg; 1895 1896 if (Info.hasWorkItemIDX()) { 1897 Arg = allocateVGPR32Input(CCInfo, Mask); 1898 Info.setWorkItemIDX(Arg); 1899 } 1900 1901 if (Info.hasWorkItemIDY()) { 1902 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1903 Info.setWorkItemIDY(Arg); 1904 } 1905 1906 if (Info.hasWorkItemIDZ()) 1907 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1908 } 1909 1910 /// Allocate implicit function VGPR arguments in fixed registers. 1911 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1912 CCState &CCInfo, MachineFunction &MF, 1913 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1914 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1915 if (!Reg) 1916 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1917 1918 const unsigned Mask = 0x3ff; 1919 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1920 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1921 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1922 } 1923 1924 void SITargetLowering::allocateSpecialInputSGPRs( 1925 CCState &CCInfo, 1926 MachineFunction &MF, 1927 const SIRegisterInfo &TRI, 1928 SIMachineFunctionInfo &Info) const { 1929 auto &ArgInfo = Info.getArgInfo(); 1930 1931 // TODO: Unify handling with private memory pointers. 1932 1933 if (Info.hasDispatchPtr()) 1934 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1935 1936 if (Info.hasQueuePtr()) 1937 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1938 1939 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1940 // constant offset from the kernarg segment. 1941 if (Info.hasImplicitArgPtr()) 1942 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1943 1944 if (Info.hasDispatchID()) 1945 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1946 1947 // flat_scratch_init is not applicable for non-kernel functions. 1948 1949 if (Info.hasWorkGroupIDX()) 1950 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1951 1952 if (Info.hasWorkGroupIDY()) 1953 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1954 1955 if (Info.hasWorkGroupIDZ()) 1956 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1957 } 1958 1959 // Allocate special inputs passed in user SGPRs. 1960 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1961 MachineFunction &MF, 1962 const SIRegisterInfo &TRI, 1963 SIMachineFunctionInfo &Info) const { 1964 if (Info.hasImplicitBufferPtr()) { 1965 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1966 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1967 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1968 } 1969 1970 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1971 if (Info.hasPrivateSegmentBuffer()) { 1972 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1973 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1974 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1975 } 1976 1977 if (Info.hasDispatchPtr()) { 1978 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 1979 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1980 CCInfo.AllocateReg(DispatchPtrReg); 1981 } 1982 1983 if (Info.hasQueuePtr()) { 1984 Register QueuePtrReg = Info.addQueuePtr(TRI); 1985 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1986 CCInfo.AllocateReg(QueuePtrReg); 1987 } 1988 1989 if (Info.hasKernargSegmentPtr()) { 1990 MachineRegisterInfo &MRI = MF.getRegInfo(); 1991 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1992 CCInfo.AllocateReg(InputPtrReg); 1993 1994 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1995 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1996 } 1997 1998 if (Info.hasDispatchID()) { 1999 Register DispatchIDReg = Info.addDispatchID(TRI); 2000 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2001 CCInfo.AllocateReg(DispatchIDReg); 2002 } 2003 2004 if (Info.hasFlatScratchInit()) { 2005 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2006 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2007 CCInfo.AllocateReg(FlatScratchInitReg); 2008 } 2009 2010 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2011 // these from the dispatch pointer. 2012 } 2013 2014 // Allocate special input registers that are initialized per-wave. 2015 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2016 MachineFunction &MF, 2017 SIMachineFunctionInfo &Info, 2018 CallingConv::ID CallConv, 2019 bool IsShader) const { 2020 if (Info.hasWorkGroupIDX()) { 2021 Register Reg = Info.addWorkGroupIDX(); 2022 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2023 CCInfo.AllocateReg(Reg); 2024 } 2025 2026 if (Info.hasWorkGroupIDY()) { 2027 Register Reg = Info.addWorkGroupIDY(); 2028 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2029 CCInfo.AllocateReg(Reg); 2030 } 2031 2032 if (Info.hasWorkGroupIDZ()) { 2033 Register Reg = Info.addWorkGroupIDZ(); 2034 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2035 CCInfo.AllocateReg(Reg); 2036 } 2037 2038 if (Info.hasWorkGroupInfo()) { 2039 Register Reg = Info.addWorkGroupInfo(); 2040 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2041 CCInfo.AllocateReg(Reg); 2042 } 2043 2044 if (Info.hasPrivateSegmentWaveByteOffset()) { 2045 // Scratch wave offset passed in system SGPR. 2046 unsigned PrivateSegmentWaveByteOffsetReg; 2047 2048 if (IsShader) { 2049 PrivateSegmentWaveByteOffsetReg = 2050 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2051 2052 // This is true if the scratch wave byte offset doesn't have a fixed 2053 // location. 2054 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2055 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2056 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2057 } 2058 } else 2059 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2060 2061 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2062 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2063 } 2064 } 2065 2066 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2067 MachineFunction &MF, 2068 const SIRegisterInfo &TRI, 2069 SIMachineFunctionInfo &Info) { 2070 // Now that we've figured out where the scratch register inputs are, see if 2071 // should reserve the arguments and use them directly. 2072 MachineFrameInfo &MFI = MF.getFrameInfo(); 2073 bool HasStackObjects = MFI.hasStackObjects(); 2074 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2075 2076 // Record that we know we have non-spill stack objects so we don't need to 2077 // check all stack objects later. 2078 if (HasStackObjects) 2079 Info.setHasNonSpillStackObjects(true); 2080 2081 // Everything live out of a block is spilled with fast regalloc, so it's 2082 // almost certain that spilling will be required. 2083 if (TM.getOptLevel() == CodeGenOpt::None) 2084 HasStackObjects = true; 2085 2086 // For now assume stack access is needed in any callee functions, so we need 2087 // the scratch registers to pass in. 2088 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2089 2090 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2091 // If we have stack objects, we unquestionably need the private buffer 2092 // resource. For the Code Object V2 ABI, this will be the first 4 user 2093 // SGPR inputs. We can reserve those and use them directly. 2094 2095 Register PrivateSegmentBufferReg = 2096 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2097 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2098 } else { 2099 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2100 // We tentatively reserve the last registers (skipping the last registers 2101 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2102 // we'll replace these with the ones immediately after those which were 2103 // really allocated. In the prologue copies will be inserted from the 2104 // argument to these reserved registers. 2105 2106 // Without HSA, relocations are used for the scratch pointer and the 2107 // buffer resource setup is always inserted in the prologue. Scratch wave 2108 // offset is still in an input SGPR. 2109 Info.setScratchRSrcReg(ReservedBufferReg); 2110 } 2111 2112 MachineRegisterInfo &MRI = MF.getRegInfo(); 2113 2114 // For entry functions we have to set up the stack pointer if we use it, 2115 // whereas non-entry functions get this "for free". This means there is no 2116 // intrinsic advantage to using S32 over S34 in cases where we do not have 2117 // calls but do need a frame pointer (i.e. if we are requested to have one 2118 // because frame pointer elimination is disabled). To keep things simple we 2119 // only ever use S32 as the call ABI stack pointer, and so using it does not 2120 // imply we need a separate frame pointer. 2121 // 2122 // Try to use s32 as the SP, but move it if it would interfere with input 2123 // arguments. This won't work with calls though. 2124 // 2125 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2126 // registers. 2127 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2128 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2129 } else { 2130 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2131 2132 if (MFI.hasCalls()) 2133 report_fatal_error("call in graphics shader with too many input SGPRs"); 2134 2135 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2136 if (!MRI.isLiveIn(Reg)) { 2137 Info.setStackPtrOffsetReg(Reg); 2138 break; 2139 } 2140 } 2141 2142 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2143 report_fatal_error("failed to find register for SP"); 2144 } 2145 2146 // hasFP should be accurate for entry functions even before the frame is 2147 // finalized, because it does not rely on the known stack size, only 2148 // properties like whether variable sized objects are present. 2149 if (ST.getFrameLowering()->hasFP(MF)) { 2150 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2151 } 2152 } 2153 2154 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2155 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2156 return !Info->isEntryFunction(); 2157 } 2158 2159 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2160 2161 } 2162 2163 void SITargetLowering::insertCopiesSplitCSR( 2164 MachineBasicBlock *Entry, 2165 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2166 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2167 2168 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2169 if (!IStart) 2170 return; 2171 2172 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2173 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2174 MachineBasicBlock::iterator MBBI = Entry->begin(); 2175 for (const MCPhysReg *I = IStart; *I; ++I) { 2176 const TargetRegisterClass *RC = nullptr; 2177 if (AMDGPU::SReg_64RegClass.contains(*I)) 2178 RC = &AMDGPU::SGPR_64RegClass; 2179 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2180 RC = &AMDGPU::SGPR_32RegClass; 2181 else 2182 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2183 2184 Register NewVR = MRI->createVirtualRegister(RC); 2185 // Create copy from CSR to a virtual register. 2186 Entry->addLiveIn(*I); 2187 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2188 .addReg(*I); 2189 2190 // Insert the copy-back instructions right before the terminator. 2191 for (auto *Exit : Exits) 2192 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2193 TII->get(TargetOpcode::COPY), *I) 2194 .addReg(NewVR); 2195 } 2196 } 2197 2198 SDValue SITargetLowering::LowerFormalArguments( 2199 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2200 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2201 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2202 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2203 2204 MachineFunction &MF = DAG.getMachineFunction(); 2205 const Function &Fn = MF.getFunction(); 2206 FunctionType *FType = MF.getFunction().getFunctionType(); 2207 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2208 2209 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2210 DiagnosticInfoUnsupported NoGraphicsHSA( 2211 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2212 DAG.getContext()->diagnose(NoGraphicsHSA); 2213 return DAG.getEntryNode(); 2214 } 2215 2216 SmallVector<ISD::InputArg, 16> Splits; 2217 SmallVector<CCValAssign, 16> ArgLocs; 2218 BitVector Skipped(Ins.size()); 2219 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2220 *DAG.getContext()); 2221 2222 bool IsShader = AMDGPU::isShader(CallConv); 2223 bool IsKernel = AMDGPU::isKernel(CallConv); 2224 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2225 2226 if (IsShader) { 2227 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2228 2229 // At least one interpolation mode must be enabled or else the GPU will 2230 // hang. 2231 // 2232 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2233 // set PSInputAddr, the user wants to enable some bits after the compilation 2234 // based on run-time states. Since we can't know what the final PSInputEna 2235 // will look like, so we shouldn't do anything here and the user should take 2236 // responsibility for the correct programming. 2237 // 2238 // Otherwise, the following restrictions apply: 2239 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2240 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2241 // enabled too. 2242 if (CallConv == CallingConv::AMDGPU_PS) { 2243 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2244 ((Info->getPSInputAddr() & 0xF) == 0 && 2245 Info->isPSInputAllocated(11))) { 2246 CCInfo.AllocateReg(AMDGPU::VGPR0); 2247 CCInfo.AllocateReg(AMDGPU::VGPR1); 2248 Info->markPSInputAllocated(0); 2249 Info->markPSInputEnabled(0); 2250 } 2251 if (Subtarget->isAmdPalOS()) { 2252 // For isAmdPalOS, the user does not enable some bits after compilation 2253 // based on run-time states; the register values being generated here are 2254 // the final ones set in hardware. Therefore we need to apply the 2255 // workaround to PSInputAddr and PSInputEnable together. (The case where 2256 // a bit is set in PSInputAddr but not PSInputEnable is where the 2257 // frontend set up an input arg for a particular interpolation mode, but 2258 // nothing uses that input arg. Really we should have an earlier pass 2259 // that removes such an arg.) 2260 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2261 if ((PsInputBits & 0x7F) == 0 || 2262 ((PsInputBits & 0xF) == 0 && 2263 (PsInputBits >> 11 & 1))) 2264 Info->markPSInputEnabled( 2265 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2266 } 2267 } 2268 2269 assert(!Info->hasDispatchPtr() && 2270 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2271 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2272 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2273 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2274 !Info->hasWorkItemIDZ()); 2275 } else if (IsKernel) { 2276 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2277 } else { 2278 Splits.append(Ins.begin(), Ins.end()); 2279 } 2280 2281 if (IsEntryFunc) { 2282 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2283 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2284 } else { 2285 // For the fixed ABI, pass workitem IDs in the last argument register. 2286 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2287 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2288 } 2289 2290 if (IsKernel) { 2291 analyzeFormalArgumentsCompute(CCInfo, Ins); 2292 } else { 2293 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2294 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2295 } 2296 2297 SmallVector<SDValue, 16> Chains; 2298 2299 // FIXME: This is the minimum kernel argument alignment. We should improve 2300 // this to the maximum alignment of the arguments. 2301 // 2302 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2303 // kern arg offset. 2304 const Align KernelArgBaseAlign = Align(16); 2305 2306 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2307 const ISD::InputArg &Arg = Ins[i]; 2308 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2309 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2310 continue; 2311 } 2312 2313 CCValAssign &VA = ArgLocs[ArgIdx++]; 2314 MVT VT = VA.getLocVT(); 2315 2316 if (IsEntryFunc && VA.isMemLoc()) { 2317 VT = Ins[i].VT; 2318 EVT MemVT = VA.getLocVT(); 2319 2320 const uint64_t Offset = VA.getLocMemOffset(); 2321 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2322 2323 if (Arg.Flags.isByRef()) { 2324 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2325 2326 const GCNTargetMachine &TM = 2327 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2328 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2329 Arg.Flags.getPointerAddrSpace())) { 2330 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2331 Arg.Flags.getPointerAddrSpace()); 2332 } 2333 2334 InVals.push_back(Ptr); 2335 continue; 2336 } 2337 2338 SDValue Arg = lowerKernargMemParameter( 2339 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2340 Chains.push_back(Arg.getValue(1)); 2341 2342 auto *ParamTy = 2343 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2344 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2345 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2346 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2347 // On SI local pointers are just offsets into LDS, so they are always 2348 // less than 16-bits. On CI and newer they could potentially be 2349 // real pointers, so we can't guarantee their size. 2350 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2351 DAG.getValueType(MVT::i16)); 2352 } 2353 2354 InVals.push_back(Arg); 2355 continue; 2356 } else if (!IsEntryFunc && VA.isMemLoc()) { 2357 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2358 InVals.push_back(Val); 2359 if (!Arg.Flags.isByVal()) 2360 Chains.push_back(Val.getValue(1)); 2361 continue; 2362 } 2363 2364 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2365 2366 Register Reg = VA.getLocReg(); 2367 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2368 EVT ValVT = VA.getValVT(); 2369 2370 Reg = MF.addLiveIn(Reg, RC); 2371 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2372 2373 if (Arg.Flags.isSRet()) { 2374 // The return object should be reasonably addressable. 2375 2376 // FIXME: This helps when the return is a real sret. If it is a 2377 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2378 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2379 unsigned NumBits 2380 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2381 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2382 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2383 } 2384 2385 // If this is an 8 or 16-bit value, it is really passed promoted 2386 // to 32 bits. Insert an assert[sz]ext to capture this, then 2387 // truncate to the right size. 2388 switch (VA.getLocInfo()) { 2389 case CCValAssign::Full: 2390 break; 2391 case CCValAssign::BCvt: 2392 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2393 break; 2394 case CCValAssign::SExt: 2395 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2396 DAG.getValueType(ValVT)); 2397 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2398 break; 2399 case CCValAssign::ZExt: 2400 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2401 DAG.getValueType(ValVT)); 2402 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2403 break; 2404 case CCValAssign::AExt: 2405 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2406 break; 2407 default: 2408 llvm_unreachable("Unknown loc info!"); 2409 } 2410 2411 InVals.push_back(Val); 2412 } 2413 2414 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2415 // Special inputs come after user arguments. 2416 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2417 } 2418 2419 // Start adding system SGPRs. 2420 if (IsEntryFunc) { 2421 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2422 } else { 2423 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2424 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2425 } 2426 2427 auto &ArgUsageInfo = 2428 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2429 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2430 2431 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2432 Info->setBytesInStackArgArea(StackArgSize); 2433 2434 return Chains.empty() ? Chain : 2435 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2436 } 2437 2438 // TODO: If return values can't fit in registers, we should return as many as 2439 // possible in registers before passing on stack. 2440 bool SITargetLowering::CanLowerReturn( 2441 CallingConv::ID CallConv, 2442 MachineFunction &MF, bool IsVarArg, 2443 const SmallVectorImpl<ISD::OutputArg> &Outs, 2444 LLVMContext &Context) const { 2445 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2446 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2447 // for shaders. Vector types should be explicitly handled by CC. 2448 if (AMDGPU::isEntryFunctionCC(CallConv)) 2449 return true; 2450 2451 SmallVector<CCValAssign, 16> RVLocs; 2452 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2453 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2454 } 2455 2456 SDValue 2457 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2458 bool isVarArg, 2459 const SmallVectorImpl<ISD::OutputArg> &Outs, 2460 const SmallVectorImpl<SDValue> &OutVals, 2461 const SDLoc &DL, SelectionDAG &DAG) const { 2462 MachineFunction &MF = DAG.getMachineFunction(); 2463 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2464 2465 if (AMDGPU::isKernel(CallConv)) { 2466 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2467 OutVals, DL, DAG); 2468 } 2469 2470 bool IsShader = AMDGPU::isShader(CallConv); 2471 2472 Info->setIfReturnsVoid(Outs.empty()); 2473 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2474 2475 // CCValAssign - represent the assignment of the return value to a location. 2476 SmallVector<CCValAssign, 48> RVLocs; 2477 SmallVector<ISD::OutputArg, 48> Splits; 2478 2479 // CCState - Info about the registers and stack slots. 2480 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2481 *DAG.getContext()); 2482 2483 // Analyze outgoing return values. 2484 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2485 2486 SDValue Flag; 2487 SmallVector<SDValue, 48> RetOps; 2488 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2489 2490 // Add return address for callable functions. 2491 if (!Info->isEntryFunction()) { 2492 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2493 SDValue ReturnAddrReg = CreateLiveInRegister( 2494 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2495 2496 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2497 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2498 MVT::i64); 2499 Chain = 2500 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2501 Flag = Chain.getValue(1); 2502 RetOps.push_back(ReturnAddrVirtualReg); 2503 } 2504 2505 // Copy the result values into the output registers. 2506 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2507 ++I, ++RealRVLocIdx) { 2508 CCValAssign &VA = RVLocs[I]; 2509 assert(VA.isRegLoc() && "Can only return in registers!"); 2510 // TODO: Partially return in registers if return values don't fit. 2511 SDValue Arg = OutVals[RealRVLocIdx]; 2512 2513 // Copied from other backends. 2514 switch (VA.getLocInfo()) { 2515 case CCValAssign::Full: 2516 break; 2517 case CCValAssign::BCvt: 2518 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2519 break; 2520 case CCValAssign::SExt: 2521 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2522 break; 2523 case CCValAssign::ZExt: 2524 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2525 break; 2526 case CCValAssign::AExt: 2527 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2528 break; 2529 default: 2530 llvm_unreachable("Unknown loc info!"); 2531 } 2532 2533 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2534 Flag = Chain.getValue(1); 2535 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2536 } 2537 2538 // FIXME: Does sret work properly? 2539 if (!Info->isEntryFunction()) { 2540 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2541 const MCPhysReg *I = 2542 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2543 if (I) { 2544 for (; *I; ++I) { 2545 if (AMDGPU::SReg_64RegClass.contains(*I)) 2546 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2547 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2548 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2549 else 2550 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2551 } 2552 } 2553 } 2554 2555 // Update chain and glue. 2556 RetOps[0] = Chain; 2557 if (Flag.getNode()) 2558 RetOps.push_back(Flag); 2559 2560 unsigned Opc = AMDGPUISD::ENDPGM; 2561 if (!IsWaveEnd) 2562 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2563 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2564 } 2565 2566 SDValue SITargetLowering::LowerCallResult( 2567 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2568 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2569 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2570 SDValue ThisVal) const { 2571 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2572 2573 // Assign locations to each value returned by this call. 2574 SmallVector<CCValAssign, 16> RVLocs; 2575 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2576 *DAG.getContext()); 2577 CCInfo.AnalyzeCallResult(Ins, RetCC); 2578 2579 // Copy all of the result registers out of their specified physreg. 2580 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2581 CCValAssign VA = RVLocs[i]; 2582 SDValue Val; 2583 2584 if (VA.isRegLoc()) { 2585 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2586 Chain = Val.getValue(1); 2587 InFlag = Val.getValue(2); 2588 } else if (VA.isMemLoc()) { 2589 report_fatal_error("TODO: return values in memory"); 2590 } else 2591 llvm_unreachable("unknown argument location type"); 2592 2593 switch (VA.getLocInfo()) { 2594 case CCValAssign::Full: 2595 break; 2596 case CCValAssign::BCvt: 2597 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2598 break; 2599 case CCValAssign::ZExt: 2600 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2601 DAG.getValueType(VA.getValVT())); 2602 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2603 break; 2604 case CCValAssign::SExt: 2605 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2606 DAG.getValueType(VA.getValVT())); 2607 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2608 break; 2609 case CCValAssign::AExt: 2610 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2611 break; 2612 default: 2613 llvm_unreachable("Unknown loc info!"); 2614 } 2615 2616 InVals.push_back(Val); 2617 } 2618 2619 return Chain; 2620 } 2621 2622 // Add code to pass special inputs required depending on used features separate 2623 // from the explicit user arguments present in the IR. 2624 void SITargetLowering::passSpecialInputs( 2625 CallLoweringInfo &CLI, 2626 CCState &CCInfo, 2627 const SIMachineFunctionInfo &Info, 2628 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2629 SmallVectorImpl<SDValue> &MemOpChains, 2630 SDValue Chain) const { 2631 // If we don't have a call site, this was a call inserted by 2632 // legalization. These can never use special inputs. 2633 if (!CLI.CB) 2634 return; 2635 2636 SelectionDAG &DAG = CLI.DAG; 2637 const SDLoc &DL = CLI.DL; 2638 2639 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2640 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2641 2642 const AMDGPUFunctionArgInfo *CalleeArgInfo 2643 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2644 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2645 auto &ArgUsageInfo = 2646 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2647 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2648 } 2649 2650 // TODO: Unify with private memory register handling. This is complicated by 2651 // the fact that at least in kernels, the input argument is not necessarily 2652 // in the same location as the input. 2653 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2654 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2655 AMDGPUFunctionArgInfo::QUEUE_PTR, 2656 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2657 AMDGPUFunctionArgInfo::DISPATCH_ID, 2658 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2659 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2660 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2661 }; 2662 2663 for (auto InputID : InputRegs) { 2664 const ArgDescriptor *OutgoingArg; 2665 const TargetRegisterClass *ArgRC; 2666 LLT ArgTy; 2667 2668 std::tie(OutgoingArg, ArgRC, ArgTy) = 2669 CalleeArgInfo->getPreloadedValue(InputID); 2670 if (!OutgoingArg) 2671 continue; 2672 2673 const ArgDescriptor *IncomingArg; 2674 const TargetRegisterClass *IncomingArgRC; 2675 LLT Ty; 2676 std::tie(IncomingArg, IncomingArgRC, Ty) = 2677 CallerArgInfo.getPreloadedValue(InputID); 2678 assert(IncomingArgRC == ArgRC); 2679 2680 // All special arguments are ints for now. 2681 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2682 SDValue InputReg; 2683 2684 if (IncomingArg) { 2685 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2686 } else { 2687 // The implicit arg ptr is special because it doesn't have a corresponding 2688 // input for kernels, and is computed from the kernarg segment pointer. 2689 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2690 InputReg = getImplicitArgPtr(DAG, DL); 2691 } 2692 2693 if (OutgoingArg->isRegister()) { 2694 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2695 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2696 report_fatal_error("failed to allocate implicit input argument"); 2697 } else { 2698 unsigned SpecialArgOffset = 2699 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2700 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2701 SpecialArgOffset); 2702 MemOpChains.push_back(ArgStore); 2703 } 2704 } 2705 2706 // Pack workitem IDs into a single register or pass it as is if already 2707 // packed. 2708 const ArgDescriptor *OutgoingArg; 2709 const TargetRegisterClass *ArgRC; 2710 LLT Ty; 2711 2712 std::tie(OutgoingArg, ArgRC, Ty) = 2713 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2714 if (!OutgoingArg) 2715 std::tie(OutgoingArg, ArgRC, Ty) = 2716 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2717 if (!OutgoingArg) 2718 std::tie(OutgoingArg, ArgRC, Ty) = 2719 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2720 if (!OutgoingArg) 2721 return; 2722 2723 const ArgDescriptor *IncomingArgX = std::get<0>( 2724 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2725 const ArgDescriptor *IncomingArgY = std::get<0>( 2726 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2727 const ArgDescriptor *IncomingArgZ = std::get<0>( 2728 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2729 2730 SDValue InputReg; 2731 SDLoc SL; 2732 2733 // If incoming ids are not packed we need to pack them. 2734 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2735 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2736 2737 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2738 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2739 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2740 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2741 InputReg = InputReg.getNode() ? 2742 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2743 } 2744 2745 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2746 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2747 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2748 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2749 InputReg = InputReg.getNode() ? 2750 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2751 } 2752 2753 if (!InputReg.getNode()) { 2754 // Workitem ids are already packed, any of present incoming arguments 2755 // will carry all required fields. 2756 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2757 IncomingArgX ? *IncomingArgX : 2758 IncomingArgY ? *IncomingArgY : 2759 *IncomingArgZ, ~0u); 2760 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2761 } 2762 2763 if (OutgoingArg->isRegister()) { 2764 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2765 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2766 } else { 2767 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2768 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2769 SpecialArgOffset); 2770 MemOpChains.push_back(ArgStore); 2771 } 2772 } 2773 2774 static bool canGuaranteeTCO(CallingConv::ID CC) { 2775 return CC == CallingConv::Fast; 2776 } 2777 2778 /// Return true if we might ever do TCO for calls with this calling convention. 2779 static bool mayTailCallThisCC(CallingConv::ID CC) { 2780 switch (CC) { 2781 case CallingConv::C: 2782 return true; 2783 default: 2784 return canGuaranteeTCO(CC); 2785 } 2786 } 2787 2788 bool SITargetLowering::isEligibleForTailCallOptimization( 2789 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2790 const SmallVectorImpl<ISD::OutputArg> &Outs, 2791 const SmallVectorImpl<SDValue> &OutVals, 2792 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2793 if (!mayTailCallThisCC(CalleeCC)) 2794 return false; 2795 2796 MachineFunction &MF = DAG.getMachineFunction(); 2797 const Function &CallerF = MF.getFunction(); 2798 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2799 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2800 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2801 2802 // Kernels aren't callable, and don't have a live in return address so it 2803 // doesn't make sense to do a tail call with entry functions. 2804 if (!CallerPreserved) 2805 return false; 2806 2807 bool CCMatch = CallerCC == CalleeCC; 2808 2809 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2810 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2811 return true; 2812 return false; 2813 } 2814 2815 // TODO: Can we handle var args? 2816 if (IsVarArg) 2817 return false; 2818 2819 for (const Argument &Arg : CallerF.args()) { 2820 if (Arg.hasByValAttr()) 2821 return false; 2822 } 2823 2824 LLVMContext &Ctx = *DAG.getContext(); 2825 2826 // Check that the call results are passed in the same way. 2827 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2828 CCAssignFnForCall(CalleeCC, IsVarArg), 2829 CCAssignFnForCall(CallerCC, IsVarArg))) 2830 return false; 2831 2832 // The callee has to preserve all registers the caller needs to preserve. 2833 if (!CCMatch) { 2834 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2835 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2836 return false; 2837 } 2838 2839 // Nothing more to check if the callee is taking no arguments. 2840 if (Outs.empty()) 2841 return true; 2842 2843 SmallVector<CCValAssign, 16> ArgLocs; 2844 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2845 2846 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2847 2848 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2849 // If the stack arguments for this call do not fit into our own save area then 2850 // the call cannot be made tail. 2851 // TODO: Is this really necessary? 2852 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2853 return false; 2854 2855 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2856 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2857 } 2858 2859 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2860 if (!CI->isTailCall()) 2861 return false; 2862 2863 const Function *ParentFn = CI->getParent()->getParent(); 2864 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2865 return false; 2866 return true; 2867 } 2868 2869 // The wave scratch offset register is used as the global base pointer. 2870 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2871 SmallVectorImpl<SDValue> &InVals) const { 2872 SelectionDAG &DAG = CLI.DAG; 2873 const SDLoc &DL = CLI.DL; 2874 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2875 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2876 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2877 SDValue Chain = CLI.Chain; 2878 SDValue Callee = CLI.Callee; 2879 bool &IsTailCall = CLI.IsTailCall; 2880 CallingConv::ID CallConv = CLI.CallConv; 2881 bool IsVarArg = CLI.IsVarArg; 2882 bool IsSibCall = false; 2883 bool IsThisReturn = false; 2884 MachineFunction &MF = DAG.getMachineFunction(); 2885 2886 if (Callee.isUndef() || isNullConstant(Callee)) { 2887 if (!CLI.IsTailCall) { 2888 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2889 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2890 } 2891 2892 return Chain; 2893 } 2894 2895 if (IsVarArg) { 2896 return lowerUnhandledCall(CLI, InVals, 2897 "unsupported call to variadic function "); 2898 } 2899 2900 if (!CLI.CB) 2901 report_fatal_error("unsupported libcall legalization"); 2902 2903 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2904 !CLI.CB->getCalledFunction()) { 2905 return lowerUnhandledCall(CLI, InVals, 2906 "unsupported indirect call to function "); 2907 } 2908 2909 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2910 return lowerUnhandledCall(CLI, InVals, 2911 "unsupported required tail call to function "); 2912 } 2913 2914 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2915 // Note the issue is with the CC of the calling function, not of the call 2916 // itself. 2917 return lowerUnhandledCall(CLI, InVals, 2918 "unsupported call from graphics shader of function "); 2919 } 2920 2921 if (IsTailCall) { 2922 IsTailCall = isEligibleForTailCallOptimization( 2923 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2924 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2925 report_fatal_error("failed to perform tail call elimination on a call " 2926 "site marked musttail"); 2927 } 2928 2929 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2930 2931 // A sibling call is one where we're under the usual C ABI and not planning 2932 // to change that but can still do a tail call: 2933 if (!TailCallOpt && IsTailCall) 2934 IsSibCall = true; 2935 2936 if (IsTailCall) 2937 ++NumTailCalls; 2938 } 2939 2940 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2941 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2942 SmallVector<SDValue, 8> MemOpChains; 2943 2944 // Analyze operands of the call, assigning locations to each operand. 2945 SmallVector<CCValAssign, 16> ArgLocs; 2946 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2947 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2948 2949 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2950 // With a fixed ABI, allocate fixed registers before user arguments. 2951 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2952 } 2953 2954 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2955 2956 // Get a count of how many bytes are to be pushed on the stack. 2957 unsigned NumBytes = CCInfo.getNextStackOffset(); 2958 2959 if (IsSibCall) { 2960 // Since we're not changing the ABI to make this a tail call, the memory 2961 // operands are already available in the caller's incoming argument space. 2962 NumBytes = 0; 2963 } 2964 2965 // FPDiff is the byte offset of the call's argument area from the callee's. 2966 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2967 // by this amount for a tail call. In a sibling call it must be 0 because the 2968 // caller will deallocate the entire stack and the callee still expects its 2969 // arguments to begin at SP+0. Completely unused for non-tail calls. 2970 int32_t FPDiff = 0; 2971 MachineFrameInfo &MFI = MF.getFrameInfo(); 2972 2973 // Adjust the stack pointer for the new arguments... 2974 // These operations are automatically eliminated by the prolog/epilog pass 2975 if (!IsSibCall) { 2976 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2977 2978 SmallVector<SDValue, 4> CopyFromChains; 2979 2980 // In the HSA case, this should be an identity copy. 2981 SDValue ScratchRSrcReg 2982 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2983 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2984 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2985 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2986 } 2987 2988 MVT PtrVT = MVT::i32; 2989 2990 // Walk the register/memloc assignments, inserting copies/loads. 2991 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2992 CCValAssign &VA = ArgLocs[i]; 2993 SDValue Arg = OutVals[i]; 2994 2995 // Promote the value if needed. 2996 switch (VA.getLocInfo()) { 2997 case CCValAssign::Full: 2998 break; 2999 case CCValAssign::BCvt: 3000 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3001 break; 3002 case CCValAssign::ZExt: 3003 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3004 break; 3005 case CCValAssign::SExt: 3006 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3007 break; 3008 case CCValAssign::AExt: 3009 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3010 break; 3011 case CCValAssign::FPExt: 3012 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3013 break; 3014 default: 3015 llvm_unreachable("Unknown loc info!"); 3016 } 3017 3018 if (VA.isRegLoc()) { 3019 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3020 } else { 3021 assert(VA.isMemLoc()); 3022 3023 SDValue DstAddr; 3024 MachinePointerInfo DstInfo; 3025 3026 unsigned LocMemOffset = VA.getLocMemOffset(); 3027 int32_t Offset = LocMemOffset; 3028 3029 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3030 MaybeAlign Alignment; 3031 3032 if (IsTailCall) { 3033 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3034 unsigned OpSize = Flags.isByVal() ? 3035 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3036 3037 // FIXME: We can have better than the minimum byval required alignment. 3038 Alignment = 3039 Flags.isByVal() 3040 ? Flags.getNonZeroByValAlign() 3041 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3042 3043 Offset = Offset + FPDiff; 3044 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3045 3046 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3047 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3048 3049 // Make sure any stack arguments overlapping with where we're storing 3050 // are loaded before this eventual operation. Otherwise they'll be 3051 // clobbered. 3052 3053 // FIXME: Why is this really necessary? This seems to just result in a 3054 // lot of code to copy the stack and write them back to the same 3055 // locations, which are supposed to be immutable? 3056 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3057 } else { 3058 DstAddr = PtrOff; 3059 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3060 Alignment = 3061 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3062 } 3063 3064 if (Outs[i].Flags.isByVal()) { 3065 SDValue SizeNode = 3066 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3067 SDValue Cpy = 3068 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3069 Outs[i].Flags.getNonZeroByValAlign(), 3070 /*isVol = */ false, /*AlwaysInline = */ true, 3071 /*isTailCall = */ false, DstInfo, 3072 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3073 3074 MemOpChains.push_back(Cpy); 3075 } else { 3076 SDValue Store = 3077 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3078 MemOpChains.push_back(Store); 3079 } 3080 } 3081 } 3082 3083 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3084 // Copy special input registers after user input arguments. 3085 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3086 } 3087 3088 if (!MemOpChains.empty()) 3089 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3090 3091 // Build a sequence of copy-to-reg nodes chained together with token chain 3092 // and flag operands which copy the outgoing args into the appropriate regs. 3093 SDValue InFlag; 3094 for (auto &RegToPass : RegsToPass) { 3095 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3096 RegToPass.second, InFlag); 3097 InFlag = Chain.getValue(1); 3098 } 3099 3100 3101 SDValue PhysReturnAddrReg; 3102 if (IsTailCall) { 3103 // Since the return is being combined with the call, we need to pass on the 3104 // return address. 3105 3106 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3107 SDValue ReturnAddrReg = CreateLiveInRegister( 3108 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3109 3110 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3111 MVT::i64); 3112 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3113 InFlag = Chain.getValue(1); 3114 } 3115 3116 // We don't usually want to end the call-sequence here because we would tidy 3117 // the frame up *after* the call, however in the ABI-changing tail-call case 3118 // we've carefully laid out the parameters so that when sp is reset they'll be 3119 // in the correct location. 3120 if (IsTailCall && !IsSibCall) { 3121 Chain = DAG.getCALLSEQ_END(Chain, 3122 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3123 DAG.getTargetConstant(0, DL, MVT::i32), 3124 InFlag, DL); 3125 InFlag = Chain.getValue(1); 3126 } 3127 3128 std::vector<SDValue> Ops; 3129 Ops.push_back(Chain); 3130 Ops.push_back(Callee); 3131 // Add a redundant copy of the callee global which will not be legalized, as 3132 // we need direct access to the callee later. 3133 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3134 const GlobalValue *GV = GSD->getGlobal(); 3135 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3136 } else { 3137 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3138 } 3139 3140 if (IsTailCall) { 3141 // Each tail call may have to adjust the stack by a different amount, so 3142 // this information must travel along with the operation for eventual 3143 // consumption by emitEpilogue. 3144 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3145 3146 Ops.push_back(PhysReturnAddrReg); 3147 } 3148 3149 // Add argument registers to the end of the list so that they are known live 3150 // into the call. 3151 for (auto &RegToPass : RegsToPass) { 3152 Ops.push_back(DAG.getRegister(RegToPass.first, 3153 RegToPass.second.getValueType())); 3154 } 3155 3156 // Add a register mask operand representing the call-preserved registers. 3157 3158 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3159 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3160 assert(Mask && "Missing call preserved mask for calling convention"); 3161 Ops.push_back(DAG.getRegisterMask(Mask)); 3162 3163 if (InFlag.getNode()) 3164 Ops.push_back(InFlag); 3165 3166 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3167 3168 // If we're doing a tall call, use a TC_RETURN here rather than an 3169 // actual call instruction. 3170 if (IsTailCall) { 3171 MFI.setHasTailCall(); 3172 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3173 } 3174 3175 // Returns a chain and a flag for retval copy to use. 3176 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3177 Chain = Call.getValue(0); 3178 InFlag = Call.getValue(1); 3179 3180 uint64_t CalleePopBytes = NumBytes; 3181 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3182 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3183 InFlag, DL); 3184 if (!Ins.empty()) 3185 InFlag = Chain.getValue(1); 3186 3187 // Handle result values, copying them out of physregs into vregs that we 3188 // return. 3189 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3190 InVals, IsThisReturn, 3191 IsThisReturn ? OutVals[0] : SDValue()); 3192 } 3193 3194 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3195 // except for applying the wave size scale to the increment amount. 3196 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3197 SDValue Op, SelectionDAG &DAG) const { 3198 const MachineFunction &MF = DAG.getMachineFunction(); 3199 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3200 3201 SDLoc dl(Op); 3202 EVT VT = Op.getValueType(); 3203 SDValue Tmp1 = Op; 3204 SDValue Tmp2 = Op.getValue(1); 3205 SDValue Tmp3 = Op.getOperand(2); 3206 SDValue Chain = Tmp1.getOperand(0); 3207 3208 Register SPReg = Info->getStackPtrOffsetReg(); 3209 3210 // Chain the dynamic stack allocation so that it doesn't modify the stack 3211 // pointer when other instructions are using the stack. 3212 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3213 3214 SDValue Size = Tmp2.getOperand(1); 3215 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3216 Chain = SP.getValue(1); 3217 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3218 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3219 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3220 unsigned Opc = 3221 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3222 ISD::ADD : ISD::SUB; 3223 3224 SDValue ScaledSize = DAG.getNode( 3225 ISD::SHL, dl, VT, Size, 3226 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3227 3228 Align StackAlign = TFL->getStackAlign(); 3229 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3230 if (Alignment && *Alignment > StackAlign) { 3231 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3232 DAG.getConstant(-(uint64_t)Alignment->value() 3233 << ST.getWavefrontSizeLog2(), 3234 dl, VT)); 3235 } 3236 3237 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3238 Tmp2 = DAG.getCALLSEQ_END( 3239 Chain, DAG.getIntPtrConstant(0, dl, true), 3240 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3241 3242 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3243 } 3244 3245 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3246 SelectionDAG &DAG) const { 3247 // We only handle constant sizes here to allow non-entry block, static sized 3248 // allocas. A truly dynamic value is more difficult to support because we 3249 // don't know if the size value is uniform or not. If the size isn't uniform, 3250 // we would need to do a wave reduction to get the maximum size to know how 3251 // much to increment the uniform stack pointer. 3252 SDValue Size = Op.getOperand(1); 3253 if (isa<ConstantSDNode>(Size)) 3254 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3255 3256 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3257 } 3258 3259 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3260 const MachineFunction &MF) const { 3261 Register Reg = StringSwitch<Register>(RegName) 3262 .Case("m0", AMDGPU::M0) 3263 .Case("exec", AMDGPU::EXEC) 3264 .Case("exec_lo", AMDGPU::EXEC_LO) 3265 .Case("exec_hi", AMDGPU::EXEC_HI) 3266 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3267 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3268 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3269 .Default(Register()); 3270 3271 if (Reg == AMDGPU::NoRegister) { 3272 report_fatal_error(Twine("invalid register name \"" 3273 + StringRef(RegName) + "\".")); 3274 3275 } 3276 3277 if (!Subtarget->hasFlatScrRegister() && 3278 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3279 report_fatal_error(Twine("invalid register \"" 3280 + StringRef(RegName) + "\" for subtarget.")); 3281 } 3282 3283 switch (Reg) { 3284 case AMDGPU::M0: 3285 case AMDGPU::EXEC_LO: 3286 case AMDGPU::EXEC_HI: 3287 case AMDGPU::FLAT_SCR_LO: 3288 case AMDGPU::FLAT_SCR_HI: 3289 if (VT.getSizeInBits() == 32) 3290 return Reg; 3291 break; 3292 case AMDGPU::EXEC: 3293 case AMDGPU::FLAT_SCR: 3294 if (VT.getSizeInBits() == 64) 3295 return Reg; 3296 break; 3297 default: 3298 llvm_unreachable("missing register type checking"); 3299 } 3300 3301 report_fatal_error(Twine("invalid type for register \"" 3302 + StringRef(RegName) + "\".")); 3303 } 3304 3305 // If kill is not the last instruction, split the block so kill is always a 3306 // proper terminator. 3307 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3308 MachineBasicBlock *BB) const { 3309 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3310 3311 MachineBasicBlock::iterator SplitPoint(&MI); 3312 ++SplitPoint; 3313 3314 if (SplitPoint == BB->end()) { 3315 // Don't bother with a new block. 3316 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3317 return BB; 3318 } 3319 3320 MachineFunction *MF = BB->getParent(); 3321 MachineBasicBlock *SplitBB 3322 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3323 3324 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3325 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3326 3327 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3328 BB->addSuccessor(SplitBB); 3329 3330 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3331 return SplitBB; 3332 } 3333 3334 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3335 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3336 // be the first instruction in the remainder block. 3337 // 3338 /// \returns { LoopBody, Remainder } 3339 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3340 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3341 MachineFunction *MF = MBB.getParent(); 3342 MachineBasicBlock::iterator I(&MI); 3343 3344 // To insert the loop we need to split the block. Move everything after this 3345 // point to a new block, and insert a new empty block between the two. 3346 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3347 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3348 MachineFunction::iterator MBBI(MBB); 3349 ++MBBI; 3350 3351 MF->insert(MBBI, LoopBB); 3352 MF->insert(MBBI, RemainderBB); 3353 3354 LoopBB->addSuccessor(LoopBB); 3355 LoopBB->addSuccessor(RemainderBB); 3356 3357 // Move the rest of the block into a new block. 3358 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3359 3360 if (InstInLoop) { 3361 auto Next = std::next(I); 3362 3363 // Move instruction to loop body. 3364 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3365 3366 // Move the rest of the block. 3367 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3368 } else { 3369 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3370 } 3371 3372 MBB.addSuccessor(LoopBB); 3373 3374 return std::make_pair(LoopBB, RemainderBB); 3375 } 3376 3377 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3378 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3379 MachineBasicBlock *MBB = MI.getParent(); 3380 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3381 auto I = MI.getIterator(); 3382 auto E = std::next(I); 3383 3384 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3385 .addImm(0); 3386 3387 MIBundleBuilder Bundler(*MBB, I, E); 3388 finalizeBundle(*MBB, Bundler.begin()); 3389 } 3390 3391 MachineBasicBlock * 3392 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3393 MachineBasicBlock *BB) const { 3394 const DebugLoc &DL = MI.getDebugLoc(); 3395 3396 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3397 3398 MachineBasicBlock *LoopBB; 3399 MachineBasicBlock *RemainderBB; 3400 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3401 3402 // Apparently kill flags are only valid if the def is in the same block? 3403 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3404 Src->setIsKill(false); 3405 3406 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3407 3408 MachineBasicBlock::iterator I = LoopBB->end(); 3409 3410 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3411 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3412 3413 // Clear TRAP_STS.MEM_VIOL 3414 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3415 .addImm(0) 3416 .addImm(EncodedReg); 3417 3418 bundleInstWithWaitcnt(MI); 3419 3420 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3421 3422 // Load and check TRAP_STS.MEM_VIOL 3423 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3424 .addImm(EncodedReg); 3425 3426 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3427 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3428 .addReg(Reg, RegState::Kill) 3429 .addImm(0); 3430 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3431 .addMBB(LoopBB); 3432 3433 return RemainderBB; 3434 } 3435 3436 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3437 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3438 // will only do one iteration. In the worst case, this will loop 64 times. 3439 // 3440 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3441 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3442 const SIInstrInfo *TII, 3443 MachineRegisterInfo &MRI, 3444 MachineBasicBlock &OrigBB, 3445 MachineBasicBlock &LoopBB, 3446 const DebugLoc &DL, 3447 const MachineOperand &IdxReg, 3448 unsigned InitReg, 3449 unsigned ResultReg, 3450 unsigned PhiReg, 3451 unsigned InitSaveExecReg, 3452 int Offset, 3453 bool UseGPRIdxMode, 3454 bool IsIndirectSrc) { 3455 MachineFunction *MF = OrigBB.getParent(); 3456 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3457 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3458 MachineBasicBlock::iterator I = LoopBB.begin(); 3459 3460 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3461 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3462 Register NewExec = MRI.createVirtualRegister(BoolRC); 3463 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3464 Register CondReg = MRI.createVirtualRegister(BoolRC); 3465 3466 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3467 .addReg(InitReg) 3468 .addMBB(&OrigBB) 3469 .addReg(ResultReg) 3470 .addMBB(&LoopBB); 3471 3472 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3473 .addReg(InitSaveExecReg) 3474 .addMBB(&OrigBB) 3475 .addReg(NewExec) 3476 .addMBB(&LoopBB); 3477 3478 // Read the next variant <- also loop target. 3479 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3480 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3481 3482 // Compare the just read M0 value to all possible Idx values. 3483 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3484 .addReg(CurrentIdxReg) 3485 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3486 3487 // Update EXEC, save the original EXEC value to VCC. 3488 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3489 : AMDGPU::S_AND_SAVEEXEC_B64), 3490 NewExec) 3491 .addReg(CondReg, RegState::Kill); 3492 3493 MRI.setSimpleHint(NewExec, CondReg); 3494 3495 if (UseGPRIdxMode) { 3496 unsigned IdxReg; 3497 if (Offset == 0) { 3498 IdxReg = CurrentIdxReg; 3499 } else { 3500 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3501 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3502 .addReg(CurrentIdxReg, RegState::Kill) 3503 .addImm(Offset); 3504 } 3505 unsigned IdxMode = IsIndirectSrc ? 3506 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3507 MachineInstr *SetOn = 3508 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3509 .addReg(IdxReg, RegState::Kill) 3510 .addImm(IdxMode); 3511 SetOn->getOperand(3).setIsUndef(); 3512 } else { 3513 // Move index from VCC into M0 3514 if (Offset == 0) { 3515 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3516 .addReg(CurrentIdxReg, RegState::Kill); 3517 } else { 3518 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3519 .addReg(CurrentIdxReg, RegState::Kill) 3520 .addImm(Offset); 3521 } 3522 } 3523 3524 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3525 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3526 MachineInstr *InsertPt = 3527 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3528 : AMDGPU::S_XOR_B64_term), Exec) 3529 .addReg(Exec) 3530 .addReg(NewExec); 3531 3532 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3533 // s_cbranch_scc0? 3534 3535 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3536 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3537 .addMBB(&LoopBB); 3538 3539 return InsertPt->getIterator(); 3540 } 3541 3542 // This has slightly sub-optimal regalloc when the source vector is killed by 3543 // the read. The register allocator does not understand that the kill is 3544 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3545 // subregister from it, using 1 more VGPR than necessary. This was saved when 3546 // this was expanded after register allocation. 3547 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3548 MachineBasicBlock &MBB, 3549 MachineInstr &MI, 3550 unsigned InitResultReg, 3551 unsigned PhiReg, 3552 int Offset, 3553 bool UseGPRIdxMode, 3554 bool IsIndirectSrc) { 3555 MachineFunction *MF = MBB.getParent(); 3556 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3557 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3558 MachineRegisterInfo &MRI = MF->getRegInfo(); 3559 const DebugLoc &DL = MI.getDebugLoc(); 3560 MachineBasicBlock::iterator I(&MI); 3561 3562 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3563 Register DstReg = MI.getOperand(0).getReg(); 3564 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3565 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3566 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3567 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3568 3569 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3570 3571 // Save the EXEC mask 3572 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3573 .addReg(Exec); 3574 3575 MachineBasicBlock *LoopBB; 3576 MachineBasicBlock *RemainderBB; 3577 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3578 3579 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3580 3581 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3582 InitResultReg, DstReg, PhiReg, TmpExec, 3583 Offset, UseGPRIdxMode, IsIndirectSrc); 3584 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3585 MachineFunction::iterator MBBI(LoopBB); 3586 ++MBBI; 3587 MF->insert(MBBI, LandingPad); 3588 LoopBB->removeSuccessor(RemainderBB); 3589 LandingPad->addSuccessor(RemainderBB); 3590 LoopBB->addSuccessor(LandingPad); 3591 MachineBasicBlock::iterator First = LandingPad->begin(); 3592 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3593 .addReg(SaveExec); 3594 3595 return InsPt; 3596 } 3597 3598 // Returns subreg index, offset 3599 static std::pair<unsigned, int> 3600 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3601 const TargetRegisterClass *SuperRC, 3602 unsigned VecReg, 3603 int Offset) { 3604 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3605 3606 // Skip out of bounds offsets, or else we would end up using an undefined 3607 // register. 3608 if (Offset >= NumElts || Offset < 0) 3609 return std::make_pair(AMDGPU::sub0, Offset); 3610 3611 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3612 } 3613 3614 // Return true if the index is an SGPR and was set. 3615 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3616 MachineRegisterInfo &MRI, 3617 MachineInstr &MI, 3618 int Offset, 3619 bool UseGPRIdxMode, 3620 bool IsIndirectSrc) { 3621 MachineBasicBlock *MBB = MI.getParent(); 3622 const DebugLoc &DL = MI.getDebugLoc(); 3623 MachineBasicBlock::iterator I(&MI); 3624 3625 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3626 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3627 3628 assert(Idx->getReg() != AMDGPU::NoRegister); 3629 3630 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3631 return false; 3632 3633 if (UseGPRIdxMode) { 3634 unsigned IdxMode = IsIndirectSrc ? 3635 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3636 if (Offset == 0) { 3637 MachineInstr *SetOn = 3638 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3639 .add(*Idx) 3640 .addImm(IdxMode); 3641 3642 SetOn->getOperand(3).setIsUndef(); 3643 } else { 3644 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3645 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3646 .add(*Idx) 3647 .addImm(Offset); 3648 MachineInstr *SetOn = 3649 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3650 .addReg(Tmp, RegState::Kill) 3651 .addImm(IdxMode); 3652 3653 SetOn->getOperand(3).setIsUndef(); 3654 } 3655 3656 return true; 3657 } 3658 3659 if (Offset == 0) { 3660 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3661 .add(*Idx); 3662 } else { 3663 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3664 .add(*Idx) 3665 .addImm(Offset); 3666 } 3667 3668 return true; 3669 } 3670 3671 // Control flow needs to be inserted if indexing with a VGPR. 3672 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3673 MachineBasicBlock &MBB, 3674 const GCNSubtarget &ST) { 3675 const SIInstrInfo *TII = ST.getInstrInfo(); 3676 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3677 MachineFunction *MF = MBB.getParent(); 3678 MachineRegisterInfo &MRI = MF->getRegInfo(); 3679 3680 Register Dst = MI.getOperand(0).getReg(); 3681 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3682 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3683 3684 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3685 3686 unsigned SubReg; 3687 std::tie(SubReg, Offset) 3688 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3689 3690 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3691 3692 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3693 MachineBasicBlock::iterator I(&MI); 3694 const DebugLoc &DL = MI.getDebugLoc(); 3695 3696 if (UseGPRIdxMode) { 3697 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3698 // to avoid interfering with other uses, so probably requires a new 3699 // optimization pass. 3700 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3701 .addReg(SrcReg, 0, SubReg) 3702 .addReg(SrcReg, RegState::Implicit) 3703 .addReg(AMDGPU::M0, RegState::Implicit); 3704 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3705 } else { 3706 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3707 .addReg(SrcReg, 0, SubReg) 3708 .addReg(SrcReg, RegState::Implicit); 3709 } 3710 3711 MI.eraseFromParent(); 3712 3713 return &MBB; 3714 } 3715 3716 const DebugLoc &DL = MI.getDebugLoc(); 3717 MachineBasicBlock::iterator I(&MI); 3718 3719 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3720 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3721 3722 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3723 3724 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3725 Offset, UseGPRIdxMode, true); 3726 MachineBasicBlock *LoopBB = InsPt->getParent(); 3727 3728 if (UseGPRIdxMode) { 3729 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3730 .addReg(SrcReg, 0, SubReg) 3731 .addReg(SrcReg, RegState::Implicit) 3732 .addReg(AMDGPU::M0, RegState::Implicit); 3733 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3734 } else { 3735 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3736 .addReg(SrcReg, 0, SubReg) 3737 .addReg(SrcReg, RegState::Implicit); 3738 } 3739 3740 MI.eraseFromParent(); 3741 3742 return LoopBB; 3743 } 3744 3745 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3746 MachineBasicBlock &MBB, 3747 const GCNSubtarget &ST) { 3748 const SIInstrInfo *TII = ST.getInstrInfo(); 3749 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3750 MachineFunction *MF = MBB.getParent(); 3751 MachineRegisterInfo &MRI = MF->getRegInfo(); 3752 3753 Register Dst = MI.getOperand(0).getReg(); 3754 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3755 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3756 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3757 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3758 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3759 3760 // This can be an immediate, but will be folded later. 3761 assert(Val->getReg()); 3762 3763 unsigned SubReg; 3764 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3765 SrcVec->getReg(), 3766 Offset); 3767 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3768 3769 if (Idx->getReg() == AMDGPU::NoRegister) { 3770 MachineBasicBlock::iterator I(&MI); 3771 const DebugLoc &DL = MI.getDebugLoc(); 3772 3773 assert(Offset == 0); 3774 3775 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3776 .add(*SrcVec) 3777 .add(*Val) 3778 .addImm(SubReg); 3779 3780 MI.eraseFromParent(); 3781 return &MBB; 3782 } 3783 3784 const MCInstrDesc &MovRelDesc 3785 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3786 3787 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3788 MachineBasicBlock::iterator I(&MI); 3789 const DebugLoc &DL = MI.getDebugLoc(); 3790 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3791 .addReg(SrcVec->getReg()) 3792 .add(*Val) 3793 .addImm(SubReg); 3794 if (UseGPRIdxMode) 3795 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3796 3797 MI.eraseFromParent(); 3798 return &MBB; 3799 } 3800 3801 if (Val->isReg()) 3802 MRI.clearKillFlags(Val->getReg()); 3803 3804 const DebugLoc &DL = MI.getDebugLoc(); 3805 3806 Register PhiReg = MRI.createVirtualRegister(VecRC); 3807 3808 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3809 Offset, UseGPRIdxMode, false); 3810 MachineBasicBlock *LoopBB = InsPt->getParent(); 3811 3812 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3813 .addReg(PhiReg) 3814 .add(*Val) 3815 .addImm(AMDGPU::sub0); 3816 if (UseGPRIdxMode) 3817 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3818 3819 MI.eraseFromParent(); 3820 return LoopBB; 3821 } 3822 3823 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3824 MachineInstr &MI, MachineBasicBlock *BB) const { 3825 3826 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3827 MachineFunction *MF = BB->getParent(); 3828 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3829 3830 switch (MI.getOpcode()) { 3831 case AMDGPU::S_UADDO_PSEUDO: 3832 case AMDGPU::S_USUBO_PSEUDO: { 3833 const DebugLoc &DL = MI.getDebugLoc(); 3834 MachineOperand &Dest0 = MI.getOperand(0); 3835 MachineOperand &Dest1 = MI.getOperand(1); 3836 MachineOperand &Src0 = MI.getOperand(2); 3837 MachineOperand &Src1 = MI.getOperand(3); 3838 3839 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3840 ? AMDGPU::S_ADD_I32 3841 : AMDGPU::S_SUB_I32; 3842 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3843 3844 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3845 .addImm(1) 3846 .addImm(0); 3847 3848 MI.eraseFromParent(); 3849 return BB; 3850 } 3851 case AMDGPU::S_ADD_U64_PSEUDO: 3852 case AMDGPU::S_SUB_U64_PSEUDO: { 3853 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3854 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3855 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3856 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3857 const DebugLoc &DL = MI.getDebugLoc(); 3858 3859 MachineOperand &Dest = MI.getOperand(0); 3860 MachineOperand &Src0 = MI.getOperand(1); 3861 MachineOperand &Src1 = MI.getOperand(2); 3862 3863 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3864 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3865 3866 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3867 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3868 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3869 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3870 3871 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3872 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3873 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3874 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3875 3876 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3877 3878 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3879 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3880 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3881 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3882 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3883 .addReg(DestSub0) 3884 .addImm(AMDGPU::sub0) 3885 .addReg(DestSub1) 3886 .addImm(AMDGPU::sub1); 3887 MI.eraseFromParent(); 3888 return BB; 3889 } 3890 case AMDGPU::V_ADD_U64_PSEUDO: 3891 case AMDGPU::V_SUB_U64_PSEUDO: { 3892 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3893 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3894 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3895 const DebugLoc &DL = MI.getDebugLoc(); 3896 3897 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3898 3899 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3900 3901 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3902 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3903 3904 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3905 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3906 3907 MachineOperand &Dest = MI.getOperand(0); 3908 MachineOperand &Src0 = MI.getOperand(1); 3909 MachineOperand &Src1 = MI.getOperand(2); 3910 3911 const TargetRegisterClass *Src0RC = Src0.isReg() 3912 ? MRI.getRegClass(Src0.getReg()) 3913 : &AMDGPU::VReg_64RegClass; 3914 const TargetRegisterClass *Src1RC = Src1.isReg() 3915 ? MRI.getRegClass(Src1.getReg()) 3916 : &AMDGPU::VReg_64RegClass; 3917 3918 const TargetRegisterClass *Src0SubRC = 3919 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3920 const TargetRegisterClass *Src1SubRC = 3921 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3922 3923 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3924 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3925 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3926 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3927 3928 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3929 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3930 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3931 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3932 3933 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3934 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3935 .addReg(CarryReg, RegState::Define) 3936 .add(SrcReg0Sub0) 3937 .add(SrcReg1Sub0) 3938 .addImm(0); // clamp bit 3939 3940 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3941 MachineInstr *HiHalf = 3942 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3943 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3944 .add(SrcReg0Sub1) 3945 .add(SrcReg1Sub1) 3946 .addReg(CarryReg, RegState::Kill) 3947 .addImm(0); // clamp bit 3948 3949 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3950 .addReg(DestSub0) 3951 .addImm(AMDGPU::sub0) 3952 .addReg(DestSub1) 3953 .addImm(AMDGPU::sub1); 3954 TII->legalizeOperands(*LoHalf); 3955 TII->legalizeOperands(*HiHalf); 3956 MI.eraseFromParent(); 3957 return BB; 3958 } 3959 case AMDGPU::S_ADD_CO_PSEUDO: 3960 case AMDGPU::S_SUB_CO_PSEUDO: { 3961 // This pseudo has a chance to be selected 3962 // only from uniform add/subcarry node. All the VGPR operands 3963 // therefore assumed to be splat vectors. 3964 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3965 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3966 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3967 MachineBasicBlock::iterator MII = MI; 3968 const DebugLoc &DL = MI.getDebugLoc(); 3969 MachineOperand &Dest = MI.getOperand(0); 3970 MachineOperand &CarryDest = MI.getOperand(1); 3971 MachineOperand &Src0 = MI.getOperand(2); 3972 MachineOperand &Src1 = MI.getOperand(3); 3973 MachineOperand &Src2 = MI.getOperand(4); 3974 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3975 ? AMDGPU::S_ADDC_U32 3976 : AMDGPU::S_SUBB_U32; 3977 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3978 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3979 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3980 .addReg(Src0.getReg()); 3981 Src0.setReg(RegOp0); 3982 } 3983 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3984 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3985 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3986 .addReg(Src1.getReg()); 3987 Src1.setReg(RegOp1); 3988 } 3989 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3990 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3991 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3992 .addReg(Src2.getReg()); 3993 Src2.setReg(RegOp2); 3994 } 3995 3996 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3997 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3998 .addReg(Src2.getReg()) 3999 .addImm(0); 4000 } else { 4001 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4002 .addReg(Src2.getReg()) 4003 .addImm(0); 4004 } 4005 4006 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4007 4008 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4009 .addReg(AMDGPU::SCC); 4010 MI.eraseFromParent(); 4011 return BB; 4012 } 4013 case AMDGPU::SI_INIT_M0: { 4014 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4015 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4016 .add(MI.getOperand(0)); 4017 MI.eraseFromParent(); 4018 return BB; 4019 } 4020 case AMDGPU::SI_INIT_EXEC: 4021 // This should be before all vector instructions. 4022 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4023 AMDGPU::EXEC) 4024 .addImm(MI.getOperand(0).getImm()); 4025 MI.eraseFromParent(); 4026 return BB; 4027 4028 case AMDGPU::SI_INIT_EXEC_LO: 4029 // This should be before all vector instructions. 4030 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4031 AMDGPU::EXEC_LO) 4032 .addImm(MI.getOperand(0).getImm()); 4033 MI.eraseFromParent(); 4034 return BB; 4035 4036 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4037 // Extract the thread count from an SGPR input and set EXEC accordingly. 4038 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4039 // 4040 // S_BFE_U32 count, input, {shift, 7} 4041 // S_BFM_B64 exec, count, 0 4042 // S_CMP_EQ_U32 count, 64 4043 // S_CMOV_B64 exec, -1 4044 MachineInstr *FirstMI = &*BB->begin(); 4045 MachineRegisterInfo &MRI = MF->getRegInfo(); 4046 Register InputReg = MI.getOperand(0).getReg(); 4047 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4048 bool Found = false; 4049 4050 // Move the COPY of the input reg to the beginning, so that we can use it. 4051 for (auto I = BB->begin(); I != &MI; I++) { 4052 if (I->getOpcode() != TargetOpcode::COPY || 4053 I->getOperand(0).getReg() != InputReg) 4054 continue; 4055 4056 if (I == FirstMI) { 4057 FirstMI = &*++BB->begin(); 4058 } else { 4059 I->removeFromParent(); 4060 BB->insert(FirstMI, &*I); 4061 } 4062 Found = true; 4063 break; 4064 } 4065 assert(Found); 4066 (void)Found; 4067 4068 // This should be before all vector instructions. 4069 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4070 bool isWave32 = getSubtarget()->isWave32(); 4071 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4072 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4073 .addReg(InputReg) 4074 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4075 BuildMI(*BB, FirstMI, DebugLoc(), 4076 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4077 Exec) 4078 .addReg(CountReg) 4079 .addImm(0); 4080 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4081 .addReg(CountReg, RegState::Kill) 4082 .addImm(getSubtarget()->getWavefrontSize()); 4083 BuildMI(*BB, FirstMI, DebugLoc(), 4084 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4085 Exec) 4086 .addImm(-1); 4087 MI.eraseFromParent(); 4088 return BB; 4089 } 4090 4091 case AMDGPU::GET_GROUPSTATICSIZE: { 4092 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4093 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4094 DebugLoc DL = MI.getDebugLoc(); 4095 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4096 .add(MI.getOperand(0)) 4097 .addImm(MFI->getLDSSize()); 4098 MI.eraseFromParent(); 4099 return BB; 4100 } 4101 case AMDGPU::SI_INDIRECT_SRC_V1: 4102 case AMDGPU::SI_INDIRECT_SRC_V2: 4103 case AMDGPU::SI_INDIRECT_SRC_V4: 4104 case AMDGPU::SI_INDIRECT_SRC_V8: 4105 case AMDGPU::SI_INDIRECT_SRC_V16: 4106 case AMDGPU::SI_INDIRECT_SRC_V32: 4107 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4108 case AMDGPU::SI_INDIRECT_DST_V1: 4109 case AMDGPU::SI_INDIRECT_DST_V2: 4110 case AMDGPU::SI_INDIRECT_DST_V4: 4111 case AMDGPU::SI_INDIRECT_DST_V8: 4112 case AMDGPU::SI_INDIRECT_DST_V16: 4113 case AMDGPU::SI_INDIRECT_DST_V32: 4114 return emitIndirectDst(MI, *BB, *getSubtarget()); 4115 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4116 case AMDGPU::SI_KILL_I1_PSEUDO: 4117 return splitKillBlock(MI, BB); 4118 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4119 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4120 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4121 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4122 4123 Register Dst = MI.getOperand(0).getReg(); 4124 Register Src0 = MI.getOperand(1).getReg(); 4125 Register Src1 = MI.getOperand(2).getReg(); 4126 const DebugLoc &DL = MI.getDebugLoc(); 4127 Register SrcCond = MI.getOperand(3).getReg(); 4128 4129 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4130 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4131 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4132 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4133 4134 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4135 .addReg(SrcCond); 4136 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4137 .addImm(0) 4138 .addReg(Src0, 0, AMDGPU::sub0) 4139 .addImm(0) 4140 .addReg(Src1, 0, AMDGPU::sub0) 4141 .addReg(SrcCondCopy); 4142 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4143 .addImm(0) 4144 .addReg(Src0, 0, AMDGPU::sub1) 4145 .addImm(0) 4146 .addReg(Src1, 0, AMDGPU::sub1) 4147 .addReg(SrcCondCopy); 4148 4149 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4150 .addReg(DstLo) 4151 .addImm(AMDGPU::sub0) 4152 .addReg(DstHi) 4153 .addImm(AMDGPU::sub1); 4154 MI.eraseFromParent(); 4155 return BB; 4156 } 4157 case AMDGPU::SI_BR_UNDEF: { 4158 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4159 const DebugLoc &DL = MI.getDebugLoc(); 4160 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4161 .add(MI.getOperand(0)); 4162 Br->getOperand(1).setIsUndef(true); // read undef SCC 4163 MI.eraseFromParent(); 4164 return BB; 4165 } 4166 case AMDGPU::ADJCALLSTACKUP: 4167 case AMDGPU::ADJCALLSTACKDOWN: { 4168 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4169 MachineInstrBuilder MIB(*MF, &MI); 4170 4171 // Add an implicit use of the frame offset reg to prevent the restore copy 4172 // inserted after the call from being reorderd after stack operations in the 4173 // the caller's frame. 4174 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4175 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4176 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4177 return BB; 4178 } 4179 case AMDGPU::SI_CALL_ISEL: { 4180 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4181 const DebugLoc &DL = MI.getDebugLoc(); 4182 4183 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4184 4185 MachineInstrBuilder MIB; 4186 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4187 4188 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4189 MIB.add(MI.getOperand(I)); 4190 4191 MIB.cloneMemRefs(MI); 4192 MI.eraseFromParent(); 4193 return BB; 4194 } 4195 case AMDGPU::V_ADD_CO_U32_e32: 4196 case AMDGPU::V_SUB_CO_U32_e32: 4197 case AMDGPU::V_SUBREV_CO_U32_e32: { 4198 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4199 const DebugLoc &DL = MI.getDebugLoc(); 4200 unsigned Opc = MI.getOpcode(); 4201 4202 bool NeedClampOperand = false; 4203 if (TII->pseudoToMCOpcode(Opc) == -1) { 4204 Opc = AMDGPU::getVOPe64(Opc); 4205 NeedClampOperand = true; 4206 } 4207 4208 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4209 if (TII->isVOP3(*I)) { 4210 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4211 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4212 I.addReg(TRI->getVCC(), RegState::Define); 4213 } 4214 I.add(MI.getOperand(1)) 4215 .add(MI.getOperand(2)); 4216 if (NeedClampOperand) 4217 I.addImm(0); // clamp bit for e64 encoding 4218 4219 TII->legalizeOperands(*I); 4220 4221 MI.eraseFromParent(); 4222 return BB; 4223 } 4224 case AMDGPU::DS_GWS_INIT: 4225 case AMDGPU::DS_GWS_SEMA_V: 4226 case AMDGPU::DS_GWS_SEMA_BR: 4227 case AMDGPU::DS_GWS_SEMA_P: 4228 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4229 case AMDGPU::DS_GWS_BARRIER: 4230 // A s_waitcnt 0 is required to be the instruction immediately following. 4231 if (getSubtarget()->hasGWSAutoReplay()) { 4232 bundleInstWithWaitcnt(MI); 4233 return BB; 4234 } 4235 4236 return emitGWSMemViolTestLoop(MI, BB); 4237 case AMDGPU::S_SETREG_B32: { 4238 if (!getSubtarget()->hasDenormModeInst()) 4239 return BB; 4240 4241 // Try to optimize cases that only set the denormal mode or rounding mode. 4242 // 4243 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4244 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4245 // instead. 4246 // 4247 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4248 // allow you to have a no side effect instruction in the output of a 4249 // sideeffecting pattern. 4250 4251 // TODO: Should also emit a no side effects pseudo if only FP bits are 4252 // touched, even if not all of them or to a variable. 4253 unsigned ID, Offset, Width; 4254 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4255 if (ID != AMDGPU::Hwreg::ID_MODE) 4256 return BB; 4257 4258 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4259 const unsigned SetMask = WidthMask << Offset; 4260 unsigned SetDenormOp = 0; 4261 unsigned SetRoundOp = 0; 4262 4263 // The dedicated instructions can only set the whole denorm or round mode at 4264 // once, not a subset of bits in either. 4265 if (SetMask == 4266 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4267 // If this fully sets both the round and denorm mode, emit the two 4268 // dedicated instructions for these. 4269 SetRoundOp = AMDGPU::S_ROUND_MODE; 4270 SetDenormOp = AMDGPU::S_DENORM_MODE; 4271 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4272 SetRoundOp = AMDGPU::S_ROUND_MODE; 4273 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4274 SetDenormOp = AMDGPU::S_DENORM_MODE; 4275 } 4276 4277 if (SetRoundOp || SetDenormOp) { 4278 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4279 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4280 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4281 unsigned ImmVal = Def->getOperand(1).getImm(); 4282 if (SetRoundOp) { 4283 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4284 .addImm(ImmVal & 0xf); 4285 4286 // If we also have the denorm mode, get just the denorm mode bits. 4287 ImmVal >>= 4; 4288 } 4289 4290 if (SetDenormOp) { 4291 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4292 .addImm(ImmVal & 0xf); 4293 } 4294 4295 MI.eraseFromParent(); 4296 } 4297 } 4298 4299 return BB; 4300 } 4301 default: 4302 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4303 } 4304 } 4305 4306 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4307 return isTypeLegal(VT.getScalarType()); 4308 } 4309 4310 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4311 // This currently forces unfolding various combinations of fsub into fma with 4312 // free fneg'd operands. As long as we have fast FMA (controlled by 4313 // isFMAFasterThanFMulAndFAdd), we should perform these. 4314 4315 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4316 // most of these combines appear to be cycle neutral but save on instruction 4317 // count / code size. 4318 return true; 4319 } 4320 4321 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4322 EVT VT) const { 4323 if (!VT.isVector()) { 4324 return MVT::i1; 4325 } 4326 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4327 } 4328 4329 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4330 // TODO: Should i16 be used always if legal? For now it would force VALU 4331 // shifts. 4332 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4333 } 4334 4335 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4336 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4337 ? Ty.changeElementSize(16) 4338 : Ty.changeElementSize(32); 4339 } 4340 4341 // Answering this is somewhat tricky and depends on the specific device which 4342 // have different rates for fma or all f64 operations. 4343 // 4344 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4345 // regardless of which device (although the number of cycles differs between 4346 // devices), so it is always profitable for f64. 4347 // 4348 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4349 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4350 // which we can always do even without fused FP ops since it returns the same 4351 // result as the separate operations and since it is always full 4352 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4353 // however does not support denormals, so we do report fma as faster if we have 4354 // a fast fma device and require denormals. 4355 // 4356 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4357 EVT VT) const { 4358 VT = VT.getScalarType(); 4359 4360 switch (VT.getSimpleVT().SimpleTy) { 4361 case MVT::f32: { 4362 // If mad is not available this depends only on if f32 fma is full rate. 4363 if (!Subtarget->hasMadMacF32Insts()) 4364 return Subtarget->hasFastFMAF32(); 4365 4366 // Otherwise f32 mad is always full rate and returns the same result as 4367 // the separate operations so should be preferred over fma. 4368 // However does not support denomals. 4369 if (hasFP32Denormals(MF)) 4370 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4371 4372 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4373 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4374 } 4375 case MVT::f64: 4376 return true; 4377 case MVT::f16: 4378 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4379 default: 4380 break; 4381 } 4382 4383 return false; 4384 } 4385 4386 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4387 const SDNode *N) const { 4388 // TODO: Check future ftz flag 4389 // v_mad_f32/v_mac_f32 do not support denormals. 4390 EVT VT = N->getValueType(0); 4391 if (VT == MVT::f32) 4392 return Subtarget->hasMadMacF32Insts() && 4393 !hasFP32Denormals(DAG.getMachineFunction()); 4394 if (VT == MVT::f16) { 4395 return Subtarget->hasMadF16() && 4396 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4397 } 4398 4399 return false; 4400 } 4401 4402 //===----------------------------------------------------------------------===// 4403 // Custom DAG Lowering Operations 4404 //===----------------------------------------------------------------------===// 4405 4406 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4407 // wider vector type is legal. 4408 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4409 SelectionDAG &DAG) const { 4410 unsigned Opc = Op.getOpcode(); 4411 EVT VT = Op.getValueType(); 4412 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4413 4414 SDValue Lo, Hi; 4415 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4416 4417 SDLoc SL(Op); 4418 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4419 Op->getFlags()); 4420 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4421 Op->getFlags()); 4422 4423 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4424 } 4425 4426 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4427 // wider vector type is legal. 4428 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4429 SelectionDAG &DAG) const { 4430 unsigned Opc = Op.getOpcode(); 4431 EVT VT = Op.getValueType(); 4432 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4433 4434 SDValue Lo0, Hi0; 4435 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4436 SDValue Lo1, Hi1; 4437 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4438 4439 SDLoc SL(Op); 4440 4441 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4442 Op->getFlags()); 4443 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4444 Op->getFlags()); 4445 4446 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4447 } 4448 4449 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4450 SelectionDAG &DAG) const { 4451 unsigned Opc = Op.getOpcode(); 4452 EVT VT = Op.getValueType(); 4453 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4454 4455 SDValue Lo0, Hi0; 4456 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4457 SDValue Lo1, Hi1; 4458 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4459 SDValue Lo2, Hi2; 4460 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4461 4462 SDLoc SL(Op); 4463 4464 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4465 Op->getFlags()); 4466 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4467 Op->getFlags()); 4468 4469 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4470 } 4471 4472 4473 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4474 switch (Op.getOpcode()) { 4475 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4476 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4477 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4478 case ISD::LOAD: { 4479 SDValue Result = LowerLOAD(Op, DAG); 4480 assert((!Result.getNode() || 4481 Result.getNode()->getNumValues() == 2) && 4482 "Load should return a value and a chain"); 4483 return Result; 4484 } 4485 4486 case ISD::FSIN: 4487 case ISD::FCOS: 4488 return LowerTrig(Op, DAG); 4489 case ISD::SELECT: return LowerSELECT(Op, DAG); 4490 case ISD::FDIV: return LowerFDIV(Op, DAG); 4491 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4492 case ISD::STORE: return LowerSTORE(Op, DAG); 4493 case ISD::GlobalAddress: { 4494 MachineFunction &MF = DAG.getMachineFunction(); 4495 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4496 return LowerGlobalAddress(MFI, Op, DAG); 4497 } 4498 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4499 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4500 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4501 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4502 case ISD::INSERT_SUBVECTOR: 4503 return lowerINSERT_SUBVECTOR(Op, DAG); 4504 case ISD::INSERT_VECTOR_ELT: 4505 return lowerINSERT_VECTOR_ELT(Op, DAG); 4506 case ISD::EXTRACT_VECTOR_ELT: 4507 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4508 case ISD::VECTOR_SHUFFLE: 4509 return lowerVECTOR_SHUFFLE(Op, DAG); 4510 case ISD::BUILD_VECTOR: 4511 return lowerBUILD_VECTOR(Op, DAG); 4512 case ISD::FP_ROUND: 4513 return lowerFP_ROUND(Op, DAG); 4514 case ISD::TRAP: 4515 return lowerTRAP(Op, DAG); 4516 case ISD::DEBUGTRAP: 4517 return lowerDEBUGTRAP(Op, DAG); 4518 case ISD::FABS: 4519 case ISD::FNEG: 4520 case ISD::FCANONICALIZE: 4521 case ISD::BSWAP: 4522 return splitUnaryVectorOp(Op, DAG); 4523 case ISD::FMINNUM: 4524 case ISD::FMAXNUM: 4525 return lowerFMINNUM_FMAXNUM(Op, DAG); 4526 case ISD::FMA: 4527 return splitTernaryVectorOp(Op, DAG); 4528 case ISD::SHL: 4529 case ISD::SRA: 4530 case ISD::SRL: 4531 case ISD::ADD: 4532 case ISD::SUB: 4533 case ISD::MUL: 4534 case ISD::SMIN: 4535 case ISD::SMAX: 4536 case ISD::UMIN: 4537 case ISD::UMAX: 4538 case ISD::FADD: 4539 case ISD::FMUL: 4540 case ISD::FMINNUM_IEEE: 4541 case ISD::FMAXNUM_IEEE: 4542 case ISD::UADDSAT: 4543 case ISD::USUBSAT: 4544 case ISD::SADDSAT: 4545 case ISD::SSUBSAT: 4546 return splitBinaryVectorOp(Op, DAG); 4547 case ISD::SMULO: 4548 case ISD::UMULO: 4549 return lowerXMULO(Op, DAG); 4550 case ISD::DYNAMIC_STACKALLOC: 4551 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4552 } 4553 return SDValue(); 4554 } 4555 4556 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4557 const SDLoc &DL, 4558 SelectionDAG &DAG, bool Unpacked) { 4559 if (!LoadVT.isVector()) 4560 return Result; 4561 4562 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4563 // Truncate to v2i16/v4i16. 4564 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4565 4566 // Workaround legalizer not scalarizing truncate after vector op 4567 // legalization but not creating intermediate vector trunc. 4568 SmallVector<SDValue, 4> Elts; 4569 DAG.ExtractVectorElements(Result, Elts); 4570 for (SDValue &Elt : Elts) 4571 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4572 4573 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4574 4575 // Bitcast to original type (v2f16/v4f16). 4576 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4577 } 4578 4579 // Cast back to the original packed type. 4580 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4581 } 4582 4583 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4584 MemSDNode *M, 4585 SelectionDAG &DAG, 4586 ArrayRef<SDValue> Ops, 4587 bool IsIntrinsic) const { 4588 SDLoc DL(M); 4589 4590 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4591 EVT LoadVT = M->getValueType(0); 4592 4593 EVT EquivLoadVT = LoadVT; 4594 if (Unpacked && LoadVT.isVector()) { 4595 EquivLoadVT = LoadVT.isVector() ? 4596 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4597 LoadVT.getVectorNumElements()) : LoadVT; 4598 } 4599 4600 // Change from v4f16/v2f16 to EquivLoadVT. 4601 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4602 4603 SDValue Load 4604 = DAG.getMemIntrinsicNode( 4605 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4606 VTList, Ops, M->getMemoryVT(), 4607 M->getMemOperand()); 4608 if (!Unpacked) // Just adjusted the opcode. 4609 return Load; 4610 4611 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4612 4613 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4614 } 4615 4616 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4617 SelectionDAG &DAG, 4618 ArrayRef<SDValue> Ops) const { 4619 SDLoc DL(M); 4620 EVT LoadVT = M->getValueType(0); 4621 EVT EltType = LoadVT.getScalarType(); 4622 EVT IntVT = LoadVT.changeTypeToInteger(); 4623 4624 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4625 4626 unsigned Opc = 4627 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4628 4629 if (IsD16) { 4630 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4631 } 4632 4633 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4634 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4635 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4636 4637 if (isTypeLegal(LoadVT)) { 4638 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4639 M->getMemOperand(), DAG); 4640 } 4641 4642 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4643 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4644 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4645 M->getMemOperand(), DAG); 4646 return DAG.getMergeValues( 4647 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4648 DL); 4649 } 4650 4651 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4652 SDNode *N, SelectionDAG &DAG) { 4653 EVT VT = N->getValueType(0); 4654 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4655 unsigned CondCode = CD->getZExtValue(); 4656 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4657 return DAG.getUNDEF(VT); 4658 4659 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4660 4661 SDValue LHS = N->getOperand(1); 4662 SDValue RHS = N->getOperand(2); 4663 4664 SDLoc DL(N); 4665 4666 EVT CmpVT = LHS.getValueType(); 4667 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4668 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4669 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4670 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4671 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4672 } 4673 4674 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4675 4676 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4677 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4678 4679 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4680 DAG.getCondCode(CCOpcode)); 4681 if (VT.bitsEq(CCVT)) 4682 return SetCC; 4683 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4684 } 4685 4686 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4687 SDNode *N, SelectionDAG &DAG) { 4688 EVT VT = N->getValueType(0); 4689 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4690 4691 unsigned CondCode = CD->getZExtValue(); 4692 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4693 return DAG.getUNDEF(VT); 4694 4695 SDValue Src0 = N->getOperand(1); 4696 SDValue Src1 = N->getOperand(2); 4697 EVT CmpVT = Src0.getValueType(); 4698 SDLoc SL(N); 4699 4700 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4701 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4702 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4703 } 4704 4705 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4706 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4707 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4708 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4709 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4710 Src1, DAG.getCondCode(CCOpcode)); 4711 if (VT.bitsEq(CCVT)) 4712 return SetCC; 4713 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4714 } 4715 4716 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4717 SelectionDAG &DAG) { 4718 EVT VT = N->getValueType(0); 4719 SDValue Src = N->getOperand(1); 4720 SDLoc SL(N); 4721 4722 if (Src.getOpcode() == ISD::SETCC) { 4723 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4724 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4725 Src.getOperand(1), Src.getOperand(2)); 4726 } 4727 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4728 // (ballot 0) -> 0 4729 if (Arg->isNullValue()) 4730 return DAG.getConstant(0, SL, VT); 4731 4732 // (ballot 1) -> EXEC/EXEC_LO 4733 if (Arg->isOne()) { 4734 Register Exec; 4735 if (VT.getScalarSizeInBits() == 32) 4736 Exec = AMDGPU::EXEC_LO; 4737 else if (VT.getScalarSizeInBits() == 64) 4738 Exec = AMDGPU::EXEC; 4739 else 4740 return SDValue(); 4741 4742 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4743 } 4744 } 4745 4746 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4747 // ISD::SETNE) 4748 return DAG.getNode( 4749 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4750 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4751 } 4752 4753 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4754 SmallVectorImpl<SDValue> &Results, 4755 SelectionDAG &DAG) const { 4756 switch (N->getOpcode()) { 4757 case ISD::INSERT_VECTOR_ELT: { 4758 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4759 Results.push_back(Res); 4760 return; 4761 } 4762 case ISD::EXTRACT_VECTOR_ELT: { 4763 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4764 Results.push_back(Res); 4765 return; 4766 } 4767 case ISD::INTRINSIC_WO_CHAIN: { 4768 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4769 switch (IID) { 4770 case Intrinsic::amdgcn_cvt_pkrtz: { 4771 SDValue Src0 = N->getOperand(1); 4772 SDValue Src1 = N->getOperand(2); 4773 SDLoc SL(N); 4774 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4775 Src0, Src1); 4776 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4777 return; 4778 } 4779 case Intrinsic::amdgcn_cvt_pknorm_i16: 4780 case Intrinsic::amdgcn_cvt_pknorm_u16: 4781 case Intrinsic::amdgcn_cvt_pk_i16: 4782 case Intrinsic::amdgcn_cvt_pk_u16: { 4783 SDValue Src0 = N->getOperand(1); 4784 SDValue Src1 = N->getOperand(2); 4785 SDLoc SL(N); 4786 unsigned Opcode; 4787 4788 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4789 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4790 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4791 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4792 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4793 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4794 else 4795 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4796 4797 EVT VT = N->getValueType(0); 4798 if (isTypeLegal(VT)) 4799 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4800 else { 4801 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4802 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4803 } 4804 return; 4805 } 4806 } 4807 break; 4808 } 4809 case ISD::INTRINSIC_W_CHAIN: { 4810 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4811 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4812 // FIXME: Hacky 4813 Results.push_back(Res.getOperand(0)); 4814 Results.push_back(Res.getOperand(1)); 4815 } else { 4816 Results.push_back(Res); 4817 Results.push_back(Res.getValue(1)); 4818 } 4819 return; 4820 } 4821 4822 break; 4823 } 4824 case ISD::SELECT: { 4825 SDLoc SL(N); 4826 EVT VT = N->getValueType(0); 4827 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4828 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4829 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4830 4831 EVT SelectVT = NewVT; 4832 if (NewVT.bitsLT(MVT::i32)) { 4833 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4834 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4835 SelectVT = MVT::i32; 4836 } 4837 4838 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4839 N->getOperand(0), LHS, RHS); 4840 4841 if (NewVT != SelectVT) 4842 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4843 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4844 return; 4845 } 4846 case ISD::FNEG: { 4847 if (N->getValueType(0) != MVT::v2f16) 4848 break; 4849 4850 SDLoc SL(N); 4851 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4852 4853 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4854 BC, 4855 DAG.getConstant(0x80008000, SL, MVT::i32)); 4856 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4857 return; 4858 } 4859 case ISD::FABS: { 4860 if (N->getValueType(0) != MVT::v2f16) 4861 break; 4862 4863 SDLoc SL(N); 4864 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4865 4866 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4867 BC, 4868 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4869 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4870 return; 4871 } 4872 default: 4873 break; 4874 } 4875 } 4876 4877 /// Helper function for LowerBRCOND 4878 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4879 4880 SDNode *Parent = Value.getNode(); 4881 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4882 I != E; ++I) { 4883 4884 if (I.getUse().get() != Value) 4885 continue; 4886 4887 if (I->getOpcode() == Opcode) 4888 return *I; 4889 } 4890 return nullptr; 4891 } 4892 4893 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4894 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4895 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4896 case Intrinsic::amdgcn_if: 4897 return AMDGPUISD::IF; 4898 case Intrinsic::amdgcn_else: 4899 return AMDGPUISD::ELSE; 4900 case Intrinsic::amdgcn_loop: 4901 return AMDGPUISD::LOOP; 4902 case Intrinsic::amdgcn_end_cf: 4903 llvm_unreachable("should not occur"); 4904 default: 4905 return 0; 4906 } 4907 } 4908 4909 // break, if_break, else_break are all only used as inputs to loop, not 4910 // directly as branch conditions. 4911 return 0; 4912 } 4913 4914 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4915 const Triple &TT = getTargetMachine().getTargetTriple(); 4916 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4917 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4918 AMDGPU::shouldEmitConstantsToTextSection(TT); 4919 } 4920 4921 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4922 // FIXME: Either avoid relying on address space here or change the default 4923 // address space for functions to avoid the explicit check. 4924 return (GV->getValueType()->isFunctionTy() || 4925 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4926 !shouldEmitFixup(GV) && 4927 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4928 } 4929 4930 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4931 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4932 } 4933 4934 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4935 if (!GV->hasExternalLinkage()) 4936 return true; 4937 4938 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4939 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4940 } 4941 4942 /// This transforms the control flow intrinsics to get the branch destination as 4943 /// last parameter, also switches branch target with BR if the need arise 4944 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4945 SelectionDAG &DAG) const { 4946 SDLoc DL(BRCOND); 4947 4948 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4949 SDValue Target = BRCOND.getOperand(2); 4950 SDNode *BR = nullptr; 4951 SDNode *SetCC = nullptr; 4952 4953 if (Intr->getOpcode() == ISD::SETCC) { 4954 // As long as we negate the condition everything is fine 4955 SetCC = Intr; 4956 Intr = SetCC->getOperand(0).getNode(); 4957 4958 } else { 4959 // Get the target from BR if we don't negate the condition 4960 BR = findUser(BRCOND, ISD::BR); 4961 assert(BR && "brcond missing unconditional branch user"); 4962 Target = BR->getOperand(1); 4963 } 4964 4965 unsigned CFNode = isCFIntrinsic(Intr); 4966 if (CFNode == 0) { 4967 // This is a uniform branch so we don't need to legalize. 4968 return BRCOND; 4969 } 4970 4971 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4972 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4973 4974 assert(!SetCC || 4975 (SetCC->getConstantOperandVal(1) == 1 && 4976 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4977 ISD::SETNE)); 4978 4979 // operands of the new intrinsic call 4980 SmallVector<SDValue, 4> Ops; 4981 if (HaveChain) 4982 Ops.push_back(BRCOND.getOperand(0)); 4983 4984 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4985 Ops.push_back(Target); 4986 4987 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4988 4989 // build the new intrinsic call 4990 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4991 4992 if (!HaveChain) { 4993 SDValue Ops[] = { 4994 SDValue(Result, 0), 4995 BRCOND.getOperand(0) 4996 }; 4997 4998 Result = DAG.getMergeValues(Ops, DL).getNode(); 4999 } 5000 5001 if (BR) { 5002 // Give the branch instruction our target 5003 SDValue Ops[] = { 5004 BR->getOperand(0), 5005 BRCOND.getOperand(2) 5006 }; 5007 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5008 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5009 } 5010 5011 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5012 5013 // Copy the intrinsic results to registers 5014 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5015 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5016 if (!CopyToReg) 5017 continue; 5018 5019 Chain = DAG.getCopyToReg( 5020 Chain, DL, 5021 CopyToReg->getOperand(1), 5022 SDValue(Result, i - 1), 5023 SDValue()); 5024 5025 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5026 } 5027 5028 // Remove the old intrinsic from the chain 5029 DAG.ReplaceAllUsesOfValueWith( 5030 SDValue(Intr, Intr->getNumValues() - 1), 5031 Intr->getOperand(0)); 5032 5033 return Chain; 5034 } 5035 5036 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5037 SelectionDAG &DAG) const { 5038 MVT VT = Op.getSimpleValueType(); 5039 SDLoc DL(Op); 5040 // Checking the depth 5041 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5042 return DAG.getConstant(0, DL, VT); 5043 5044 MachineFunction &MF = DAG.getMachineFunction(); 5045 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5046 // Check for kernel and shader functions 5047 if (Info->isEntryFunction()) 5048 return DAG.getConstant(0, DL, VT); 5049 5050 MachineFrameInfo &MFI = MF.getFrameInfo(); 5051 // There is a call to @llvm.returnaddress in this function 5052 MFI.setReturnAddressIsTaken(true); 5053 5054 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5055 // Get the return address reg and mark it as an implicit live-in 5056 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5057 5058 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5059 } 5060 5061 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5062 SDValue Op, 5063 const SDLoc &DL, 5064 EVT VT) const { 5065 return Op.getValueType().bitsLE(VT) ? 5066 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5067 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5068 DAG.getTargetConstant(0, DL, MVT::i32)); 5069 } 5070 5071 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5072 assert(Op.getValueType() == MVT::f16 && 5073 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5074 5075 SDValue Src = Op.getOperand(0); 5076 EVT SrcVT = Src.getValueType(); 5077 if (SrcVT != MVT::f64) 5078 return Op; 5079 5080 SDLoc DL(Op); 5081 5082 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5083 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5084 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5085 } 5086 5087 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5088 SelectionDAG &DAG) const { 5089 EVT VT = Op.getValueType(); 5090 const MachineFunction &MF = DAG.getMachineFunction(); 5091 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5092 bool IsIEEEMode = Info->getMode().IEEE; 5093 5094 // FIXME: Assert during selection that this is only selected for 5095 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5096 // mode functions, but this happens to be OK since it's only done in cases 5097 // where there is known no sNaN. 5098 if (IsIEEEMode) 5099 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5100 5101 if (VT == MVT::v4f16) 5102 return splitBinaryVectorOp(Op, DAG); 5103 return Op; 5104 } 5105 5106 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5107 EVT VT = Op.getValueType(); 5108 SDLoc SL(Op); 5109 SDValue LHS = Op.getOperand(0); 5110 SDValue RHS = Op.getOperand(1); 5111 bool isSigned = Op.getOpcode() == ISD::SMULO; 5112 5113 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5114 const APInt &C = RHSC->getAPIntValue(); 5115 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5116 if (C.isPowerOf2()) { 5117 // smulo(x, signed_min) is same as umulo(x, signed_min). 5118 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5119 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5120 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5121 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5122 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5123 SL, VT, Result, ShiftAmt), 5124 LHS, ISD::SETNE); 5125 return DAG.getMergeValues({ Result, Overflow }, SL); 5126 } 5127 } 5128 5129 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5130 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5131 SL, VT, LHS, RHS); 5132 5133 SDValue Sign = isSigned 5134 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5135 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5136 : DAG.getConstant(0, SL, VT); 5137 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5138 5139 return DAG.getMergeValues({ Result, Overflow }, SL); 5140 } 5141 5142 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5143 SDLoc SL(Op); 5144 SDValue Chain = Op.getOperand(0); 5145 5146 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5147 !Subtarget->isTrapHandlerEnabled()) 5148 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5149 5150 MachineFunction &MF = DAG.getMachineFunction(); 5151 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5152 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5153 assert(UserSGPR != AMDGPU::NoRegister); 5154 SDValue QueuePtr = CreateLiveInRegister( 5155 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5156 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5157 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5158 QueuePtr, SDValue()); 5159 SDValue Ops[] = { 5160 ToReg, 5161 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5162 SGPR01, 5163 ToReg.getValue(1) 5164 }; 5165 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5166 } 5167 5168 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5169 SDLoc SL(Op); 5170 SDValue Chain = Op.getOperand(0); 5171 MachineFunction &MF = DAG.getMachineFunction(); 5172 5173 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5174 !Subtarget->isTrapHandlerEnabled()) { 5175 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5176 "debugtrap handler not supported", 5177 Op.getDebugLoc(), 5178 DS_Warning); 5179 LLVMContext &Ctx = MF.getFunction().getContext(); 5180 Ctx.diagnose(NoTrap); 5181 return Chain; 5182 } 5183 5184 SDValue Ops[] = { 5185 Chain, 5186 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5187 }; 5188 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5189 } 5190 5191 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5192 SelectionDAG &DAG) const { 5193 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5194 if (Subtarget->hasApertureRegs()) { 5195 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5196 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5197 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5198 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5199 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5200 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5201 unsigned Encoding = 5202 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5203 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5204 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5205 5206 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5207 SDValue ApertureReg = SDValue( 5208 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5209 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5210 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5211 } 5212 5213 MachineFunction &MF = DAG.getMachineFunction(); 5214 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5215 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5216 assert(UserSGPR != AMDGPU::NoRegister); 5217 5218 SDValue QueuePtr = CreateLiveInRegister( 5219 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5220 5221 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5222 // private_segment_aperture_base_hi. 5223 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5224 5225 SDValue Ptr = 5226 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5227 5228 // TODO: Use custom target PseudoSourceValue. 5229 // TODO: We should use the value from the IR intrinsic call, but it might not 5230 // be available and how do we get it? 5231 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5232 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5233 commonAlignment(Align(64), StructOffset), 5234 MachineMemOperand::MODereferenceable | 5235 MachineMemOperand::MOInvariant); 5236 } 5237 5238 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5239 SelectionDAG &DAG) const { 5240 SDLoc SL(Op); 5241 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5242 5243 SDValue Src = ASC->getOperand(0); 5244 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5245 5246 const AMDGPUTargetMachine &TM = 5247 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5248 5249 // flat -> local/private 5250 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5251 unsigned DestAS = ASC->getDestAddressSpace(); 5252 5253 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5254 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5255 unsigned NullVal = TM.getNullPointerValue(DestAS); 5256 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5257 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5258 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5259 5260 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5261 NonNull, Ptr, SegmentNullPtr); 5262 } 5263 } 5264 5265 // local/private -> flat 5266 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5267 unsigned SrcAS = ASC->getSrcAddressSpace(); 5268 5269 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5270 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5271 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5272 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5273 5274 SDValue NonNull 5275 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5276 5277 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5278 SDValue CvtPtr 5279 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5280 5281 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5282 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5283 FlatNullPtr); 5284 } 5285 } 5286 5287 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5288 Src.getValueType() == MVT::i64) 5289 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5290 5291 // global <-> flat are no-ops and never emitted. 5292 5293 const MachineFunction &MF = DAG.getMachineFunction(); 5294 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5295 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5296 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5297 5298 return DAG.getUNDEF(ASC->getValueType(0)); 5299 } 5300 5301 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5302 // the small vector and inserting them into the big vector. That is better than 5303 // the default expansion of doing it via a stack slot. Even though the use of 5304 // the stack slot would be optimized away afterwards, the stack slot itself 5305 // remains. 5306 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5307 SelectionDAG &DAG) const { 5308 SDValue Vec = Op.getOperand(0); 5309 SDValue Ins = Op.getOperand(1); 5310 SDValue Idx = Op.getOperand(2); 5311 EVT VecVT = Vec.getValueType(); 5312 EVT InsVT = Ins.getValueType(); 5313 EVT EltVT = VecVT.getVectorElementType(); 5314 unsigned InsNumElts = InsVT.getVectorNumElements(); 5315 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5316 SDLoc SL(Op); 5317 5318 for (unsigned I = 0; I != InsNumElts; ++I) { 5319 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5320 DAG.getConstant(I, SL, MVT::i32)); 5321 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5322 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5323 } 5324 return Vec; 5325 } 5326 5327 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5328 SelectionDAG &DAG) const { 5329 SDValue Vec = Op.getOperand(0); 5330 SDValue InsVal = Op.getOperand(1); 5331 SDValue Idx = Op.getOperand(2); 5332 EVT VecVT = Vec.getValueType(); 5333 EVT EltVT = VecVT.getVectorElementType(); 5334 unsigned VecSize = VecVT.getSizeInBits(); 5335 unsigned EltSize = EltVT.getSizeInBits(); 5336 5337 5338 assert(VecSize <= 64); 5339 5340 unsigned NumElts = VecVT.getVectorNumElements(); 5341 SDLoc SL(Op); 5342 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5343 5344 if (NumElts == 4 && EltSize == 16 && KIdx) { 5345 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5346 5347 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5348 DAG.getConstant(0, SL, MVT::i32)); 5349 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5350 DAG.getConstant(1, SL, MVT::i32)); 5351 5352 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5353 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5354 5355 unsigned Idx = KIdx->getZExtValue(); 5356 bool InsertLo = Idx < 2; 5357 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5358 InsertLo ? LoVec : HiVec, 5359 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5360 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5361 5362 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5363 5364 SDValue Concat = InsertLo ? 5365 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5366 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5367 5368 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5369 } 5370 5371 if (isa<ConstantSDNode>(Idx)) 5372 return SDValue(); 5373 5374 MVT IntVT = MVT::getIntegerVT(VecSize); 5375 5376 // Avoid stack access for dynamic indexing. 5377 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5378 5379 // Create a congruent vector with the target value in each element so that 5380 // the required element can be masked and ORed into the target vector. 5381 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5382 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5383 5384 assert(isPowerOf2_32(EltSize)); 5385 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5386 5387 // Convert vector index to bit-index. 5388 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5389 5390 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5391 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5392 DAG.getConstant(0xffff, SL, IntVT), 5393 ScaledIdx); 5394 5395 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5396 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5397 DAG.getNOT(SL, BFM, IntVT), BCVec); 5398 5399 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5400 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5401 } 5402 5403 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5404 SelectionDAG &DAG) const { 5405 SDLoc SL(Op); 5406 5407 EVT ResultVT = Op.getValueType(); 5408 SDValue Vec = Op.getOperand(0); 5409 SDValue Idx = Op.getOperand(1); 5410 EVT VecVT = Vec.getValueType(); 5411 unsigned VecSize = VecVT.getSizeInBits(); 5412 EVT EltVT = VecVT.getVectorElementType(); 5413 assert(VecSize <= 64); 5414 5415 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5416 5417 // Make sure we do any optimizations that will make it easier to fold 5418 // source modifiers before obscuring it with bit operations. 5419 5420 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5421 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5422 return Combined; 5423 5424 unsigned EltSize = EltVT.getSizeInBits(); 5425 assert(isPowerOf2_32(EltSize)); 5426 5427 MVT IntVT = MVT::getIntegerVT(VecSize); 5428 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5429 5430 // Convert vector index to bit-index (* EltSize) 5431 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5432 5433 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5434 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5435 5436 if (ResultVT == MVT::f16) { 5437 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5438 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5439 } 5440 5441 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5442 } 5443 5444 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5445 assert(Elt % 2 == 0); 5446 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5447 } 5448 5449 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5450 SelectionDAG &DAG) const { 5451 SDLoc SL(Op); 5452 EVT ResultVT = Op.getValueType(); 5453 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5454 5455 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5456 EVT EltVT = PackVT.getVectorElementType(); 5457 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5458 5459 // vector_shuffle <0,1,6,7> lhs, rhs 5460 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5461 // 5462 // vector_shuffle <6,7,2,3> lhs, rhs 5463 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5464 // 5465 // vector_shuffle <6,7,0,1> lhs, rhs 5466 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5467 5468 // Avoid scalarizing when both halves are reading from consecutive elements. 5469 SmallVector<SDValue, 4> Pieces; 5470 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5471 if (elementPairIsContiguous(SVN->getMask(), I)) { 5472 const int Idx = SVN->getMaskElt(I); 5473 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5474 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5475 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5476 PackVT, SVN->getOperand(VecIdx), 5477 DAG.getConstant(EltIdx, SL, MVT::i32)); 5478 Pieces.push_back(SubVec); 5479 } else { 5480 const int Idx0 = SVN->getMaskElt(I); 5481 const int Idx1 = SVN->getMaskElt(I + 1); 5482 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5483 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5484 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5485 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5486 5487 SDValue Vec0 = SVN->getOperand(VecIdx0); 5488 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5489 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5490 5491 SDValue Vec1 = SVN->getOperand(VecIdx1); 5492 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5493 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5494 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5495 } 5496 } 5497 5498 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5499 } 5500 5501 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5502 SelectionDAG &DAG) const { 5503 SDLoc SL(Op); 5504 EVT VT = Op.getValueType(); 5505 5506 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5507 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5508 5509 // Turn into pair of packed build_vectors. 5510 // TODO: Special case for constants that can be materialized with s_mov_b64. 5511 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5512 { Op.getOperand(0), Op.getOperand(1) }); 5513 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5514 { Op.getOperand(2), Op.getOperand(3) }); 5515 5516 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5517 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5518 5519 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5520 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5521 } 5522 5523 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5524 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5525 5526 SDValue Lo = Op.getOperand(0); 5527 SDValue Hi = Op.getOperand(1); 5528 5529 // Avoid adding defined bits with the zero_extend. 5530 if (Hi.isUndef()) { 5531 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5532 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5533 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5534 } 5535 5536 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5537 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5538 5539 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5540 DAG.getConstant(16, SL, MVT::i32)); 5541 if (Lo.isUndef()) 5542 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5543 5544 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5545 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5546 5547 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5548 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5549 } 5550 5551 bool 5552 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5553 // We can fold offsets for anything that doesn't require a GOT relocation. 5554 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5555 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5556 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5557 !shouldEmitGOTReloc(GA->getGlobal()); 5558 } 5559 5560 static SDValue 5561 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5562 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5563 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5564 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5565 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5566 // lowered to the following code sequence: 5567 // 5568 // For constant address space: 5569 // s_getpc_b64 s[0:1] 5570 // s_add_u32 s0, s0, $symbol 5571 // s_addc_u32 s1, s1, 0 5572 // 5573 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5574 // a fixup or relocation is emitted to replace $symbol with a literal 5575 // constant, which is a pc-relative offset from the encoding of the $symbol 5576 // operand to the global variable. 5577 // 5578 // For global address space: 5579 // s_getpc_b64 s[0:1] 5580 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5581 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5582 // 5583 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5584 // fixups or relocations are emitted to replace $symbol@*@lo and 5585 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5586 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5587 // operand to the global variable. 5588 // 5589 // What we want here is an offset from the value returned by s_getpc 5590 // (which is the address of the s_add_u32 instruction) to the global 5591 // variable, but since the encoding of $symbol starts 4 bytes after the start 5592 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5593 // small. This requires us to add 4 to the global variable offset in order to 5594 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5595 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5596 // instruction. 5597 SDValue PtrLo = 5598 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5599 SDValue PtrHi; 5600 if (GAFlags == SIInstrInfo::MO_NONE) { 5601 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5602 } else { 5603 PtrHi = 5604 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5605 } 5606 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5607 } 5608 5609 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5610 SDValue Op, 5611 SelectionDAG &DAG) const { 5612 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5613 SDLoc DL(GSD); 5614 EVT PtrVT = Op.getValueType(); 5615 5616 const GlobalValue *GV = GSD->getGlobal(); 5617 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5618 shouldUseLDSConstAddress(GV)) || 5619 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5620 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5621 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5622 GV->hasExternalLinkage()) { 5623 Type *Ty = GV->getValueType(); 5624 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5625 // zero-sized type in other languages to declare the dynamic shared 5626 // memory which size is not known at the compile time. They will be 5627 // allocated by the runtime and placed directly after the static 5628 // allocated ones. They all share the same offset. 5629 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5630 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5631 // Adjust alignment for that dynamic shared memory array. 5632 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5633 return SDValue( 5634 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5635 } 5636 } 5637 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5638 } 5639 5640 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5641 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5642 SIInstrInfo::MO_ABS32_LO); 5643 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5644 } 5645 5646 if (shouldEmitFixup(GV)) 5647 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5648 else if (shouldEmitPCReloc(GV)) 5649 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5650 SIInstrInfo::MO_REL32); 5651 5652 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5653 SIInstrInfo::MO_GOTPCREL32); 5654 5655 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5656 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5657 const DataLayout &DataLayout = DAG.getDataLayout(); 5658 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5659 MachinePointerInfo PtrInfo 5660 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5661 5662 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5663 MachineMemOperand::MODereferenceable | 5664 MachineMemOperand::MOInvariant); 5665 } 5666 5667 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5668 const SDLoc &DL, SDValue V) const { 5669 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5670 // the destination register. 5671 // 5672 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5673 // so we will end up with redundant moves to m0. 5674 // 5675 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5676 5677 // A Null SDValue creates a glue result. 5678 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5679 V, Chain); 5680 return SDValue(M0, 0); 5681 } 5682 5683 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5684 SDValue Op, 5685 MVT VT, 5686 unsigned Offset) const { 5687 SDLoc SL(Op); 5688 SDValue Param = lowerKernargMemParameter( 5689 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5690 // The local size values will have the hi 16-bits as zero. 5691 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5692 DAG.getValueType(VT)); 5693 } 5694 5695 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5696 EVT VT) { 5697 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5698 "non-hsa intrinsic with hsa target", 5699 DL.getDebugLoc()); 5700 DAG.getContext()->diagnose(BadIntrin); 5701 return DAG.getUNDEF(VT); 5702 } 5703 5704 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5705 EVT VT) { 5706 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5707 "intrinsic not supported on subtarget", 5708 DL.getDebugLoc()); 5709 DAG.getContext()->diagnose(BadIntrin); 5710 return DAG.getUNDEF(VT); 5711 } 5712 5713 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5714 ArrayRef<SDValue> Elts) { 5715 assert(!Elts.empty()); 5716 MVT Type; 5717 unsigned NumElts; 5718 5719 if (Elts.size() == 1) { 5720 Type = MVT::f32; 5721 NumElts = 1; 5722 } else if (Elts.size() == 2) { 5723 Type = MVT::v2f32; 5724 NumElts = 2; 5725 } else if (Elts.size() == 3) { 5726 Type = MVT::v3f32; 5727 NumElts = 3; 5728 } else if (Elts.size() <= 4) { 5729 Type = MVT::v4f32; 5730 NumElts = 4; 5731 } else if (Elts.size() <= 8) { 5732 Type = MVT::v8f32; 5733 NumElts = 8; 5734 } else { 5735 assert(Elts.size() <= 16); 5736 Type = MVT::v16f32; 5737 NumElts = 16; 5738 } 5739 5740 SmallVector<SDValue, 16> VecElts(NumElts); 5741 for (unsigned i = 0; i < Elts.size(); ++i) { 5742 SDValue Elt = Elts[i]; 5743 if (Elt.getValueType() != MVT::f32) 5744 Elt = DAG.getBitcast(MVT::f32, Elt); 5745 VecElts[i] = Elt; 5746 } 5747 for (unsigned i = Elts.size(); i < NumElts; ++i) 5748 VecElts[i] = DAG.getUNDEF(MVT::f32); 5749 5750 if (NumElts == 1) 5751 return VecElts[0]; 5752 return DAG.getBuildVector(Type, DL, VecElts); 5753 } 5754 5755 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5756 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5757 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5758 5759 uint64_t Value = CachePolicyConst->getZExtValue(); 5760 SDLoc DL(CachePolicy); 5761 if (GLC) { 5762 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5763 Value &= ~(uint64_t)0x1; 5764 } 5765 if (SLC) { 5766 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5767 Value &= ~(uint64_t)0x2; 5768 } 5769 if (DLC) { 5770 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5771 Value &= ~(uint64_t)0x4; 5772 } 5773 5774 return Value == 0; 5775 } 5776 5777 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5778 SDValue Src, int ExtraElts) { 5779 EVT SrcVT = Src.getValueType(); 5780 5781 SmallVector<SDValue, 8> Elts; 5782 5783 if (SrcVT.isVector()) 5784 DAG.ExtractVectorElements(Src, Elts); 5785 else 5786 Elts.push_back(Src); 5787 5788 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5789 while (ExtraElts--) 5790 Elts.push_back(Undef); 5791 5792 return DAG.getBuildVector(CastVT, DL, Elts); 5793 } 5794 5795 // Re-construct the required return value for a image load intrinsic. 5796 // This is more complicated due to the optional use TexFailCtrl which means the required 5797 // return type is an aggregate 5798 static SDValue constructRetValue(SelectionDAG &DAG, 5799 MachineSDNode *Result, 5800 ArrayRef<EVT> ResultTypes, 5801 bool IsTexFail, bool Unpacked, bool IsD16, 5802 int DMaskPop, int NumVDataDwords, 5803 const SDLoc &DL, LLVMContext &Context) { 5804 // Determine the required return type. This is the same regardless of IsTexFail flag 5805 EVT ReqRetVT = ResultTypes[0]; 5806 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5807 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5808 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5809 5810 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5811 DMaskPop : (DMaskPop + 1) / 2; 5812 5813 MVT DataDwordVT = NumDataDwords == 1 ? 5814 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5815 5816 MVT MaskPopVT = MaskPopDwords == 1 ? 5817 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5818 5819 SDValue Data(Result, 0); 5820 SDValue TexFail; 5821 5822 if (IsTexFail) { 5823 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5824 if (MaskPopVT.isVector()) { 5825 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5826 SDValue(Result, 0), ZeroIdx); 5827 } else { 5828 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5829 SDValue(Result, 0), ZeroIdx); 5830 } 5831 5832 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5833 SDValue(Result, 0), 5834 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5835 } 5836 5837 if (DataDwordVT.isVector()) 5838 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5839 NumDataDwords - MaskPopDwords); 5840 5841 if (IsD16) 5842 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5843 5844 if (!ReqRetVT.isVector()) 5845 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5846 5847 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5848 5849 if (TexFail) 5850 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5851 5852 if (Result->getNumValues() == 1) 5853 return Data; 5854 5855 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5856 } 5857 5858 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5859 SDValue *LWE, bool &IsTexFail) { 5860 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5861 5862 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5863 if (Value) { 5864 IsTexFail = true; 5865 } 5866 5867 SDLoc DL(TexFailCtrlConst); 5868 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5869 Value &= ~(uint64_t)0x1; 5870 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5871 Value &= ~(uint64_t)0x2; 5872 5873 return Value == 0; 5874 } 5875 5876 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5877 MVT PackVectorVT, 5878 SmallVectorImpl<SDValue> &PackedAddrs, 5879 unsigned DimIdx, unsigned EndIdx, 5880 unsigned NumGradients) { 5881 SDLoc DL(Op); 5882 for (unsigned I = DimIdx; I < EndIdx; I++) { 5883 SDValue Addr = Op.getOperand(I); 5884 5885 // Gradients are packed with undef for each coordinate. 5886 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5887 // 1D: undef,dx/dh; undef,dx/dv 5888 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5889 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5890 if (((I + 1) >= EndIdx) || 5891 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5892 I == DimIdx + NumGradients - 1))) { 5893 if (Addr.getValueType() != MVT::i16) 5894 Addr = DAG.getBitcast(MVT::i16, Addr); 5895 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5896 } else { 5897 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5898 I++; 5899 } 5900 Addr = DAG.getBitcast(MVT::f32, Addr); 5901 PackedAddrs.push_back(Addr); 5902 } 5903 } 5904 5905 SDValue SITargetLowering::lowerImage(SDValue Op, 5906 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5907 SelectionDAG &DAG) const { 5908 SDLoc DL(Op); 5909 MachineFunction &MF = DAG.getMachineFunction(); 5910 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5911 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5912 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5913 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5914 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5915 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5916 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5917 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5918 unsigned IntrOpcode = Intr->BaseOpcode; 5919 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5920 5921 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5922 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5923 bool IsD16 = false; 5924 bool IsG16 = false; 5925 bool IsA16 = false; 5926 SDValue VData; 5927 int NumVDataDwords; 5928 bool AdjustRetType = false; 5929 5930 unsigned AddrIdx; // Index of first address argument 5931 unsigned DMask; 5932 unsigned DMaskLanes = 0; 5933 5934 if (BaseOpcode->Atomic) { 5935 VData = Op.getOperand(2); 5936 5937 bool Is64Bit = VData.getValueType() == MVT::i64; 5938 if (BaseOpcode->AtomicX2) { 5939 SDValue VData2 = Op.getOperand(3); 5940 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5941 {VData, VData2}); 5942 if (Is64Bit) 5943 VData = DAG.getBitcast(MVT::v4i32, VData); 5944 5945 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5946 DMask = Is64Bit ? 0xf : 0x3; 5947 NumVDataDwords = Is64Bit ? 4 : 2; 5948 AddrIdx = 4; 5949 } else { 5950 DMask = Is64Bit ? 0x3 : 0x1; 5951 NumVDataDwords = Is64Bit ? 2 : 1; 5952 AddrIdx = 3; 5953 } 5954 } else { 5955 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5956 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5957 DMask = DMaskConst->getZExtValue(); 5958 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5959 5960 if (BaseOpcode->Store) { 5961 VData = Op.getOperand(2); 5962 5963 MVT StoreVT = VData.getSimpleValueType(); 5964 if (StoreVT.getScalarType() == MVT::f16) { 5965 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5966 return Op; // D16 is unsupported for this instruction 5967 5968 IsD16 = true; 5969 VData = handleD16VData(VData, DAG); 5970 } 5971 5972 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5973 } else { 5974 // Work out the num dwords based on the dmask popcount and underlying type 5975 // and whether packing is supported. 5976 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5977 if (LoadVT.getScalarType() == MVT::f16) { 5978 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5979 return Op; // D16 is unsupported for this instruction 5980 5981 IsD16 = true; 5982 } 5983 5984 // Confirm that the return type is large enough for the dmask specified 5985 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5986 (!LoadVT.isVector() && DMaskLanes > 1)) 5987 return Op; 5988 5989 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5990 NumVDataDwords = (DMaskLanes + 1) / 2; 5991 else 5992 NumVDataDwords = DMaskLanes; 5993 5994 AdjustRetType = true; 5995 } 5996 5997 AddrIdx = DMaskIdx + 1; 5998 } 5999 6000 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 6001 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 6002 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 6003 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 6004 NumCoords + NumLCM; 6005 unsigned NumMIVAddrs = NumVAddrs; 6006 6007 SmallVector<SDValue, 4> VAddrs; 6008 6009 // Optimize _L to _LZ when _L is zero 6010 if (LZMappingInfo) { 6011 if (auto ConstantLod = 6012 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 6013 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6014 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6015 NumMIVAddrs--; // remove 'lod' 6016 } 6017 } 6018 } 6019 6020 // Optimize _mip away, when 'lod' is zero 6021 if (MIPMappingInfo) { 6022 if (auto ConstantLod = 6023 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 6024 if (ConstantLod->isNullValue()) { 6025 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6026 NumMIVAddrs--; // remove 'lod' 6027 } 6028 } 6029 } 6030 6031 // Push back extra arguments. 6032 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 6033 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 6034 6035 // Check for 16 bit addresses or derivatives and pack if true. 6036 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 6037 unsigned CoordIdx = DimIdx + NumGradients; 6038 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 6039 6040 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 6041 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6042 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6043 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6044 6045 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 6046 VAddrScalarVT = VAddrVT.getScalarType(); 6047 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6048 if (IsA16 || IsG16) { 6049 if (IsA16) { 6050 if (!ST->hasA16()) { 6051 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6052 "support 16 bit addresses\n"); 6053 return Op; 6054 } 6055 if (!IsG16) { 6056 LLVM_DEBUG( 6057 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6058 "need 16 bit derivatives but got 32 bit derivatives\n"); 6059 return Op; 6060 } 6061 } else if (!ST->hasG16()) { 6062 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6063 "support 16 bit derivatives\n"); 6064 return Op; 6065 } 6066 6067 if (BaseOpcode->Gradients && !IsA16) { 6068 if (!ST->hasG16()) { 6069 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6070 "support 16 bit derivatives\n"); 6071 return Op; 6072 } 6073 // Activate g16 6074 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6075 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6076 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6077 } 6078 6079 // Don't compress addresses for G16 6080 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 6081 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 6082 PackEndIdx, NumGradients); 6083 6084 if (!IsA16) { 6085 // Add uncompressed address 6086 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 6087 VAddrs.push_back(Op.getOperand(I)); 6088 } 6089 } else { 6090 for (unsigned I = DimIdx; I < CoordsEnd; I++) 6091 VAddrs.push_back(Op.getOperand(I)); 6092 } 6093 6094 // If the register allocator cannot place the address registers contiguously 6095 // without introducing moves, then using the non-sequential address encoding 6096 // is always preferable, since it saves VALU instructions and is usually a 6097 // wash in terms of code size or even better. 6098 // 6099 // However, we currently have no way of hinting to the register allocator that 6100 // MIMG addresses should be placed contiguously when it is possible to do so, 6101 // so force non-NSA for the common 2-address case as a heuristic. 6102 // 6103 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6104 // allocation when possible. 6105 bool UseNSA = 6106 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6107 SDValue VAddr; 6108 if (!UseNSA) 6109 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6110 6111 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6112 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6113 unsigned CtrlIdx; // Index of texfailctrl argument 6114 SDValue Unorm; 6115 if (!BaseOpcode->Sampler) { 6116 Unorm = True; 6117 CtrlIdx = AddrIdx + NumVAddrs + 1; 6118 } else { 6119 auto UnormConst = 6120 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6121 6122 Unorm = UnormConst->getZExtValue() ? True : False; 6123 CtrlIdx = AddrIdx + NumVAddrs + 3; 6124 } 6125 6126 SDValue TFE; 6127 SDValue LWE; 6128 SDValue TexFail = Op.getOperand(CtrlIdx); 6129 bool IsTexFail = false; 6130 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6131 return Op; 6132 6133 if (IsTexFail) { 6134 if (!DMaskLanes) { 6135 // Expecting to get an error flag since TFC is on - and dmask is 0 6136 // Force dmask to be at least 1 otherwise the instruction will fail 6137 DMask = 0x1; 6138 DMaskLanes = 1; 6139 NumVDataDwords = 1; 6140 } 6141 NumVDataDwords += 1; 6142 AdjustRetType = true; 6143 } 6144 6145 // Has something earlier tagged that the return type needs adjusting 6146 // This happens if the instruction is a load or has set TexFailCtrl flags 6147 if (AdjustRetType) { 6148 // NumVDataDwords reflects the true number of dwords required in the return type 6149 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6150 // This is a no-op load. This can be eliminated 6151 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6152 if (isa<MemSDNode>(Op)) 6153 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6154 return Undef; 6155 } 6156 6157 EVT NewVT = NumVDataDwords > 1 ? 6158 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6159 : MVT::i32; 6160 6161 ResultTypes[0] = NewVT; 6162 if (ResultTypes.size() == 3) { 6163 // Original result was aggregate type used for TexFailCtrl results 6164 // The actual instruction returns as a vector type which has now been 6165 // created. Remove the aggregate result. 6166 ResultTypes.erase(&ResultTypes[1]); 6167 } 6168 } 6169 6170 SDValue GLC; 6171 SDValue SLC; 6172 SDValue DLC; 6173 if (BaseOpcode->Atomic) { 6174 GLC = True; // TODO no-return optimization 6175 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6176 IsGFX10 ? &DLC : nullptr)) 6177 return Op; 6178 } else { 6179 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6180 IsGFX10 ? &DLC : nullptr)) 6181 return Op; 6182 } 6183 6184 SmallVector<SDValue, 26> Ops; 6185 if (BaseOpcode->Store || BaseOpcode->Atomic) 6186 Ops.push_back(VData); // vdata 6187 if (UseNSA) { 6188 for (const SDValue &Addr : VAddrs) 6189 Ops.push_back(Addr); 6190 } else { 6191 Ops.push_back(VAddr); 6192 } 6193 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6194 if (BaseOpcode->Sampler) 6195 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6196 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6197 if (IsGFX10) 6198 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6199 Ops.push_back(Unorm); 6200 if (IsGFX10) 6201 Ops.push_back(DLC); 6202 Ops.push_back(GLC); 6203 Ops.push_back(SLC); 6204 Ops.push_back(IsA16 && // r128, a16 for gfx9 6205 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6206 if (IsGFX10) 6207 Ops.push_back(IsA16 ? True : False); 6208 Ops.push_back(TFE); 6209 Ops.push_back(LWE); 6210 if (!IsGFX10) 6211 Ops.push_back(DimInfo->DA ? True : False); 6212 if (BaseOpcode->HasD16) 6213 Ops.push_back(IsD16 ? True : False); 6214 if (isa<MemSDNode>(Op)) 6215 Ops.push_back(Op.getOperand(0)); // chain 6216 6217 int NumVAddrDwords = 6218 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6219 int Opcode = -1; 6220 6221 if (IsGFX10) { 6222 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6223 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6224 : AMDGPU::MIMGEncGfx10Default, 6225 NumVDataDwords, NumVAddrDwords); 6226 } else { 6227 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6228 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6229 NumVDataDwords, NumVAddrDwords); 6230 if (Opcode == -1) 6231 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6232 NumVDataDwords, NumVAddrDwords); 6233 } 6234 assert(Opcode != -1); 6235 6236 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6237 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6238 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6239 DAG.setNodeMemRefs(NewNode, {MemRef}); 6240 } 6241 6242 if (BaseOpcode->AtomicX2) { 6243 SmallVector<SDValue, 1> Elt; 6244 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6245 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6246 } else if (!BaseOpcode->Store) { 6247 return constructRetValue(DAG, NewNode, 6248 OrigResultTypes, IsTexFail, 6249 Subtarget->hasUnpackedD16VMem(), IsD16, 6250 DMaskLanes, NumVDataDwords, DL, 6251 *DAG.getContext()); 6252 } 6253 6254 return SDValue(NewNode, 0); 6255 } 6256 6257 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6258 SDValue Offset, SDValue CachePolicy, 6259 SelectionDAG &DAG) const { 6260 MachineFunction &MF = DAG.getMachineFunction(); 6261 6262 const DataLayout &DataLayout = DAG.getDataLayout(); 6263 Align Alignment = 6264 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6265 6266 MachineMemOperand *MMO = MF.getMachineMemOperand( 6267 MachinePointerInfo(), 6268 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6269 MachineMemOperand::MOInvariant, 6270 VT.getStoreSize(), Alignment); 6271 6272 if (!Offset->isDivergent()) { 6273 SDValue Ops[] = { 6274 Rsrc, 6275 Offset, // Offset 6276 CachePolicy 6277 }; 6278 6279 // Widen vec3 load to vec4. 6280 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6281 EVT WidenedVT = 6282 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6283 auto WidenedOp = DAG.getMemIntrinsicNode( 6284 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6285 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6286 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6287 DAG.getVectorIdxConstant(0, DL)); 6288 return Subvector; 6289 } 6290 6291 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6292 DAG.getVTList(VT), Ops, VT, MMO); 6293 } 6294 6295 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6296 // assume that the buffer is unswizzled. 6297 SmallVector<SDValue, 4> Loads; 6298 unsigned NumLoads = 1; 6299 MVT LoadVT = VT.getSimpleVT(); 6300 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6301 assert((LoadVT.getScalarType() == MVT::i32 || 6302 LoadVT.getScalarType() == MVT::f32)); 6303 6304 if (NumElts == 8 || NumElts == 16) { 6305 NumLoads = NumElts / 4; 6306 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6307 } 6308 6309 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6310 SDValue Ops[] = { 6311 DAG.getEntryNode(), // Chain 6312 Rsrc, // rsrc 6313 DAG.getConstant(0, DL, MVT::i32), // vindex 6314 {}, // voffset 6315 {}, // soffset 6316 {}, // offset 6317 CachePolicy, // cachepolicy 6318 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6319 }; 6320 6321 // Use the alignment to ensure that the required offsets will fit into the 6322 // immediate offsets. 6323 setBufferOffsets(Offset, DAG, &Ops[3], 6324 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6325 6326 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6327 for (unsigned i = 0; i < NumLoads; ++i) { 6328 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6329 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6330 LoadVT, MMO, DAG)); 6331 } 6332 6333 if (NumElts == 8 || NumElts == 16) 6334 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6335 6336 return Loads[0]; 6337 } 6338 6339 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6340 SelectionDAG &DAG) const { 6341 MachineFunction &MF = DAG.getMachineFunction(); 6342 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6343 6344 EVT VT = Op.getValueType(); 6345 SDLoc DL(Op); 6346 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6347 6348 // TODO: Should this propagate fast-math-flags? 6349 6350 switch (IntrinsicID) { 6351 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6352 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6353 return emitNonHSAIntrinsicError(DAG, DL, VT); 6354 return getPreloadedValue(DAG, *MFI, VT, 6355 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6356 } 6357 case Intrinsic::amdgcn_dispatch_ptr: 6358 case Intrinsic::amdgcn_queue_ptr: { 6359 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6360 DiagnosticInfoUnsupported BadIntrin( 6361 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6362 DL.getDebugLoc()); 6363 DAG.getContext()->diagnose(BadIntrin); 6364 return DAG.getUNDEF(VT); 6365 } 6366 6367 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6368 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6369 return getPreloadedValue(DAG, *MFI, VT, RegID); 6370 } 6371 case Intrinsic::amdgcn_implicitarg_ptr: { 6372 if (MFI->isEntryFunction()) 6373 return getImplicitArgPtr(DAG, DL); 6374 return getPreloadedValue(DAG, *MFI, VT, 6375 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6376 } 6377 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6378 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6379 // This only makes sense to call in a kernel, so just lower to null. 6380 return DAG.getConstant(0, DL, VT); 6381 } 6382 6383 return getPreloadedValue(DAG, *MFI, VT, 6384 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6385 } 6386 case Intrinsic::amdgcn_dispatch_id: { 6387 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6388 } 6389 case Intrinsic::amdgcn_rcp: 6390 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6391 case Intrinsic::amdgcn_rsq: 6392 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6393 case Intrinsic::amdgcn_rsq_legacy: 6394 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6395 return emitRemovedIntrinsicError(DAG, DL, VT); 6396 return SDValue(); 6397 case Intrinsic::amdgcn_rcp_legacy: 6398 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6399 return emitRemovedIntrinsicError(DAG, DL, VT); 6400 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6401 case Intrinsic::amdgcn_rsq_clamp: { 6402 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6403 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6404 6405 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6406 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6407 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6408 6409 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6410 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6411 DAG.getConstantFP(Max, DL, VT)); 6412 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6413 DAG.getConstantFP(Min, DL, VT)); 6414 } 6415 case Intrinsic::r600_read_ngroups_x: 6416 if (Subtarget->isAmdHsaOS()) 6417 return emitNonHSAIntrinsicError(DAG, DL, VT); 6418 6419 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6420 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6421 false); 6422 case Intrinsic::r600_read_ngroups_y: 6423 if (Subtarget->isAmdHsaOS()) 6424 return emitNonHSAIntrinsicError(DAG, DL, VT); 6425 6426 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6427 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6428 false); 6429 case Intrinsic::r600_read_ngroups_z: 6430 if (Subtarget->isAmdHsaOS()) 6431 return emitNonHSAIntrinsicError(DAG, DL, VT); 6432 6433 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6434 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6435 false); 6436 case Intrinsic::r600_read_global_size_x: 6437 if (Subtarget->isAmdHsaOS()) 6438 return emitNonHSAIntrinsicError(DAG, DL, VT); 6439 6440 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6441 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6442 Align(4), false); 6443 case Intrinsic::r600_read_global_size_y: 6444 if (Subtarget->isAmdHsaOS()) 6445 return emitNonHSAIntrinsicError(DAG, DL, VT); 6446 6447 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6448 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6449 Align(4), false); 6450 case Intrinsic::r600_read_global_size_z: 6451 if (Subtarget->isAmdHsaOS()) 6452 return emitNonHSAIntrinsicError(DAG, DL, VT); 6453 6454 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6455 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6456 Align(4), false); 6457 case Intrinsic::r600_read_local_size_x: 6458 if (Subtarget->isAmdHsaOS()) 6459 return emitNonHSAIntrinsicError(DAG, DL, VT); 6460 6461 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6462 SI::KernelInputOffsets::LOCAL_SIZE_X); 6463 case Intrinsic::r600_read_local_size_y: 6464 if (Subtarget->isAmdHsaOS()) 6465 return emitNonHSAIntrinsicError(DAG, DL, VT); 6466 6467 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6468 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6469 case Intrinsic::r600_read_local_size_z: 6470 if (Subtarget->isAmdHsaOS()) 6471 return emitNonHSAIntrinsicError(DAG, DL, VT); 6472 6473 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6474 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6475 case Intrinsic::amdgcn_workgroup_id_x: 6476 return getPreloadedValue(DAG, *MFI, VT, 6477 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6478 case Intrinsic::amdgcn_workgroup_id_y: 6479 return getPreloadedValue(DAG, *MFI, VT, 6480 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6481 case Intrinsic::amdgcn_workgroup_id_z: 6482 return getPreloadedValue(DAG, *MFI, VT, 6483 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6484 case Intrinsic::amdgcn_workitem_id_x: 6485 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6486 SDLoc(DAG.getEntryNode()), 6487 MFI->getArgInfo().WorkItemIDX); 6488 case Intrinsic::amdgcn_workitem_id_y: 6489 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6490 SDLoc(DAG.getEntryNode()), 6491 MFI->getArgInfo().WorkItemIDY); 6492 case Intrinsic::amdgcn_workitem_id_z: 6493 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6494 SDLoc(DAG.getEntryNode()), 6495 MFI->getArgInfo().WorkItemIDZ); 6496 case Intrinsic::amdgcn_wavefrontsize: 6497 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6498 SDLoc(Op), MVT::i32); 6499 case Intrinsic::amdgcn_s_buffer_load: { 6500 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6501 SDValue GLC; 6502 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6503 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6504 IsGFX10 ? &DLC : nullptr)) 6505 return Op; 6506 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6507 DAG); 6508 } 6509 case Intrinsic::amdgcn_fdiv_fast: 6510 return lowerFDIV_FAST(Op, DAG); 6511 case Intrinsic::amdgcn_sin: 6512 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6513 6514 case Intrinsic::amdgcn_cos: 6515 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6516 6517 case Intrinsic::amdgcn_mul_u24: 6518 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6519 case Intrinsic::amdgcn_mul_i24: 6520 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6521 6522 case Intrinsic::amdgcn_log_clamp: { 6523 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6524 return SDValue(); 6525 6526 DiagnosticInfoUnsupported BadIntrin( 6527 MF.getFunction(), "intrinsic not supported on subtarget", 6528 DL.getDebugLoc()); 6529 DAG.getContext()->diagnose(BadIntrin); 6530 return DAG.getUNDEF(VT); 6531 } 6532 case Intrinsic::amdgcn_ldexp: 6533 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6534 Op.getOperand(1), Op.getOperand(2)); 6535 6536 case Intrinsic::amdgcn_fract: 6537 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6538 6539 case Intrinsic::amdgcn_class: 6540 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6541 Op.getOperand(1), Op.getOperand(2)); 6542 case Intrinsic::amdgcn_div_fmas: 6543 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6544 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6545 Op.getOperand(4)); 6546 6547 case Intrinsic::amdgcn_div_fixup: 6548 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6549 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6550 6551 case Intrinsic::amdgcn_div_scale: { 6552 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6553 6554 // Translate to the operands expected by the machine instruction. The 6555 // first parameter must be the same as the first instruction. 6556 SDValue Numerator = Op.getOperand(1); 6557 SDValue Denominator = Op.getOperand(2); 6558 6559 // Note this order is opposite of the machine instruction's operations, 6560 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6561 // intrinsic has the numerator as the first operand to match a normal 6562 // division operation. 6563 6564 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6565 6566 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6567 Denominator, Numerator); 6568 } 6569 case Intrinsic::amdgcn_icmp: { 6570 // There is a Pat that handles this variant, so return it as-is. 6571 if (Op.getOperand(1).getValueType() == MVT::i1 && 6572 Op.getConstantOperandVal(2) == 0 && 6573 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6574 return Op; 6575 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6576 } 6577 case Intrinsic::amdgcn_fcmp: { 6578 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6579 } 6580 case Intrinsic::amdgcn_ballot: 6581 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6582 case Intrinsic::amdgcn_fmed3: 6583 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6584 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6585 case Intrinsic::amdgcn_fdot2: 6586 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6587 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6588 Op.getOperand(4)); 6589 case Intrinsic::amdgcn_fmul_legacy: 6590 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6591 Op.getOperand(1), Op.getOperand(2)); 6592 case Intrinsic::amdgcn_sffbh: 6593 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6594 case Intrinsic::amdgcn_sbfe: 6595 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6596 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6597 case Intrinsic::amdgcn_ubfe: 6598 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6599 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6600 case Intrinsic::amdgcn_cvt_pkrtz: 6601 case Intrinsic::amdgcn_cvt_pknorm_i16: 6602 case Intrinsic::amdgcn_cvt_pknorm_u16: 6603 case Intrinsic::amdgcn_cvt_pk_i16: 6604 case Intrinsic::amdgcn_cvt_pk_u16: { 6605 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6606 EVT VT = Op.getValueType(); 6607 unsigned Opcode; 6608 6609 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6610 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6611 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6612 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6613 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6614 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6615 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6616 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6617 else 6618 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6619 6620 if (isTypeLegal(VT)) 6621 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6622 6623 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6624 Op.getOperand(1), Op.getOperand(2)); 6625 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6626 } 6627 case Intrinsic::amdgcn_fmad_ftz: 6628 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6629 Op.getOperand(2), Op.getOperand(3)); 6630 6631 case Intrinsic::amdgcn_if_break: 6632 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6633 Op->getOperand(1), Op->getOperand(2)), 0); 6634 6635 case Intrinsic::amdgcn_groupstaticsize: { 6636 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6637 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6638 return Op; 6639 6640 const Module *M = MF.getFunction().getParent(); 6641 const GlobalValue *GV = 6642 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6643 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6644 SIInstrInfo::MO_ABS32_LO); 6645 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6646 } 6647 case Intrinsic::amdgcn_is_shared: 6648 case Intrinsic::amdgcn_is_private: { 6649 SDLoc SL(Op); 6650 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6651 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6652 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6653 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6654 Op.getOperand(1)); 6655 6656 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6657 DAG.getConstant(1, SL, MVT::i32)); 6658 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6659 } 6660 case Intrinsic::amdgcn_alignbit: 6661 return DAG.getNode(ISD::FSHR, DL, VT, 6662 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6663 case Intrinsic::amdgcn_reloc_constant: { 6664 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6665 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6666 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6667 auto RelocSymbol = cast<GlobalVariable>( 6668 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6669 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6670 SIInstrInfo::MO_ABS32_LO); 6671 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6672 } 6673 default: 6674 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6675 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6676 return lowerImage(Op, ImageDimIntr, DAG); 6677 6678 return Op; 6679 } 6680 } 6681 6682 // This function computes an appropriate offset to pass to 6683 // MachineMemOperand::setOffset() based on the offset inputs to 6684 // an intrinsic. If any of the offsets are non-contstant or 6685 // if VIndex is non-zero then this function returns 0. Otherwise, 6686 // it returns the sum of VOffset, SOffset, and Offset. 6687 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6688 SDValue SOffset, 6689 SDValue Offset, 6690 SDValue VIndex = SDValue()) { 6691 6692 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6693 !isa<ConstantSDNode>(Offset)) 6694 return 0; 6695 6696 if (VIndex) { 6697 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6698 return 0; 6699 } 6700 6701 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6702 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6703 cast<ConstantSDNode>(Offset)->getSExtValue(); 6704 } 6705 6706 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6707 SelectionDAG &DAG, 6708 unsigned NewOpcode) const { 6709 SDLoc DL(Op); 6710 6711 SDValue VData = Op.getOperand(2); 6712 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6713 SDValue Ops[] = { 6714 Op.getOperand(0), // Chain 6715 VData, // vdata 6716 Op.getOperand(3), // rsrc 6717 DAG.getConstant(0, DL, MVT::i32), // vindex 6718 Offsets.first, // voffset 6719 Op.getOperand(5), // soffset 6720 Offsets.second, // offset 6721 Op.getOperand(6), // cachepolicy 6722 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6723 }; 6724 6725 auto *M = cast<MemSDNode>(Op); 6726 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6727 6728 EVT MemVT = VData.getValueType(); 6729 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6730 M->getMemOperand()); 6731 } 6732 6733 SDValue 6734 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6735 unsigned NewOpcode) const { 6736 SDLoc DL(Op); 6737 6738 SDValue VData = Op.getOperand(2); 6739 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6740 SDValue Ops[] = { 6741 Op.getOperand(0), // Chain 6742 VData, // vdata 6743 Op.getOperand(3), // rsrc 6744 Op.getOperand(4), // vindex 6745 Offsets.first, // voffset 6746 Op.getOperand(6), // soffset 6747 Offsets.second, // offset 6748 Op.getOperand(7), // cachepolicy 6749 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6750 }; 6751 6752 auto *M = cast<MemSDNode>(Op); 6753 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6754 Ops[3])); 6755 6756 EVT MemVT = VData.getValueType(); 6757 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6758 M->getMemOperand()); 6759 } 6760 6761 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6762 SelectionDAG &DAG) const { 6763 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6764 SDLoc DL(Op); 6765 6766 switch (IntrID) { 6767 case Intrinsic::amdgcn_ds_ordered_add: 6768 case Intrinsic::amdgcn_ds_ordered_swap: { 6769 MemSDNode *M = cast<MemSDNode>(Op); 6770 SDValue Chain = M->getOperand(0); 6771 SDValue M0 = M->getOperand(2); 6772 SDValue Value = M->getOperand(3); 6773 unsigned IndexOperand = M->getConstantOperandVal(7); 6774 unsigned WaveRelease = M->getConstantOperandVal(8); 6775 unsigned WaveDone = M->getConstantOperandVal(9); 6776 6777 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6778 IndexOperand &= ~0x3f; 6779 unsigned CountDw = 0; 6780 6781 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6782 CountDw = (IndexOperand >> 24) & 0xf; 6783 IndexOperand &= ~(0xf << 24); 6784 6785 if (CountDw < 1 || CountDw > 4) { 6786 report_fatal_error( 6787 "ds_ordered_count: dword count must be between 1 and 4"); 6788 } 6789 } 6790 6791 if (IndexOperand) 6792 report_fatal_error("ds_ordered_count: bad index operand"); 6793 6794 if (WaveDone && !WaveRelease) 6795 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6796 6797 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6798 unsigned ShaderType = 6799 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6800 unsigned Offset0 = OrderedCountIndex << 2; 6801 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6802 (Instruction << 4); 6803 6804 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6805 Offset1 |= (CountDw - 1) << 6; 6806 6807 unsigned Offset = Offset0 | (Offset1 << 8); 6808 6809 SDValue Ops[] = { 6810 Chain, 6811 Value, 6812 DAG.getTargetConstant(Offset, DL, MVT::i16), 6813 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6814 }; 6815 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6816 M->getVTList(), Ops, M->getMemoryVT(), 6817 M->getMemOperand()); 6818 } 6819 case Intrinsic::amdgcn_ds_fadd: { 6820 MemSDNode *M = cast<MemSDNode>(Op); 6821 unsigned Opc; 6822 switch (IntrID) { 6823 case Intrinsic::amdgcn_ds_fadd: 6824 Opc = ISD::ATOMIC_LOAD_FADD; 6825 break; 6826 } 6827 6828 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6829 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6830 M->getMemOperand()); 6831 } 6832 case Intrinsic::amdgcn_atomic_inc: 6833 case Intrinsic::amdgcn_atomic_dec: 6834 case Intrinsic::amdgcn_ds_fmin: 6835 case Intrinsic::amdgcn_ds_fmax: { 6836 MemSDNode *M = cast<MemSDNode>(Op); 6837 unsigned Opc; 6838 switch (IntrID) { 6839 case Intrinsic::amdgcn_atomic_inc: 6840 Opc = AMDGPUISD::ATOMIC_INC; 6841 break; 6842 case Intrinsic::amdgcn_atomic_dec: 6843 Opc = AMDGPUISD::ATOMIC_DEC; 6844 break; 6845 case Intrinsic::amdgcn_ds_fmin: 6846 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6847 break; 6848 case Intrinsic::amdgcn_ds_fmax: 6849 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6850 break; 6851 default: 6852 llvm_unreachable("Unknown intrinsic!"); 6853 } 6854 SDValue Ops[] = { 6855 M->getOperand(0), // Chain 6856 M->getOperand(2), // Ptr 6857 M->getOperand(3) // Value 6858 }; 6859 6860 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6861 M->getMemoryVT(), M->getMemOperand()); 6862 } 6863 case Intrinsic::amdgcn_buffer_load: 6864 case Intrinsic::amdgcn_buffer_load_format: { 6865 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6866 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6867 unsigned IdxEn = 1; 6868 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6869 IdxEn = Idx->getZExtValue() != 0; 6870 SDValue Ops[] = { 6871 Op.getOperand(0), // Chain 6872 Op.getOperand(2), // rsrc 6873 Op.getOperand(3), // vindex 6874 SDValue(), // voffset -- will be set by setBufferOffsets 6875 SDValue(), // soffset -- will be set by setBufferOffsets 6876 SDValue(), // offset -- will be set by setBufferOffsets 6877 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6878 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6879 }; 6880 6881 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6882 // We don't know the offset if vindex is non-zero, so clear it. 6883 if (IdxEn) 6884 Offset = 0; 6885 6886 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6887 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6888 6889 EVT VT = Op.getValueType(); 6890 EVT IntVT = VT.changeTypeToInteger(); 6891 auto *M = cast<MemSDNode>(Op); 6892 M->getMemOperand()->setOffset(Offset); 6893 EVT LoadVT = Op.getValueType(); 6894 6895 if (LoadVT.getScalarType() == MVT::f16) 6896 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6897 M, DAG, Ops); 6898 6899 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6900 if (LoadVT.getScalarType() == MVT::i8 || 6901 LoadVT.getScalarType() == MVT::i16) 6902 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6903 6904 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6905 M->getMemOperand(), DAG); 6906 } 6907 case Intrinsic::amdgcn_raw_buffer_load: 6908 case Intrinsic::amdgcn_raw_buffer_load_format: { 6909 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6910 6911 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6912 SDValue Ops[] = { 6913 Op.getOperand(0), // Chain 6914 Op.getOperand(2), // rsrc 6915 DAG.getConstant(0, DL, MVT::i32), // vindex 6916 Offsets.first, // voffset 6917 Op.getOperand(4), // soffset 6918 Offsets.second, // offset 6919 Op.getOperand(5), // cachepolicy, swizzled buffer 6920 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6921 }; 6922 6923 auto *M = cast<MemSDNode>(Op); 6924 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6925 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6926 } 6927 case Intrinsic::amdgcn_struct_buffer_load: 6928 case Intrinsic::amdgcn_struct_buffer_load_format: { 6929 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6930 6931 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6932 SDValue Ops[] = { 6933 Op.getOperand(0), // Chain 6934 Op.getOperand(2), // rsrc 6935 Op.getOperand(3), // vindex 6936 Offsets.first, // voffset 6937 Op.getOperand(5), // soffset 6938 Offsets.second, // offset 6939 Op.getOperand(6), // cachepolicy, swizzled buffer 6940 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6941 }; 6942 6943 auto *M = cast<MemSDNode>(Op); 6944 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6945 Ops[2])); 6946 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6947 } 6948 case Intrinsic::amdgcn_tbuffer_load: { 6949 MemSDNode *M = cast<MemSDNode>(Op); 6950 EVT LoadVT = Op.getValueType(); 6951 6952 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6953 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6954 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6955 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6956 unsigned IdxEn = 1; 6957 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6958 IdxEn = Idx->getZExtValue() != 0; 6959 SDValue Ops[] = { 6960 Op.getOperand(0), // Chain 6961 Op.getOperand(2), // rsrc 6962 Op.getOperand(3), // vindex 6963 Op.getOperand(4), // voffset 6964 Op.getOperand(5), // soffset 6965 Op.getOperand(6), // offset 6966 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6967 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6968 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6969 }; 6970 6971 if (LoadVT.getScalarType() == MVT::f16) 6972 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6973 M, DAG, Ops); 6974 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6975 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6976 DAG); 6977 } 6978 case Intrinsic::amdgcn_raw_tbuffer_load: { 6979 MemSDNode *M = cast<MemSDNode>(Op); 6980 EVT LoadVT = Op.getValueType(); 6981 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6982 6983 SDValue Ops[] = { 6984 Op.getOperand(0), // Chain 6985 Op.getOperand(2), // rsrc 6986 DAG.getConstant(0, DL, MVT::i32), // vindex 6987 Offsets.first, // voffset 6988 Op.getOperand(4), // soffset 6989 Offsets.second, // offset 6990 Op.getOperand(5), // format 6991 Op.getOperand(6), // cachepolicy, swizzled buffer 6992 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6993 }; 6994 6995 if (LoadVT.getScalarType() == MVT::f16) 6996 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6997 M, DAG, Ops); 6998 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6999 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7000 DAG); 7001 } 7002 case Intrinsic::amdgcn_struct_tbuffer_load: { 7003 MemSDNode *M = cast<MemSDNode>(Op); 7004 EVT LoadVT = Op.getValueType(); 7005 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7006 7007 SDValue Ops[] = { 7008 Op.getOperand(0), // Chain 7009 Op.getOperand(2), // rsrc 7010 Op.getOperand(3), // vindex 7011 Offsets.first, // voffset 7012 Op.getOperand(5), // soffset 7013 Offsets.second, // offset 7014 Op.getOperand(6), // format 7015 Op.getOperand(7), // cachepolicy, swizzled buffer 7016 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7017 }; 7018 7019 if (LoadVT.getScalarType() == MVT::f16) 7020 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7021 M, DAG, Ops); 7022 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7023 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7024 DAG); 7025 } 7026 case Intrinsic::amdgcn_buffer_atomic_swap: 7027 case Intrinsic::amdgcn_buffer_atomic_add: 7028 case Intrinsic::amdgcn_buffer_atomic_sub: 7029 case Intrinsic::amdgcn_buffer_atomic_csub: 7030 case Intrinsic::amdgcn_buffer_atomic_smin: 7031 case Intrinsic::amdgcn_buffer_atomic_umin: 7032 case Intrinsic::amdgcn_buffer_atomic_smax: 7033 case Intrinsic::amdgcn_buffer_atomic_umax: 7034 case Intrinsic::amdgcn_buffer_atomic_and: 7035 case Intrinsic::amdgcn_buffer_atomic_or: 7036 case Intrinsic::amdgcn_buffer_atomic_xor: 7037 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7038 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7039 unsigned IdxEn = 1; 7040 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7041 IdxEn = Idx->getZExtValue() != 0; 7042 SDValue Ops[] = { 7043 Op.getOperand(0), // Chain 7044 Op.getOperand(2), // vdata 7045 Op.getOperand(3), // rsrc 7046 Op.getOperand(4), // vindex 7047 SDValue(), // voffset -- will be set by setBufferOffsets 7048 SDValue(), // soffset -- will be set by setBufferOffsets 7049 SDValue(), // offset -- will be set by setBufferOffsets 7050 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7051 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7052 }; 7053 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7054 // We don't know the offset if vindex is non-zero, so clear it. 7055 if (IdxEn) 7056 Offset = 0; 7057 EVT VT = Op.getValueType(); 7058 7059 auto *M = cast<MemSDNode>(Op); 7060 M->getMemOperand()->setOffset(Offset); 7061 unsigned Opcode = 0; 7062 7063 switch (IntrID) { 7064 case Intrinsic::amdgcn_buffer_atomic_swap: 7065 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7066 break; 7067 case Intrinsic::amdgcn_buffer_atomic_add: 7068 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7069 break; 7070 case Intrinsic::amdgcn_buffer_atomic_sub: 7071 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7072 break; 7073 case Intrinsic::amdgcn_buffer_atomic_csub: 7074 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7075 break; 7076 case Intrinsic::amdgcn_buffer_atomic_smin: 7077 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7078 break; 7079 case Intrinsic::amdgcn_buffer_atomic_umin: 7080 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7081 break; 7082 case Intrinsic::amdgcn_buffer_atomic_smax: 7083 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7084 break; 7085 case Intrinsic::amdgcn_buffer_atomic_umax: 7086 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7087 break; 7088 case Intrinsic::amdgcn_buffer_atomic_and: 7089 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7090 break; 7091 case Intrinsic::amdgcn_buffer_atomic_or: 7092 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7093 break; 7094 case Intrinsic::amdgcn_buffer_atomic_xor: 7095 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7096 break; 7097 case Intrinsic::amdgcn_buffer_atomic_fadd: 7098 if (!Op.getValue(0).use_empty()) { 7099 DiagnosticInfoUnsupported 7100 NoFpRet(DAG.getMachineFunction().getFunction(), 7101 "return versions of fp atomics not supported", 7102 DL.getDebugLoc(), DS_Error); 7103 DAG.getContext()->diagnose(NoFpRet); 7104 return SDValue(); 7105 } 7106 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7107 break; 7108 default: 7109 llvm_unreachable("unhandled atomic opcode"); 7110 } 7111 7112 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7113 M->getMemOperand()); 7114 } 7115 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7116 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7117 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7118 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7119 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7120 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7121 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7122 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7123 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7124 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7125 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7126 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7127 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7128 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7129 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7130 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7131 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7132 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7133 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7134 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7135 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7136 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7137 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7138 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7139 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7140 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7141 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7142 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7143 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7144 return lowerStructBufferAtomicIntrin(Op, DAG, 7145 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7146 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7147 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7148 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7149 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7150 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7151 return lowerStructBufferAtomicIntrin(Op, DAG, 7152 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7153 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7154 return lowerStructBufferAtomicIntrin(Op, DAG, 7155 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7156 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7157 return lowerStructBufferAtomicIntrin(Op, DAG, 7158 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7159 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7160 return lowerStructBufferAtomicIntrin(Op, DAG, 7161 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7162 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7163 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7164 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7165 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7166 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7167 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7168 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7169 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7170 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7171 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7172 7173 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7174 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7175 unsigned IdxEn = 1; 7176 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7177 IdxEn = Idx->getZExtValue() != 0; 7178 SDValue Ops[] = { 7179 Op.getOperand(0), // Chain 7180 Op.getOperand(2), // src 7181 Op.getOperand(3), // cmp 7182 Op.getOperand(4), // rsrc 7183 Op.getOperand(5), // vindex 7184 SDValue(), // voffset -- will be set by setBufferOffsets 7185 SDValue(), // soffset -- will be set by setBufferOffsets 7186 SDValue(), // offset -- will be set by setBufferOffsets 7187 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7188 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7189 }; 7190 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7191 // We don't know the offset if vindex is non-zero, so clear it. 7192 if (IdxEn) 7193 Offset = 0; 7194 EVT VT = Op.getValueType(); 7195 auto *M = cast<MemSDNode>(Op); 7196 M->getMemOperand()->setOffset(Offset); 7197 7198 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7199 Op->getVTList(), Ops, VT, M->getMemOperand()); 7200 } 7201 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7202 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7203 SDValue Ops[] = { 7204 Op.getOperand(0), // Chain 7205 Op.getOperand(2), // src 7206 Op.getOperand(3), // cmp 7207 Op.getOperand(4), // rsrc 7208 DAG.getConstant(0, DL, MVT::i32), // vindex 7209 Offsets.first, // voffset 7210 Op.getOperand(6), // soffset 7211 Offsets.second, // offset 7212 Op.getOperand(7), // cachepolicy 7213 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7214 }; 7215 EVT VT = Op.getValueType(); 7216 auto *M = cast<MemSDNode>(Op); 7217 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7218 7219 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7220 Op->getVTList(), Ops, VT, M->getMemOperand()); 7221 } 7222 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7223 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7224 SDValue Ops[] = { 7225 Op.getOperand(0), // Chain 7226 Op.getOperand(2), // src 7227 Op.getOperand(3), // cmp 7228 Op.getOperand(4), // rsrc 7229 Op.getOperand(5), // vindex 7230 Offsets.first, // voffset 7231 Op.getOperand(7), // soffset 7232 Offsets.second, // offset 7233 Op.getOperand(8), // cachepolicy 7234 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7235 }; 7236 EVT VT = Op.getValueType(); 7237 auto *M = cast<MemSDNode>(Op); 7238 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7239 Ops[4])); 7240 7241 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7242 Op->getVTList(), Ops, VT, M->getMemOperand()); 7243 } 7244 case Intrinsic::amdgcn_global_atomic_fadd: { 7245 if (!Op.getValue(0).use_empty()) { 7246 DiagnosticInfoUnsupported 7247 NoFpRet(DAG.getMachineFunction().getFunction(), 7248 "return versions of fp atomics not supported", 7249 DL.getDebugLoc(), DS_Error); 7250 DAG.getContext()->diagnose(NoFpRet); 7251 return SDValue(); 7252 } 7253 MemSDNode *M = cast<MemSDNode>(Op); 7254 SDValue Ops[] = { 7255 M->getOperand(0), // Chain 7256 M->getOperand(2), // Ptr 7257 M->getOperand(3) // Value 7258 }; 7259 7260 EVT VT = Op.getOperand(3).getValueType(); 7261 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7262 DAG.getVTList(VT, MVT::Other), Ops, 7263 M->getMemOperand()); 7264 } 7265 default: 7266 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7267 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7268 return lowerImage(Op, ImageDimIntr, DAG); 7269 7270 return SDValue(); 7271 } 7272 } 7273 7274 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7275 // dwordx4 if on SI. 7276 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7277 SDVTList VTList, 7278 ArrayRef<SDValue> Ops, EVT MemVT, 7279 MachineMemOperand *MMO, 7280 SelectionDAG &DAG) const { 7281 EVT VT = VTList.VTs[0]; 7282 EVT WidenedVT = VT; 7283 EVT WidenedMemVT = MemVT; 7284 if (!Subtarget->hasDwordx3LoadStores() && 7285 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7286 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7287 WidenedVT.getVectorElementType(), 4); 7288 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7289 WidenedMemVT.getVectorElementType(), 4); 7290 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7291 } 7292 7293 assert(VTList.NumVTs == 2); 7294 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7295 7296 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7297 WidenedMemVT, MMO); 7298 if (WidenedVT != VT) { 7299 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7300 DAG.getVectorIdxConstant(0, DL)); 7301 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7302 } 7303 return NewOp; 7304 } 7305 7306 SDValue SITargetLowering::handleD16VData(SDValue VData, 7307 SelectionDAG &DAG) const { 7308 EVT StoreVT = VData.getValueType(); 7309 7310 // No change for f16 and legal vector D16 types. 7311 if (!StoreVT.isVector()) 7312 return VData; 7313 7314 SDLoc DL(VData); 7315 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7316 7317 if (Subtarget->hasUnpackedD16VMem()) { 7318 // We need to unpack the packed data to store. 7319 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7320 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7321 7322 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7323 StoreVT.getVectorNumElements()); 7324 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7325 return DAG.UnrollVectorOp(ZExt.getNode()); 7326 } 7327 7328 assert(isTypeLegal(StoreVT)); 7329 return VData; 7330 } 7331 7332 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7333 SelectionDAG &DAG) const { 7334 SDLoc DL(Op); 7335 SDValue Chain = Op.getOperand(0); 7336 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7337 MachineFunction &MF = DAG.getMachineFunction(); 7338 7339 switch (IntrinsicID) { 7340 case Intrinsic::amdgcn_exp_compr: { 7341 SDValue Src0 = Op.getOperand(4); 7342 SDValue Src1 = Op.getOperand(5); 7343 // Hack around illegal type on SI by directly selecting it. 7344 if (isTypeLegal(Src0.getValueType())) 7345 return SDValue(); 7346 7347 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7348 SDValue Undef = DAG.getUNDEF(MVT::f32); 7349 const SDValue Ops[] = { 7350 Op.getOperand(2), // tgt 7351 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7352 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7353 Undef, // src2 7354 Undef, // src3 7355 Op.getOperand(7), // vm 7356 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7357 Op.getOperand(3), // en 7358 Op.getOperand(0) // Chain 7359 }; 7360 7361 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7362 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7363 } 7364 case Intrinsic::amdgcn_s_barrier: { 7365 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7366 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7367 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7368 if (WGSize <= ST.getWavefrontSize()) 7369 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7370 Op.getOperand(0)), 0); 7371 } 7372 return SDValue(); 7373 }; 7374 case Intrinsic::amdgcn_tbuffer_store: { 7375 SDValue VData = Op.getOperand(2); 7376 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7377 if (IsD16) 7378 VData = handleD16VData(VData, DAG); 7379 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7380 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7381 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7382 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7383 unsigned IdxEn = 1; 7384 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7385 IdxEn = Idx->getZExtValue() != 0; 7386 SDValue Ops[] = { 7387 Chain, 7388 VData, // vdata 7389 Op.getOperand(3), // rsrc 7390 Op.getOperand(4), // vindex 7391 Op.getOperand(5), // voffset 7392 Op.getOperand(6), // soffset 7393 Op.getOperand(7), // offset 7394 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7395 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7396 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7397 }; 7398 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7399 AMDGPUISD::TBUFFER_STORE_FORMAT; 7400 MemSDNode *M = cast<MemSDNode>(Op); 7401 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7402 M->getMemoryVT(), M->getMemOperand()); 7403 } 7404 7405 case Intrinsic::amdgcn_struct_tbuffer_store: { 7406 SDValue VData = Op.getOperand(2); 7407 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7408 if (IsD16) 7409 VData = handleD16VData(VData, DAG); 7410 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7411 SDValue Ops[] = { 7412 Chain, 7413 VData, // vdata 7414 Op.getOperand(3), // rsrc 7415 Op.getOperand(4), // vindex 7416 Offsets.first, // voffset 7417 Op.getOperand(6), // soffset 7418 Offsets.second, // offset 7419 Op.getOperand(7), // format 7420 Op.getOperand(8), // cachepolicy, swizzled buffer 7421 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7422 }; 7423 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7424 AMDGPUISD::TBUFFER_STORE_FORMAT; 7425 MemSDNode *M = cast<MemSDNode>(Op); 7426 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7427 M->getMemoryVT(), M->getMemOperand()); 7428 } 7429 7430 case Intrinsic::amdgcn_raw_tbuffer_store: { 7431 SDValue VData = Op.getOperand(2); 7432 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7433 if (IsD16) 7434 VData = handleD16VData(VData, DAG); 7435 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7436 SDValue Ops[] = { 7437 Chain, 7438 VData, // vdata 7439 Op.getOperand(3), // rsrc 7440 DAG.getConstant(0, DL, MVT::i32), // vindex 7441 Offsets.first, // voffset 7442 Op.getOperand(5), // soffset 7443 Offsets.second, // offset 7444 Op.getOperand(6), // format 7445 Op.getOperand(7), // cachepolicy, swizzled buffer 7446 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7447 }; 7448 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7449 AMDGPUISD::TBUFFER_STORE_FORMAT; 7450 MemSDNode *M = cast<MemSDNode>(Op); 7451 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7452 M->getMemoryVT(), M->getMemOperand()); 7453 } 7454 7455 case Intrinsic::amdgcn_buffer_store: 7456 case Intrinsic::amdgcn_buffer_store_format: { 7457 SDValue VData = Op.getOperand(2); 7458 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7459 if (IsD16) 7460 VData = handleD16VData(VData, DAG); 7461 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7462 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7463 unsigned IdxEn = 1; 7464 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7465 IdxEn = Idx->getZExtValue() != 0; 7466 SDValue Ops[] = { 7467 Chain, 7468 VData, 7469 Op.getOperand(3), // rsrc 7470 Op.getOperand(4), // vindex 7471 SDValue(), // voffset -- will be set by setBufferOffsets 7472 SDValue(), // soffset -- will be set by setBufferOffsets 7473 SDValue(), // offset -- will be set by setBufferOffsets 7474 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7475 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7476 }; 7477 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7478 // We don't know the offset if vindex is non-zero, so clear it. 7479 if (IdxEn) 7480 Offset = 0; 7481 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7482 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7483 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7484 MemSDNode *M = cast<MemSDNode>(Op); 7485 M->getMemOperand()->setOffset(Offset); 7486 7487 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7488 EVT VDataType = VData.getValueType().getScalarType(); 7489 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7490 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7491 7492 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7493 M->getMemoryVT(), M->getMemOperand()); 7494 } 7495 7496 case Intrinsic::amdgcn_raw_buffer_store: 7497 case Intrinsic::amdgcn_raw_buffer_store_format: { 7498 const bool IsFormat = 7499 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7500 7501 SDValue VData = Op.getOperand(2); 7502 EVT VDataVT = VData.getValueType(); 7503 EVT EltType = VDataVT.getScalarType(); 7504 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7505 if (IsD16) 7506 VData = handleD16VData(VData, DAG); 7507 7508 if (!isTypeLegal(VDataVT)) { 7509 VData = 7510 DAG.getNode(ISD::BITCAST, DL, 7511 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7512 } 7513 7514 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7515 SDValue Ops[] = { 7516 Chain, 7517 VData, 7518 Op.getOperand(3), // rsrc 7519 DAG.getConstant(0, DL, MVT::i32), // vindex 7520 Offsets.first, // voffset 7521 Op.getOperand(5), // soffset 7522 Offsets.second, // offset 7523 Op.getOperand(6), // cachepolicy, swizzled buffer 7524 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7525 }; 7526 unsigned Opc = 7527 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7528 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7529 MemSDNode *M = cast<MemSDNode>(Op); 7530 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7531 7532 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7533 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7534 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7535 7536 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7537 M->getMemoryVT(), M->getMemOperand()); 7538 } 7539 7540 case Intrinsic::amdgcn_struct_buffer_store: 7541 case Intrinsic::amdgcn_struct_buffer_store_format: { 7542 const bool IsFormat = 7543 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7544 7545 SDValue VData = Op.getOperand(2); 7546 EVT VDataVT = VData.getValueType(); 7547 EVT EltType = VDataVT.getScalarType(); 7548 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7549 7550 if (IsD16) 7551 VData = handleD16VData(VData, DAG); 7552 7553 if (!isTypeLegal(VDataVT)) { 7554 VData = 7555 DAG.getNode(ISD::BITCAST, DL, 7556 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7557 } 7558 7559 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7560 SDValue Ops[] = { 7561 Chain, 7562 VData, 7563 Op.getOperand(3), // rsrc 7564 Op.getOperand(4), // vindex 7565 Offsets.first, // voffset 7566 Op.getOperand(6), // soffset 7567 Offsets.second, // offset 7568 Op.getOperand(7), // cachepolicy, swizzled buffer 7569 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7570 }; 7571 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7572 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7573 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7574 MemSDNode *M = cast<MemSDNode>(Op); 7575 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7576 Ops[3])); 7577 7578 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7579 EVT VDataType = VData.getValueType().getScalarType(); 7580 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7581 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7582 7583 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7584 M->getMemoryVT(), M->getMemOperand()); 7585 } 7586 case Intrinsic::amdgcn_end_cf: 7587 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7588 Op->getOperand(2), Chain), 0); 7589 7590 default: { 7591 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7592 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7593 return lowerImage(Op, ImageDimIntr, DAG); 7594 7595 return Op; 7596 } 7597 } 7598 } 7599 7600 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7601 // offset (the offset that is included in bounds checking and swizzling, to be 7602 // split between the instruction's voffset and immoffset fields) and soffset 7603 // (the offset that is excluded from bounds checking and swizzling, to go in 7604 // the instruction's soffset field). This function takes the first kind of 7605 // offset and figures out how to split it between voffset and immoffset. 7606 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7607 SDValue Offset, SelectionDAG &DAG) const { 7608 SDLoc DL(Offset); 7609 const unsigned MaxImm = 4095; 7610 SDValue N0 = Offset; 7611 ConstantSDNode *C1 = nullptr; 7612 7613 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7614 N0 = SDValue(); 7615 else if (DAG.isBaseWithConstantOffset(N0)) { 7616 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7617 N0 = N0.getOperand(0); 7618 } 7619 7620 if (C1) { 7621 unsigned ImmOffset = C1->getZExtValue(); 7622 // If the immediate value is too big for the immoffset field, put the value 7623 // and -4096 into the immoffset field so that the value that is copied/added 7624 // for the voffset field is a multiple of 4096, and it stands more chance 7625 // of being CSEd with the copy/add for another similar load/store. 7626 // However, do not do that rounding down to a multiple of 4096 if that is a 7627 // negative number, as it appears to be illegal to have a negative offset 7628 // in the vgpr, even if adding the immediate offset makes it positive. 7629 unsigned Overflow = ImmOffset & ~MaxImm; 7630 ImmOffset -= Overflow; 7631 if ((int32_t)Overflow < 0) { 7632 Overflow += ImmOffset; 7633 ImmOffset = 0; 7634 } 7635 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7636 if (Overflow) { 7637 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7638 if (!N0) 7639 N0 = OverflowVal; 7640 else { 7641 SDValue Ops[] = { N0, OverflowVal }; 7642 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7643 } 7644 } 7645 } 7646 if (!N0) 7647 N0 = DAG.getConstant(0, DL, MVT::i32); 7648 if (!C1) 7649 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7650 return {N0, SDValue(C1, 0)}; 7651 } 7652 7653 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7654 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7655 // pointed to by Offsets. 7656 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7657 SelectionDAG &DAG, SDValue *Offsets, 7658 Align Alignment) const { 7659 SDLoc DL(CombinedOffset); 7660 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7661 uint32_t Imm = C->getZExtValue(); 7662 uint32_t SOffset, ImmOffset; 7663 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7664 Alignment)) { 7665 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7666 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7667 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7668 return SOffset + ImmOffset; 7669 } 7670 } 7671 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7672 SDValue N0 = CombinedOffset.getOperand(0); 7673 SDValue N1 = CombinedOffset.getOperand(1); 7674 uint32_t SOffset, ImmOffset; 7675 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7676 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7677 Subtarget, Alignment)) { 7678 Offsets[0] = N0; 7679 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7680 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7681 return 0; 7682 } 7683 } 7684 Offsets[0] = CombinedOffset; 7685 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7686 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7687 return 0; 7688 } 7689 7690 // Handle 8 bit and 16 bit buffer loads 7691 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7692 EVT LoadVT, SDLoc DL, 7693 ArrayRef<SDValue> Ops, 7694 MemSDNode *M) const { 7695 EVT IntVT = LoadVT.changeTypeToInteger(); 7696 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7697 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7698 7699 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7700 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7701 Ops, IntVT, 7702 M->getMemOperand()); 7703 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7704 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7705 7706 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7707 } 7708 7709 // Handle 8 bit and 16 bit buffer stores 7710 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7711 EVT VDataType, SDLoc DL, 7712 SDValue Ops[], 7713 MemSDNode *M) const { 7714 if (VDataType == MVT::f16) 7715 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7716 7717 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7718 Ops[1] = BufferStoreExt; 7719 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7720 AMDGPUISD::BUFFER_STORE_SHORT; 7721 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7722 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7723 M->getMemOperand()); 7724 } 7725 7726 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7727 ISD::LoadExtType ExtType, SDValue Op, 7728 const SDLoc &SL, EVT VT) { 7729 if (VT.bitsLT(Op.getValueType())) 7730 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7731 7732 switch (ExtType) { 7733 case ISD::SEXTLOAD: 7734 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7735 case ISD::ZEXTLOAD: 7736 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7737 case ISD::EXTLOAD: 7738 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7739 case ISD::NON_EXTLOAD: 7740 return Op; 7741 } 7742 7743 llvm_unreachable("invalid ext type"); 7744 } 7745 7746 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7747 SelectionDAG &DAG = DCI.DAG; 7748 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7749 return SDValue(); 7750 7751 // FIXME: Constant loads should all be marked invariant. 7752 unsigned AS = Ld->getAddressSpace(); 7753 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7754 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7755 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7756 return SDValue(); 7757 7758 // Don't do this early, since it may interfere with adjacent load merging for 7759 // illegal types. We can avoid losing alignment information for exotic types 7760 // pre-legalize. 7761 EVT MemVT = Ld->getMemoryVT(); 7762 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7763 MemVT.getSizeInBits() >= 32) 7764 return SDValue(); 7765 7766 SDLoc SL(Ld); 7767 7768 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7769 "unexpected vector extload"); 7770 7771 // TODO: Drop only high part of range. 7772 SDValue Ptr = Ld->getBasePtr(); 7773 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7774 MVT::i32, SL, Ld->getChain(), Ptr, 7775 Ld->getOffset(), 7776 Ld->getPointerInfo(), MVT::i32, 7777 Ld->getAlignment(), 7778 Ld->getMemOperand()->getFlags(), 7779 Ld->getAAInfo(), 7780 nullptr); // Drop ranges 7781 7782 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7783 if (MemVT.isFloatingPoint()) { 7784 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7785 "unexpected fp extload"); 7786 TruncVT = MemVT.changeTypeToInteger(); 7787 } 7788 7789 SDValue Cvt = NewLoad; 7790 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7791 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7792 DAG.getValueType(TruncVT)); 7793 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7794 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7795 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7796 } else { 7797 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7798 } 7799 7800 EVT VT = Ld->getValueType(0); 7801 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7802 7803 DCI.AddToWorklist(Cvt.getNode()); 7804 7805 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7806 // the appropriate extension from the 32-bit load. 7807 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7808 DCI.AddToWorklist(Cvt.getNode()); 7809 7810 // Handle conversion back to floating point if necessary. 7811 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7812 7813 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7814 } 7815 7816 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7817 SDLoc DL(Op); 7818 LoadSDNode *Load = cast<LoadSDNode>(Op); 7819 ISD::LoadExtType ExtType = Load->getExtensionType(); 7820 EVT MemVT = Load->getMemoryVT(); 7821 7822 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7823 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7824 return SDValue(); 7825 7826 // FIXME: Copied from PPC 7827 // First, load into 32 bits, then truncate to 1 bit. 7828 7829 SDValue Chain = Load->getChain(); 7830 SDValue BasePtr = Load->getBasePtr(); 7831 MachineMemOperand *MMO = Load->getMemOperand(); 7832 7833 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7834 7835 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7836 BasePtr, RealMemVT, MMO); 7837 7838 if (!MemVT.isVector()) { 7839 SDValue Ops[] = { 7840 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7841 NewLD.getValue(1) 7842 }; 7843 7844 return DAG.getMergeValues(Ops, DL); 7845 } 7846 7847 SmallVector<SDValue, 3> Elts; 7848 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7849 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7850 DAG.getConstant(I, DL, MVT::i32)); 7851 7852 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7853 } 7854 7855 SDValue Ops[] = { 7856 DAG.getBuildVector(MemVT, DL, Elts), 7857 NewLD.getValue(1) 7858 }; 7859 7860 return DAG.getMergeValues(Ops, DL); 7861 } 7862 7863 if (!MemVT.isVector()) 7864 return SDValue(); 7865 7866 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7867 "Custom lowering for non-i32 vectors hasn't been implemented."); 7868 7869 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7870 MemVT, *Load->getMemOperand())) { 7871 SDValue Ops[2]; 7872 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7873 return DAG.getMergeValues(Ops, DL); 7874 } 7875 7876 unsigned Alignment = Load->getAlignment(); 7877 unsigned AS = Load->getAddressSpace(); 7878 if (Subtarget->hasLDSMisalignedBug() && 7879 AS == AMDGPUAS::FLAT_ADDRESS && 7880 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7881 return SplitVectorLoad(Op, DAG); 7882 } 7883 7884 MachineFunction &MF = DAG.getMachineFunction(); 7885 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7886 // If there is a possibilty that flat instruction access scratch memory 7887 // then we need to use the same legalization rules we use for private. 7888 if (AS == AMDGPUAS::FLAT_ADDRESS && 7889 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7890 AS = MFI->hasFlatScratchInit() ? 7891 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7892 7893 unsigned NumElements = MemVT.getVectorNumElements(); 7894 7895 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7896 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7897 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7898 if (MemVT.isPow2VectorType()) 7899 return SDValue(); 7900 if (NumElements == 3) 7901 return WidenVectorLoad(Op, DAG); 7902 return SplitVectorLoad(Op, DAG); 7903 } 7904 // Non-uniform loads will be selected to MUBUF instructions, so they 7905 // have the same legalization requirements as global and private 7906 // loads. 7907 // 7908 } 7909 7910 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7911 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7912 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7913 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7914 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7915 Alignment >= 4 && NumElements < 32) { 7916 if (MemVT.isPow2VectorType()) 7917 return SDValue(); 7918 if (NumElements == 3) 7919 return WidenVectorLoad(Op, DAG); 7920 return SplitVectorLoad(Op, DAG); 7921 } 7922 // Non-uniform loads will be selected to MUBUF instructions, so they 7923 // have the same legalization requirements as global and private 7924 // loads. 7925 // 7926 } 7927 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7928 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7929 AS == AMDGPUAS::GLOBAL_ADDRESS || 7930 AS == AMDGPUAS::FLAT_ADDRESS) { 7931 if (NumElements > 4) 7932 return SplitVectorLoad(Op, DAG); 7933 // v3 loads not supported on SI. 7934 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7935 return WidenVectorLoad(Op, DAG); 7936 // v3 and v4 loads are supported for private and global memory. 7937 return SDValue(); 7938 } 7939 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7940 // Depending on the setting of the private_element_size field in the 7941 // resource descriptor, we can only make private accesses up to a certain 7942 // size. 7943 switch (Subtarget->getMaxPrivateElementSize()) { 7944 case 4: { 7945 SDValue Ops[2]; 7946 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7947 return DAG.getMergeValues(Ops, DL); 7948 } 7949 case 8: 7950 if (NumElements > 2) 7951 return SplitVectorLoad(Op, DAG); 7952 return SDValue(); 7953 case 16: 7954 // Same as global/flat 7955 if (NumElements > 4) 7956 return SplitVectorLoad(Op, DAG); 7957 // v3 loads not supported on SI. 7958 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7959 return WidenVectorLoad(Op, DAG); 7960 return SDValue(); 7961 default: 7962 llvm_unreachable("unsupported private_element_size"); 7963 } 7964 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7965 // Use ds_read_b128 or ds_read_b96 when possible. 7966 if (Subtarget->hasDS96AndDS128() && 7967 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 7968 MemVT.getStoreSize() == 12) && 7969 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 7970 Load->getAlign())) 7971 return SDValue(); 7972 7973 if (NumElements > 2) 7974 return SplitVectorLoad(Op, DAG); 7975 7976 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7977 // address is negative, then the instruction is incorrectly treated as 7978 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7979 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7980 // load later in the SILoadStoreOptimizer. 7981 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7982 NumElements == 2 && MemVT.getStoreSize() == 8 && 7983 Load->getAlignment() < 8) { 7984 return SplitVectorLoad(Op, DAG); 7985 } 7986 } 7987 return SDValue(); 7988 } 7989 7990 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7991 EVT VT = Op.getValueType(); 7992 assert(VT.getSizeInBits() == 64); 7993 7994 SDLoc DL(Op); 7995 SDValue Cond = Op.getOperand(0); 7996 7997 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7998 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7999 8000 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8001 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8002 8003 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8004 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8005 8006 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8007 8008 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8009 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8010 8011 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8012 8013 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8014 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8015 } 8016 8017 // Catch division cases where we can use shortcuts with rcp and rsq 8018 // instructions. 8019 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8020 SelectionDAG &DAG) const { 8021 SDLoc SL(Op); 8022 SDValue LHS = Op.getOperand(0); 8023 SDValue RHS = Op.getOperand(1); 8024 EVT VT = Op.getValueType(); 8025 const SDNodeFlags Flags = Op->getFlags(); 8026 8027 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8028 Flags.hasApproximateFuncs(); 8029 8030 // Without !fpmath accuracy information, we can't do more because we don't 8031 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8032 if (!AllowInaccurateRcp) 8033 return SDValue(); 8034 8035 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8036 if (CLHS->isExactlyValue(1.0)) { 8037 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8038 // the CI documentation has a worst case error of 1 ulp. 8039 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8040 // use it as long as we aren't trying to use denormals. 8041 // 8042 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8043 8044 // 1.0 / sqrt(x) -> rsq(x) 8045 8046 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8047 // error seems really high at 2^29 ULP. 8048 if (RHS.getOpcode() == ISD::FSQRT) 8049 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8050 8051 // 1.0 / x -> rcp(x) 8052 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8053 } 8054 8055 // Same as for 1.0, but expand the sign out of the constant. 8056 if (CLHS->isExactlyValue(-1.0)) { 8057 // -1.0 / x -> rcp (fneg x) 8058 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8059 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8060 } 8061 } 8062 8063 // Turn into multiply by the reciprocal. 8064 // x / y -> x * (1.0 / y) 8065 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8066 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8067 } 8068 8069 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8070 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8071 SDNodeFlags Flags) { 8072 if (GlueChain->getNumValues() <= 1) { 8073 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8074 } 8075 8076 assert(GlueChain->getNumValues() == 3); 8077 8078 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8079 switch (Opcode) { 8080 default: llvm_unreachable("no chain equivalent for opcode"); 8081 case ISD::FMUL: 8082 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8083 break; 8084 } 8085 8086 return DAG.getNode(Opcode, SL, VTList, 8087 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8088 Flags); 8089 } 8090 8091 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8092 EVT VT, SDValue A, SDValue B, SDValue C, 8093 SDValue GlueChain, SDNodeFlags Flags) { 8094 if (GlueChain->getNumValues() <= 1) { 8095 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8096 } 8097 8098 assert(GlueChain->getNumValues() == 3); 8099 8100 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8101 switch (Opcode) { 8102 default: llvm_unreachable("no chain equivalent for opcode"); 8103 case ISD::FMA: 8104 Opcode = AMDGPUISD::FMA_W_CHAIN; 8105 break; 8106 } 8107 8108 return DAG.getNode(Opcode, SL, VTList, 8109 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8110 Flags); 8111 } 8112 8113 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8114 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8115 return FastLowered; 8116 8117 SDLoc SL(Op); 8118 SDValue Src0 = Op.getOperand(0); 8119 SDValue Src1 = Op.getOperand(1); 8120 8121 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8122 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8123 8124 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8125 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8126 8127 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8128 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8129 8130 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8131 } 8132 8133 // Faster 2.5 ULP division that does not support denormals. 8134 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8135 SDLoc SL(Op); 8136 SDValue LHS = Op.getOperand(1); 8137 SDValue RHS = Op.getOperand(2); 8138 8139 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8140 8141 const APFloat K0Val(BitsToFloat(0x6f800000)); 8142 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8143 8144 const APFloat K1Val(BitsToFloat(0x2f800000)); 8145 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8146 8147 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8148 8149 EVT SetCCVT = 8150 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8151 8152 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8153 8154 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8155 8156 // TODO: Should this propagate fast-math-flags? 8157 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8158 8159 // rcp does not support denormals. 8160 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8161 8162 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8163 8164 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8165 } 8166 8167 // Returns immediate value for setting the F32 denorm mode when using the 8168 // S_DENORM_MODE instruction. 8169 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8170 const SDLoc &SL, const GCNSubtarget *ST) { 8171 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8172 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8173 ? FP_DENORM_FLUSH_NONE 8174 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8175 8176 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8177 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8178 } 8179 8180 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8181 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8182 return FastLowered; 8183 8184 // The selection matcher assumes anything with a chain selecting to a 8185 // mayRaiseFPException machine instruction. Since we're introducing a chain 8186 // here, we need to explicitly report nofpexcept for the regular fdiv 8187 // lowering. 8188 SDNodeFlags Flags = Op->getFlags(); 8189 Flags.setNoFPExcept(true); 8190 8191 SDLoc SL(Op); 8192 SDValue LHS = Op.getOperand(0); 8193 SDValue RHS = Op.getOperand(1); 8194 8195 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8196 8197 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8198 8199 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8200 {RHS, RHS, LHS}, Flags); 8201 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8202 {LHS, RHS, LHS}, Flags); 8203 8204 // Denominator is scaled to not be denormal, so using rcp is ok. 8205 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8206 DenominatorScaled, Flags); 8207 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8208 DenominatorScaled, Flags); 8209 8210 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8211 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8212 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8213 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8214 8215 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8216 8217 if (!HasFP32Denormals) { 8218 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8219 // lowering. The chain dependence is insufficient, and we need glue. We do 8220 // not need the glue variants in a strictfp function. 8221 8222 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8223 8224 SDNode *EnableDenorm; 8225 if (Subtarget->hasDenormModeInst()) { 8226 const SDValue EnableDenormValue = 8227 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8228 8229 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8230 DAG.getEntryNode(), EnableDenormValue).getNode(); 8231 } else { 8232 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8233 SL, MVT::i32); 8234 EnableDenorm = 8235 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8236 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8237 } 8238 8239 SDValue Ops[3] = { 8240 NegDivScale0, 8241 SDValue(EnableDenorm, 0), 8242 SDValue(EnableDenorm, 1) 8243 }; 8244 8245 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8246 } 8247 8248 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8249 ApproxRcp, One, NegDivScale0, Flags); 8250 8251 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8252 ApproxRcp, Fma0, Flags); 8253 8254 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8255 Fma1, Fma1, Flags); 8256 8257 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8258 NumeratorScaled, Mul, Flags); 8259 8260 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8261 Fma2, Fma1, Mul, Fma2, Flags); 8262 8263 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8264 NumeratorScaled, Fma3, Flags); 8265 8266 if (!HasFP32Denormals) { 8267 SDNode *DisableDenorm; 8268 if (Subtarget->hasDenormModeInst()) { 8269 const SDValue DisableDenormValue = 8270 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8271 8272 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8273 Fma4.getValue(1), DisableDenormValue, 8274 Fma4.getValue(2)).getNode(); 8275 } else { 8276 const SDValue DisableDenormValue = 8277 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8278 8279 DisableDenorm = DAG.getMachineNode( 8280 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8281 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8282 } 8283 8284 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8285 SDValue(DisableDenorm, 0), DAG.getRoot()); 8286 DAG.setRoot(OutputChain); 8287 } 8288 8289 SDValue Scale = NumeratorScaled.getValue(1); 8290 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8291 {Fma4, Fma1, Fma3, Scale}, Flags); 8292 8293 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8294 } 8295 8296 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8297 if (DAG.getTarget().Options.UnsafeFPMath) 8298 return lowerFastUnsafeFDIV(Op, DAG); 8299 8300 SDLoc SL(Op); 8301 SDValue X = Op.getOperand(0); 8302 SDValue Y = Op.getOperand(1); 8303 8304 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8305 8306 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8307 8308 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8309 8310 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8311 8312 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8313 8314 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8315 8316 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8317 8318 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8319 8320 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8321 8322 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8323 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8324 8325 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8326 NegDivScale0, Mul, DivScale1); 8327 8328 SDValue Scale; 8329 8330 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8331 // Workaround a hardware bug on SI where the condition output from div_scale 8332 // is not usable. 8333 8334 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8335 8336 // Figure out if the scale to use for div_fmas. 8337 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8338 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8339 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8340 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8341 8342 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8343 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8344 8345 SDValue Scale0Hi 8346 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8347 SDValue Scale1Hi 8348 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8349 8350 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8351 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8352 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8353 } else { 8354 Scale = DivScale1.getValue(1); 8355 } 8356 8357 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8358 Fma4, Fma3, Mul, Scale); 8359 8360 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8361 } 8362 8363 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8364 EVT VT = Op.getValueType(); 8365 8366 if (VT == MVT::f32) 8367 return LowerFDIV32(Op, DAG); 8368 8369 if (VT == MVT::f64) 8370 return LowerFDIV64(Op, DAG); 8371 8372 if (VT == MVT::f16) 8373 return LowerFDIV16(Op, DAG); 8374 8375 llvm_unreachable("Unexpected type for fdiv"); 8376 } 8377 8378 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8379 SDLoc DL(Op); 8380 StoreSDNode *Store = cast<StoreSDNode>(Op); 8381 EVT VT = Store->getMemoryVT(); 8382 8383 if (VT == MVT::i1) { 8384 return DAG.getTruncStore(Store->getChain(), DL, 8385 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8386 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8387 } 8388 8389 assert(VT.isVector() && 8390 Store->getValue().getValueType().getScalarType() == MVT::i32); 8391 8392 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8393 VT, *Store->getMemOperand())) { 8394 return expandUnalignedStore(Store, DAG); 8395 } 8396 8397 unsigned AS = Store->getAddressSpace(); 8398 if (Subtarget->hasLDSMisalignedBug() && 8399 AS == AMDGPUAS::FLAT_ADDRESS && 8400 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8401 return SplitVectorStore(Op, DAG); 8402 } 8403 8404 MachineFunction &MF = DAG.getMachineFunction(); 8405 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8406 // If there is a possibilty that flat instruction access scratch memory 8407 // then we need to use the same legalization rules we use for private. 8408 if (AS == AMDGPUAS::FLAT_ADDRESS && 8409 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8410 AS = MFI->hasFlatScratchInit() ? 8411 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8412 8413 unsigned NumElements = VT.getVectorNumElements(); 8414 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8415 AS == AMDGPUAS::FLAT_ADDRESS) { 8416 if (NumElements > 4) 8417 return SplitVectorStore(Op, DAG); 8418 // v3 stores not supported on SI. 8419 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8420 return SplitVectorStore(Op, DAG); 8421 return SDValue(); 8422 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8423 switch (Subtarget->getMaxPrivateElementSize()) { 8424 case 4: 8425 return scalarizeVectorStore(Store, DAG); 8426 case 8: 8427 if (NumElements > 2) 8428 return SplitVectorStore(Op, DAG); 8429 return SDValue(); 8430 case 16: 8431 if (NumElements > 4 || NumElements == 3) 8432 return SplitVectorStore(Op, DAG); 8433 return SDValue(); 8434 default: 8435 llvm_unreachable("unsupported private_element_size"); 8436 } 8437 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8438 // Use ds_write_b128 or ds_write_b96 when possible. 8439 if (Subtarget->hasDS96AndDS128() && 8440 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8441 (VT.getStoreSize() == 12)) && 8442 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8443 Store->getAlign())) 8444 return SDValue(); 8445 8446 if (NumElements > 2) 8447 return SplitVectorStore(Op, DAG); 8448 8449 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8450 // address is negative, then the instruction is incorrectly treated as 8451 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8452 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8453 // store later in the SILoadStoreOptimizer. 8454 if (!Subtarget->hasUsableDSOffset() && 8455 NumElements == 2 && VT.getStoreSize() == 8 && 8456 Store->getAlignment() < 8) { 8457 return SplitVectorStore(Op, DAG); 8458 } 8459 8460 return SDValue(); 8461 } else { 8462 llvm_unreachable("unhandled address space"); 8463 } 8464 } 8465 8466 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8467 SDLoc DL(Op); 8468 EVT VT = Op.getValueType(); 8469 SDValue Arg = Op.getOperand(0); 8470 SDValue TrigVal; 8471 8472 // Propagate fast-math flags so that the multiply we introduce can be folded 8473 // if Arg is already the result of a multiply by constant. 8474 auto Flags = Op->getFlags(); 8475 8476 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8477 8478 if (Subtarget->hasTrigReducedRange()) { 8479 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8480 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8481 } else { 8482 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8483 } 8484 8485 switch (Op.getOpcode()) { 8486 case ISD::FCOS: 8487 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8488 case ISD::FSIN: 8489 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8490 default: 8491 llvm_unreachable("Wrong trig opcode"); 8492 } 8493 } 8494 8495 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8496 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8497 assert(AtomicNode->isCompareAndSwap()); 8498 unsigned AS = AtomicNode->getAddressSpace(); 8499 8500 // No custom lowering required for local address space 8501 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8502 return Op; 8503 8504 // Non-local address space requires custom lowering for atomic compare 8505 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8506 SDLoc DL(Op); 8507 SDValue ChainIn = Op.getOperand(0); 8508 SDValue Addr = Op.getOperand(1); 8509 SDValue Old = Op.getOperand(2); 8510 SDValue New = Op.getOperand(3); 8511 EVT VT = Op.getValueType(); 8512 MVT SimpleVT = VT.getSimpleVT(); 8513 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8514 8515 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8516 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8517 8518 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8519 Ops, VT, AtomicNode->getMemOperand()); 8520 } 8521 8522 //===----------------------------------------------------------------------===// 8523 // Custom DAG optimizations 8524 //===----------------------------------------------------------------------===// 8525 8526 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8527 DAGCombinerInfo &DCI) const { 8528 EVT VT = N->getValueType(0); 8529 EVT ScalarVT = VT.getScalarType(); 8530 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8531 return SDValue(); 8532 8533 SelectionDAG &DAG = DCI.DAG; 8534 SDLoc DL(N); 8535 8536 SDValue Src = N->getOperand(0); 8537 EVT SrcVT = Src.getValueType(); 8538 8539 // TODO: We could try to match extracting the higher bytes, which would be 8540 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8541 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8542 // about in practice. 8543 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8544 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8545 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8546 DCI.AddToWorklist(Cvt.getNode()); 8547 8548 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8549 if (ScalarVT != MVT::f32) { 8550 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8551 DAG.getTargetConstant(0, DL, MVT::i32)); 8552 } 8553 return Cvt; 8554 } 8555 } 8556 8557 return SDValue(); 8558 } 8559 8560 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8561 8562 // This is a variant of 8563 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8564 // 8565 // The normal DAG combiner will do this, but only if the add has one use since 8566 // that would increase the number of instructions. 8567 // 8568 // This prevents us from seeing a constant offset that can be folded into a 8569 // memory instruction's addressing mode. If we know the resulting add offset of 8570 // a pointer can be folded into an addressing offset, we can replace the pointer 8571 // operand with the add of new constant offset. This eliminates one of the uses, 8572 // and may allow the remaining use to also be simplified. 8573 // 8574 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8575 unsigned AddrSpace, 8576 EVT MemVT, 8577 DAGCombinerInfo &DCI) const { 8578 SDValue N0 = N->getOperand(0); 8579 SDValue N1 = N->getOperand(1); 8580 8581 // We only do this to handle cases where it's profitable when there are 8582 // multiple uses of the add, so defer to the standard combine. 8583 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8584 N0->hasOneUse()) 8585 return SDValue(); 8586 8587 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8588 if (!CN1) 8589 return SDValue(); 8590 8591 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8592 if (!CAdd) 8593 return SDValue(); 8594 8595 // If the resulting offset is too large, we can't fold it into the addressing 8596 // mode offset. 8597 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8598 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8599 8600 AddrMode AM; 8601 AM.HasBaseReg = true; 8602 AM.BaseOffs = Offset.getSExtValue(); 8603 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8604 return SDValue(); 8605 8606 SelectionDAG &DAG = DCI.DAG; 8607 SDLoc SL(N); 8608 EVT VT = N->getValueType(0); 8609 8610 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8611 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8612 8613 SDNodeFlags Flags; 8614 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8615 (N0.getOpcode() == ISD::OR || 8616 N0->getFlags().hasNoUnsignedWrap())); 8617 8618 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8619 } 8620 8621 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8622 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8623 /// specific intrinsic, but they all place the pointer operand first. 8624 static unsigned getBasePtrIndex(const MemSDNode *N) { 8625 switch (N->getOpcode()) { 8626 case ISD::STORE: 8627 case ISD::INTRINSIC_W_CHAIN: 8628 case ISD::INTRINSIC_VOID: 8629 return 2; 8630 default: 8631 return 1; 8632 } 8633 } 8634 8635 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8636 DAGCombinerInfo &DCI) const { 8637 SelectionDAG &DAG = DCI.DAG; 8638 SDLoc SL(N); 8639 8640 unsigned PtrIdx = getBasePtrIndex(N); 8641 SDValue Ptr = N->getOperand(PtrIdx); 8642 8643 // TODO: We could also do this for multiplies. 8644 if (Ptr.getOpcode() == ISD::SHL) { 8645 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8646 N->getMemoryVT(), DCI); 8647 if (NewPtr) { 8648 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8649 8650 NewOps[PtrIdx] = NewPtr; 8651 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8652 } 8653 } 8654 8655 return SDValue(); 8656 } 8657 8658 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8659 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8660 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8661 (Opc == ISD::XOR && Val == 0); 8662 } 8663 8664 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8665 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8666 // integer combine opportunities since most 64-bit operations are decomposed 8667 // this way. TODO: We won't want this for SALU especially if it is an inline 8668 // immediate. 8669 SDValue SITargetLowering::splitBinaryBitConstantOp( 8670 DAGCombinerInfo &DCI, 8671 const SDLoc &SL, 8672 unsigned Opc, SDValue LHS, 8673 const ConstantSDNode *CRHS) const { 8674 uint64_t Val = CRHS->getZExtValue(); 8675 uint32_t ValLo = Lo_32(Val); 8676 uint32_t ValHi = Hi_32(Val); 8677 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8678 8679 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8680 bitOpWithConstantIsReducible(Opc, ValHi)) || 8681 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8682 // If we need to materialize a 64-bit immediate, it will be split up later 8683 // anyway. Avoid creating the harder to understand 64-bit immediate 8684 // materialization. 8685 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8686 } 8687 8688 return SDValue(); 8689 } 8690 8691 // Returns true if argument is a boolean value which is not serialized into 8692 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8693 static bool isBoolSGPR(SDValue V) { 8694 if (V.getValueType() != MVT::i1) 8695 return false; 8696 switch (V.getOpcode()) { 8697 default: break; 8698 case ISD::SETCC: 8699 case ISD::AND: 8700 case ISD::OR: 8701 case ISD::XOR: 8702 case AMDGPUISD::FP_CLASS: 8703 return true; 8704 } 8705 return false; 8706 } 8707 8708 // If a constant has all zeroes or all ones within each byte return it. 8709 // Otherwise return 0. 8710 static uint32_t getConstantPermuteMask(uint32_t C) { 8711 // 0xff for any zero byte in the mask 8712 uint32_t ZeroByteMask = 0; 8713 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8714 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8715 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8716 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8717 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8718 if ((NonZeroByteMask & C) != NonZeroByteMask) 8719 return 0; // Partial bytes selected. 8720 return C; 8721 } 8722 8723 // Check if a node selects whole bytes from its operand 0 starting at a byte 8724 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8725 // or -1 if not succeeded. 8726 // Note byte select encoding: 8727 // value 0-3 selects corresponding source byte; 8728 // value 0xc selects zero; 8729 // value 0xff selects 0xff. 8730 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8731 assert(V.getValueSizeInBits() == 32); 8732 8733 if (V.getNumOperands() != 2) 8734 return ~0; 8735 8736 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8737 if (!N1) 8738 return ~0; 8739 8740 uint32_t C = N1->getZExtValue(); 8741 8742 switch (V.getOpcode()) { 8743 default: 8744 break; 8745 case ISD::AND: 8746 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8747 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8748 } 8749 break; 8750 8751 case ISD::OR: 8752 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8753 return (0x03020100 & ~ConstMask) | ConstMask; 8754 } 8755 break; 8756 8757 case ISD::SHL: 8758 if (C % 8) 8759 return ~0; 8760 8761 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8762 8763 case ISD::SRL: 8764 if (C % 8) 8765 return ~0; 8766 8767 return uint32_t(0x0c0c0c0c03020100ull >> C); 8768 } 8769 8770 return ~0; 8771 } 8772 8773 SDValue SITargetLowering::performAndCombine(SDNode *N, 8774 DAGCombinerInfo &DCI) const { 8775 if (DCI.isBeforeLegalize()) 8776 return SDValue(); 8777 8778 SelectionDAG &DAG = DCI.DAG; 8779 EVT VT = N->getValueType(0); 8780 SDValue LHS = N->getOperand(0); 8781 SDValue RHS = N->getOperand(1); 8782 8783 8784 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8785 if (VT == MVT::i64 && CRHS) { 8786 if (SDValue Split 8787 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8788 return Split; 8789 } 8790 8791 if (CRHS && VT == MVT::i32) { 8792 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8793 // nb = number of trailing zeroes in mask 8794 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8795 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8796 uint64_t Mask = CRHS->getZExtValue(); 8797 unsigned Bits = countPopulation(Mask); 8798 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8799 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8800 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8801 unsigned Shift = CShift->getZExtValue(); 8802 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8803 unsigned Offset = NB + Shift; 8804 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8805 SDLoc SL(N); 8806 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8807 LHS->getOperand(0), 8808 DAG.getConstant(Offset, SL, MVT::i32), 8809 DAG.getConstant(Bits, SL, MVT::i32)); 8810 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8811 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8812 DAG.getValueType(NarrowVT)); 8813 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8814 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8815 return Shl; 8816 } 8817 } 8818 } 8819 8820 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8821 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8822 isa<ConstantSDNode>(LHS.getOperand(2))) { 8823 uint32_t Sel = getConstantPermuteMask(Mask); 8824 if (!Sel) 8825 return SDValue(); 8826 8827 // Select 0xc for all zero bytes 8828 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8829 SDLoc DL(N); 8830 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8831 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8832 } 8833 } 8834 8835 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8836 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8837 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8838 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8839 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8840 8841 SDValue X = LHS.getOperand(0); 8842 SDValue Y = RHS.getOperand(0); 8843 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8844 return SDValue(); 8845 8846 if (LCC == ISD::SETO) { 8847 if (X != LHS.getOperand(1)) 8848 return SDValue(); 8849 8850 if (RCC == ISD::SETUNE) { 8851 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8852 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8853 return SDValue(); 8854 8855 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8856 SIInstrFlags::N_SUBNORMAL | 8857 SIInstrFlags::N_ZERO | 8858 SIInstrFlags::P_ZERO | 8859 SIInstrFlags::P_SUBNORMAL | 8860 SIInstrFlags::P_NORMAL; 8861 8862 static_assert(((~(SIInstrFlags::S_NAN | 8863 SIInstrFlags::Q_NAN | 8864 SIInstrFlags::N_INFINITY | 8865 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8866 "mask not equal"); 8867 8868 SDLoc DL(N); 8869 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8870 X, DAG.getConstant(Mask, DL, MVT::i32)); 8871 } 8872 } 8873 } 8874 8875 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8876 std::swap(LHS, RHS); 8877 8878 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8879 RHS.hasOneUse()) { 8880 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8881 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8882 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8883 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8884 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8885 (RHS.getOperand(0) == LHS.getOperand(0) && 8886 LHS.getOperand(0) == LHS.getOperand(1))) { 8887 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8888 unsigned NewMask = LCC == ISD::SETO ? 8889 Mask->getZExtValue() & ~OrdMask : 8890 Mask->getZExtValue() & OrdMask; 8891 8892 SDLoc DL(N); 8893 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8894 DAG.getConstant(NewMask, DL, MVT::i32)); 8895 } 8896 } 8897 8898 if (VT == MVT::i32 && 8899 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8900 // and x, (sext cc from i1) => select cc, x, 0 8901 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8902 std::swap(LHS, RHS); 8903 if (isBoolSGPR(RHS.getOperand(0))) 8904 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8905 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8906 } 8907 8908 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8909 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8910 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8911 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8912 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8913 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8914 if (LHSMask != ~0u && RHSMask != ~0u) { 8915 // Canonicalize the expression in an attempt to have fewer unique masks 8916 // and therefore fewer registers used to hold the masks. 8917 if (LHSMask > RHSMask) { 8918 std::swap(LHSMask, RHSMask); 8919 std::swap(LHS, RHS); 8920 } 8921 8922 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8923 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8924 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8925 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8926 8927 // Check of we need to combine values from two sources within a byte. 8928 if (!(LHSUsedLanes & RHSUsedLanes) && 8929 // If we select high and lower word keep it for SDWA. 8930 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8931 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8932 // Each byte in each mask is either selector mask 0-3, or has higher 8933 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8934 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8935 // mask which is not 0xff wins. By anding both masks we have a correct 8936 // result except that 0x0c shall be corrected to give 0x0c only. 8937 uint32_t Mask = LHSMask & RHSMask; 8938 for (unsigned I = 0; I < 32; I += 8) { 8939 uint32_t ByteSel = 0xff << I; 8940 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8941 Mask &= (0x0c << I) & 0xffffffff; 8942 } 8943 8944 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8945 // or 0x0c. 8946 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8947 SDLoc DL(N); 8948 8949 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8950 LHS.getOperand(0), RHS.getOperand(0), 8951 DAG.getConstant(Sel, DL, MVT::i32)); 8952 } 8953 } 8954 } 8955 8956 return SDValue(); 8957 } 8958 8959 SDValue SITargetLowering::performOrCombine(SDNode *N, 8960 DAGCombinerInfo &DCI) const { 8961 SelectionDAG &DAG = DCI.DAG; 8962 SDValue LHS = N->getOperand(0); 8963 SDValue RHS = N->getOperand(1); 8964 8965 EVT VT = N->getValueType(0); 8966 if (VT == MVT::i1) { 8967 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8968 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8969 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8970 SDValue Src = LHS.getOperand(0); 8971 if (Src != RHS.getOperand(0)) 8972 return SDValue(); 8973 8974 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8975 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8976 if (!CLHS || !CRHS) 8977 return SDValue(); 8978 8979 // Only 10 bits are used. 8980 static const uint32_t MaxMask = 0x3ff; 8981 8982 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8983 SDLoc DL(N); 8984 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8985 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8986 } 8987 8988 return SDValue(); 8989 } 8990 8991 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8992 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8993 LHS.getOpcode() == AMDGPUISD::PERM && 8994 isa<ConstantSDNode>(LHS.getOperand(2))) { 8995 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8996 if (!Sel) 8997 return SDValue(); 8998 8999 Sel |= LHS.getConstantOperandVal(2); 9000 SDLoc DL(N); 9001 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9002 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9003 } 9004 9005 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9006 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9007 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9008 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9009 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9010 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9011 if (LHSMask != ~0u && RHSMask != ~0u) { 9012 // Canonicalize the expression in an attempt to have fewer unique masks 9013 // and therefore fewer registers used to hold the masks. 9014 if (LHSMask > RHSMask) { 9015 std::swap(LHSMask, RHSMask); 9016 std::swap(LHS, RHS); 9017 } 9018 9019 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9020 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9021 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9022 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9023 9024 // Check of we need to combine values from two sources within a byte. 9025 if (!(LHSUsedLanes & RHSUsedLanes) && 9026 // If we select high and lower word keep it for SDWA. 9027 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9028 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9029 // Kill zero bytes selected by other mask. Zero value is 0xc. 9030 LHSMask &= ~RHSUsedLanes; 9031 RHSMask &= ~LHSUsedLanes; 9032 // Add 4 to each active LHS lane 9033 LHSMask |= LHSUsedLanes & 0x04040404; 9034 // Combine masks 9035 uint32_t Sel = LHSMask | RHSMask; 9036 SDLoc DL(N); 9037 9038 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9039 LHS.getOperand(0), RHS.getOperand(0), 9040 DAG.getConstant(Sel, DL, MVT::i32)); 9041 } 9042 } 9043 } 9044 9045 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9046 return SDValue(); 9047 9048 // TODO: This could be a generic combine with a predicate for extracting the 9049 // high half of an integer being free. 9050 9051 // (or i64:x, (zero_extend i32:y)) -> 9052 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9053 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9054 RHS.getOpcode() != ISD::ZERO_EXTEND) 9055 std::swap(LHS, RHS); 9056 9057 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9058 SDValue ExtSrc = RHS.getOperand(0); 9059 EVT SrcVT = ExtSrc.getValueType(); 9060 if (SrcVT == MVT::i32) { 9061 SDLoc SL(N); 9062 SDValue LowLHS, HiBits; 9063 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9064 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9065 9066 DCI.AddToWorklist(LowOr.getNode()); 9067 DCI.AddToWorklist(HiBits.getNode()); 9068 9069 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9070 LowOr, HiBits); 9071 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9072 } 9073 } 9074 9075 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9076 if (CRHS) { 9077 if (SDValue Split 9078 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9079 return Split; 9080 } 9081 9082 return SDValue(); 9083 } 9084 9085 SDValue SITargetLowering::performXorCombine(SDNode *N, 9086 DAGCombinerInfo &DCI) const { 9087 EVT VT = N->getValueType(0); 9088 if (VT != MVT::i64) 9089 return SDValue(); 9090 9091 SDValue LHS = N->getOperand(0); 9092 SDValue RHS = N->getOperand(1); 9093 9094 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9095 if (CRHS) { 9096 if (SDValue Split 9097 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9098 return Split; 9099 } 9100 9101 return SDValue(); 9102 } 9103 9104 // Instructions that will be lowered with a final instruction that zeros the 9105 // high result bits. 9106 // XXX - probably only need to list legal operations. 9107 static bool fp16SrcZerosHighBits(unsigned Opc) { 9108 switch (Opc) { 9109 case ISD::FADD: 9110 case ISD::FSUB: 9111 case ISD::FMUL: 9112 case ISD::FDIV: 9113 case ISD::FREM: 9114 case ISD::FMA: 9115 case ISD::FMAD: 9116 case ISD::FCANONICALIZE: 9117 case ISD::FP_ROUND: 9118 case ISD::UINT_TO_FP: 9119 case ISD::SINT_TO_FP: 9120 case ISD::FABS: 9121 // Fabs is lowered to a bit operation, but it's an and which will clear the 9122 // high bits anyway. 9123 case ISD::FSQRT: 9124 case ISD::FSIN: 9125 case ISD::FCOS: 9126 case ISD::FPOWI: 9127 case ISD::FPOW: 9128 case ISD::FLOG: 9129 case ISD::FLOG2: 9130 case ISD::FLOG10: 9131 case ISD::FEXP: 9132 case ISD::FEXP2: 9133 case ISD::FCEIL: 9134 case ISD::FTRUNC: 9135 case ISD::FRINT: 9136 case ISD::FNEARBYINT: 9137 case ISD::FROUND: 9138 case ISD::FFLOOR: 9139 case ISD::FMINNUM: 9140 case ISD::FMAXNUM: 9141 case AMDGPUISD::FRACT: 9142 case AMDGPUISD::CLAMP: 9143 case AMDGPUISD::COS_HW: 9144 case AMDGPUISD::SIN_HW: 9145 case AMDGPUISD::FMIN3: 9146 case AMDGPUISD::FMAX3: 9147 case AMDGPUISD::FMED3: 9148 case AMDGPUISD::FMAD_FTZ: 9149 case AMDGPUISD::RCP: 9150 case AMDGPUISD::RSQ: 9151 case AMDGPUISD::RCP_IFLAG: 9152 case AMDGPUISD::LDEXP: 9153 return true; 9154 default: 9155 // fcopysign, select and others may be lowered to 32-bit bit operations 9156 // which don't zero the high bits. 9157 return false; 9158 } 9159 } 9160 9161 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9162 DAGCombinerInfo &DCI) const { 9163 if (!Subtarget->has16BitInsts() || 9164 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9165 return SDValue(); 9166 9167 EVT VT = N->getValueType(0); 9168 if (VT != MVT::i32) 9169 return SDValue(); 9170 9171 SDValue Src = N->getOperand(0); 9172 if (Src.getValueType() != MVT::i16) 9173 return SDValue(); 9174 9175 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9176 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9177 if (Src.getOpcode() == ISD::BITCAST) { 9178 SDValue BCSrc = Src.getOperand(0); 9179 if (BCSrc.getValueType() == MVT::f16 && 9180 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9181 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9182 } 9183 9184 return SDValue(); 9185 } 9186 9187 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9188 DAGCombinerInfo &DCI) 9189 const { 9190 SDValue Src = N->getOperand(0); 9191 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9192 9193 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9194 VTSign->getVT() == MVT::i8) || 9195 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9196 VTSign->getVT() == MVT::i16)) && 9197 Src.hasOneUse()) { 9198 auto *M = cast<MemSDNode>(Src); 9199 SDValue Ops[] = { 9200 Src.getOperand(0), // Chain 9201 Src.getOperand(1), // rsrc 9202 Src.getOperand(2), // vindex 9203 Src.getOperand(3), // voffset 9204 Src.getOperand(4), // soffset 9205 Src.getOperand(5), // offset 9206 Src.getOperand(6), 9207 Src.getOperand(7) 9208 }; 9209 // replace with BUFFER_LOAD_BYTE/SHORT 9210 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9211 Src.getOperand(0).getValueType()); 9212 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9213 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9214 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9215 ResList, 9216 Ops, M->getMemoryVT(), 9217 M->getMemOperand()); 9218 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9219 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9220 } 9221 return SDValue(); 9222 } 9223 9224 SDValue SITargetLowering::performClassCombine(SDNode *N, 9225 DAGCombinerInfo &DCI) const { 9226 SelectionDAG &DAG = DCI.DAG; 9227 SDValue Mask = N->getOperand(1); 9228 9229 // fp_class x, 0 -> false 9230 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9231 if (CMask->isNullValue()) 9232 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9233 } 9234 9235 if (N->getOperand(0).isUndef()) 9236 return DAG.getUNDEF(MVT::i1); 9237 9238 return SDValue(); 9239 } 9240 9241 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9242 DAGCombinerInfo &DCI) const { 9243 EVT VT = N->getValueType(0); 9244 SDValue N0 = N->getOperand(0); 9245 9246 if (N0.isUndef()) 9247 return N0; 9248 9249 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9250 N0.getOpcode() == ISD::SINT_TO_FP)) { 9251 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9252 N->getFlags()); 9253 } 9254 9255 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9256 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9257 N0.getOperand(0), N->getFlags()); 9258 } 9259 9260 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9261 } 9262 9263 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9264 unsigned MaxDepth) const { 9265 unsigned Opcode = Op.getOpcode(); 9266 if (Opcode == ISD::FCANONICALIZE) 9267 return true; 9268 9269 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9270 auto F = CFP->getValueAPF(); 9271 if (F.isNaN() && F.isSignaling()) 9272 return false; 9273 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9274 } 9275 9276 // If source is a result of another standard FP operation it is already in 9277 // canonical form. 9278 if (MaxDepth == 0) 9279 return false; 9280 9281 switch (Opcode) { 9282 // These will flush denorms if required. 9283 case ISD::FADD: 9284 case ISD::FSUB: 9285 case ISD::FMUL: 9286 case ISD::FCEIL: 9287 case ISD::FFLOOR: 9288 case ISD::FMA: 9289 case ISD::FMAD: 9290 case ISD::FSQRT: 9291 case ISD::FDIV: 9292 case ISD::FREM: 9293 case ISD::FP_ROUND: 9294 case ISD::FP_EXTEND: 9295 case AMDGPUISD::FMUL_LEGACY: 9296 case AMDGPUISD::FMAD_FTZ: 9297 case AMDGPUISD::RCP: 9298 case AMDGPUISD::RSQ: 9299 case AMDGPUISD::RSQ_CLAMP: 9300 case AMDGPUISD::RCP_LEGACY: 9301 case AMDGPUISD::RCP_IFLAG: 9302 case AMDGPUISD::DIV_SCALE: 9303 case AMDGPUISD::DIV_FMAS: 9304 case AMDGPUISD::DIV_FIXUP: 9305 case AMDGPUISD::FRACT: 9306 case AMDGPUISD::LDEXP: 9307 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9308 case AMDGPUISD::CVT_F32_UBYTE0: 9309 case AMDGPUISD::CVT_F32_UBYTE1: 9310 case AMDGPUISD::CVT_F32_UBYTE2: 9311 case AMDGPUISD::CVT_F32_UBYTE3: 9312 return true; 9313 9314 // It can/will be lowered or combined as a bit operation. 9315 // Need to check their input recursively to handle. 9316 case ISD::FNEG: 9317 case ISD::FABS: 9318 case ISD::FCOPYSIGN: 9319 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9320 9321 case ISD::FSIN: 9322 case ISD::FCOS: 9323 case ISD::FSINCOS: 9324 return Op.getValueType().getScalarType() != MVT::f16; 9325 9326 case ISD::FMINNUM: 9327 case ISD::FMAXNUM: 9328 case ISD::FMINNUM_IEEE: 9329 case ISD::FMAXNUM_IEEE: 9330 case AMDGPUISD::CLAMP: 9331 case AMDGPUISD::FMED3: 9332 case AMDGPUISD::FMAX3: 9333 case AMDGPUISD::FMIN3: { 9334 // FIXME: Shouldn't treat the generic operations different based these. 9335 // However, we aren't really required to flush the result from 9336 // minnum/maxnum.. 9337 9338 // snans will be quieted, so we only need to worry about denormals. 9339 if (Subtarget->supportsMinMaxDenormModes() || 9340 denormalsEnabledForType(DAG, Op.getValueType())) 9341 return true; 9342 9343 // Flushing may be required. 9344 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9345 // targets need to check their input recursively. 9346 9347 // FIXME: Does this apply with clamp? It's implemented with max. 9348 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9349 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9350 return false; 9351 } 9352 9353 return true; 9354 } 9355 case ISD::SELECT: { 9356 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9357 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9358 } 9359 case ISD::BUILD_VECTOR: { 9360 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9361 SDValue SrcOp = Op.getOperand(i); 9362 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9363 return false; 9364 } 9365 9366 return true; 9367 } 9368 case ISD::EXTRACT_VECTOR_ELT: 9369 case ISD::EXTRACT_SUBVECTOR: { 9370 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9371 } 9372 case ISD::INSERT_VECTOR_ELT: { 9373 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9374 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9375 } 9376 case ISD::UNDEF: 9377 // Could be anything. 9378 return false; 9379 9380 case ISD::BITCAST: { 9381 // Hack round the mess we make when legalizing extract_vector_elt 9382 SDValue Src = Op.getOperand(0); 9383 if (Src.getValueType() == MVT::i16 && 9384 Src.getOpcode() == ISD::TRUNCATE) { 9385 SDValue TruncSrc = Src.getOperand(0); 9386 if (TruncSrc.getValueType() == MVT::i32 && 9387 TruncSrc.getOpcode() == ISD::BITCAST && 9388 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9389 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9390 } 9391 } 9392 9393 return false; 9394 } 9395 case ISD::INTRINSIC_WO_CHAIN: { 9396 unsigned IntrinsicID 9397 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9398 // TODO: Handle more intrinsics 9399 switch (IntrinsicID) { 9400 case Intrinsic::amdgcn_cvt_pkrtz: 9401 case Intrinsic::amdgcn_cubeid: 9402 case Intrinsic::amdgcn_frexp_mant: 9403 case Intrinsic::amdgcn_fdot2: 9404 case Intrinsic::amdgcn_rcp: 9405 case Intrinsic::amdgcn_rsq: 9406 case Intrinsic::amdgcn_rsq_clamp: 9407 case Intrinsic::amdgcn_rcp_legacy: 9408 case Intrinsic::amdgcn_rsq_legacy: 9409 case Intrinsic::amdgcn_trig_preop: 9410 return true; 9411 default: 9412 break; 9413 } 9414 9415 LLVM_FALLTHROUGH; 9416 } 9417 default: 9418 return denormalsEnabledForType(DAG, Op.getValueType()) && 9419 DAG.isKnownNeverSNaN(Op); 9420 } 9421 9422 llvm_unreachable("invalid operation"); 9423 } 9424 9425 // Constant fold canonicalize. 9426 SDValue SITargetLowering::getCanonicalConstantFP( 9427 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9428 // Flush denormals to 0 if not enabled. 9429 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9430 return DAG.getConstantFP(0.0, SL, VT); 9431 9432 if (C.isNaN()) { 9433 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9434 if (C.isSignaling()) { 9435 // Quiet a signaling NaN. 9436 // FIXME: Is this supposed to preserve payload bits? 9437 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9438 } 9439 9440 // Make sure it is the canonical NaN bitpattern. 9441 // 9442 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9443 // immediate? 9444 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9445 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9446 } 9447 9448 // Already canonical. 9449 return DAG.getConstantFP(C, SL, VT); 9450 } 9451 9452 static bool vectorEltWillFoldAway(SDValue Op) { 9453 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9454 } 9455 9456 SDValue SITargetLowering::performFCanonicalizeCombine( 9457 SDNode *N, 9458 DAGCombinerInfo &DCI) const { 9459 SelectionDAG &DAG = DCI.DAG; 9460 SDValue N0 = N->getOperand(0); 9461 EVT VT = N->getValueType(0); 9462 9463 // fcanonicalize undef -> qnan 9464 if (N0.isUndef()) { 9465 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9466 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9467 } 9468 9469 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9470 EVT VT = N->getValueType(0); 9471 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9472 } 9473 9474 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9475 // (fcanonicalize k) 9476 // 9477 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9478 9479 // TODO: This could be better with wider vectors that will be split to v2f16, 9480 // and to consider uses since there aren't that many packed operations. 9481 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9482 isTypeLegal(MVT::v2f16)) { 9483 SDLoc SL(N); 9484 SDValue NewElts[2]; 9485 SDValue Lo = N0.getOperand(0); 9486 SDValue Hi = N0.getOperand(1); 9487 EVT EltVT = Lo.getValueType(); 9488 9489 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9490 for (unsigned I = 0; I != 2; ++I) { 9491 SDValue Op = N0.getOperand(I); 9492 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9493 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9494 CFP->getValueAPF()); 9495 } else if (Op.isUndef()) { 9496 // Handled below based on what the other operand is. 9497 NewElts[I] = Op; 9498 } else { 9499 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9500 } 9501 } 9502 9503 // If one half is undef, and one is constant, perfer a splat vector rather 9504 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9505 // cheaper to use and may be free with a packed operation. 9506 if (NewElts[0].isUndef()) { 9507 if (isa<ConstantFPSDNode>(NewElts[1])) 9508 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9509 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9510 } 9511 9512 if (NewElts[1].isUndef()) { 9513 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9514 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9515 } 9516 9517 return DAG.getBuildVector(VT, SL, NewElts); 9518 } 9519 } 9520 9521 unsigned SrcOpc = N0.getOpcode(); 9522 9523 // If it's free to do so, push canonicalizes further up the source, which may 9524 // find a canonical source. 9525 // 9526 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9527 // sNaNs. 9528 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9529 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9530 if (CRHS && N0.hasOneUse()) { 9531 SDLoc SL(N); 9532 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9533 N0.getOperand(0)); 9534 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9535 DCI.AddToWorklist(Canon0.getNode()); 9536 9537 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9538 } 9539 } 9540 9541 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9542 } 9543 9544 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9545 switch (Opc) { 9546 case ISD::FMAXNUM: 9547 case ISD::FMAXNUM_IEEE: 9548 return AMDGPUISD::FMAX3; 9549 case ISD::SMAX: 9550 return AMDGPUISD::SMAX3; 9551 case ISD::UMAX: 9552 return AMDGPUISD::UMAX3; 9553 case ISD::FMINNUM: 9554 case ISD::FMINNUM_IEEE: 9555 return AMDGPUISD::FMIN3; 9556 case ISD::SMIN: 9557 return AMDGPUISD::SMIN3; 9558 case ISD::UMIN: 9559 return AMDGPUISD::UMIN3; 9560 default: 9561 llvm_unreachable("Not a min/max opcode"); 9562 } 9563 } 9564 9565 SDValue SITargetLowering::performIntMed3ImmCombine( 9566 SelectionDAG &DAG, const SDLoc &SL, 9567 SDValue Op0, SDValue Op1, bool Signed) const { 9568 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9569 if (!K1) 9570 return SDValue(); 9571 9572 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9573 if (!K0) 9574 return SDValue(); 9575 9576 if (Signed) { 9577 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9578 return SDValue(); 9579 } else { 9580 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9581 return SDValue(); 9582 } 9583 9584 EVT VT = K0->getValueType(0); 9585 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9586 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9587 return DAG.getNode(Med3Opc, SL, VT, 9588 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9589 } 9590 9591 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9592 MVT NVT = MVT::i32; 9593 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9594 9595 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9596 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9597 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9598 9599 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9600 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9601 } 9602 9603 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9604 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9605 return C; 9606 9607 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9608 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9609 return C; 9610 } 9611 9612 return nullptr; 9613 } 9614 9615 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9616 const SDLoc &SL, 9617 SDValue Op0, 9618 SDValue Op1) const { 9619 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9620 if (!K1) 9621 return SDValue(); 9622 9623 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9624 if (!K0) 9625 return SDValue(); 9626 9627 // Ordered >= (although NaN inputs should have folded away by now). 9628 if (K0->getValueAPF() > K1->getValueAPF()) 9629 return SDValue(); 9630 9631 const MachineFunction &MF = DAG.getMachineFunction(); 9632 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9633 9634 // TODO: Check IEEE bit enabled? 9635 EVT VT = Op0.getValueType(); 9636 if (Info->getMode().DX10Clamp) { 9637 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9638 // hardware fmed3 behavior converting to a min. 9639 // FIXME: Should this be allowing -0.0? 9640 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9641 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9642 } 9643 9644 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9645 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9646 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9647 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9648 // then give the other result, which is different from med3 with a NaN 9649 // input. 9650 SDValue Var = Op0.getOperand(0); 9651 if (!DAG.isKnownNeverSNaN(Var)) 9652 return SDValue(); 9653 9654 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9655 9656 if ((!K0->hasOneUse() || 9657 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9658 (!K1->hasOneUse() || 9659 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9660 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9661 Var, SDValue(K0, 0), SDValue(K1, 0)); 9662 } 9663 } 9664 9665 return SDValue(); 9666 } 9667 9668 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9669 DAGCombinerInfo &DCI) const { 9670 SelectionDAG &DAG = DCI.DAG; 9671 9672 EVT VT = N->getValueType(0); 9673 unsigned Opc = N->getOpcode(); 9674 SDValue Op0 = N->getOperand(0); 9675 SDValue Op1 = N->getOperand(1); 9676 9677 // Only do this if the inner op has one use since this will just increases 9678 // register pressure for no benefit. 9679 9680 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9681 !VT.isVector() && 9682 (VT == MVT::i32 || VT == MVT::f32 || 9683 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9684 // max(max(a, b), c) -> max3(a, b, c) 9685 // min(min(a, b), c) -> min3(a, b, c) 9686 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9687 SDLoc DL(N); 9688 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9689 DL, 9690 N->getValueType(0), 9691 Op0.getOperand(0), 9692 Op0.getOperand(1), 9693 Op1); 9694 } 9695 9696 // Try commuted. 9697 // max(a, max(b, c)) -> max3(a, b, c) 9698 // min(a, min(b, c)) -> min3(a, b, c) 9699 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9700 SDLoc DL(N); 9701 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9702 DL, 9703 N->getValueType(0), 9704 Op0, 9705 Op1.getOperand(0), 9706 Op1.getOperand(1)); 9707 } 9708 } 9709 9710 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9711 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9712 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9713 return Med3; 9714 } 9715 9716 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9717 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9718 return Med3; 9719 } 9720 9721 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9722 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9723 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9724 (Opc == AMDGPUISD::FMIN_LEGACY && 9725 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9726 (VT == MVT::f32 || VT == MVT::f64 || 9727 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9728 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9729 Op0.hasOneUse()) { 9730 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9731 return Res; 9732 } 9733 9734 return SDValue(); 9735 } 9736 9737 static bool isClampZeroToOne(SDValue A, SDValue B) { 9738 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9739 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9740 // FIXME: Should this be allowing -0.0? 9741 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9742 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9743 } 9744 } 9745 9746 return false; 9747 } 9748 9749 // FIXME: Should only worry about snans for version with chain. 9750 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9751 DAGCombinerInfo &DCI) const { 9752 EVT VT = N->getValueType(0); 9753 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9754 // NaNs. With a NaN input, the order of the operands may change the result. 9755 9756 SelectionDAG &DAG = DCI.DAG; 9757 SDLoc SL(N); 9758 9759 SDValue Src0 = N->getOperand(0); 9760 SDValue Src1 = N->getOperand(1); 9761 SDValue Src2 = N->getOperand(2); 9762 9763 if (isClampZeroToOne(Src0, Src1)) { 9764 // const_a, const_b, x -> clamp is safe in all cases including signaling 9765 // nans. 9766 // FIXME: Should this be allowing -0.0? 9767 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9768 } 9769 9770 const MachineFunction &MF = DAG.getMachineFunction(); 9771 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9772 9773 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9774 // handling no dx10-clamp? 9775 if (Info->getMode().DX10Clamp) { 9776 // If NaNs is clamped to 0, we are free to reorder the inputs. 9777 9778 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9779 std::swap(Src0, Src1); 9780 9781 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9782 std::swap(Src1, Src2); 9783 9784 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9785 std::swap(Src0, Src1); 9786 9787 if (isClampZeroToOne(Src1, Src2)) 9788 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9789 } 9790 9791 return SDValue(); 9792 } 9793 9794 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9795 DAGCombinerInfo &DCI) const { 9796 SDValue Src0 = N->getOperand(0); 9797 SDValue Src1 = N->getOperand(1); 9798 if (Src0.isUndef() && Src1.isUndef()) 9799 return DCI.DAG.getUNDEF(N->getValueType(0)); 9800 return SDValue(); 9801 } 9802 9803 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9804 // expanded into a set of cmp/select instructions. 9805 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9806 unsigned NumElem, 9807 bool IsDivergentIdx) { 9808 if (UseDivergentRegisterIndexing) 9809 return false; 9810 9811 unsigned VecSize = EltSize * NumElem; 9812 9813 // Sub-dword vectors of size 2 dword or less have better implementation. 9814 if (VecSize <= 64 && EltSize < 32) 9815 return false; 9816 9817 // Always expand the rest of sub-dword instructions, otherwise it will be 9818 // lowered via memory. 9819 if (EltSize < 32) 9820 return true; 9821 9822 // Always do this if var-idx is divergent, otherwise it will become a loop. 9823 if (IsDivergentIdx) 9824 return true; 9825 9826 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9827 unsigned NumInsts = NumElem /* Number of compares */ + 9828 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9829 return NumInsts <= 16; 9830 } 9831 9832 static bool shouldExpandVectorDynExt(SDNode *N) { 9833 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9834 if (isa<ConstantSDNode>(Idx)) 9835 return false; 9836 9837 SDValue Vec = N->getOperand(0); 9838 EVT VecVT = Vec.getValueType(); 9839 EVT EltVT = VecVT.getVectorElementType(); 9840 unsigned EltSize = EltVT.getSizeInBits(); 9841 unsigned NumElem = VecVT.getVectorNumElements(); 9842 9843 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9844 Idx->isDivergent()); 9845 } 9846 9847 SDValue SITargetLowering::performExtractVectorEltCombine( 9848 SDNode *N, DAGCombinerInfo &DCI) const { 9849 SDValue Vec = N->getOperand(0); 9850 SelectionDAG &DAG = DCI.DAG; 9851 9852 EVT VecVT = Vec.getValueType(); 9853 EVT EltVT = VecVT.getVectorElementType(); 9854 9855 if ((Vec.getOpcode() == ISD::FNEG || 9856 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9857 SDLoc SL(N); 9858 EVT EltVT = N->getValueType(0); 9859 SDValue Idx = N->getOperand(1); 9860 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9861 Vec.getOperand(0), Idx); 9862 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9863 } 9864 9865 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9866 // => 9867 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9868 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9869 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9870 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9871 SDLoc SL(N); 9872 EVT EltVT = N->getValueType(0); 9873 SDValue Idx = N->getOperand(1); 9874 unsigned Opc = Vec.getOpcode(); 9875 9876 switch(Opc) { 9877 default: 9878 break; 9879 // TODO: Support other binary operations. 9880 case ISD::FADD: 9881 case ISD::FSUB: 9882 case ISD::FMUL: 9883 case ISD::ADD: 9884 case ISD::UMIN: 9885 case ISD::UMAX: 9886 case ISD::SMIN: 9887 case ISD::SMAX: 9888 case ISD::FMAXNUM: 9889 case ISD::FMINNUM: 9890 case ISD::FMAXNUM_IEEE: 9891 case ISD::FMINNUM_IEEE: { 9892 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9893 Vec.getOperand(0), Idx); 9894 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9895 Vec.getOperand(1), Idx); 9896 9897 DCI.AddToWorklist(Elt0.getNode()); 9898 DCI.AddToWorklist(Elt1.getNode()); 9899 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9900 } 9901 } 9902 } 9903 9904 unsigned VecSize = VecVT.getSizeInBits(); 9905 unsigned EltSize = EltVT.getSizeInBits(); 9906 9907 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9908 if (::shouldExpandVectorDynExt(N)) { 9909 SDLoc SL(N); 9910 SDValue Idx = N->getOperand(1); 9911 SDValue V; 9912 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9913 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9914 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9915 if (I == 0) 9916 V = Elt; 9917 else 9918 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9919 } 9920 return V; 9921 } 9922 9923 if (!DCI.isBeforeLegalize()) 9924 return SDValue(); 9925 9926 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9927 // elements. This exposes more load reduction opportunities by replacing 9928 // multiple small extract_vector_elements with a single 32-bit extract. 9929 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9930 if (isa<MemSDNode>(Vec) && 9931 EltSize <= 16 && 9932 EltVT.isByteSized() && 9933 VecSize > 32 && 9934 VecSize % 32 == 0 && 9935 Idx) { 9936 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9937 9938 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9939 unsigned EltIdx = BitIndex / 32; 9940 unsigned LeftoverBitIdx = BitIndex % 32; 9941 SDLoc SL(N); 9942 9943 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9944 DCI.AddToWorklist(Cast.getNode()); 9945 9946 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9947 DAG.getConstant(EltIdx, SL, MVT::i32)); 9948 DCI.AddToWorklist(Elt.getNode()); 9949 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9950 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9951 DCI.AddToWorklist(Srl.getNode()); 9952 9953 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9954 DCI.AddToWorklist(Trunc.getNode()); 9955 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9956 } 9957 9958 return SDValue(); 9959 } 9960 9961 SDValue 9962 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9963 DAGCombinerInfo &DCI) const { 9964 SDValue Vec = N->getOperand(0); 9965 SDValue Idx = N->getOperand(2); 9966 EVT VecVT = Vec.getValueType(); 9967 EVT EltVT = VecVT.getVectorElementType(); 9968 9969 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9970 // => BUILD_VECTOR n x select (e, const-idx) 9971 if (!::shouldExpandVectorDynExt(N)) 9972 return SDValue(); 9973 9974 SelectionDAG &DAG = DCI.DAG; 9975 SDLoc SL(N); 9976 SDValue Ins = N->getOperand(1); 9977 EVT IdxVT = Idx.getValueType(); 9978 9979 SmallVector<SDValue, 16> Ops; 9980 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9981 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9982 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9983 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9984 Ops.push_back(V); 9985 } 9986 9987 return DAG.getBuildVector(VecVT, SL, Ops); 9988 } 9989 9990 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9991 const SDNode *N0, 9992 const SDNode *N1) const { 9993 EVT VT = N0->getValueType(0); 9994 9995 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9996 // support denormals ever. 9997 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9998 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9999 getSubtarget()->hasMadF16())) && 10000 isOperationLegal(ISD::FMAD, VT)) 10001 return ISD::FMAD; 10002 10003 const TargetOptions &Options = DAG.getTarget().Options; 10004 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10005 (N0->getFlags().hasAllowContract() && 10006 N1->getFlags().hasAllowContract())) && 10007 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10008 return ISD::FMA; 10009 } 10010 10011 return 0; 10012 } 10013 10014 // For a reassociatable opcode perform: 10015 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10016 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10017 SelectionDAG &DAG) const { 10018 EVT VT = N->getValueType(0); 10019 if (VT != MVT::i32 && VT != MVT::i64) 10020 return SDValue(); 10021 10022 unsigned Opc = N->getOpcode(); 10023 SDValue Op0 = N->getOperand(0); 10024 SDValue Op1 = N->getOperand(1); 10025 10026 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10027 return SDValue(); 10028 10029 if (Op0->isDivergent()) 10030 std::swap(Op0, Op1); 10031 10032 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10033 return SDValue(); 10034 10035 SDValue Op2 = Op1.getOperand(1); 10036 Op1 = Op1.getOperand(0); 10037 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10038 return SDValue(); 10039 10040 if (Op1->isDivergent()) 10041 std::swap(Op1, Op2); 10042 10043 // If either operand is constant this will conflict with 10044 // DAGCombiner::ReassociateOps(). 10045 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10046 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10047 return SDValue(); 10048 10049 SDLoc SL(N); 10050 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10051 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10052 } 10053 10054 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10055 EVT VT, 10056 SDValue N0, SDValue N1, SDValue N2, 10057 bool Signed) { 10058 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10059 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10060 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10061 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10062 } 10063 10064 SDValue SITargetLowering::performAddCombine(SDNode *N, 10065 DAGCombinerInfo &DCI) const { 10066 SelectionDAG &DAG = DCI.DAG; 10067 EVT VT = N->getValueType(0); 10068 SDLoc SL(N); 10069 SDValue LHS = N->getOperand(0); 10070 SDValue RHS = N->getOperand(1); 10071 10072 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10073 && Subtarget->hasMad64_32() && 10074 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10075 VT.getScalarSizeInBits() <= 64) { 10076 if (LHS.getOpcode() != ISD::MUL) 10077 std::swap(LHS, RHS); 10078 10079 SDValue MulLHS = LHS.getOperand(0); 10080 SDValue MulRHS = LHS.getOperand(1); 10081 SDValue AddRHS = RHS; 10082 10083 // TODO: Maybe restrict if SGPR inputs. 10084 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10085 numBitsUnsigned(MulRHS, DAG) <= 32) { 10086 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10087 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10088 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10089 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10090 } 10091 10092 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10093 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10094 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10095 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10096 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10097 } 10098 10099 return SDValue(); 10100 } 10101 10102 if (SDValue V = reassociateScalarOps(N, DAG)) { 10103 return V; 10104 } 10105 10106 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10107 return SDValue(); 10108 10109 // add x, zext (setcc) => addcarry x, 0, setcc 10110 // add x, sext (setcc) => subcarry x, 0, setcc 10111 unsigned Opc = LHS.getOpcode(); 10112 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10113 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10114 std::swap(RHS, LHS); 10115 10116 Opc = RHS.getOpcode(); 10117 switch (Opc) { 10118 default: break; 10119 case ISD::ZERO_EXTEND: 10120 case ISD::SIGN_EXTEND: 10121 case ISD::ANY_EXTEND: { 10122 auto Cond = RHS.getOperand(0); 10123 // If this won't be a real VOPC output, we would still need to insert an 10124 // extra instruction anyway. 10125 if (!isBoolSGPR(Cond)) 10126 break; 10127 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10128 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10129 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10130 return DAG.getNode(Opc, SL, VTList, Args); 10131 } 10132 case ISD::ADDCARRY: { 10133 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10134 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10135 if (!C || C->getZExtValue() != 0) break; 10136 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10137 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10138 } 10139 } 10140 return SDValue(); 10141 } 10142 10143 SDValue SITargetLowering::performSubCombine(SDNode *N, 10144 DAGCombinerInfo &DCI) const { 10145 SelectionDAG &DAG = DCI.DAG; 10146 EVT VT = N->getValueType(0); 10147 10148 if (VT != MVT::i32) 10149 return SDValue(); 10150 10151 SDLoc SL(N); 10152 SDValue LHS = N->getOperand(0); 10153 SDValue RHS = N->getOperand(1); 10154 10155 // sub x, zext (setcc) => subcarry x, 0, setcc 10156 // sub x, sext (setcc) => addcarry x, 0, setcc 10157 unsigned Opc = RHS.getOpcode(); 10158 switch (Opc) { 10159 default: break; 10160 case ISD::ZERO_EXTEND: 10161 case ISD::SIGN_EXTEND: 10162 case ISD::ANY_EXTEND: { 10163 auto Cond = RHS.getOperand(0); 10164 // If this won't be a real VOPC output, we would still need to insert an 10165 // extra instruction anyway. 10166 if (!isBoolSGPR(Cond)) 10167 break; 10168 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10169 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10170 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10171 return DAG.getNode(Opc, SL, VTList, Args); 10172 } 10173 } 10174 10175 if (LHS.getOpcode() == ISD::SUBCARRY) { 10176 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10177 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10178 if (!C || !C->isNullValue()) 10179 return SDValue(); 10180 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10181 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10182 } 10183 return SDValue(); 10184 } 10185 10186 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10187 DAGCombinerInfo &DCI) const { 10188 10189 if (N->getValueType(0) != MVT::i32) 10190 return SDValue(); 10191 10192 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10193 if (!C || C->getZExtValue() != 0) 10194 return SDValue(); 10195 10196 SelectionDAG &DAG = DCI.DAG; 10197 SDValue LHS = N->getOperand(0); 10198 10199 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10200 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10201 unsigned LHSOpc = LHS.getOpcode(); 10202 unsigned Opc = N->getOpcode(); 10203 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10204 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10205 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10206 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10207 } 10208 return SDValue(); 10209 } 10210 10211 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10212 DAGCombinerInfo &DCI) const { 10213 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10214 return SDValue(); 10215 10216 SelectionDAG &DAG = DCI.DAG; 10217 EVT VT = N->getValueType(0); 10218 10219 SDLoc SL(N); 10220 SDValue LHS = N->getOperand(0); 10221 SDValue RHS = N->getOperand(1); 10222 10223 // These should really be instruction patterns, but writing patterns with 10224 // source modiifiers is a pain. 10225 10226 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10227 if (LHS.getOpcode() == ISD::FADD) { 10228 SDValue A = LHS.getOperand(0); 10229 if (A == LHS.getOperand(1)) { 10230 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10231 if (FusedOp != 0) { 10232 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10233 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10234 } 10235 } 10236 } 10237 10238 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10239 if (RHS.getOpcode() == ISD::FADD) { 10240 SDValue A = RHS.getOperand(0); 10241 if (A == RHS.getOperand(1)) { 10242 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10243 if (FusedOp != 0) { 10244 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10245 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10246 } 10247 } 10248 } 10249 10250 return SDValue(); 10251 } 10252 10253 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10254 DAGCombinerInfo &DCI) const { 10255 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10256 return SDValue(); 10257 10258 SelectionDAG &DAG = DCI.DAG; 10259 SDLoc SL(N); 10260 EVT VT = N->getValueType(0); 10261 assert(!VT.isVector()); 10262 10263 // Try to get the fneg to fold into the source modifier. This undoes generic 10264 // DAG combines and folds them into the mad. 10265 // 10266 // Only do this if we are not trying to support denormals. v_mad_f32 does 10267 // not support denormals ever. 10268 SDValue LHS = N->getOperand(0); 10269 SDValue RHS = N->getOperand(1); 10270 if (LHS.getOpcode() == ISD::FADD) { 10271 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10272 SDValue A = LHS.getOperand(0); 10273 if (A == LHS.getOperand(1)) { 10274 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10275 if (FusedOp != 0){ 10276 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10277 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10278 10279 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10280 } 10281 } 10282 } 10283 10284 if (RHS.getOpcode() == ISD::FADD) { 10285 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10286 10287 SDValue A = RHS.getOperand(0); 10288 if (A == RHS.getOperand(1)) { 10289 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10290 if (FusedOp != 0){ 10291 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10292 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10293 } 10294 } 10295 } 10296 10297 return SDValue(); 10298 } 10299 10300 SDValue SITargetLowering::performFMACombine(SDNode *N, 10301 DAGCombinerInfo &DCI) const { 10302 SelectionDAG &DAG = DCI.DAG; 10303 EVT VT = N->getValueType(0); 10304 SDLoc SL(N); 10305 10306 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10307 return SDValue(); 10308 10309 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10310 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10311 SDValue Op1 = N->getOperand(0); 10312 SDValue Op2 = N->getOperand(1); 10313 SDValue FMA = N->getOperand(2); 10314 10315 if (FMA.getOpcode() != ISD::FMA || 10316 Op1.getOpcode() != ISD::FP_EXTEND || 10317 Op2.getOpcode() != ISD::FP_EXTEND) 10318 return SDValue(); 10319 10320 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10321 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10322 // is sufficient to allow generaing fdot2. 10323 const TargetOptions &Options = DAG.getTarget().Options; 10324 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10325 (N->getFlags().hasAllowContract() && 10326 FMA->getFlags().hasAllowContract())) { 10327 Op1 = Op1.getOperand(0); 10328 Op2 = Op2.getOperand(0); 10329 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10330 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10331 return SDValue(); 10332 10333 SDValue Vec1 = Op1.getOperand(0); 10334 SDValue Idx1 = Op1.getOperand(1); 10335 SDValue Vec2 = Op2.getOperand(0); 10336 10337 SDValue FMAOp1 = FMA.getOperand(0); 10338 SDValue FMAOp2 = FMA.getOperand(1); 10339 SDValue FMAAcc = FMA.getOperand(2); 10340 10341 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10342 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10343 return SDValue(); 10344 10345 FMAOp1 = FMAOp1.getOperand(0); 10346 FMAOp2 = FMAOp2.getOperand(0); 10347 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10348 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10349 return SDValue(); 10350 10351 SDValue Vec3 = FMAOp1.getOperand(0); 10352 SDValue Vec4 = FMAOp2.getOperand(0); 10353 SDValue Idx2 = FMAOp1.getOperand(1); 10354 10355 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10356 // Idx1 and Idx2 cannot be the same. 10357 Idx1 == Idx2) 10358 return SDValue(); 10359 10360 if (Vec1 == Vec2 || Vec3 == Vec4) 10361 return SDValue(); 10362 10363 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10364 return SDValue(); 10365 10366 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10367 (Vec1 == Vec4 && Vec2 == Vec3)) { 10368 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10369 DAG.getTargetConstant(0, SL, MVT::i1)); 10370 } 10371 } 10372 return SDValue(); 10373 } 10374 10375 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10376 DAGCombinerInfo &DCI) const { 10377 SelectionDAG &DAG = DCI.DAG; 10378 SDLoc SL(N); 10379 10380 SDValue LHS = N->getOperand(0); 10381 SDValue RHS = N->getOperand(1); 10382 EVT VT = LHS.getValueType(); 10383 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10384 10385 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10386 if (!CRHS) { 10387 CRHS = dyn_cast<ConstantSDNode>(LHS); 10388 if (CRHS) { 10389 std::swap(LHS, RHS); 10390 CC = getSetCCSwappedOperands(CC); 10391 } 10392 } 10393 10394 if (CRHS) { 10395 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10396 isBoolSGPR(LHS.getOperand(0))) { 10397 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10398 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10399 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10400 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10401 if ((CRHS->isAllOnesValue() && 10402 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10403 (CRHS->isNullValue() && 10404 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10405 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10406 DAG.getConstant(-1, SL, MVT::i1)); 10407 if ((CRHS->isAllOnesValue() && 10408 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10409 (CRHS->isNullValue() && 10410 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10411 return LHS.getOperand(0); 10412 } 10413 10414 uint64_t CRHSVal = CRHS->getZExtValue(); 10415 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10416 LHS.getOpcode() == ISD::SELECT && 10417 isa<ConstantSDNode>(LHS.getOperand(1)) && 10418 isa<ConstantSDNode>(LHS.getOperand(2)) && 10419 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10420 isBoolSGPR(LHS.getOperand(0))) { 10421 // Given CT != FT: 10422 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10423 // setcc (select cc, CT, CF), CF, ne => cc 10424 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10425 // setcc (select cc, CT, CF), CT, eq => cc 10426 uint64_t CT = LHS.getConstantOperandVal(1); 10427 uint64_t CF = LHS.getConstantOperandVal(2); 10428 10429 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10430 (CT == CRHSVal && CC == ISD::SETNE)) 10431 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10432 DAG.getConstant(-1, SL, MVT::i1)); 10433 if ((CF == CRHSVal && CC == ISD::SETNE) || 10434 (CT == CRHSVal && CC == ISD::SETEQ)) 10435 return LHS.getOperand(0); 10436 } 10437 } 10438 10439 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10440 VT != MVT::f16)) 10441 return SDValue(); 10442 10443 // Match isinf/isfinite pattern 10444 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10445 // (fcmp one (fabs x), inf) -> (fp_class x, 10446 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10447 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10448 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10449 if (!CRHS) 10450 return SDValue(); 10451 10452 const APFloat &APF = CRHS->getValueAPF(); 10453 if (APF.isInfinity() && !APF.isNegative()) { 10454 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10455 SIInstrFlags::N_INFINITY; 10456 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10457 SIInstrFlags::P_ZERO | 10458 SIInstrFlags::N_NORMAL | 10459 SIInstrFlags::P_NORMAL | 10460 SIInstrFlags::N_SUBNORMAL | 10461 SIInstrFlags::P_SUBNORMAL; 10462 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10463 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10464 DAG.getConstant(Mask, SL, MVT::i32)); 10465 } 10466 } 10467 10468 return SDValue(); 10469 } 10470 10471 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10472 DAGCombinerInfo &DCI) const { 10473 SelectionDAG &DAG = DCI.DAG; 10474 SDLoc SL(N); 10475 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10476 10477 SDValue Src = N->getOperand(0); 10478 SDValue Shift = N->getOperand(0); 10479 10480 // TODO: Extend type shouldn't matter (assuming legal types). 10481 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10482 Shift = Shift.getOperand(0); 10483 10484 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10485 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10486 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10487 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10488 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10489 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10490 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10491 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10492 SDLoc(Shift.getOperand(0)), MVT::i32); 10493 10494 unsigned ShiftOffset = 8 * Offset; 10495 if (Shift.getOpcode() == ISD::SHL) 10496 ShiftOffset -= C->getZExtValue(); 10497 else 10498 ShiftOffset += C->getZExtValue(); 10499 10500 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10501 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10502 MVT::f32, Shift); 10503 } 10504 } 10505 } 10506 10507 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10508 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10509 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10510 // We simplified Src. If this node is not dead, visit it again so it is 10511 // folded properly. 10512 if (N->getOpcode() != ISD::DELETED_NODE) 10513 DCI.AddToWorklist(N); 10514 return SDValue(N, 0); 10515 } 10516 10517 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10518 if (SDValue DemandedSrc = 10519 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10520 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10521 10522 return SDValue(); 10523 } 10524 10525 SDValue SITargetLowering::performClampCombine(SDNode *N, 10526 DAGCombinerInfo &DCI) const { 10527 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10528 if (!CSrc) 10529 return SDValue(); 10530 10531 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10532 const APFloat &F = CSrc->getValueAPF(); 10533 APFloat Zero = APFloat::getZero(F.getSemantics()); 10534 if (F < Zero || 10535 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10536 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10537 } 10538 10539 APFloat One(F.getSemantics(), "1.0"); 10540 if (F > One) 10541 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10542 10543 return SDValue(CSrc, 0); 10544 } 10545 10546 10547 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10548 DAGCombinerInfo &DCI) const { 10549 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10550 return SDValue(); 10551 switch (N->getOpcode()) { 10552 case ISD::ADD: 10553 return performAddCombine(N, DCI); 10554 case ISD::SUB: 10555 return performSubCombine(N, DCI); 10556 case ISD::ADDCARRY: 10557 case ISD::SUBCARRY: 10558 return performAddCarrySubCarryCombine(N, DCI); 10559 case ISD::FADD: 10560 return performFAddCombine(N, DCI); 10561 case ISD::FSUB: 10562 return performFSubCombine(N, DCI); 10563 case ISD::SETCC: 10564 return performSetCCCombine(N, DCI); 10565 case ISD::FMAXNUM: 10566 case ISD::FMINNUM: 10567 case ISD::FMAXNUM_IEEE: 10568 case ISD::FMINNUM_IEEE: 10569 case ISD::SMAX: 10570 case ISD::SMIN: 10571 case ISD::UMAX: 10572 case ISD::UMIN: 10573 case AMDGPUISD::FMIN_LEGACY: 10574 case AMDGPUISD::FMAX_LEGACY: 10575 return performMinMaxCombine(N, DCI); 10576 case ISD::FMA: 10577 return performFMACombine(N, DCI); 10578 case ISD::AND: 10579 return performAndCombine(N, DCI); 10580 case ISD::OR: 10581 return performOrCombine(N, DCI); 10582 case ISD::XOR: 10583 return performXorCombine(N, DCI); 10584 case ISD::ZERO_EXTEND: 10585 return performZeroExtendCombine(N, DCI); 10586 case ISD::SIGN_EXTEND_INREG: 10587 return performSignExtendInRegCombine(N , DCI); 10588 case AMDGPUISD::FP_CLASS: 10589 return performClassCombine(N, DCI); 10590 case ISD::FCANONICALIZE: 10591 return performFCanonicalizeCombine(N, DCI); 10592 case AMDGPUISD::RCP: 10593 return performRcpCombine(N, DCI); 10594 case AMDGPUISD::FRACT: 10595 case AMDGPUISD::RSQ: 10596 case AMDGPUISD::RCP_LEGACY: 10597 case AMDGPUISD::RCP_IFLAG: 10598 case AMDGPUISD::RSQ_CLAMP: 10599 case AMDGPUISD::LDEXP: { 10600 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10601 SDValue Src = N->getOperand(0); 10602 if (Src.isUndef()) 10603 return Src; 10604 break; 10605 } 10606 case ISD::SINT_TO_FP: 10607 case ISD::UINT_TO_FP: 10608 return performUCharToFloatCombine(N, DCI); 10609 case AMDGPUISD::CVT_F32_UBYTE0: 10610 case AMDGPUISD::CVT_F32_UBYTE1: 10611 case AMDGPUISD::CVT_F32_UBYTE2: 10612 case AMDGPUISD::CVT_F32_UBYTE3: 10613 return performCvtF32UByteNCombine(N, DCI); 10614 case AMDGPUISD::FMED3: 10615 return performFMed3Combine(N, DCI); 10616 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10617 return performCvtPkRTZCombine(N, DCI); 10618 case AMDGPUISD::CLAMP: 10619 return performClampCombine(N, DCI); 10620 case ISD::SCALAR_TO_VECTOR: { 10621 SelectionDAG &DAG = DCI.DAG; 10622 EVT VT = N->getValueType(0); 10623 10624 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10625 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10626 SDLoc SL(N); 10627 SDValue Src = N->getOperand(0); 10628 EVT EltVT = Src.getValueType(); 10629 if (EltVT == MVT::f16) 10630 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10631 10632 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10633 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10634 } 10635 10636 break; 10637 } 10638 case ISD::EXTRACT_VECTOR_ELT: 10639 return performExtractVectorEltCombine(N, DCI); 10640 case ISD::INSERT_VECTOR_ELT: 10641 return performInsertVectorEltCombine(N, DCI); 10642 case ISD::LOAD: { 10643 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10644 return Widended; 10645 LLVM_FALLTHROUGH; 10646 } 10647 default: { 10648 if (!DCI.isBeforeLegalize()) { 10649 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10650 return performMemSDNodeCombine(MemNode, DCI); 10651 } 10652 10653 break; 10654 } 10655 } 10656 10657 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10658 } 10659 10660 /// Helper function for adjustWritemask 10661 static unsigned SubIdx2Lane(unsigned Idx) { 10662 switch (Idx) { 10663 default: return 0; 10664 case AMDGPU::sub0: return 0; 10665 case AMDGPU::sub1: return 1; 10666 case AMDGPU::sub2: return 2; 10667 case AMDGPU::sub3: return 3; 10668 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10669 } 10670 } 10671 10672 /// Adjust the writemask of MIMG instructions 10673 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10674 SelectionDAG &DAG) const { 10675 unsigned Opcode = Node->getMachineOpcode(); 10676 10677 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10678 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10679 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10680 return Node; // not implemented for D16 10681 10682 SDNode *Users[5] = { nullptr }; 10683 unsigned Lane = 0; 10684 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10685 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10686 unsigned NewDmask = 0; 10687 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10688 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10689 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10690 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10691 unsigned TFCLane = 0; 10692 bool HasChain = Node->getNumValues() > 1; 10693 10694 if (OldDmask == 0) { 10695 // These are folded out, but on the chance it happens don't assert. 10696 return Node; 10697 } 10698 10699 unsigned OldBitsSet = countPopulation(OldDmask); 10700 // Work out which is the TFE/LWE lane if that is enabled. 10701 if (UsesTFC) { 10702 TFCLane = OldBitsSet; 10703 } 10704 10705 // Try to figure out the used register components 10706 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10707 I != E; ++I) { 10708 10709 // Don't look at users of the chain. 10710 if (I.getUse().getResNo() != 0) 10711 continue; 10712 10713 // Abort if we can't understand the usage 10714 if (!I->isMachineOpcode() || 10715 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10716 return Node; 10717 10718 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10719 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10720 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10721 // set, etc. 10722 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10723 10724 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10725 if (UsesTFC && Lane == TFCLane) { 10726 Users[Lane] = *I; 10727 } else { 10728 // Set which texture component corresponds to the lane. 10729 unsigned Comp; 10730 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10731 Comp = countTrailingZeros(Dmask); 10732 Dmask &= ~(1 << Comp); 10733 } 10734 10735 // Abort if we have more than one user per component. 10736 if (Users[Lane]) 10737 return Node; 10738 10739 Users[Lane] = *I; 10740 NewDmask |= 1 << Comp; 10741 } 10742 } 10743 10744 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10745 bool NoChannels = !NewDmask; 10746 if (NoChannels) { 10747 if (!UsesTFC) { 10748 // No uses of the result and not using TFC. Then do nothing. 10749 return Node; 10750 } 10751 // If the original dmask has one channel - then nothing to do 10752 if (OldBitsSet == 1) 10753 return Node; 10754 // Use an arbitrary dmask - required for the instruction to work 10755 NewDmask = 1; 10756 } 10757 // Abort if there's no change 10758 if (NewDmask == OldDmask) 10759 return Node; 10760 10761 unsigned BitsSet = countPopulation(NewDmask); 10762 10763 // Check for TFE or LWE - increase the number of channels by one to account 10764 // for the extra return value 10765 // This will need adjustment for D16 if this is also included in 10766 // adjustWriteMask (this function) but at present D16 are excluded. 10767 unsigned NewChannels = BitsSet + UsesTFC; 10768 10769 int NewOpcode = 10770 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10771 assert(NewOpcode != -1 && 10772 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10773 "failed to find equivalent MIMG op"); 10774 10775 // Adjust the writemask in the node 10776 SmallVector<SDValue, 12> Ops; 10777 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10778 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10779 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10780 10781 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10782 10783 MVT ResultVT = NewChannels == 1 ? 10784 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10785 NewChannels == 5 ? 8 : NewChannels); 10786 SDVTList NewVTList = HasChain ? 10787 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10788 10789 10790 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10791 NewVTList, Ops); 10792 10793 if (HasChain) { 10794 // Update chain. 10795 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10796 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10797 } 10798 10799 if (NewChannels == 1) { 10800 assert(Node->hasNUsesOfValue(1, 0)); 10801 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10802 SDLoc(Node), Users[Lane]->getValueType(0), 10803 SDValue(NewNode, 0)); 10804 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10805 return nullptr; 10806 } 10807 10808 // Update the users of the node with the new indices 10809 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10810 SDNode *User = Users[i]; 10811 if (!User) { 10812 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10813 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10814 if (i || !NoChannels) 10815 continue; 10816 } else { 10817 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10818 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10819 } 10820 10821 switch (Idx) { 10822 default: break; 10823 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10824 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10825 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10826 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10827 } 10828 } 10829 10830 DAG.RemoveDeadNode(Node); 10831 return nullptr; 10832 } 10833 10834 static bool isFrameIndexOp(SDValue Op) { 10835 if (Op.getOpcode() == ISD::AssertZext) 10836 Op = Op.getOperand(0); 10837 10838 return isa<FrameIndexSDNode>(Op); 10839 } 10840 10841 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10842 /// with frame index operands. 10843 /// LLVM assumes that inputs are to these instructions are registers. 10844 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10845 SelectionDAG &DAG) const { 10846 if (Node->getOpcode() == ISD::CopyToReg) { 10847 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10848 SDValue SrcVal = Node->getOperand(2); 10849 10850 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10851 // to try understanding copies to physical registers. 10852 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 10853 SDLoc SL(Node); 10854 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10855 SDValue VReg = DAG.getRegister( 10856 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10857 10858 SDNode *Glued = Node->getGluedNode(); 10859 SDValue ToVReg 10860 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10861 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10862 SDValue ToResultReg 10863 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10864 VReg, ToVReg.getValue(1)); 10865 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10866 DAG.RemoveDeadNode(Node); 10867 return ToResultReg.getNode(); 10868 } 10869 } 10870 10871 SmallVector<SDValue, 8> Ops; 10872 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10873 if (!isFrameIndexOp(Node->getOperand(i))) { 10874 Ops.push_back(Node->getOperand(i)); 10875 continue; 10876 } 10877 10878 SDLoc DL(Node); 10879 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10880 Node->getOperand(i).getValueType(), 10881 Node->getOperand(i)), 0)); 10882 } 10883 10884 return DAG.UpdateNodeOperands(Node, Ops); 10885 } 10886 10887 /// Fold the instructions after selecting them. 10888 /// Returns null if users were already updated. 10889 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10890 SelectionDAG &DAG) const { 10891 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10892 unsigned Opcode = Node->getMachineOpcode(); 10893 10894 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10895 !TII->isGather4(Opcode)) { 10896 return adjustWritemask(Node, DAG); 10897 } 10898 10899 if (Opcode == AMDGPU::INSERT_SUBREG || 10900 Opcode == AMDGPU::REG_SEQUENCE) { 10901 legalizeTargetIndependentNode(Node, DAG); 10902 return Node; 10903 } 10904 10905 switch (Opcode) { 10906 case AMDGPU::V_DIV_SCALE_F32: 10907 case AMDGPU::V_DIV_SCALE_F64: { 10908 // Satisfy the operand register constraint when one of the inputs is 10909 // undefined. Ordinarily each undef value will have its own implicit_def of 10910 // a vreg, so force these to use a single register. 10911 SDValue Src0 = Node->getOperand(0); 10912 SDValue Src1 = Node->getOperand(1); 10913 SDValue Src2 = Node->getOperand(2); 10914 10915 if ((Src0.isMachineOpcode() && 10916 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10917 (Src0 == Src1 || Src0 == Src2)) 10918 break; 10919 10920 MVT VT = Src0.getValueType().getSimpleVT(); 10921 const TargetRegisterClass *RC = 10922 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10923 10924 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10925 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10926 10927 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10928 UndefReg, Src0, SDValue()); 10929 10930 // src0 must be the same register as src1 or src2, even if the value is 10931 // undefined, so make sure we don't violate this constraint. 10932 if (Src0.isMachineOpcode() && 10933 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10934 if (Src1.isMachineOpcode() && 10935 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10936 Src0 = Src1; 10937 else if (Src2.isMachineOpcode() && 10938 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10939 Src0 = Src2; 10940 else { 10941 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10942 Src0 = UndefReg; 10943 Src1 = UndefReg; 10944 } 10945 } else 10946 break; 10947 10948 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10949 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10950 Ops.push_back(Node->getOperand(I)); 10951 10952 Ops.push_back(ImpDef.getValue(1)); 10953 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10954 } 10955 default: 10956 break; 10957 } 10958 10959 return Node; 10960 } 10961 10962 /// Assign the register class depending on the number of 10963 /// bits set in the writemask 10964 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10965 SDNode *Node) const { 10966 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10967 10968 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10969 10970 if (TII->isVOP3(MI.getOpcode())) { 10971 // Make sure constant bus requirements are respected. 10972 TII->legalizeOperandsVOP3(MRI, MI); 10973 10974 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10975 // This saves a chain-copy of registers and better ballance register 10976 // use between vgpr and agpr as agpr tuples tend to be big. 10977 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10978 unsigned Opc = MI.getOpcode(); 10979 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10980 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10981 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10982 if (I == -1) 10983 break; 10984 MachineOperand &Op = MI.getOperand(I); 10985 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10986 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10987 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 10988 continue; 10989 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10990 if (!Src || !Src->isCopy() || 10991 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10992 continue; 10993 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10994 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10995 // All uses of agpr64 and agpr32 can also accept vgpr except for 10996 // v_accvgpr_read, but we do not produce agpr reads during selection, 10997 // so no use checks are needed. 10998 MRI.setRegClass(Op.getReg(), NewRC); 10999 } 11000 } 11001 11002 return; 11003 } 11004 11005 // Replace unused atomics with the no return version. 11006 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11007 if (NoRetAtomicOp != -1) { 11008 if (!Node->hasAnyUseOfValue(0)) { 11009 MI.setDesc(TII->get(NoRetAtomicOp)); 11010 MI.RemoveOperand(0); 11011 return; 11012 } 11013 11014 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11015 // instruction, because the return type of these instructions is a vec2 of 11016 // the memory type, so it can be tied to the input operand. 11017 // This means these instructions always have a use, so we need to add a 11018 // special case to check if the atomic has only one extract_subreg use, 11019 // which itself has no uses. 11020 if ((Node->hasNUsesOfValue(1, 0) && 11021 Node->use_begin()->isMachineOpcode() && 11022 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11023 !Node->use_begin()->hasAnyUseOfValue(0))) { 11024 Register Def = MI.getOperand(0).getReg(); 11025 11026 // Change this into a noret atomic. 11027 MI.setDesc(TII->get(NoRetAtomicOp)); 11028 MI.RemoveOperand(0); 11029 11030 // If we only remove the def operand from the atomic instruction, the 11031 // extract_subreg will be left with a use of a vreg without a def. 11032 // So we need to insert an implicit_def to avoid machine verifier 11033 // errors. 11034 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11035 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11036 } 11037 return; 11038 } 11039 } 11040 11041 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11042 uint64_t Val) { 11043 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11044 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11045 } 11046 11047 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11048 const SDLoc &DL, 11049 SDValue Ptr) const { 11050 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11051 11052 // Build the half of the subregister with the constants before building the 11053 // full 128-bit register. If we are building multiple resource descriptors, 11054 // this will allow CSEing of the 2-component register. 11055 const SDValue Ops0[] = { 11056 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11057 buildSMovImm32(DAG, DL, 0), 11058 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11059 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11060 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11061 }; 11062 11063 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11064 MVT::v2i32, Ops0), 0); 11065 11066 // Combine the constants and the pointer. 11067 const SDValue Ops1[] = { 11068 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11069 Ptr, 11070 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11071 SubRegHi, 11072 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11073 }; 11074 11075 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11076 } 11077 11078 /// Return a resource descriptor with the 'Add TID' bit enabled 11079 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11080 /// of the resource descriptor) to create an offset, which is added to 11081 /// the resource pointer. 11082 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11083 SDValue Ptr, uint32_t RsrcDword1, 11084 uint64_t RsrcDword2And3) const { 11085 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11086 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11087 if (RsrcDword1) { 11088 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11089 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11090 0); 11091 } 11092 11093 SDValue DataLo = buildSMovImm32(DAG, DL, 11094 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11095 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11096 11097 const SDValue Ops[] = { 11098 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11099 PtrLo, 11100 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11101 PtrHi, 11102 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11103 DataLo, 11104 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11105 DataHi, 11106 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11107 }; 11108 11109 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11110 } 11111 11112 //===----------------------------------------------------------------------===// 11113 // SI Inline Assembly Support 11114 //===----------------------------------------------------------------------===// 11115 11116 std::pair<unsigned, const TargetRegisterClass *> 11117 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11118 StringRef Constraint, 11119 MVT VT) const { 11120 const TargetRegisterClass *RC = nullptr; 11121 if (Constraint.size() == 1) { 11122 const unsigned BitWidth = VT.getSizeInBits(); 11123 switch (Constraint[0]) { 11124 default: 11125 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11126 case 's': 11127 case 'r': 11128 switch (BitWidth) { 11129 case 16: 11130 RC = &AMDGPU::SReg_32RegClass; 11131 break; 11132 case 64: 11133 RC = &AMDGPU::SGPR_64RegClass; 11134 break; 11135 default: 11136 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11137 if (!RC) 11138 return std::make_pair(0U, nullptr); 11139 break; 11140 } 11141 break; 11142 case 'v': 11143 switch (BitWidth) { 11144 case 16: 11145 RC = &AMDGPU::VGPR_32RegClass; 11146 break; 11147 default: 11148 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11149 if (!RC) 11150 return std::make_pair(0U, nullptr); 11151 break; 11152 } 11153 break; 11154 case 'a': 11155 if (!Subtarget->hasMAIInsts()) 11156 break; 11157 switch (BitWidth) { 11158 case 16: 11159 RC = &AMDGPU::AGPR_32RegClass; 11160 break; 11161 default: 11162 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11163 if (!RC) 11164 return std::make_pair(0U, nullptr); 11165 break; 11166 } 11167 break; 11168 } 11169 // We actually support i128, i16 and f16 as inline parameters 11170 // even if they are not reported as legal 11171 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11172 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11173 return std::make_pair(0U, RC); 11174 } 11175 11176 if (Constraint.size() > 1) { 11177 if (Constraint[1] == 'v') { 11178 RC = &AMDGPU::VGPR_32RegClass; 11179 } else if (Constraint[1] == 's') { 11180 RC = &AMDGPU::SGPR_32RegClass; 11181 } else if (Constraint[1] == 'a') { 11182 RC = &AMDGPU::AGPR_32RegClass; 11183 } 11184 11185 if (RC) { 11186 uint32_t Idx; 11187 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11188 if (!Failed && Idx < RC->getNumRegs()) 11189 return std::make_pair(RC->getRegister(Idx), RC); 11190 } 11191 } 11192 11193 // FIXME: Returns VS_32 for physical SGPR constraints 11194 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11195 } 11196 11197 static bool isImmConstraint(StringRef Constraint) { 11198 if (Constraint.size() == 1) { 11199 switch (Constraint[0]) { 11200 default: break; 11201 case 'I': 11202 case 'J': 11203 case 'A': 11204 case 'B': 11205 case 'C': 11206 return true; 11207 } 11208 } else if (Constraint == "DA" || 11209 Constraint == "DB") { 11210 return true; 11211 } 11212 return false; 11213 } 11214 11215 SITargetLowering::ConstraintType 11216 SITargetLowering::getConstraintType(StringRef Constraint) const { 11217 if (Constraint.size() == 1) { 11218 switch (Constraint[0]) { 11219 default: break; 11220 case 's': 11221 case 'v': 11222 case 'a': 11223 return C_RegisterClass; 11224 } 11225 } 11226 if (isImmConstraint(Constraint)) { 11227 return C_Other; 11228 } 11229 return TargetLowering::getConstraintType(Constraint); 11230 } 11231 11232 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11233 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11234 Val = Val & maskTrailingOnes<uint64_t>(Size); 11235 } 11236 return Val; 11237 } 11238 11239 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11240 std::string &Constraint, 11241 std::vector<SDValue> &Ops, 11242 SelectionDAG &DAG) const { 11243 if (isImmConstraint(Constraint)) { 11244 uint64_t Val; 11245 if (getAsmOperandConstVal(Op, Val) && 11246 checkAsmConstraintVal(Op, Constraint, Val)) { 11247 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11248 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11249 } 11250 } else { 11251 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11252 } 11253 } 11254 11255 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11256 unsigned Size = Op.getScalarValueSizeInBits(); 11257 if (Size > 64) 11258 return false; 11259 11260 if (Size == 16 && !Subtarget->has16BitInsts()) 11261 return false; 11262 11263 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11264 Val = C->getSExtValue(); 11265 return true; 11266 } 11267 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11268 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11269 return true; 11270 } 11271 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11272 if (Size != 16 || Op.getNumOperands() != 2) 11273 return false; 11274 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11275 return false; 11276 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11277 Val = C->getSExtValue(); 11278 return true; 11279 } 11280 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11281 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11282 return true; 11283 } 11284 } 11285 11286 return false; 11287 } 11288 11289 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11290 const std::string &Constraint, 11291 uint64_t Val) const { 11292 if (Constraint.size() == 1) { 11293 switch (Constraint[0]) { 11294 case 'I': 11295 return AMDGPU::isInlinableIntLiteral(Val); 11296 case 'J': 11297 return isInt<16>(Val); 11298 case 'A': 11299 return checkAsmConstraintValA(Op, Val); 11300 case 'B': 11301 return isInt<32>(Val); 11302 case 'C': 11303 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11304 AMDGPU::isInlinableIntLiteral(Val); 11305 default: 11306 break; 11307 } 11308 } else if (Constraint.size() == 2) { 11309 if (Constraint == "DA") { 11310 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11311 int64_t LoBits = static_cast<int32_t>(Val); 11312 return checkAsmConstraintValA(Op, HiBits, 32) && 11313 checkAsmConstraintValA(Op, LoBits, 32); 11314 } 11315 if (Constraint == "DB") { 11316 return true; 11317 } 11318 } 11319 llvm_unreachable("Invalid asm constraint"); 11320 } 11321 11322 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11323 uint64_t Val, 11324 unsigned MaxSize) const { 11325 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11326 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11327 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11328 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11329 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11330 return true; 11331 } 11332 return false; 11333 } 11334 11335 // Figure out which registers should be reserved for stack access. Only after 11336 // the function is legalized do we know all of the non-spill stack objects or if 11337 // calls are present. 11338 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11339 MachineRegisterInfo &MRI = MF.getRegInfo(); 11340 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11341 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11342 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11343 11344 if (Info->isEntryFunction()) { 11345 // Callable functions have fixed registers used for stack access. 11346 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11347 } 11348 11349 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11350 Info->getStackPtrOffsetReg())); 11351 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11352 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11353 11354 // We need to worry about replacing the default register with itself in case 11355 // of MIR testcases missing the MFI. 11356 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11357 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11358 11359 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11360 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11361 11362 Info->limitOccupancy(MF); 11363 11364 if (ST.isWave32() && !MF.empty()) { 11365 // Add VCC_HI def because many instructions marked as imp-use VCC where 11366 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11367 // having a use of undef. 11368 11369 const SIInstrInfo *TII = ST.getInstrInfo(); 11370 DebugLoc DL; 11371 11372 MachineBasicBlock &MBB = MF.front(); 11373 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11374 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11375 11376 for (auto &MBB : MF) { 11377 for (auto &MI : MBB) { 11378 TII->fixImplicitOperands(MI); 11379 } 11380 } 11381 } 11382 11383 TargetLoweringBase::finalizeLowering(MF); 11384 11385 // Allocate a VGPR for future SGPR Spill if 11386 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11387 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11388 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11389 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11390 Info->reserveVGPRforSGPRSpills(MF); 11391 } 11392 11393 void SITargetLowering::computeKnownBitsForFrameIndex( 11394 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11395 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11396 11397 // Set the high bits to zero based on the maximum allowed scratch size per 11398 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11399 // calculation won't overflow, so assume the sign bit is never set. 11400 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11401 } 11402 11403 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11404 KnownBits &Known, unsigned Dim) { 11405 unsigned MaxValue = 11406 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11407 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11408 } 11409 11410 void SITargetLowering::computeKnownBitsForTargetInstr( 11411 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11412 const MachineRegisterInfo &MRI, unsigned Depth) const { 11413 const MachineInstr *MI = MRI.getVRegDef(R); 11414 switch (MI->getOpcode()) { 11415 case AMDGPU::G_INTRINSIC: { 11416 switch (MI->getIntrinsicID()) { 11417 case Intrinsic::amdgcn_workitem_id_x: 11418 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11419 break; 11420 case Intrinsic::amdgcn_workitem_id_y: 11421 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11422 break; 11423 case Intrinsic::amdgcn_workitem_id_z: 11424 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11425 break; 11426 case Intrinsic::amdgcn_mbcnt_lo: 11427 case Intrinsic::amdgcn_mbcnt_hi: { 11428 // These return at most the wavefront size - 1. 11429 unsigned Size = MRI.getType(R).getSizeInBits(); 11430 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11431 break; 11432 } 11433 case Intrinsic::amdgcn_groupstaticsize: { 11434 // We can report everything over the maximum size as 0. We can't report 11435 // based on the actual size because we don't know if it's accurate or not 11436 // at any given point. 11437 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11438 break; 11439 } 11440 default: 11441 break; 11442 } 11443 } 11444 } 11445 } 11446 11447 Align SITargetLowering::computeKnownAlignForTargetInstr( 11448 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11449 unsigned Depth) const { 11450 const MachineInstr *MI = MRI.getVRegDef(R); 11451 switch (MI->getOpcode()) { 11452 case AMDGPU::G_INTRINSIC: 11453 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11454 // FIXME: Can this move to generic code? What about the case where the call 11455 // site specifies a lower alignment? 11456 Intrinsic::ID IID = MI->getIntrinsicID(); 11457 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11458 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11459 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11460 return *RetAlign; 11461 return Align(1); 11462 } 11463 default: 11464 return Align(1); 11465 } 11466 } 11467 11468 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11469 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11470 const Align CacheLineAlign = Align(64); 11471 11472 // Pre-GFX10 target did not benefit from loop alignment 11473 if (!ML || DisableLoopAlignment || 11474 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11475 getSubtarget()->hasInstFwdPrefetchBug()) 11476 return PrefAlign; 11477 11478 // On GFX10 I$ is 4 x 64 bytes cache lines. 11479 // By default prefetcher keeps one cache line behind and reads two ahead. 11480 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11481 // behind and one ahead. 11482 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11483 // If loop fits 64 bytes it always spans no more than two cache lines and 11484 // does not need an alignment. 11485 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11486 // Else if loop is less or equal 192 bytes we need two lines behind. 11487 11488 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11489 const MachineBasicBlock *Header = ML->getHeader(); 11490 if (Header->getAlignment() != PrefAlign) 11491 return Header->getAlignment(); // Already processed. 11492 11493 unsigned LoopSize = 0; 11494 for (const MachineBasicBlock *MBB : ML->blocks()) { 11495 // If inner loop block is aligned assume in average half of the alignment 11496 // size to be added as nops. 11497 if (MBB != Header) 11498 LoopSize += MBB->getAlignment().value() / 2; 11499 11500 for (const MachineInstr &MI : *MBB) { 11501 LoopSize += TII->getInstSizeInBytes(MI); 11502 if (LoopSize > 192) 11503 return PrefAlign; 11504 } 11505 } 11506 11507 if (LoopSize <= 64) 11508 return PrefAlign; 11509 11510 if (LoopSize <= 128) 11511 return CacheLineAlign; 11512 11513 // If any of parent loops is surrounded by prefetch instructions do not 11514 // insert new for inner loop, which would reset parent's settings. 11515 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11516 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11517 auto I = Exit->getFirstNonDebugInstr(); 11518 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11519 return CacheLineAlign; 11520 } 11521 } 11522 11523 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11524 MachineBasicBlock *Exit = ML->getExitBlock(); 11525 11526 if (Pre && Exit) { 11527 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11528 TII->get(AMDGPU::S_INST_PREFETCH)) 11529 .addImm(1); // prefetch 2 lines behind PC 11530 11531 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11532 TII->get(AMDGPU::S_INST_PREFETCH)) 11533 .addImm(2); // prefetch 1 line behind PC 11534 } 11535 11536 return CacheLineAlign; 11537 } 11538 11539 LLVM_ATTRIBUTE_UNUSED 11540 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11541 assert(N->getOpcode() == ISD::CopyFromReg); 11542 do { 11543 // Follow the chain until we find an INLINEASM node. 11544 N = N->getOperand(0).getNode(); 11545 if (N->getOpcode() == ISD::INLINEASM || 11546 N->getOpcode() == ISD::INLINEASM_BR) 11547 return true; 11548 } while (N->getOpcode() == ISD::CopyFromReg); 11549 return false; 11550 } 11551 11552 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11553 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11554 { 11555 switch (N->getOpcode()) { 11556 case ISD::CopyFromReg: 11557 { 11558 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11559 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11560 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11561 Register Reg = R->getReg(); 11562 11563 // FIXME: Why does this need to consider isLiveIn? 11564 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11565 return !TRI->isSGPRReg(MRI, Reg); 11566 11567 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11568 return KDA->isDivergent(V); 11569 11570 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11571 return !TRI->isSGPRReg(MRI, Reg); 11572 } 11573 break; 11574 case ISD::LOAD: { 11575 const LoadSDNode *L = cast<LoadSDNode>(N); 11576 unsigned AS = L->getAddressSpace(); 11577 // A flat load may access private memory. 11578 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11579 } break; 11580 case ISD::CALLSEQ_END: 11581 return true; 11582 break; 11583 case ISD::INTRINSIC_WO_CHAIN: 11584 { 11585 11586 } 11587 return AMDGPU::isIntrinsicSourceOfDivergence( 11588 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11589 case ISD::INTRINSIC_W_CHAIN: 11590 return AMDGPU::isIntrinsicSourceOfDivergence( 11591 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11592 } 11593 return false; 11594 } 11595 11596 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11597 EVT VT) const { 11598 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11599 case MVT::f32: 11600 return hasFP32Denormals(DAG.getMachineFunction()); 11601 case MVT::f64: 11602 case MVT::f16: 11603 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11604 default: 11605 return false; 11606 } 11607 } 11608 11609 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11610 const SelectionDAG &DAG, 11611 bool SNaN, 11612 unsigned Depth) const { 11613 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11614 const MachineFunction &MF = DAG.getMachineFunction(); 11615 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11616 11617 if (Info->getMode().DX10Clamp) 11618 return true; // Clamped to 0. 11619 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11620 } 11621 11622 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11623 SNaN, Depth); 11624 } 11625 11626 TargetLowering::AtomicExpansionKind 11627 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11628 switch (RMW->getOperation()) { 11629 case AtomicRMWInst::FAdd: { 11630 Type *Ty = RMW->getType(); 11631 11632 // We don't have a way to support 16-bit atomics now, so just leave them 11633 // as-is. 11634 if (Ty->isHalfTy()) 11635 return AtomicExpansionKind::None; 11636 11637 if (!Ty->isFloatTy()) 11638 return AtomicExpansionKind::CmpXChg; 11639 11640 // TODO: Do have these for flat. Older targets also had them for buffers. 11641 unsigned AS = RMW->getPointerAddressSpace(); 11642 11643 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11644 return RMW->use_empty() ? AtomicExpansionKind::None : 11645 AtomicExpansionKind::CmpXChg; 11646 } 11647 11648 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11649 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11650 } 11651 default: 11652 break; 11653 } 11654 11655 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11656 } 11657 11658 const TargetRegisterClass * 11659 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11660 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11661 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11662 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11663 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11664 : &AMDGPU::SReg_32RegClass; 11665 if (!TRI->isSGPRClass(RC) && !isDivergent) 11666 return TRI->getEquivalentSGPRClass(RC); 11667 else if (TRI->isSGPRClass(RC) && isDivergent) 11668 return TRI->getEquivalentVGPRClass(RC); 11669 11670 return RC; 11671 } 11672 11673 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11674 // uniform values (as produced by the mask results of control flow intrinsics) 11675 // used outside of divergent blocks. The phi users need to also be treated as 11676 // always uniform. 11677 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11678 unsigned WaveSize) { 11679 // FIXME: We asssume we never cast the mask results of a control flow 11680 // intrinsic. 11681 // Early exit if the type won't be consistent as a compile time hack. 11682 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11683 if (!IT || IT->getBitWidth() != WaveSize) 11684 return false; 11685 11686 if (!isa<Instruction>(V)) 11687 return false; 11688 if (!Visited.insert(V).second) 11689 return false; 11690 bool Result = false; 11691 for (auto U : V->users()) { 11692 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11693 if (V == U->getOperand(1)) { 11694 switch (Intrinsic->getIntrinsicID()) { 11695 default: 11696 Result = false; 11697 break; 11698 case Intrinsic::amdgcn_if_break: 11699 case Intrinsic::amdgcn_if: 11700 case Intrinsic::amdgcn_else: 11701 Result = true; 11702 break; 11703 } 11704 } 11705 if (V == U->getOperand(0)) { 11706 switch (Intrinsic->getIntrinsicID()) { 11707 default: 11708 Result = false; 11709 break; 11710 case Intrinsic::amdgcn_end_cf: 11711 case Intrinsic::amdgcn_loop: 11712 Result = true; 11713 break; 11714 } 11715 } 11716 } else { 11717 Result = hasCFUser(U, Visited, WaveSize); 11718 } 11719 if (Result) 11720 break; 11721 } 11722 return Result; 11723 } 11724 11725 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11726 const Value *V) const { 11727 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11728 if (CI->isInlineAsm()) { 11729 // FIXME: This cannot give a correct answer. This should only trigger in 11730 // the case where inline asm returns mixed SGPR and VGPR results, used 11731 // outside the defining block. We don't have a specific result to 11732 // consider, so this assumes if any value is SGPR, the overall register 11733 // also needs to be SGPR. 11734 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11735 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11736 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11737 for (auto &TC : TargetConstraints) { 11738 if (TC.Type == InlineAsm::isOutput) { 11739 ComputeConstraintToUse(TC, SDValue()); 11740 unsigned AssignedReg; 11741 const TargetRegisterClass *RC; 11742 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11743 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11744 if (RC) { 11745 MachineRegisterInfo &MRI = MF.getRegInfo(); 11746 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11747 return true; 11748 else if (SIRI->isSGPRClass(RC)) 11749 return true; 11750 } 11751 } 11752 } 11753 } 11754 } 11755 SmallPtrSet<const Value *, 16> Visited; 11756 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11757 } 11758 11759 std::pair<int, MVT> 11760 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11761 Type *Ty) const { 11762 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11763 auto Size = DL.getTypeSizeInBits(Ty); 11764 // Maximum load or store can handle 8 dwords for scalar and 4 for 11765 // vector ALU. Let's assume anything above 8 dwords is expensive 11766 // even if legal. 11767 if (Size <= 256) 11768 return Cost; 11769 11770 Cost.first = (Size + 255) / 256; 11771 return Cost; 11772 } 11773