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 "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/BinaryFormat/ELF.h" 24 #include "llvm/CodeGen/Analysis.h" 25 #include "llvm/CodeGen/FunctionLoweringInfo.h" 26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineLoopInfo.h" 29 #include "llvm/IR/DiagnosticInfo.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/IntrinsicsAMDGPU.h" 32 #include "llvm/IR/IntrinsicsR600.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/KnownBits.h" 35 36 using namespace llvm; 37 38 #define DEBUG_TYPE "si-lower" 39 40 STATISTIC(NumTailCalls, "Number of tail calls"); 41 42 static cl::opt<bool> DisableLoopAlignment( 43 "amdgpu-disable-loop-alignment", 44 cl::desc("Do not align and prefetch loops"), 45 cl::init(false)); 46 47 static cl::opt<bool> VGPRReserveforSGPRSpill( 48 "amdgpu-reserve-vgpr-for-sgpr-spill", 49 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 50 51 static cl::opt<bool> UseDivergentRegisterIndexing( 52 "amdgpu-use-divergent-register-indexing", 53 cl::Hidden, 54 cl::desc("Use indirect register addressing for divergent indexes"), 55 cl::init(false)); 56 57 static bool hasFP32Denormals(const MachineFunction &MF) { 58 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 59 return Info->getMode().allFP32Denormals(); 60 } 61 62 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 63 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 64 return Info->getMode().allFP64FP16Denormals(); 65 } 66 67 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 68 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 69 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 70 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 71 return AMDGPU::SGPR0 + Reg; 72 } 73 } 74 llvm_unreachable("Cannot allocate sgpr"); 75 } 76 77 SITargetLowering::SITargetLowering(const TargetMachine &TM, 78 const GCNSubtarget &STI) 79 : AMDGPUTargetLowering(TM, STI), 80 Subtarget(&STI) { 81 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 82 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 83 84 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 85 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 86 87 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 88 89 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 90 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 91 92 addRegisterClass(MVT::f64, V64RegClass); 93 addRegisterClass(MVT::v2f32, V64RegClass); 94 95 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 96 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 97 98 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 99 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 100 101 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 102 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 103 104 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 105 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 106 107 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 108 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 109 110 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 111 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 112 113 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 114 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 115 116 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 117 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 118 119 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 120 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 121 122 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 123 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 124 125 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 126 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 127 128 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 129 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 130 131 if (Subtarget->has16BitInsts()) { 132 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 133 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 134 135 // Unless there are also VOP3P operations, not operations are really legal. 136 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 137 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 138 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 139 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 140 } 141 142 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 143 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 144 145 computeRegisterProperties(Subtarget->getRegisterInfo()); 146 147 // The boolean content concept here is too inflexible. Compares only ever 148 // really produce a 1-bit result. Any copy/extend from these will turn into a 149 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 150 // it's what most targets use. 151 setBooleanContents(ZeroOrOneBooleanContent); 152 setBooleanVectorContents(ZeroOrOneBooleanContent); 153 154 // We need to custom lower vector stores from local memory 155 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::i1, Custom); 164 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 165 166 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 174 setOperationAction(ISD::STORE, MVT::i1, Custom); 175 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 176 177 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 178 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 179 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 180 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 181 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 182 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 183 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 184 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 185 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 186 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 187 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 188 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 189 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 190 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 191 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 192 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 193 194 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 195 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 196 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 197 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 200 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 201 202 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 203 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 204 205 setOperationAction(ISD::SELECT, MVT::i1, Promote); 206 setOperationAction(ISD::SELECT, MVT::i64, Custom); 207 setOperationAction(ISD::SELECT, MVT::f64, Promote); 208 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 209 210 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 215 216 setOperationAction(ISD::SETCC, MVT::i1, Promote); 217 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 218 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 219 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 220 221 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 222 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 223 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 224 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 225 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 227 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 228 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 229 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 230 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 231 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 232 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 233 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 234 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 235 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 236 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 237 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 246 247 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 248 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 249 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 251 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 253 254 setOperationAction(ISD::UADDO, MVT::i32, Legal); 255 setOperationAction(ISD::USUBO, MVT::i32, Legal); 256 257 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 258 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 259 260 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 261 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 263 264 #if 0 265 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 266 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 267 #endif 268 269 // We only support LOAD/STORE and vector manipulation ops for vectors 270 // with > 4 elements. 271 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 272 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 273 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 274 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 275 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 276 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 277 switch (Op) { 278 case ISD::LOAD: 279 case ISD::STORE: 280 case ISD::BUILD_VECTOR: 281 case ISD::BITCAST: 282 case ISD::EXTRACT_VECTOR_ELT: 283 case ISD::INSERT_VECTOR_ELT: 284 case ISD::EXTRACT_SUBVECTOR: 285 case ISD::SCALAR_TO_VECTOR: 286 break; 287 case ISD::INSERT_SUBVECTOR: 288 case ISD::CONCAT_VECTORS: 289 setOperationAction(Op, VT, Custom); 290 break; 291 default: 292 setOperationAction(Op, VT, Expand); 293 break; 294 } 295 } 296 } 297 298 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 299 300 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 301 // is expanded to avoid having two separate loops in case the index is a VGPR. 302 303 // Most operations are naturally 32-bit vector operations. We only support 304 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 305 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 306 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 307 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 308 309 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 310 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 311 312 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 313 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 314 315 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 316 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 317 } 318 319 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 320 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 321 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 322 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 324 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 325 326 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 327 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 328 329 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 330 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 331 } 332 333 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 334 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 335 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 336 337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 338 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 339 340 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 341 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 344 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 345 } 346 347 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 348 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 349 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 350 351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 352 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 353 354 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 355 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 358 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 359 } 360 361 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 362 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 363 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 364 365 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 366 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 367 368 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 369 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 372 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 373 } 374 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 379 380 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 381 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 382 383 // Avoid stack access for these. 384 // TODO: Generalize to more vector types. 385 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 386 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 387 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 388 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 389 390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 396 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 401 402 // Deal with vec3 vector operations when widened to vec4. 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 407 408 // Deal with vec5/6/7 vector operations when widened to vec8. 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 417 418 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 419 // and output demarshalling 420 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 421 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 422 423 // We can't return success/failure, only the old value, 424 // let LLVM add the comparison 425 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 426 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 427 428 if (Subtarget->hasFlatAddressSpace()) { 429 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 430 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 431 } 432 433 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 434 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 435 436 // FIXME: This should be narrowed to i32, but that only happens if i64 is 437 // illegal. 438 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 439 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 440 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 441 442 // On SI this is s_memtime and s_memrealtime on VI. 443 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 444 setOperationAction(ISD::TRAP, MVT::Other, Custom); 445 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 446 447 if (Subtarget->has16BitInsts()) { 448 setOperationAction(ISD::FPOW, MVT::f16, Promote); 449 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 450 setOperationAction(ISD::FLOG, MVT::f16, Custom); 451 setOperationAction(ISD::FEXP, MVT::f16, Custom); 452 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 453 } 454 455 if (Subtarget->hasMadMacF32Insts()) 456 setOperationAction(ISD::FMAD, MVT::f32, Legal); 457 458 if (!Subtarget->hasBFI()) { 459 // fcopysign can be done in a single instruction with BFI. 460 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 461 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 462 } 463 464 if (!Subtarget->hasBCNT(32)) 465 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 466 467 if (!Subtarget->hasBCNT(64)) 468 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 469 470 if (Subtarget->hasFFBH()) { 471 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 473 } 474 475 if (Subtarget->hasFFBL()) { 476 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 478 } 479 480 // We only really have 32-bit BFE instructions (and 16-bit on VI). 481 // 482 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 483 // effort to match them now. We want this to be false for i64 cases when the 484 // extraction isn't restricted to the upper or lower half. Ideally we would 485 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 486 // span the midpoint are probably relatively rare, so don't worry about them 487 // for now. 488 if (Subtarget->hasBFE()) 489 setHasExtractBitsInsn(true); 490 491 // Clamp modifier on add/sub 492 if (Subtarget->hasIntClamp()) { 493 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 494 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 495 } 496 497 if (Subtarget->hasAddNoCarry()) { 498 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 502 } 503 504 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 508 509 510 // These are really only legal for ieee_mode functions. We should be avoiding 511 // them for functions that don't have ieee_mode enabled, so just say they are 512 // legal. 513 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 517 518 519 if (Subtarget->haveRoundOpsF64()) { 520 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 521 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 522 setOperationAction(ISD::FRINT, MVT::f64, Legal); 523 } else { 524 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 525 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 526 setOperationAction(ISD::FRINT, MVT::f64, Custom); 527 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 528 } 529 530 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 531 532 setOperationAction(ISD::FSIN, MVT::f32, Custom); 533 setOperationAction(ISD::FCOS, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f64, Custom); 536 537 if (Subtarget->has16BitInsts()) { 538 setOperationAction(ISD::Constant, MVT::i16, Legal); 539 540 setOperationAction(ISD::SMIN, MVT::i16, Legal); 541 setOperationAction(ISD::SMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::UMIN, MVT::i16, Legal); 544 setOperationAction(ISD::UMAX, MVT::i16, Legal); 545 546 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 547 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 548 549 setOperationAction(ISD::ROTR, MVT::i16, Expand); 550 setOperationAction(ISD::ROTL, MVT::i16, Expand); 551 552 setOperationAction(ISD::SDIV, MVT::i16, Promote); 553 setOperationAction(ISD::UDIV, MVT::i16, Promote); 554 setOperationAction(ISD::SREM, MVT::i16, Promote); 555 setOperationAction(ISD::UREM, MVT::i16, Promote); 556 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 557 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 558 559 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 560 561 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 566 567 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 568 569 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::LOAD, MVT::i16, Custom); 572 573 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 574 575 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 576 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 577 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 579 580 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 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 if (Subtarget->hasPackedFP32Ops()) { 775 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 776 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 777 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 778 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 779 780 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 781 setOperationAction(ISD::FADD, VT, Custom); 782 setOperationAction(ISD::FMUL, VT, Custom); 783 setOperationAction(ISD::FMA, VT, Custom); 784 } 785 } 786 } 787 788 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 789 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 790 791 if (Subtarget->has16BitInsts()) { 792 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 793 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 794 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 795 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 796 } else { 797 // Legalization hack. 798 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 799 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 800 801 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 802 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 803 } 804 805 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 806 setOperationAction(ISD::SELECT, VT, Custom); 807 } 808 809 setOperationAction(ISD::SMULO, MVT::i64, Custom); 810 setOperationAction(ISD::UMULO, MVT::i64, Custom); 811 812 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 813 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 814 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 815 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 816 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 817 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 818 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 819 820 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 821 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 822 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 823 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 824 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 825 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 826 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 827 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 828 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 829 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 830 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 831 832 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 833 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 834 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 835 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 836 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 837 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 838 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 839 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 840 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 841 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 842 843 setTargetDAGCombine(ISD::ADD); 844 setTargetDAGCombine(ISD::ADDCARRY); 845 setTargetDAGCombine(ISD::SUB); 846 setTargetDAGCombine(ISD::SUBCARRY); 847 setTargetDAGCombine(ISD::FADD); 848 setTargetDAGCombine(ISD::FSUB); 849 setTargetDAGCombine(ISD::FMINNUM); 850 setTargetDAGCombine(ISD::FMAXNUM); 851 setTargetDAGCombine(ISD::FMINNUM_IEEE); 852 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 853 setTargetDAGCombine(ISD::FMA); 854 setTargetDAGCombine(ISD::SMIN); 855 setTargetDAGCombine(ISD::SMAX); 856 setTargetDAGCombine(ISD::UMIN); 857 setTargetDAGCombine(ISD::UMAX); 858 setTargetDAGCombine(ISD::SETCC); 859 setTargetDAGCombine(ISD::AND); 860 setTargetDAGCombine(ISD::OR); 861 setTargetDAGCombine(ISD::XOR); 862 setTargetDAGCombine(ISD::SINT_TO_FP); 863 setTargetDAGCombine(ISD::UINT_TO_FP); 864 setTargetDAGCombine(ISD::FCANONICALIZE); 865 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 866 setTargetDAGCombine(ISD::ZERO_EXTEND); 867 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 868 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 869 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 870 871 // All memory operations. Some folding on the pointer operand is done to help 872 // matching the constant offsets in the addressing modes. 873 setTargetDAGCombine(ISD::LOAD); 874 setTargetDAGCombine(ISD::STORE); 875 setTargetDAGCombine(ISD::ATOMIC_LOAD); 876 setTargetDAGCombine(ISD::ATOMIC_STORE); 877 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 878 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 879 setTargetDAGCombine(ISD::ATOMIC_SWAP); 880 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 881 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 882 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 883 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 884 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 885 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 886 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 887 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 888 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 889 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 890 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 891 setTargetDAGCombine(ISD::INTRINSIC_VOID); 892 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 893 894 // FIXME: In other contexts we pretend this is a per-function property. 895 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 896 897 setSchedulingPreference(Sched::RegPressure); 898 } 899 900 const GCNSubtarget *SITargetLowering::getSubtarget() const { 901 return Subtarget; 902 } 903 904 //===----------------------------------------------------------------------===// 905 // TargetLowering queries 906 //===----------------------------------------------------------------------===// 907 908 // v_mad_mix* support a conversion from f16 to f32. 909 // 910 // There is only one special case when denormals are enabled we don't currently, 911 // where this is OK to use. 912 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 913 EVT DestVT, EVT SrcVT) const { 914 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 915 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 916 DestVT.getScalarType() == MVT::f32 && 917 SrcVT.getScalarType() == MVT::f16 && 918 // TODO: This probably only requires no input flushing? 919 !hasFP32Denormals(DAG.getMachineFunction()); 920 } 921 922 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 923 // SI has some legal vector types, but no legal vector operations. Say no 924 // shuffles are legal in order to prefer scalarizing some vector operations. 925 return false; 926 } 927 928 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 929 CallingConv::ID CC, 930 EVT VT) const { 931 if (CC == CallingConv::AMDGPU_KERNEL) 932 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 933 934 if (VT.isVector()) { 935 EVT ScalarVT = VT.getScalarType(); 936 unsigned Size = ScalarVT.getSizeInBits(); 937 if (Size == 16) { 938 if (Subtarget->has16BitInsts()) 939 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 940 return VT.isInteger() ? MVT::i32 : MVT::f32; 941 } 942 943 if (Size < 16) 944 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 945 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 946 } 947 948 if (VT.getSizeInBits() > 32) 949 return MVT::i32; 950 951 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 952 } 953 954 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 955 CallingConv::ID CC, 956 EVT VT) const { 957 if (CC == CallingConv::AMDGPU_KERNEL) 958 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 959 960 if (VT.isVector()) { 961 unsigned NumElts = VT.getVectorNumElements(); 962 EVT ScalarVT = VT.getScalarType(); 963 unsigned Size = ScalarVT.getSizeInBits(); 964 965 // FIXME: Should probably promote 8-bit vectors to i16. 966 if (Size == 16 && Subtarget->has16BitInsts()) 967 return (NumElts + 1) / 2; 968 969 if (Size <= 32) 970 return NumElts; 971 972 if (Size > 32) 973 return NumElts * ((Size + 31) / 32); 974 } else if (VT.getSizeInBits() > 32) 975 return (VT.getSizeInBits() + 31) / 32; 976 977 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 978 } 979 980 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 981 LLVMContext &Context, CallingConv::ID CC, 982 EVT VT, EVT &IntermediateVT, 983 unsigned &NumIntermediates, MVT &RegisterVT) const { 984 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 985 unsigned NumElts = VT.getVectorNumElements(); 986 EVT ScalarVT = VT.getScalarType(); 987 unsigned Size = ScalarVT.getSizeInBits(); 988 // FIXME: We should fix the ABI to be the same on targets without 16-bit 989 // support, but unless we can properly handle 3-vectors, it will be still be 990 // inconsistent. 991 if (Size == 16 && Subtarget->has16BitInsts()) { 992 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 993 IntermediateVT = RegisterVT; 994 NumIntermediates = (NumElts + 1) / 2; 995 return NumIntermediates; 996 } 997 998 if (Size == 32) { 999 RegisterVT = ScalarVT.getSimpleVT(); 1000 IntermediateVT = RegisterVT; 1001 NumIntermediates = NumElts; 1002 return NumIntermediates; 1003 } 1004 1005 if (Size < 16 && Subtarget->has16BitInsts()) { 1006 // FIXME: Should probably form v2i16 pieces 1007 RegisterVT = MVT::i16; 1008 IntermediateVT = ScalarVT; 1009 NumIntermediates = NumElts; 1010 return NumIntermediates; 1011 } 1012 1013 1014 if (Size != 16 && Size <= 32) { 1015 RegisterVT = MVT::i32; 1016 IntermediateVT = ScalarVT; 1017 NumIntermediates = NumElts; 1018 return NumIntermediates; 1019 } 1020 1021 if (Size > 32) { 1022 RegisterVT = MVT::i32; 1023 IntermediateVT = RegisterVT; 1024 NumIntermediates = NumElts * ((Size + 31) / 32); 1025 return NumIntermediates; 1026 } 1027 } 1028 1029 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1030 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1031 } 1032 1033 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1034 assert(DMaskLanes != 0); 1035 1036 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1037 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1038 return EVT::getVectorVT(Ty->getContext(), 1039 EVT::getEVT(VT->getElementType()), 1040 NumElts); 1041 } 1042 1043 return EVT::getEVT(Ty); 1044 } 1045 1046 // Peek through TFE struct returns to only use the data size. 1047 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1048 auto *ST = dyn_cast<StructType>(Ty); 1049 if (!ST) 1050 return memVTFromImageData(Ty, DMaskLanes); 1051 1052 // Some intrinsics return an aggregate type - special case to work out the 1053 // correct memVT. 1054 // 1055 // Only limited forms of aggregate type currently expected. 1056 if (ST->getNumContainedTypes() != 2 || 1057 !ST->getContainedType(1)->isIntegerTy(32)) 1058 return EVT(); 1059 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1060 } 1061 1062 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1063 const CallInst &CI, 1064 MachineFunction &MF, 1065 unsigned IntrID) const { 1066 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1067 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1068 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1069 (Intrinsic::ID)IntrID); 1070 if (Attr.hasFnAttr(Attribute::ReadNone)) 1071 return false; 1072 1073 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1074 1075 if (RsrcIntr->IsImage) { 1076 Info.ptrVal = 1077 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1078 Info.align.reset(); 1079 } else { 1080 Info.ptrVal = 1081 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1082 } 1083 1084 Info.flags = MachineMemOperand::MODereferenceable; 1085 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1086 unsigned DMaskLanes = 4; 1087 1088 if (RsrcIntr->IsImage) { 1089 const AMDGPU::ImageDimIntrinsicInfo *Intr 1090 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1091 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1092 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1093 1094 if (!BaseOpcode->Gather4) { 1095 // If this isn't a gather, we may have excess loaded elements in the 1096 // IR type. Check the dmask for the real number of elements loaded. 1097 unsigned DMask 1098 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1099 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1100 } 1101 1102 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1103 } else 1104 Info.memVT = EVT::getEVT(CI.getType()); 1105 1106 // FIXME: What does alignment mean for an image? 1107 Info.opc = ISD::INTRINSIC_W_CHAIN; 1108 Info.flags |= MachineMemOperand::MOLoad; 1109 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1110 Info.opc = ISD::INTRINSIC_VOID; 1111 1112 Type *DataTy = CI.getArgOperand(0)->getType(); 1113 if (RsrcIntr->IsImage) { 1114 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1115 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1116 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1117 } else 1118 Info.memVT = EVT::getEVT(DataTy); 1119 1120 Info.flags |= MachineMemOperand::MOStore; 1121 } else { 1122 // Atomic 1123 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1124 ISD::INTRINSIC_W_CHAIN; 1125 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1126 Info.flags = MachineMemOperand::MOLoad | 1127 MachineMemOperand::MOStore | 1128 MachineMemOperand::MODereferenceable; 1129 1130 // XXX - Should this be volatile without known ordering? 1131 Info.flags |= MachineMemOperand::MOVolatile; 1132 } 1133 return true; 1134 } 1135 1136 switch (IntrID) { 1137 case Intrinsic::amdgcn_atomic_inc: 1138 case Intrinsic::amdgcn_atomic_dec: 1139 case Intrinsic::amdgcn_ds_ordered_add: 1140 case Intrinsic::amdgcn_ds_ordered_swap: 1141 case Intrinsic::amdgcn_ds_fadd: 1142 case Intrinsic::amdgcn_ds_fmin: 1143 case Intrinsic::amdgcn_ds_fmax: { 1144 Info.opc = ISD::INTRINSIC_W_CHAIN; 1145 Info.memVT = MVT::getVT(CI.getType()); 1146 Info.ptrVal = CI.getOperand(0); 1147 Info.align.reset(); 1148 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1149 1150 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1151 if (!Vol->isZero()) 1152 Info.flags |= MachineMemOperand::MOVolatile; 1153 1154 return true; 1155 } 1156 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1157 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1158 1159 Info.opc = ISD::INTRINSIC_W_CHAIN; 1160 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1161 Info.ptrVal = 1162 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1163 Info.align.reset(); 1164 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1165 1166 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1167 if (!Vol || !Vol->isZero()) 1168 Info.flags |= MachineMemOperand::MOVolatile; 1169 1170 return true; 1171 } 1172 case Intrinsic::amdgcn_ds_append: 1173 case Intrinsic::amdgcn_ds_consume: { 1174 Info.opc = ISD::INTRINSIC_W_CHAIN; 1175 Info.memVT = MVT::getVT(CI.getType()); 1176 Info.ptrVal = CI.getOperand(0); 1177 Info.align.reset(); 1178 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1179 1180 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1181 if (!Vol->isZero()) 1182 Info.flags |= MachineMemOperand::MOVolatile; 1183 1184 return true; 1185 } 1186 case Intrinsic::amdgcn_global_atomic_csub: { 1187 Info.opc = ISD::INTRINSIC_W_CHAIN; 1188 Info.memVT = MVT::getVT(CI.getType()); 1189 Info.ptrVal = CI.getOperand(0); 1190 Info.align.reset(); 1191 Info.flags = MachineMemOperand::MOLoad | 1192 MachineMemOperand::MOStore | 1193 MachineMemOperand::MOVolatile; 1194 return true; 1195 } 1196 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1197 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1198 Info.opc = ISD::INTRINSIC_W_CHAIN; 1199 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1200 Info.ptrVal = 1201 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1202 Info.align.reset(); 1203 Info.flags = MachineMemOperand::MOLoad | 1204 MachineMemOperand::MODereferenceable; 1205 return true; 1206 } 1207 case Intrinsic::amdgcn_global_atomic_fadd: 1208 case Intrinsic::amdgcn_global_atomic_fmin: 1209 case Intrinsic::amdgcn_global_atomic_fmax: 1210 case Intrinsic::amdgcn_flat_atomic_fadd: 1211 case Intrinsic::amdgcn_flat_atomic_fmin: 1212 case Intrinsic::amdgcn_flat_atomic_fmax: { 1213 Info.opc = ISD::INTRINSIC_W_CHAIN; 1214 Info.memVT = MVT::getVT(CI.getType()); 1215 Info.ptrVal = CI.getOperand(0); 1216 Info.align.reset(); 1217 Info.flags = MachineMemOperand::MOLoad | 1218 MachineMemOperand::MOStore | 1219 MachineMemOperand::MODereferenceable | 1220 MachineMemOperand::MOVolatile; 1221 return true; 1222 } 1223 case Intrinsic::amdgcn_ds_gws_init: 1224 case Intrinsic::amdgcn_ds_gws_barrier: 1225 case Intrinsic::amdgcn_ds_gws_sema_v: 1226 case Intrinsic::amdgcn_ds_gws_sema_br: 1227 case Intrinsic::amdgcn_ds_gws_sema_p: 1228 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1229 Info.opc = ISD::INTRINSIC_VOID; 1230 1231 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1232 Info.ptrVal = 1233 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1234 1235 // This is an abstract access, but we need to specify a type and size. 1236 Info.memVT = MVT::i32; 1237 Info.size = 4; 1238 Info.align = Align(4); 1239 1240 Info.flags = MachineMemOperand::MOStore; 1241 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1242 Info.flags = MachineMemOperand::MOLoad; 1243 return true; 1244 } 1245 default: 1246 return false; 1247 } 1248 } 1249 1250 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1251 SmallVectorImpl<Value*> &Ops, 1252 Type *&AccessTy) const { 1253 switch (II->getIntrinsicID()) { 1254 case Intrinsic::amdgcn_atomic_inc: 1255 case Intrinsic::amdgcn_atomic_dec: 1256 case Intrinsic::amdgcn_ds_ordered_add: 1257 case Intrinsic::amdgcn_ds_ordered_swap: 1258 case Intrinsic::amdgcn_ds_append: 1259 case Intrinsic::amdgcn_ds_consume: 1260 case Intrinsic::amdgcn_ds_fadd: 1261 case Intrinsic::amdgcn_ds_fmin: 1262 case Intrinsic::amdgcn_ds_fmax: 1263 case Intrinsic::amdgcn_global_atomic_fadd: 1264 case Intrinsic::amdgcn_flat_atomic_fadd: 1265 case Intrinsic::amdgcn_flat_atomic_fmin: 1266 case Intrinsic::amdgcn_flat_atomic_fmax: 1267 case Intrinsic::amdgcn_global_atomic_csub: { 1268 Value *Ptr = II->getArgOperand(0); 1269 AccessTy = II->getType(); 1270 Ops.push_back(Ptr); 1271 return true; 1272 } 1273 default: 1274 return false; 1275 } 1276 } 1277 1278 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1279 if (!Subtarget->hasFlatInstOffsets()) { 1280 // Flat instructions do not have offsets, and only have the register 1281 // address. 1282 return AM.BaseOffs == 0 && AM.Scale == 0; 1283 } 1284 1285 return AM.Scale == 0 && 1286 (AM.BaseOffs == 0 || 1287 Subtarget->getInstrInfo()->isLegalFLATOffset( 1288 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1289 } 1290 1291 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1292 if (Subtarget->hasFlatGlobalInsts()) 1293 return AM.Scale == 0 && 1294 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1295 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1296 SIInstrFlags::FlatGlobal)); 1297 1298 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1299 // Assume the we will use FLAT for all global memory accesses 1300 // on VI. 1301 // FIXME: This assumption is currently wrong. On VI we still use 1302 // MUBUF instructions for the r + i addressing mode. As currently 1303 // implemented, the MUBUF instructions only work on buffer < 4GB. 1304 // It may be possible to support > 4GB buffers with MUBUF instructions, 1305 // by setting the stride value in the resource descriptor which would 1306 // increase the size limit to (stride * 4GB). However, this is risky, 1307 // because it has never been validated. 1308 return isLegalFlatAddressingMode(AM); 1309 } 1310 1311 return isLegalMUBUFAddressingMode(AM); 1312 } 1313 1314 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1315 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1316 // additionally can do r + r + i with addr64. 32-bit has more addressing 1317 // mode options. Depending on the resource constant, it can also do 1318 // (i64 r0) + (i32 r1) * (i14 i). 1319 // 1320 // Private arrays end up using a scratch buffer most of the time, so also 1321 // assume those use MUBUF instructions. Scratch loads / stores are currently 1322 // implemented as mubuf instructions with offen bit set, so slightly 1323 // different than the normal addr64. 1324 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1325 return false; 1326 1327 // FIXME: Since we can split immediate into soffset and immediate offset, 1328 // would it make sense to allow any immediate? 1329 1330 switch (AM.Scale) { 1331 case 0: // r + i or just i, depending on HasBaseReg. 1332 return true; 1333 case 1: 1334 return true; // We have r + r or r + i. 1335 case 2: 1336 if (AM.HasBaseReg) { 1337 // Reject 2 * r + r. 1338 return false; 1339 } 1340 1341 // Allow 2 * r as r + r 1342 // Or 2 * r + i is allowed as r + r + i. 1343 return true; 1344 default: // Don't allow n * r 1345 return false; 1346 } 1347 } 1348 1349 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1350 const AddrMode &AM, Type *Ty, 1351 unsigned AS, Instruction *I) const { 1352 // No global is ever allowed as a base. 1353 if (AM.BaseGV) 1354 return false; 1355 1356 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1357 return isLegalGlobalAddressingMode(AM); 1358 1359 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1360 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1361 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1362 // If the offset isn't a multiple of 4, it probably isn't going to be 1363 // correctly aligned. 1364 // FIXME: Can we get the real alignment here? 1365 if (AM.BaseOffs % 4 != 0) 1366 return isLegalMUBUFAddressingMode(AM); 1367 1368 // There are no SMRD extloads, so if we have to do a small type access we 1369 // will use a MUBUF load. 1370 // FIXME?: We also need to do this if unaligned, but we don't know the 1371 // alignment here. 1372 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1373 return isLegalGlobalAddressingMode(AM); 1374 1375 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1376 // SMRD instructions have an 8-bit, dword offset on SI. 1377 if (!isUInt<8>(AM.BaseOffs / 4)) 1378 return false; 1379 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1380 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1381 // in 8-bits, it can use a smaller encoding. 1382 if (!isUInt<32>(AM.BaseOffs / 4)) 1383 return false; 1384 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1385 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1386 if (!isUInt<20>(AM.BaseOffs)) 1387 return false; 1388 } else 1389 llvm_unreachable("unhandled generation"); 1390 1391 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1392 return true; 1393 1394 if (AM.Scale == 1 && AM.HasBaseReg) 1395 return true; 1396 1397 return false; 1398 1399 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1400 return isLegalMUBUFAddressingMode(AM); 1401 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1402 AS == AMDGPUAS::REGION_ADDRESS) { 1403 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1404 // field. 1405 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1406 // an 8-bit dword offset but we don't know the alignment here. 1407 if (!isUInt<16>(AM.BaseOffs)) 1408 return false; 1409 1410 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1411 return true; 1412 1413 if (AM.Scale == 1 && AM.HasBaseReg) 1414 return true; 1415 1416 return false; 1417 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1418 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1419 // For an unknown address space, this usually means that this is for some 1420 // reason being used for pure arithmetic, and not based on some addressing 1421 // computation. We don't have instructions that compute pointers with any 1422 // addressing modes, so treat them as having no offset like flat 1423 // instructions. 1424 return isLegalFlatAddressingMode(AM); 1425 } 1426 1427 // Assume a user alias of global for unknown address spaces. 1428 return isLegalGlobalAddressingMode(AM); 1429 } 1430 1431 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1432 const MachineFunction &MF) const { 1433 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1434 return (MemVT.getSizeInBits() <= 4 * 32); 1435 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1436 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1437 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1438 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1439 return (MemVT.getSizeInBits() <= 2 * 32); 1440 } 1441 return true; 1442 } 1443 1444 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1445 unsigned Size, unsigned AddrSpace, Align Alignment, 1446 MachineMemOperand::Flags Flags, bool *IsFast) const { 1447 if (IsFast) 1448 *IsFast = false; 1449 1450 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1451 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1452 // Check if alignment requirements for ds_read/write instructions are 1453 // disabled. 1454 if (Subtarget->hasUnalignedDSAccessEnabled() && 1455 !Subtarget->hasLDSMisalignedBug()) { 1456 if (IsFast) 1457 *IsFast = Alignment != Align(2); 1458 return true; 1459 } 1460 1461 // Either, the alignment requirements are "enabled", or there is an 1462 // unaligned LDS access related hardware bug though alignment requirements 1463 // are "disabled". In either case, we need to check for proper alignment 1464 // requirements. 1465 // 1466 if (Size == 64) { 1467 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1468 // can do a 4 byte aligned, 8 byte access in a single operation using 1469 // ds_read2/write2_b32 with adjacent offsets. 1470 bool AlignedBy4 = Alignment >= Align(4); 1471 if (IsFast) 1472 *IsFast = AlignedBy4; 1473 1474 return AlignedBy4; 1475 } 1476 if (Size == 96) { 1477 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1478 // gfx8 and older. 1479 bool AlignedBy16 = Alignment >= Align(16); 1480 if (IsFast) 1481 *IsFast = AlignedBy16; 1482 1483 return AlignedBy16; 1484 } 1485 if (Size == 128) { 1486 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1487 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1488 // single operation using ds_read2/write2_b64. 1489 bool AlignedBy8 = Alignment >= Align(8); 1490 if (IsFast) 1491 *IsFast = AlignedBy8; 1492 1493 return AlignedBy8; 1494 } 1495 } 1496 1497 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1498 bool AlignedBy4 = Alignment >= Align(4); 1499 if (IsFast) 1500 *IsFast = AlignedBy4; 1501 1502 return AlignedBy4 || 1503 Subtarget->enableFlatScratch() || 1504 Subtarget->hasUnalignedScratchAccess(); 1505 } 1506 1507 // FIXME: We have to be conservative here and assume that flat operations 1508 // will access scratch. If we had access to the IR function, then we 1509 // could determine if any private memory was used in the function. 1510 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1511 !Subtarget->hasUnalignedScratchAccess()) { 1512 bool AlignedBy4 = Alignment >= Align(4); 1513 if (IsFast) 1514 *IsFast = AlignedBy4; 1515 1516 return AlignedBy4; 1517 } 1518 1519 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1520 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1521 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1522 // If we have an uniform constant load, it still requires using a slow 1523 // buffer instruction if unaligned. 1524 if (IsFast) { 1525 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1526 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1527 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1528 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1529 Alignment >= Align(4) : Alignment != Align(2); 1530 } 1531 1532 return true; 1533 } 1534 1535 // Smaller than dword value must be aligned. 1536 if (Size < 32) 1537 return false; 1538 1539 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1540 // byte-address are ignored, thus forcing Dword alignment. 1541 // This applies to private, global, and constant memory. 1542 if (IsFast) 1543 *IsFast = true; 1544 1545 return Size >= 32 && Alignment >= Align(4); 1546 } 1547 1548 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1549 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1550 bool *IsFast) const { 1551 if (IsFast) 1552 *IsFast = false; 1553 1554 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1555 // which isn't a simple VT. 1556 // Until MVT is extended to handle this, simply check for the size and 1557 // rely on the condition below: allow accesses if the size is a multiple of 4. 1558 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1559 VT.getStoreSize() > 16)) { 1560 return false; 1561 } 1562 1563 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1564 Alignment, Flags, IsFast); 1565 } 1566 1567 EVT SITargetLowering::getOptimalMemOpType( 1568 const MemOp &Op, const AttributeList &FuncAttributes) const { 1569 // FIXME: Should account for address space here. 1570 1571 // The default fallback uses the private pointer size as a guess for a type to 1572 // use. Make sure we switch these to 64-bit accesses. 1573 1574 if (Op.size() >= 16 && 1575 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1576 return MVT::v4i32; 1577 1578 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1579 return MVT::v2i32; 1580 1581 // Use the default. 1582 return MVT::Other; 1583 } 1584 1585 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1586 const MemSDNode *MemNode = cast<MemSDNode>(N); 1587 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1588 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1589 return I && I->getMetadata("amdgpu.noclobber"); 1590 } 1591 1592 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1593 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1594 AS == AMDGPUAS::PRIVATE_ADDRESS; 1595 } 1596 1597 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1598 unsigned DestAS) const { 1599 // Flat -> private/local is a simple truncate. 1600 // Flat -> global is no-op 1601 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1602 return true; 1603 1604 const GCNTargetMachine &TM = 1605 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1606 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1607 } 1608 1609 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1610 const MemSDNode *MemNode = cast<MemSDNode>(N); 1611 1612 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1613 } 1614 1615 TargetLoweringBase::LegalizeTypeAction 1616 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1617 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1618 VT.getScalarType().bitsLE(MVT::i16)) 1619 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1620 return TargetLoweringBase::getPreferredVectorAction(VT); 1621 } 1622 1623 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1624 Type *Ty) const { 1625 // FIXME: Could be smarter if called for vector constants. 1626 return true; 1627 } 1628 1629 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1630 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1631 switch (Op) { 1632 case ISD::LOAD: 1633 case ISD::STORE: 1634 1635 // These operations are done with 32-bit instructions anyway. 1636 case ISD::AND: 1637 case ISD::OR: 1638 case ISD::XOR: 1639 case ISD::SELECT: 1640 // TODO: Extensions? 1641 return true; 1642 default: 1643 return false; 1644 } 1645 } 1646 1647 // SimplifySetCC uses this function to determine whether or not it should 1648 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1649 if (VT == MVT::i1 && Op == ISD::SETCC) 1650 return false; 1651 1652 return TargetLowering::isTypeDesirableForOp(Op, VT); 1653 } 1654 1655 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1656 const SDLoc &SL, 1657 SDValue Chain, 1658 uint64_t Offset) const { 1659 const DataLayout &DL = DAG.getDataLayout(); 1660 MachineFunction &MF = DAG.getMachineFunction(); 1661 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1662 1663 const ArgDescriptor *InputPtrReg; 1664 const TargetRegisterClass *RC; 1665 LLT ArgTy; 1666 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1667 1668 std::tie(InputPtrReg, RC, ArgTy) = 1669 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1670 1671 // We may not have the kernarg segment argument if we have no kernel 1672 // arguments. 1673 if (!InputPtrReg) 1674 return DAG.getConstant(0, SL, PtrVT); 1675 1676 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1677 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1678 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1679 1680 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1681 } 1682 1683 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1684 const SDLoc &SL) const { 1685 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1686 FIRST_IMPLICIT); 1687 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1688 } 1689 1690 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1691 const SDLoc &SL, SDValue Val, 1692 bool Signed, 1693 const ISD::InputArg *Arg) const { 1694 // First, if it is a widened vector, narrow it. 1695 if (VT.isVector() && 1696 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1697 EVT NarrowedVT = 1698 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1699 VT.getVectorNumElements()); 1700 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1701 DAG.getConstant(0, SL, MVT::i32)); 1702 } 1703 1704 // Then convert the vector elements or scalar value. 1705 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1706 VT.bitsLT(MemVT)) { 1707 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1708 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1709 } 1710 1711 if (MemVT.isFloatingPoint()) 1712 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1713 else if (Signed) 1714 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1715 else 1716 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1717 1718 return Val; 1719 } 1720 1721 SDValue SITargetLowering::lowerKernargMemParameter( 1722 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1723 uint64_t Offset, Align Alignment, bool Signed, 1724 const ISD::InputArg *Arg) const { 1725 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1726 1727 // Try to avoid using an extload by loading earlier than the argument address, 1728 // and extracting the relevant bits. The load should hopefully be merged with 1729 // the previous argument. 1730 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1731 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1732 int64_t AlignDownOffset = alignDown(Offset, 4); 1733 int64_t OffsetDiff = Offset - AlignDownOffset; 1734 1735 EVT IntVT = MemVT.changeTypeToInteger(); 1736 1737 // TODO: If we passed in the base kernel offset we could have a better 1738 // alignment than 4, but we don't really need it. 1739 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1740 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1741 MachineMemOperand::MODereferenceable | 1742 MachineMemOperand::MOInvariant); 1743 1744 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1745 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1746 1747 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1748 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1749 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1750 1751 1752 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1753 } 1754 1755 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1756 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1757 MachineMemOperand::MODereferenceable | 1758 MachineMemOperand::MOInvariant); 1759 1760 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1761 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1762 } 1763 1764 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1765 const SDLoc &SL, SDValue Chain, 1766 const ISD::InputArg &Arg) const { 1767 MachineFunction &MF = DAG.getMachineFunction(); 1768 MachineFrameInfo &MFI = MF.getFrameInfo(); 1769 1770 if (Arg.Flags.isByVal()) { 1771 unsigned Size = Arg.Flags.getByValSize(); 1772 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1773 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1774 } 1775 1776 unsigned ArgOffset = VA.getLocMemOffset(); 1777 unsigned ArgSize = VA.getValVT().getStoreSize(); 1778 1779 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1780 1781 // Create load nodes to retrieve arguments from the stack. 1782 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1783 SDValue ArgValue; 1784 1785 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1786 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1787 MVT MemVT = VA.getValVT(); 1788 1789 switch (VA.getLocInfo()) { 1790 default: 1791 break; 1792 case CCValAssign::BCvt: 1793 MemVT = VA.getLocVT(); 1794 break; 1795 case CCValAssign::SExt: 1796 ExtType = ISD::SEXTLOAD; 1797 break; 1798 case CCValAssign::ZExt: 1799 ExtType = ISD::ZEXTLOAD; 1800 break; 1801 case CCValAssign::AExt: 1802 ExtType = ISD::EXTLOAD; 1803 break; 1804 } 1805 1806 ArgValue = DAG.getExtLoad( 1807 ExtType, SL, VA.getLocVT(), Chain, FIN, 1808 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1809 MemVT); 1810 return ArgValue; 1811 } 1812 1813 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1814 const SIMachineFunctionInfo &MFI, 1815 EVT VT, 1816 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1817 const ArgDescriptor *Reg; 1818 const TargetRegisterClass *RC; 1819 LLT Ty; 1820 1821 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1822 if (!Reg) { 1823 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1824 // It's possible for a kernarg intrinsic call to appear in a kernel with 1825 // no allocated segment, in which case we do not add the user sgpr 1826 // argument, so just return null. 1827 return DAG.getConstant(0, SDLoc(), VT); 1828 } 1829 1830 // It's undefined behavior if a function marked with the amdgpu-no-* 1831 // attributes uses the corresponding intrinsic. 1832 return DAG.getUNDEF(VT); 1833 } 1834 1835 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1836 } 1837 1838 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1839 CallingConv::ID CallConv, 1840 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1841 FunctionType *FType, 1842 SIMachineFunctionInfo *Info) { 1843 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1844 const ISD::InputArg *Arg = &Ins[I]; 1845 1846 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1847 "vector type argument should have been split"); 1848 1849 // First check if it's a PS input addr. 1850 if (CallConv == CallingConv::AMDGPU_PS && 1851 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1852 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1853 1854 // Inconveniently only the first part of the split is marked as isSplit, 1855 // so skip to the end. We only want to increment PSInputNum once for the 1856 // entire split argument. 1857 if (Arg->Flags.isSplit()) { 1858 while (!Arg->Flags.isSplitEnd()) { 1859 assert((!Arg->VT.isVector() || 1860 Arg->VT.getScalarSizeInBits() == 16) && 1861 "unexpected vector split in ps argument type"); 1862 if (!SkipArg) 1863 Splits.push_back(*Arg); 1864 Arg = &Ins[++I]; 1865 } 1866 } 1867 1868 if (SkipArg) { 1869 // We can safely skip PS inputs. 1870 Skipped.set(Arg->getOrigArgIndex()); 1871 ++PSInputNum; 1872 continue; 1873 } 1874 1875 Info->markPSInputAllocated(PSInputNum); 1876 if (Arg->Used) 1877 Info->markPSInputEnabled(PSInputNum); 1878 1879 ++PSInputNum; 1880 } 1881 1882 Splits.push_back(*Arg); 1883 } 1884 } 1885 1886 // Allocate special inputs passed in VGPRs. 1887 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1888 MachineFunction &MF, 1889 const SIRegisterInfo &TRI, 1890 SIMachineFunctionInfo &Info) const { 1891 const LLT S32 = LLT::scalar(32); 1892 MachineRegisterInfo &MRI = MF.getRegInfo(); 1893 1894 if (Info.hasWorkItemIDX()) { 1895 Register Reg = AMDGPU::VGPR0; 1896 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1897 1898 CCInfo.AllocateReg(Reg); 1899 unsigned Mask = (Subtarget->hasPackedTID() && 1900 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1901 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1902 } 1903 1904 if (Info.hasWorkItemIDY()) { 1905 assert(Info.hasWorkItemIDX()); 1906 if (Subtarget->hasPackedTID()) { 1907 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1908 0x3ff << 10)); 1909 } else { 1910 unsigned Reg = AMDGPU::VGPR1; 1911 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1912 1913 CCInfo.AllocateReg(Reg); 1914 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1915 } 1916 } 1917 1918 if (Info.hasWorkItemIDZ()) { 1919 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1920 if (Subtarget->hasPackedTID()) { 1921 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1922 0x3ff << 20)); 1923 } else { 1924 unsigned Reg = AMDGPU::VGPR2; 1925 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1926 1927 CCInfo.AllocateReg(Reg); 1928 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1929 } 1930 } 1931 } 1932 1933 // Try to allocate a VGPR at the end of the argument list, or if no argument 1934 // VGPRs are left allocating a stack slot. 1935 // If \p Mask is is given it indicates bitfield position in the register. 1936 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1937 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1938 ArgDescriptor Arg = ArgDescriptor()) { 1939 if (Arg.isSet()) 1940 return ArgDescriptor::createArg(Arg, Mask); 1941 1942 ArrayRef<MCPhysReg> ArgVGPRs 1943 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1944 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1945 if (RegIdx == ArgVGPRs.size()) { 1946 // Spill to stack required. 1947 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1948 1949 return ArgDescriptor::createStack(Offset, Mask); 1950 } 1951 1952 unsigned Reg = ArgVGPRs[RegIdx]; 1953 Reg = CCInfo.AllocateReg(Reg); 1954 assert(Reg != AMDGPU::NoRegister); 1955 1956 MachineFunction &MF = CCInfo.getMachineFunction(); 1957 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1958 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1959 return ArgDescriptor::createRegister(Reg, Mask); 1960 } 1961 1962 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1963 const TargetRegisterClass *RC, 1964 unsigned NumArgRegs) { 1965 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1966 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1967 if (RegIdx == ArgSGPRs.size()) 1968 report_fatal_error("ran out of SGPRs for arguments"); 1969 1970 unsigned Reg = ArgSGPRs[RegIdx]; 1971 Reg = CCInfo.AllocateReg(Reg); 1972 assert(Reg != AMDGPU::NoRegister); 1973 1974 MachineFunction &MF = CCInfo.getMachineFunction(); 1975 MF.addLiveIn(Reg, RC); 1976 return ArgDescriptor::createRegister(Reg); 1977 } 1978 1979 // If this has a fixed position, we still should allocate the register in the 1980 // CCInfo state. Technically we could get away with this for values passed 1981 // outside of the normal argument range. 1982 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1983 const TargetRegisterClass *RC, 1984 MCRegister Reg) { 1985 Reg = CCInfo.AllocateReg(Reg); 1986 assert(Reg != AMDGPU::NoRegister); 1987 MachineFunction &MF = CCInfo.getMachineFunction(); 1988 MF.addLiveIn(Reg, RC); 1989 } 1990 1991 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1992 if (Arg) { 1993 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1994 Arg.getRegister()); 1995 } else 1996 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1997 } 1998 1999 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2000 if (Arg) { 2001 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2002 Arg.getRegister()); 2003 } else 2004 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2005 } 2006 2007 /// Allocate implicit function VGPR arguments at the end of allocated user 2008 /// arguments. 2009 void SITargetLowering::allocateSpecialInputVGPRs( 2010 CCState &CCInfo, MachineFunction &MF, 2011 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2012 const unsigned Mask = 0x3ff; 2013 ArgDescriptor Arg; 2014 2015 if (Info.hasWorkItemIDX()) { 2016 Arg = allocateVGPR32Input(CCInfo, Mask); 2017 Info.setWorkItemIDX(Arg); 2018 } 2019 2020 if (Info.hasWorkItemIDY()) { 2021 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2022 Info.setWorkItemIDY(Arg); 2023 } 2024 2025 if (Info.hasWorkItemIDZ()) 2026 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2027 } 2028 2029 /// Allocate implicit function VGPR arguments in fixed registers. 2030 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2031 CCState &CCInfo, MachineFunction &MF, 2032 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2033 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2034 if (!Reg) 2035 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2036 2037 const unsigned Mask = 0x3ff; 2038 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2039 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2040 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2041 } 2042 2043 void SITargetLowering::allocateSpecialInputSGPRs( 2044 CCState &CCInfo, 2045 MachineFunction &MF, 2046 const SIRegisterInfo &TRI, 2047 SIMachineFunctionInfo &Info) const { 2048 auto &ArgInfo = Info.getArgInfo(); 2049 2050 // We need to allocate these in place regardless of their use. 2051 const bool IsFixed = AMDGPUTargetMachine::EnableFixedFunctionABI; 2052 2053 // TODO: Unify handling with private memory pointers. 2054 if (IsFixed || Info.hasDispatchPtr()) 2055 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2056 2057 if (IsFixed || Info.hasQueuePtr()) 2058 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2059 2060 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2061 // constant offset from the kernarg segment. 2062 if (IsFixed || Info.hasImplicitArgPtr()) 2063 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2064 2065 if (IsFixed || Info.hasDispatchID()) 2066 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2067 2068 // flat_scratch_init is not applicable for non-kernel functions. 2069 2070 if (IsFixed || Info.hasWorkGroupIDX()) 2071 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2072 2073 if (IsFixed || Info.hasWorkGroupIDY()) 2074 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2075 2076 if (IsFixed || Info.hasWorkGroupIDZ()) 2077 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2078 } 2079 2080 // Allocate special inputs passed in user SGPRs. 2081 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2082 MachineFunction &MF, 2083 const SIRegisterInfo &TRI, 2084 SIMachineFunctionInfo &Info) const { 2085 if (Info.hasImplicitBufferPtr()) { 2086 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2087 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2088 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2089 } 2090 2091 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2092 if (Info.hasPrivateSegmentBuffer()) { 2093 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2094 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2095 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2096 } 2097 2098 if (Info.hasDispatchPtr()) { 2099 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2100 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2101 CCInfo.AllocateReg(DispatchPtrReg); 2102 } 2103 2104 if (Info.hasQueuePtr()) { 2105 Register QueuePtrReg = Info.addQueuePtr(TRI); 2106 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2107 CCInfo.AllocateReg(QueuePtrReg); 2108 } 2109 2110 if (Info.hasKernargSegmentPtr()) { 2111 MachineRegisterInfo &MRI = MF.getRegInfo(); 2112 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2113 CCInfo.AllocateReg(InputPtrReg); 2114 2115 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2116 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2117 } 2118 2119 if (Info.hasDispatchID()) { 2120 Register DispatchIDReg = Info.addDispatchID(TRI); 2121 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2122 CCInfo.AllocateReg(DispatchIDReg); 2123 } 2124 2125 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2126 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2127 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2128 CCInfo.AllocateReg(FlatScratchInitReg); 2129 } 2130 2131 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2132 // these from the dispatch pointer. 2133 } 2134 2135 // Allocate special input registers that are initialized per-wave. 2136 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2137 MachineFunction &MF, 2138 SIMachineFunctionInfo &Info, 2139 CallingConv::ID CallConv, 2140 bool IsShader) const { 2141 if (Info.hasWorkGroupIDX()) { 2142 Register Reg = Info.addWorkGroupIDX(); 2143 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2144 CCInfo.AllocateReg(Reg); 2145 } 2146 2147 if (Info.hasWorkGroupIDY()) { 2148 Register Reg = Info.addWorkGroupIDY(); 2149 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2150 CCInfo.AllocateReg(Reg); 2151 } 2152 2153 if (Info.hasWorkGroupIDZ()) { 2154 Register Reg = Info.addWorkGroupIDZ(); 2155 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2156 CCInfo.AllocateReg(Reg); 2157 } 2158 2159 if (Info.hasWorkGroupInfo()) { 2160 Register Reg = Info.addWorkGroupInfo(); 2161 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2162 CCInfo.AllocateReg(Reg); 2163 } 2164 2165 if (Info.hasPrivateSegmentWaveByteOffset()) { 2166 // Scratch wave offset passed in system SGPR. 2167 unsigned PrivateSegmentWaveByteOffsetReg; 2168 2169 if (IsShader) { 2170 PrivateSegmentWaveByteOffsetReg = 2171 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2172 2173 // This is true if the scratch wave byte offset doesn't have a fixed 2174 // location. 2175 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2176 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2177 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2178 } 2179 } else 2180 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2181 2182 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2183 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2184 } 2185 } 2186 2187 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2188 MachineFunction &MF, 2189 const SIRegisterInfo &TRI, 2190 SIMachineFunctionInfo &Info) { 2191 // Now that we've figured out where the scratch register inputs are, see if 2192 // should reserve the arguments and use them directly. 2193 MachineFrameInfo &MFI = MF.getFrameInfo(); 2194 bool HasStackObjects = MFI.hasStackObjects(); 2195 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2196 2197 // Record that we know we have non-spill stack objects so we don't need to 2198 // check all stack objects later. 2199 if (HasStackObjects) 2200 Info.setHasNonSpillStackObjects(true); 2201 2202 // Everything live out of a block is spilled with fast regalloc, so it's 2203 // almost certain that spilling will be required. 2204 if (TM.getOptLevel() == CodeGenOpt::None) 2205 HasStackObjects = true; 2206 2207 // For now assume stack access is needed in any callee functions, so we need 2208 // the scratch registers to pass in. 2209 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2210 2211 if (!ST.enableFlatScratch()) { 2212 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2213 // If we have stack objects, we unquestionably need the private buffer 2214 // resource. For the Code Object V2 ABI, this will be the first 4 user 2215 // SGPR inputs. We can reserve those and use them directly. 2216 2217 Register PrivateSegmentBufferReg = 2218 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2219 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2220 } else { 2221 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2222 // We tentatively reserve the last registers (skipping the last registers 2223 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2224 // we'll replace these with the ones immediately after those which were 2225 // really allocated. In the prologue copies will be inserted from the 2226 // argument to these reserved registers. 2227 2228 // Without HSA, relocations are used for the scratch pointer and the 2229 // buffer resource setup is always inserted in the prologue. Scratch wave 2230 // offset is still in an input SGPR. 2231 Info.setScratchRSrcReg(ReservedBufferReg); 2232 } 2233 } 2234 2235 MachineRegisterInfo &MRI = MF.getRegInfo(); 2236 2237 // For entry functions we have to set up the stack pointer if we use it, 2238 // whereas non-entry functions get this "for free". This means there is no 2239 // intrinsic advantage to using S32 over S34 in cases where we do not have 2240 // calls but do need a frame pointer (i.e. if we are requested to have one 2241 // because frame pointer elimination is disabled). To keep things simple we 2242 // only ever use S32 as the call ABI stack pointer, and so using it does not 2243 // imply we need a separate frame pointer. 2244 // 2245 // Try to use s32 as the SP, but move it if it would interfere with input 2246 // arguments. This won't work with calls though. 2247 // 2248 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2249 // registers. 2250 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2251 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2252 } else { 2253 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2254 2255 if (MFI.hasCalls()) 2256 report_fatal_error("call in graphics shader with too many input SGPRs"); 2257 2258 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2259 if (!MRI.isLiveIn(Reg)) { 2260 Info.setStackPtrOffsetReg(Reg); 2261 break; 2262 } 2263 } 2264 2265 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2266 report_fatal_error("failed to find register for SP"); 2267 } 2268 2269 // hasFP should be accurate for entry functions even before the frame is 2270 // finalized, because it does not rely on the known stack size, only 2271 // properties like whether variable sized objects are present. 2272 if (ST.getFrameLowering()->hasFP(MF)) { 2273 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2274 } 2275 } 2276 2277 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2278 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2279 return !Info->isEntryFunction(); 2280 } 2281 2282 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2283 2284 } 2285 2286 void SITargetLowering::insertCopiesSplitCSR( 2287 MachineBasicBlock *Entry, 2288 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2289 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2290 2291 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2292 if (!IStart) 2293 return; 2294 2295 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2296 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2297 MachineBasicBlock::iterator MBBI = Entry->begin(); 2298 for (const MCPhysReg *I = IStart; *I; ++I) { 2299 const TargetRegisterClass *RC = nullptr; 2300 if (AMDGPU::SReg_64RegClass.contains(*I)) 2301 RC = &AMDGPU::SGPR_64RegClass; 2302 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2303 RC = &AMDGPU::SGPR_32RegClass; 2304 else 2305 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2306 2307 Register NewVR = MRI->createVirtualRegister(RC); 2308 // Create copy from CSR to a virtual register. 2309 Entry->addLiveIn(*I); 2310 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2311 .addReg(*I); 2312 2313 // Insert the copy-back instructions right before the terminator. 2314 for (auto *Exit : Exits) 2315 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2316 TII->get(TargetOpcode::COPY), *I) 2317 .addReg(NewVR); 2318 } 2319 } 2320 2321 SDValue SITargetLowering::LowerFormalArguments( 2322 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2323 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2324 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2325 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2326 2327 MachineFunction &MF = DAG.getMachineFunction(); 2328 const Function &Fn = MF.getFunction(); 2329 FunctionType *FType = MF.getFunction().getFunctionType(); 2330 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2331 2332 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2333 DiagnosticInfoUnsupported NoGraphicsHSA( 2334 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2335 DAG.getContext()->diagnose(NoGraphicsHSA); 2336 return DAG.getEntryNode(); 2337 } 2338 2339 Info->allocateModuleLDSGlobal(Fn.getParent()); 2340 2341 SmallVector<ISD::InputArg, 16> Splits; 2342 SmallVector<CCValAssign, 16> ArgLocs; 2343 BitVector Skipped(Ins.size()); 2344 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2345 *DAG.getContext()); 2346 2347 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2348 bool IsKernel = AMDGPU::isKernel(CallConv); 2349 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2350 2351 if (IsGraphics) { 2352 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2353 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2354 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2355 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2356 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2357 !Info->hasWorkItemIDZ()); 2358 } 2359 2360 if (CallConv == CallingConv::AMDGPU_PS) { 2361 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2362 2363 // At least one interpolation mode must be enabled or else the GPU will 2364 // hang. 2365 // 2366 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2367 // set PSInputAddr, the user wants to enable some bits after the compilation 2368 // based on run-time states. Since we can't know what the final PSInputEna 2369 // will look like, so we shouldn't do anything here and the user should take 2370 // responsibility for the correct programming. 2371 // 2372 // Otherwise, the following restrictions apply: 2373 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2374 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2375 // enabled too. 2376 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2377 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2378 CCInfo.AllocateReg(AMDGPU::VGPR0); 2379 CCInfo.AllocateReg(AMDGPU::VGPR1); 2380 Info->markPSInputAllocated(0); 2381 Info->markPSInputEnabled(0); 2382 } 2383 if (Subtarget->isAmdPalOS()) { 2384 // For isAmdPalOS, the user does not enable some bits after compilation 2385 // based on run-time states; the register values being generated here are 2386 // the final ones set in hardware. Therefore we need to apply the 2387 // workaround to PSInputAddr and PSInputEnable together. (The case where 2388 // a bit is set in PSInputAddr but not PSInputEnable is where the 2389 // frontend set up an input arg for a particular interpolation mode, but 2390 // nothing uses that input arg. Really we should have an earlier pass 2391 // that removes such an arg.) 2392 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2393 if ((PsInputBits & 0x7F) == 0 || 2394 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2395 Info->markPSInputEnabled( 2396 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2397 } 2398 } else if (IsKernel) { 2399 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2400 } else { 2401 Splits.append(Ins.begin(), Ins.end()); 2402 } 2403 2404 if (IsEntryFunc) { 2405 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2406 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2407 } else { 2408 // For the fixed ABI, pass workitem IDs in the last argument register. 2409 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2410 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2411 } 2412 2413 if (IsKernel) { 2414 analyzeFormalArgumentsCompute(CCInfo, Ins); 2415 } else { 2416 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2417 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2418 } 2419 2420 SmallVector<SDValue, 16> Chains; 2421 2422 // FIXME: This is the minimum kernel argument alignment. We should improve 2423 // this to the maximum alignment of the arguments. 2424 // 2425 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2426 // kern arg offset. 2427 const Align KernelArgBaseAlign = Align(16); 2428 2429 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2430 const ISD::InputArg &Arg = Ins[i]; 2431 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2432 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2433 continue; 2434 } 2435 2436 CCValAssign &VA = ArgLocs[ArgIdx++]; 2437 MVT VT = VA.getLocVT(); 2438 2439 if (IsEntryFunc && VA.isMemLoc()) { 2440 VT = Ins[i].VT; 2441 EVT MemVT = VA.getLocVT(); 2442 2443 const uint64_t Offset = VA.getLocMemOffset(); 2444 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2445 2446 if (Arg.Flags.isByRef()) { 2447 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2448 2449 const GCNTargetMachine &TM = 2450 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2451 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2452 Arg.Flags.getPointerAddrSpace())) { 2453 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2454 Arg.Flags.getPointerAddrSpace()); 2455 } 2456 2457 InVals.push_back(Ptr); 2458 continue; 2459 } 2460 2461 SDValue Arg = lowerKernargMemParameter( 2462 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2463 Chains.push_back(Arg.getValue(1)); 2464 2465 auto *ParamTy = 2466 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2467 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2468 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2469 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2470 // On SI local pointers are just offsets into LDS, so they are always 2471 // less than 16-bits. On CI and newer they could potentially be 2472 // real pointers, so we can't guarantee their size. 2473 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2474 DAG.getValueType(MVT::i16)); 2475 } 2476 2477 InVals.push_back(Arg); 2478 continue; 2479 } else if (!IsEntryFunc && VA.isMemLoc()) { 2480 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2481 InVals.push_back(Val); 2482 if (!Arg.Flags.isByVal()) 2483 Chains.push_back(Val.getValue(1)); 2484 continue; 2485 } 2486 2487 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2488 2489 Register Reg = VA.getLocReg(); 2490 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2491 EVT ValVT = VA.getValVT(); 2492 2493 Reg = MF.addLiveIn(Reg, RC); 2494 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2495 2496 if (Arg.Flags.isSRet()) { 2497 // The return object should be reasonably addressable. 2498 2499 // FIXME: This helps when the return is a real sret. If it is a 2500 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2501 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2502 unsigned NumBits 2503 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2504 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2505 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2506 } 2507 2508 // If this is an 8 or 16-bit value, it is really passed promoted 2509 // to 32 bits. Insert an assert[sz]ext to capture this, then 2510 // truncate to the right size. 2511 switch (VA.getLocInfo()) { 2512 case CCValAssign::Full: 2513 break; 2514 case CCValAssign::BCvt: 2515 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2516 break; 2517 case CCValAssign::SExt: 2518 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2519 DAG.getValueType(ValVT)); 2520 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2521 break; 2522 case CCValAssign::ZExt: 2523 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2524 DAG.getValueType(ValVT)); 2525 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2526 break; 2527 case CCValAssign::AExt: 2528 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2529 break; 2530 default: 2531 llvm_unreachable("Unknown loc info!"); 2532 } 2533 2534 InVals.push_back(Val); 2535 } 2536 2537 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2538 // Special inputs come after user arguments. 2539 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2540 } 2541 2542 // Start adding system SGPRs. 2543 if (IsEntryFunc) { 2544 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2545 } else { 2546 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2547 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2548 } 2549 2550 auto &ArgUsageInfo = 2551 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2552 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2553 2554 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2555 Info->setBytesInStackArgArea(StackArgSize); 2556 2557 return Chains.empty() ? Chain : 2558 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2559 } 2560 2561 // TODO: If return values can't fit in registers, we should return as many as 2562 // possible in registers before passing on stack. 2563 bool SITargetLowering::CanLowerReturn( 2564 CallingConv::ID CallConv, 2565 MachineFunction &MF, bool IsVarArg, 2566 const SmallVectorImpl<ISD::OutputArg> &Outs, 2567 LLVMContext &Context) const { 2568 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2569 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2570 // for shaders. Vector types should be explicitly handled by CC. 2571 if (AMDGPU::isEntryFunctionCC(CallConv)) 2572 return true; 2573 2574 SmallVector<CCValAssign, 16> RVLocs; 2575 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2576 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2577 } 2578 2579 SDValue 2580 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2581 bool isVarArg, 2582 const SmallVectorImpl<ISD::OutputArg> &Outs, 2583 const SmallVectorImpl<SDValue> &OutVals, 2584 const SDLoc &DL, SelectionDAG &DAG) const { 2585 MachineFunction &MF = DAG.getMachineFunction(); 2586 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2587 2588 if (AMDGPU::isKernel(CallConv)) { 2589 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2590 OutVals, DL, DAG); 2591 } 2592 2593 bool IsShader = AMDGPU::isShader(CallConv); 2594 2595 Info->setIfReturnsVoid(Outs.empty()); 2596 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2597 2598 // CCValAssign - represent the assignment of the return value to a location. 2599 SmallVector<CCValAssign, 48> RVLocs; 2600 SmallVector<ISD::OutputArg, 48> Splits; 2601 2602 // CCState - Info about the registers and stack slots. 2603 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2604 *DAG.getContext()); 2605 2606 // Analyze outgoing return values. 2607 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2608 2609 SDValue Flag; 2610 SmallVector<SDValue, 48> RetOps; 2611 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2612 2613 // Add return address for callable functions. 2614 if (!Info->isEntryFunction()) { 2615 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2616 SDValue ReturnAddrReg = CreateLiveInRegister( 2617 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2618 2619 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2620 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2621 MVT::i64); 2622 Chain = 2623 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2624 Flag = Chain.getValue(1); 2625 RetOps.push_back(ReturnAddrVirtualReg); 2626 } 2627 2628 // Copy the result values into the output registers. 2629 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2630 ++I, ++RealRVLocIdx) { 2631 CCValAssign &VA = RVLocs[I]; 2632 assert(VA.isRegLoc() && "Can only return in registers!"); 2633 // TODO: Partially return in registers if return values don't fit. 2634 SDValue Arg = OutVals[RealRVLocIdx]; 2635 2636 // Copied from other backends. 2637 switch (VA.getLocInfo()) { 2638 case CCValAssign::Full: 2639 break; 2640 case CCValAssign::BCvt: 2641 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2642 break; 2643 case CCValAssign::SExt: 2644 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2645 break; 2646 case CCValAssign::ZExt: 2647 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2648 break; 2649 case CCValAssign::AExt: 2650 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2651 break; 2652 default: 2653 llvm_unreachable("Unknown loc info!"); 2654 } 2655 2656 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2657 Flag = Chain.getValue(1); 2658 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2659 } 2660 2661 // FIXME: Does sret work properly? 2662 if (!Info->isEntryFunction()) { 2663 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2664 const MCPhysReg *I = 2665 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2666 if (I) { 2667 for (; *I; ++I) { 2668 if (AMDGPU::SReg_64RegClass.contains(*I)) 2669 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2670 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2671 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2672 else 2673 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2674 } 2675 } 2676 } 2677 2678 // Update chain and glue. 2679 RetOps[0] = Chain; 2680 if (Flag.getNode()) 2681 RetOps.push_back(Flag); 2682 2683 unsigned Opc = AMDGPUISD::ENDPGM; 2684 if (!IsWaveEnd) 2685 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2686 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2687 } 2688 2689 SDValue SITargetLowering::LowerCallResult( 2690 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2691 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2692 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2693 SDValue ThisVal) const { 2694 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2695 2696 // Assign locations to each value returned by this call. 2697 SmallVector<CCValAssign, 16> RVLocs; 2698 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2699 *DAG.getContext()); 2700 CCInfo.AnalyzeCallResult(Ins, RetCC); 2701 2702 // Copy all of the result registers out of their specified physreg. 2703 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2704 CCValAssign VA = RVLocs[i]; 2705 SDValue Val; 2706 2707 if (VA.isRegLoc()) { 2708 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2709 Chain = Val.getValue(1); 2710 InFlag = Val.getValue(2); 2711 } else if (VA.isMemLoc()) { 2712 report_fatal_error("TODO: return values in memory"); 2713 } else 2714 llvm_unreachable("unknown argument location type"); 2715 2716 switch (VA.getLocInfo()) { 2717 case CCValAssign::Full: 2718 break; 2719 case CCValAssign::BCvt: 2720 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2721 break; 2722 case CCValAssign::ZExt: 2723 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2724 DAG.getValueType(VA.getValVT())); 2725 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2726 break; 2727 case CCValAssign::SExt: 2728 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2729 DAG.getValueType(VA.getValVT())); 2730 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2731 break; 2732 case CCValAssign::AExt: 2733 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2734 break; 2735 default: 2736 llvm_unreachable("Unknown loc info!"); 2737 } 2738 2739 InVals.push_back(Val); 2740 } 2741 2742 return Chain; 2743 } 2744 2745 // Add code to pass special inputs required depending on used features separate 2746 // from the explicit user arguments present in the IR. 2747 void SITargetLowering::passSpecialInputs( 2748 CallLoweringInfo &CLI, 2749 CCState &CCInfo, 2750 const SIMachineFunctionInfo &Info, 2751 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2752 SmallVectorImpl<SDValue> &MemOpChains, 2753 SDValue Chain) const { 2754 // If we don't have a call site, this was a call inserted by 2755 // legalization. These can never use special inputs. 2756 if (!CLI.CB) 2757 return; 2758 2759 SelectionDAG &DAG = CLI.DAG; 2760 const SDLoc &DL = CLI.DL; 2761 2762 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2763 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2764 2765 const AMDGPUFunctionArgInfo *CalleeArgInfo 2766 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2767 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2768 auto &ArgUsageInfo = 2769 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2770 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2771 } 2772 2773 // TODO: Unify with private memory register handling. This is complicated by 2774 // the fact that at least in kernels, the input argument is not necessarily 2775 // in the same location as the input. 2776 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2777 StringLiteral> ImplicitAttrs[] = { 2778 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2779 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2780 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2781 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2782 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2783 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2784 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2785 }; 2786 2787 for (auto Attr : ImplicitAttrs) { 2788 const ArgDescriptor *OutgoingArg; 2789 const TargetRegisterClass *ArgRC; 2790 LLT ArgTy; 2791 2792 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2793 2794 // If the callee does not use the attribute value, skip copying the value. 2795 if (CLI.CB->hasFnAttr(Attr.second)) 2796 continue; 2797 2798 std::tie(OutgoingArg, ArgRC, ArgTy) = 2799 CalleeArgInfo->getPreloadedValue(InputID); 2800 if (!OutgoingArg) 2801 continue; 2802 2803 const ArgDescriptor *IncomingArg; 2804 const TargetRegisterClass *IncomingArgRC; 2805 LLT Ty; 2806 std::tie(IncomingArg, IncomingArgRC, Ty) = 2807 CallerArgInfo.getPreloadedValue(InputID); 2808 assert(IncomingArgRC == ArgRC); 2809 2810 // All special arguments are ints for now. 2811 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2812 SDValue InputReg; 2813 2814 if (IncomingArg) { 2815 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2816 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2817 // The implicit arg ptr is special because it doesn't have a corresponding 2818 // input for kernels, and is computed from the kernarg segment pointer. 2819 InputReg = getImplicitArgPtr(DAG, DL); 2820 } else { 2821 // We may have proven the input wasn't needed, although the ABI is 2822 // requiring it. We just need to allocate the register appropriately. 2823 InputReg = DAG.getUNDEF(ArgVT); 2824 } 2825 2826 if (OutgoingArg->isRegister()) { 2827 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2828 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2829 report_fatal_error("failed to allocate implicit input argument"); 2830 } else { 2831 unsigned SpecialArgOffset = 2832 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2833 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2834 SpecialArgOffset); 2835 MemOpChains.push_back(ArgStore); 2836 } 2837 } 2838 2839 // Pack workitem IDs into a single register or pass it as is if already 2840 // packed. 2841 const ArgDescriptor *OutgoingArg; 2842 const TargetRegisterClass *ArgRC; 2843 LLT Ty; 2844 2845 std::tie(OutgoingArg, ArgRC, Ty) = 2846 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2847 if (!OutgoingArg) 2848 std::tie(OutgoingArg, ArgRC, Ty) = 2849 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2850 if (!OutgoingArg) 2851 std::tie(OutgoingArg, ArgRC, Ty) = 2852 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2853 if (!OutgoingArg) 2854 return; 2855 2856 const ArgDescriptor *IncomingArgX = std::get<0>( 2857 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2858 const ArgDescriptor *IncomingArgY = std::get<0>( 2859 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2860 const ArgDescriptor *IncomingArgZ = std::get<0>( 2861 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2862 2863 SDValue InputReg; 2864 SDLoc SL; 2865 2866 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2867 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2868 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2869 2870 // If incoming ids are not packed we need to pack them. 2871 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2872 NeedWorkItemIDX) 2873 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2874 2875 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2876 NeedWorkItemIDY) { 2877 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2878 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2879 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2880 InputReg = InputReg.getNode() ? 2881 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2882 } 2883 2884 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2885 NeedWorkItemIDZ) { 2886 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2887 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2888 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2889 InputReg = InputReg.getNode() ? 2890 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2891 } 2892 2893 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2894 // Workitem ids are already packed, any of present incoming arguments 2895 // will carry all required fields. 2896 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2897 IncomingArgX ? *IncomingArgX : 2898 IncomingArgY ? *IncomingArgY : 2899 *IncomingArgZ, ~0u); 2900 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2901 } 2902 2903 if (OutgoingArg->isRegister()) { 2904 if (InputReg) 2905 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2906 2907 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2908 } else { 2909 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2910 if (InputReg) { 2911 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2912 SpecialArgOffset); 2913 MemOpChains.push_back(ArgStore); 2914 } 2915 } 2916 } 2917 2918 static bool canGuaranteeTCO(CallingConv::ID CC) { 2919 return CC == CallingConv::Fast; 2920 } 2921 2922 /// Return true if we might ever do TCO for calls with this calling convention. 2923 static bool mayTailCallThisCC(CallingConv::ID CC) { 2924 switch (CC) { 2925 case CallingConv::C: 2926 case CallingConv::AMDGPU_Gfx: 2927 return true; 2928 default: 2929 return canGuaranteeTCO(CC); 2930 } 2931 } 2932 2933 bool SITargetLowering::isEligibleForTailCallOptimization( 2934 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2935 const SmallVectorImpl<ISD::OutputArg> &Outs, 2936 const SmallVectorImpl<SDValue> &OutVals, 2937 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2938 if (!mayTailCallThisCC(CalleeCC)) 2939 return false; 2940 2941 // For a divergent call target, we need to do a waterfall loop over the 2942 // possible callees which precludes us from using a simple jump. 2943 if (Callee->isDivergent()) 2944 return false; 2945 2946 MachineFunction &MF = DAG.getMachineFunction(); 2947 const Function &CallerF = MF.getFunction(); 2948 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2949 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2950 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2951 2952 // Kernels aren't callable, and don't have a live in return address so it 2953 // doesn't make sense to do a tail call with entry functions. 2954 if (!CallerPreserved) 2955 return false; 2956 2957 bool CCMatch = CallerCC == CalleeCC; 2958 2959 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2960 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2961 return true; 2962 return false; 2963 } 2964 2965 // TODO: Can we handle var args? 2966 if (IsVarArg) 2967 return false; 2968 2969 for (const Argument &Arg : CallerF.args()) { 2970 if (Arg.hasByValAttr()) 2971 return false; 2972 } 2973 2974 LLVMContext &Ctx = *DAG.getContext(); 2975 2976 // Check that the call results are passed in the same way. 2977 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2978 CCAssignFnForCall(CalleeCC, IsVarArg), 2979 CCAssignFnForCall(CallerCC, IsVarArg))) 2980 return false; 2981 2982 // The callee has to preserve all registers the caller needs to preserve. 2983 if (!CCMatch) { 2984 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2985 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2986 return false; 2987 } 2988 2989 // Nothing more to check if the callee is taking no arguments. 2990 if (Outs.empty()) 2991 return true; 2992 2993 SmallVector<CCValAssign, 16> ArgLocs; 2994 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2995 2996 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2997 2998 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2999 // If the stack arguments for this call do not fit into our own save area then 3000 // the call cannot be made tail. 3001 // TODO: Is this really necessary? 3002 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3003 return false; 3004 3005 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3006 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3007 } 3008 3009 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3010 if (!CI->isTailCall()) 3011 return false; 3012 3013 const Function *ParentFn = CI->getParent()->getParent(); 3014 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3015 return false; 3016 return true; 3017 } 3018 3019 // The wave scratch offset register is used as the global base pointer. 3020 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3021 SmallVectorImpl<SDValue> &InVals) const { 3022 SelectionDAG &DAG = CLI.DAG; 3023 const SDLoc &DL = CLI.DL; 3024 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3025 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3026 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3027 SDValue Chain = CLI.Chain; 3028 SDValue Callee = CLI.Callee; 3029 bool &IsTailCall = CLI.IsTailCall; 3030 CallingConv::ID CallConv = CLI.CallConv; 3031 bool IsVarArg = CLI.IsVarArg; 3032 bool IsSibCall = false; 3033 bool IsThisReturn = false; 3034 MachineFunction &MF = DAG.getMachineFunction(); 3035 3036 if (Callee.isUndef() || isNullConstant(Callee)) { 3037 if (!CLI.IsTailCall) { 3038 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3039 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3040 } 3041 3042 return Chain; 3043 } 3044 3045 if (IsVarArg) { 3046 return lowerUnhandledCall(CLI, InVals, 3047 "unsupported call to variadic function "); 3048 } 3049 3050 if (!CLI.CB) 3051 report_fatal_error("unsupported libcall legalization"); 3052 3053 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3054 return lowerUnhandledCall(CLI, InVals, 3055 "unsupported required tail call to function "); 3056 } 3057 3058 if (AMDGPU::isShader(CallConv)) { 3059 // Note the issue is with the CC of the called function, not of the call 3060 // itself. 3061 return lowerUnhandledCall(CLI, InVals, 3062 "unsupported call to a shader function "); 3063 } 3064 3065 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3066 CallConv != CallingConv::AMDGPU_Gfx) { 3067 // Only allow calls with specific calling conventions. 3068 return lowerUnhandledCall(CLI, InVals, 3069 "unsupported calling convention for call from " 3070 "graphics shader of function "); 3071 } 3072 3073 if (IsTailCall) { 3074 IsTailCall = isEligibleForTailCallOptimization( 3075 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3076 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3077 report_fatal_error("failed to perform tail call elimination on a call " 3078 "site marked musttail"); 3079 } 3080 3081 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3082 3083 // A sibling call is one where we're under the usual C ABI and not planning 3084 // to change that but can still do a tail call: 3085 if (!TailCallOpt && IsTailCall) 3086 IsSibCall = true; 3087 3088 if (IsTailCall) 3089 ++NumTailCalls; 3090 } 3091 3092 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3093 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3094 SmallVector<SDValue, 8> MemOpChains; 3095 3096 // Analyze operands of the call, assigning locations to each operand. 3097 SmallVector<CCValAssign, 16> ArgLocs; 3098 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3099 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3100 3101 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3102 CallConv != CallingConv::AMDGPU_Gfx) { 3103 // With a fixed ABI, allocate fixed registers before user arguments. 3104 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3105 } 3106 3107 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3108 3109 // Get a count of how many bytes are to be pushed on the stack. 3110 unsigned NumBytes = CCInfo.getNextStackOffset(); 3111 3112 if (IsSibCall) { 3113 // Since we're not changing the ABI to make this a tail call, the memory 3114 // operands are already available in the caller's incoming argument space. 3115 NumBytes = 0; 3116 } 3117 3118 // FPDiff is the byte offset of the call's argument area from the callee's. 3119 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3120 // by this amount for a tail call. In a sibling call it must be 0 because the 3121 // caller will deallocate the entire stack and the callee still expects its 3122 // arguments to begin at SP+0. Completely unused for non-tail calls. 3123 int32_t FPDiff = 0; 3124 MachineFrameInfo &MFI = MF.getFrameInfo(); 3125 3126 // Adjust the stack pointer for the new arguments... 3127 // These operations are automatically eliminated by the prolog/epilog pass 3128 if (!IsSibCall) { 3129 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3130 3131 if (!Subtarget->enableFlatScratch()) { 3132 SmallVector<SDValue, 4> CopyFromChains; 3133 3134 // In the HSA case, this should be an identity copy. 3135 SDValue ScratchRSrcReg 3136 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3137 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3138 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3139 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3140 } 3141 } 3142 3143 MVT PtrVT = MVT::i32; 3144 3145 // Walk the register/memloc assignments, inserting copies/loads. 3146 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3147 CCValAssign &VA = ArgLocs[i]; 3148 SDValue Arg = OutVals[i]; 3149 3150 // Promote the value if needed. 3151 switch (VA.getLocInfo()) { 3152 case CCValAssign::Full: 3153 break; 3154 case CCValAssign::BCvt: 3155 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3156 break; 3157 case CCValAssign::ZExt: 3158 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3159 break; 3160 case CCValAssign::SExt: 3161 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3162 break; 3163 case CCValAssign::AExt: 3164 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3165 break; 3166 case CCValAssign::FPExt: 3167 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3168 break; 3169 default: 3170 llvm_unreachable("Unknown loc info!"); 3171 } 3172 3173 if (VA.isRegLoc()) { 3174 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3175 } else { 3176 assert(VA.isMemLoc()); 3177 3178 SDValue DstAddr; 3179 MachinePointerInfo DstInfo; 3180 3181 unsigned LocMemOffset = VA.getLocMemOffset(); 3182 int32_t Offset = LocMemOffset; 3183 3184 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3185 MaybeAlign Alignment; 3186 3187 if (IsTailCall) { 3188 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3189 unsigned OpSize = Flags.isByVal() ? 3190 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3191 3192 // FIXME: We can have better than the minimum byval required alignment. 3193 Alignment = 3194 Flags.isByVal() 3195 ? Flags.getNonZeroByValAlign() 3196 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3197 3198 Offset = Offset + FPDiff; 3199 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3200 3201 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3202 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3203 3204 // Make sure any stack arguments overlapping with where we're storing 3205 // are loaded before this eventual operation. Otherwise they'll be 3206 // clobbered. 3207 3208 // FIXME: Why is this really necessary? This seems to just result in a 3209 // lot of code to copy the stack and write them back to the same 3210 // locations, which are supposed to be immutable? 3211 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3212 } else { 3213 // Stores to the argument stack area are relative to the stack pointer. 3214 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3215 MVT::i32); 3216 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3217 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3218 Alignment = 3219 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3220 } 3221 3222 if (Outs[i].Flags.isByVal()) { 3223 SDValue SizeNode = 3224 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3225 SDValue Cpy = 3226 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3227 Outs[i].Flags.getNonZeroByValAlign(), 3228 /*isVol = */ false, /*AlwaysInline = */ true, 3229 /*isTailCall = */ false, DstInfo, 3230 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3231 3232 MemOpChains.push_back(Cpy); 3233 } else { 3234 SDValue Store = 3235 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3236 MemOpChains.push_back(Store); 3237 } 3238 } 3239 } 3240 3241 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3242 CallConv != CallingConv::AMDGPU_Gfx) { 3243 // Copy special input registers after user input arguments. 3244 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3245 } 3246 3247 if (!MemOpChains.empty()) 3248 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3249 3250 // Build a sequence of copy-to-reg nodes chained together with token chain 3251 // and flag operands which copy the outgoing args into the appropriate regs. 3252 SDValue InFlag; 3253 for (auto &RegToPass : RegsToPass) { 3254 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3255 RegToPass.second, InFlag); 3256 InFlag = Chain.getValue(1); 3257 } 3258 3259 3260 SDValue PhysReturnAddrReg; 3261 if (IsTailCall) { 3262 // Since the return is being combined with the call, we need to pass on the 3263 // return address. 3264 3265 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3266 SDValue ReturnAddrReg = CreateLiveInRegister( 3267 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3268 3269 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3270 MVT::i64); 3271 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3272 InFlag = Chain.getValue(1); 3273 } 3274 3275 // We don't usually want to end the call-sequence here because we would tidy 3276 // the frame up *after* the call, however in the ABI-changing tail-call case 3277 // we've carefully laid out the parameters so that when sp is reset they'll be 3278 // in the correct location. 3279 if (IsTailCall && !IsSibCall) { 3280 Chain = DAG.getCALLSEQ_END(Chain, 3281 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3282 DAG.getTargetConstant(0, DL, MVT::i32), 3283 InFlag, DL); 3284 InFlag = Chain.getValue(1); 3285 } 3286 3287 std::vector<SDValue> Ops; 3288 Ops.push_back(Chain); 3289 Ops.push_back(Callee); 3290 // Add a redundant copy of the callee global which will not be legalized, as 3291 // we need direct access to the callee later. 3292 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3293 const GlobalValue *GV = GSD->getGlobal(); 3294 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3295 } else { 3296 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3297 } 3298 3299 if (IsTailCall) { 3300 // Each tail call may have to adjust the stack by a different amount, so 3301 // this information must travel along with the operation for eventual 3302 // consumption by emitEpilogue. 3303 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3304 3305 Ops.push_back(PhysReturnAddrReg); 3306 } 3307 3308 // Add argument registers to the end of the list so that they are known live 3309 // into the call. 3310 for (auto &RegToPass : RegsToPass) { 3311 Ops.push_back(DAG.getRegister(RegToPass.first, 3312 RegToPass.second.getValueType())); 3313 } 3314 3315 // Add a register mask operand representing the call-preserved registers. 3316 3317 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3318 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3319 assert(Mask && "Missing call preserved mask for calling convention"); 3320 Ops.push_back(DAG.getRegisterMask(Mask)); 3321 3322 if (InFlag.getNode()) 3323 Ops.push_back(InFlag); 3324 3325 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3326 3327 // If we're doing a tall call, use a TC_RETURN here rather than an 3328 // actual call instruction. 3329 if (IsTailCall) { 3330 MFI.setHasTailCall(); 3331 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3332 } 3333 3334 // Returns a chain and a flag for retval copy to use. 3335 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3336 Chain = Call.getValue(0); 3337 InFlag = Call.getValue(1); 3338 3339 uint64_t CalleePopBytes = NumBytes; 3340 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3341 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3342 InFlag, DL); 3343 if (!Ins.empty()) 3344 InFlag = Chain.getValue(1); 3345 3346 // Handle result values, copying them out of physregs into vregs that we 3347 // return. 3348 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3349 InVals, IsThisReturn, 3350 IsThisReturn ? OutVals[0] : SDValue()); 3351 } 3352 3353 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3354 // except for applying the wave size scale to the increment amount. 3355 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3356 SDValue Op, SelectionDAG &DAG) const { 3357 const MachineFunction &MF = DAG.getMachineFunction(); 3358 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3359 3360 SDLoc dl(Op); 3361 EVT VT = Op.getValueType(); 3362 SDValue Tmp1 = Op; 3363 SDValue Tmp2 = Op.getValue(1); 3364 SDValue Tmp3 = Op.getOperand(2); 3365 SDValue Chain = Tmp1.getOperand(0); 3366 3367 Register SPReg = Info->getStackPtrOffsetReg(); 3368 3369 // Chain the dynamic stack allocation so that it doesn't modify the stack 3370 // pointer when other instructions are using the stack. 3371 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3372 3373 SDValue Size = Tmp2.getOperand(1); 3374 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3375 Chain = SP.getValue(1); 3376 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3377 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3378 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3379 unsigned Opc = 3380 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3381 ISD::ADD : ISD::SUB; 3382 3383 SDValue ScaledSize = DAG.getNode( 3384 ISD::SHL, dl, VT, Size, 3385 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3386 3387 Align StackAlign = TFL->getStackAlign(); 3388 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3389 if (Alignment && *Alignment > StackAlign) { 3390 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3391 DAG.getConstant(-(uint64_t)Alignment->value() 3392 << ST.getWavefrontSizeLog2(), 3393 dl, VT)); 3394 } 3395 3396 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3397 Tmp2 = DAG.getCALLSEQ_END( 3398 Chain, DAG.getIntPtrConstant(0, dl, true), 3399 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3400 3401 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3402 } 3403 3404 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3405 SelectionDAG &DAG) const { 3406 // We only handle constant sizes here to allow non-entry block, static sized 3407 // allocas. A truly dynamic value is more difficult to support because we 3408 // don't know if the size value is uniform or not. If the size isn't uniform, 3409 // we would need to do a wave reduction to get the maximum size to know how 3410 // much to increment the uniform stack pointer. 3411 SDValue Size = Op.getOperand(1); 3412 if (isa<ConstantSDNode>(Size)) 3413 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3414 3415 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3416 } 3417 3418 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3419 const MachineFunction &MF) const { 3420 Register Reg = StringSwitch<Register>(RegName) 3421 .Case("m0", AMDGPU::M0) 3422 .Case("exec", AMDGPU::EXEC) 3423 .Case("exec_lo", AMDGPU::EXEC_LO) 3424 .Case("exec_hi", AMDGPU::EXEC_HI) 3425 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3426 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3427 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3428 .Default(Register()); 3429 3430 if (Reg == AMDGPU::NoRegister) { 3431 report_fatal_error(Twine("invalid register name \"" 3432 + StringRef(RegName) + "\".")); 3433 3434 } 3435 3436 if (!Subtarget->hasFlatScrRegister() && 3437 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3438 report_fatal_error(Twine("invalid register \"" 3439 + StringRef(RegName) + "\" for subtarget.")); 3440 } 3441 3442 switch (Reg) { 3443 case AMDGPU::M0: 3444 case AMDGPU::EXEC_LO: 3445 case AMDGPU::EXEC_HI: 3446 case AMDGPU::FLAT_SCR_LO: 3447 case AMDGPU::FLAT_SCR_HI: 3448 if (VT.getSizeInBits() == 32) 3449 return Reg; 3450 break; 3451 case AMDGPU::EXEC: 3452 case AMDGPU::FLAT_SCR: 3453 if (VT.getSizeInBits() == 64) 3454 return Reg; 3455 break; 3456 default: 3457 llvm_unreachable("missing register type checking"); 3458 } 3459 3460 report_fatal_error(Twine("invalid type for register \"" 3461 + StringRef(RegName) + "\".")); 3462 } 3463 3464 // If kill is not the last instruction, split the block so kill is always a 3465 // proper terminator. 3466 MachineBasicBlock * 3467 SITargetLowering::splitKillBlock(MachineInstr &MI, 3468 MachineBasicBlock *BB) const { 3469 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3470 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3471 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3472 return SplitBB; 3473 } 3474 3475 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3476 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3477 // be the first instruction in the remainder block. 3478 // 3479 /// \returns { LoopBody, Remainder } 3480 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3481 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3482 MachineFunction *MF = MBB.getParent(); 3483 MachineBasicBlock::iterator I(&MI); 3484 3485 // To insert the loop we need to split the block. Move everything after this 3486 // point to a new block, and insert a new empty block between the two. 3487 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3488 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3489 MachineFunction::iterator MBBI(MBB); 3490 ++MBBI; 3491 3492 MF->insert(MBBI, LoopBB); 3493 MF->insert(MBBI, RemainderBB); 3494 3495 LoopBB->addSuccessor(LoopBB); 3496 LoopBB->addSuccessor(RemainderBB); 3497 3498 // Move the rest of the block into a new block. 3499 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3500 3501 if (InstInLoop) { 3502 auto Next = std::next(I); 3503 3504 // Move instruction to loop body. 3505 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3506 3507 // Move the rest of the block. 3508 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3509 } else { 3510 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3511 } 3512 3513 MBB.addSuccessor(LoopBB); 3514 3515 return std::make_pair(LoopBB, RemainderBB); 3516 } 3517 3518 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3519 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3520 MachineBasicBlock *MBB = MI.getParent(); 3521 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3522 auto I = MI.getIterator(); 3523 auto E = std::next(I); 3524 3525 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3526 .addImm(0); 3527 3528 MIBundleBuilder Bundler(*MBB, I, E); 3529 finalizeBundle(*MBB, Bundler.begin()); 3530 } 3531 3532 MachineBasicBlock * 3533 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3534 MachineBasicBlock *BB) const { 3535 const DebugLoc &DL = MI.getDebugLoc(); 3536 3537 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3538 3539 MachineBasicBlock *LoopBB; 3540 MachineBasicBlock *RemainderBB; 3541 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3542 3543 // Apparently kill flags are only valid if the def is in the same block? 3544 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3545 Src->setIsKill(false); 3546 3547 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3548 3549 MachineBasicBlock::iterator I = LoopBB->end(); 3550 3551 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3552 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3553 3554 // Clear TRAP_STS.MEM_VIOL 3555 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3556 .addImm(0) 3557 .addImm(EncodedReg); 3558 3559 bundleInstWithWaitcnt(MI); 3560 3561 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3562 3563 // Load and check TRAP_STS.MEM_VIOL 3564 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3565 .addImm(EncodedReg); 3566 3567 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3568 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3569 .addReg(Reg, RegState::Kill) 3570 .addImm(0); 3571 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3572 .addMBB(LoopBB); 3573 3574 return RemainderBB; 3575 } 3576 3577 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3578 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3579 // will only do one iteration. In the worst case, this will loop 64 times. 3580 // 3581 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3582 static MachineBasicBlock::iterator 3583 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3584 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3585 const DebugLoc &DL, const MachineOperand &Idx, 3586 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3587 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3588 Register &SGPRIdxReg) { 3589 3590 MachineFunction *MF = OrigBB.getParent(); 3591 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3592 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3593 MachineBasicBlock::iterator I = LoopBB.begin(); 3594 3595 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3596 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3597 Register NewExec = MRI.createVirtualRegister(BoolRC); 3598 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3599 Register CondReg = MRI.createVirtualRegister(BoolRC); 3600 3601 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3602 .addReg(InitReg) 3603 .addMBB(&OrigBB) 3604 .addReg(ResultReg) 3605 .addMBB(&LoopBB); 3606 3607 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3608 .addReg(InitSaveExecReg) 3609 .addMBB(&OrigBB) 3610 .addReg(NewExec) 3611 .addMBB(&LoopBB); 3612 3613 // Read the next variant <- also loop target. 3614 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3615 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3616 3617 // Compare the just read M0 value to all possible Idx values. 3618 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3619 .addReg(CurrentIdxReg) 3620 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3621 3622 // Update EXEC, save the original EXEC value to VCC. 3623 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3624 : AMDGPU::S_AND_SAVEEXEC_B64), 3625 NewExec) 3626 .addReg(CondReg, RegState::Kill); 3627 3628 MRI.setSimpleHint(NewExec, CondReg); 3629 3630 if (UseGPRIdxMode) { 3631 if (Offset == 0) { 3632 SGPRIdxReg = CurrentIdxReg; 3633 } else { 3634 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3635 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3636 .addReg(CurrentIdxReg, RegState::Kill) 3637 .addImm(Offset); 3638 } 3639 } else { 3640 // Move index from VCC into M0 3641 if (Offset == 0) { 3642 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3643 .addReg(CurrentIdxReg, RegState::Kill); 3644 } else { 3645 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3646 .addReg(CurrentIdxReg, RegState::Kill) 3647 .addImm(Offset); 3648 } 3649 } 3650 3651 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3652 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3653 MachineInstr *InsertPt = 3654 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3655 : AMDGPU::S_XOR_B64_term), Exec) 3656 .addReg(Exec) 3657 .addReg(NewExec); 3658 3659 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3660 // s_cbranch_scc0? 3661 3662 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3663 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3664 .addMBB(&LoopBB); 3665 3666 return InsertPt->getIterator(); 3667 } 3668 3669 // This has slightly sub-optimal regalloc when the source vector is killed by 3670 // the read. The register allocator does not understand that the kill is 3671 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3672 // subregister from it, using 1 more VGPR than necessary. This was saved when 3673 // this was expanded after register allocation. 3674 static MachineBasicBlock::iterator 3675 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3676 unsigned InitResultReg, unsigned PhiReg, int Offset, 3677 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3678 MachineFunction *MF = MBB.getParent(); 3679 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3680 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3681 MachineRegisterInfo &MRI = MF->getRegInfo(); 3682 const DebugLoc &DL = MI.getDebugLoc(); 3683 MachineBasicBlock::iterator I(&MI); 3684 3685 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3686 Register DstReg = MI.getOperand(0).getReg(); 3687 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3688 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3689 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3690 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3691 3692 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3693 3694 // Save the EXEC mask 3695 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3696 .addReg(Exec); 3697 3698 MachineBasicBlock *LoopBB; 3699 MachineBasicBlock *RemainderBB; 3700 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3701 3702 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3703 3704 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3705 InitResultReg, DstReg, PhiReg, TmpExec, 3706 Offset, UseGPRIdxMode, SGPRIdxReg); 3707 3708 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3709 MachineFunction::iterator MBBI(LoopBB); 3710 ++MBBI; 3711 MF->insert(MBBI, LandingPad); 3712 LoopBB->removeSuccessor(RemainderBB); 3713 LandingPad->addSuccessor(RemainderBB); 3714 LoopBB->addSuccessor(LandingPad); 3715 MachineBasicBlock::iterator First = LandingPad->begin(); 3716 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3717 .addReg(SaveExec); 3718 3719 return InsPt; 3720 } 3721 3722 // Returns subreg index, offset 3723 static std::pair<unsigned, int> 3724 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3725 const TargetRegisterClass *SuperRC, 3726 unsigned VecReg, 3727 int Offset) { 3728 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3729 3730 // Skip out of bounds offsets, or else we would end up using an undefined 3731 // register. 3732 if (Offset >= NumElts || Offset < 0) 3733 return std::make_pair(AMDGPU::sub0, Offset); 3734 3735 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3736 } 3737 3738 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3739 MachineRegisterInfo &MRI, MachineInstr &MI, 3740 int Offset) { 3741 MachineBasicBlock *MBB = MI.getParent(); 3742 const DebugLoc &DL = MI.getDebugLoc(); 3743 MachineBasicBlock::iterator I(&MI); 3744 3745 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3746 3747 assert(Idx->getReg() != AMDGPU::NoRegister); 3748 3749 if (Offset == 0) { 3750 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3751 } else { 3752 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3753 .add(*Idx) 3754 .addImm(Offset); 3755 } 3756 } 3757 3758 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3759 MachineRegisterInfo &MRI, MachineInstr &MI, 3760 int Offset) { 3761 MachineBasicBlock *MBB = MI.getParent(); 3762 const DebugLoc &DL = MI.getDebugLoc(); 3763 MachineBasicBlock::iterator I(&MI); 3764 3765 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3766 3767 if (Offset == 0) 3768 return Idx->getReg(); 3769 3770 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3771 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3772 .add(*Idx) 3773 .addImm(Offset); 3774 return Tmp; 3775 } 3776 3777 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3778 MachineBasicBlock &MBB, 3779 const GCNSubtarget &ST) { 3780 const SIInstrInfo *TII = ST.getInstrInfo(); 3781 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3782 MachineFunction *MF = MBB.getParent(); 3783 MachineRegisterInfo &MRI = MF->getRegInfo(); 3784 3785 Register Dst = MI.getOperand(0).getReg(); 3786 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3787 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3788 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3789 3790 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3791 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3792 3793 unsigned SubReg; 3794 std::tie(SubReg, Offset) 3795 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3796 3797 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3798 3799 // Check for a SGPR index. 3800 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3801 MachineBasicBlock::iterator I(&MI); 3802 const DebugLoc &DL = MI.getDebugLoc(); 3803 3804 if (UseGPRIdxMode) { 3805 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3806 // to avoid interfering with other uses, so probably requires a new 3807 // optimization pass. 3808 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3809 3810 const MCInstrDesc &GPRIDXDesc = 3811 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3812 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3813 .addReg(SrcReg) 3814 .addReg(Idx) 3815 .addImm(SubReg); 3816 } else { 3817 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3818 3819 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3820 .addReg(SrcReg, 0, SubReg) 3821 .addReg(SrcReg, RegState::Implicit); 3822 } 3823 3824 MI.eraseFromParent(); 3825 3826 return &MBB; 3827 } 3828 3829 // Control flow needs to be inserted if indexing with a VGPR. 3830 const DebugLoc &DL = MI.getDebugLoc(); 3831 MachineBasicBlock::iterator I(&MI); 3832 3833 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3834 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3835 3836 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3837 3838 Register SGPRIdxReg; 3839 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3840 UseGPRIdxMode, SGPRIdxReg); 3841 3842 MachineBasicBlock *LoopBB = InsPt->getParent(); 3843 3844 if (UseGPRIdxMode) { 3845 const MCInstrDesc &GPRIDXDesc = 3846 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3847 3848 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3849 .addReg(SrcReg) 3850 .addReg(SGPRIdxReg) 3851 .addImm(SubReg); 3852 } else { 3853 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3854 .addReg(SrcReg, 0, SubReg) 3855 .addReg(SrcReg, RegState::Implicit); 3856 } 3857 3858 MI.eraseFromParent(); 3859 3860 return LoopBB; 3861 } 3862 3863 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3864 MachineBasicBlock &MBB, 3865 const GCNSubtarget &ST) { 3866 const SIInstrInfo *TII = ST.getInstrInfo(); 3867 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3868 MachineFunction *MF = MBB.getParent(); 3869 MachineRegisterInfo &MRI = MF->getRegInfo(); 3870 3871 Register Dst = MI.getOperand(0).getReg(); 3872 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3873 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3874 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3875 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3876 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3877 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3878 3879 // This can be an immediate, but will be folded later. 3880 assert(Val->getReg()); 3881 3882 unsigned SubReg; 3883 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3884 SrcVec->getReg(), 3885 Offset); 3886 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3887 3888 if (Idx->getReg() == AMDGPU::NoRegister) { 3889 MachineBasicBlock::iterator I(&MI); 3890 const DebugLoc &DL = MI.getDebugLoc(); 3891 3892 assert(Offset == 0); 3893 3894 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3895 .add(*SrcVec) 3896 .add(*Val) 3897 .addImm(SubReg); 3898 3899 MI.eraseFromParent(); 3900 return &MBB; 3901 } 3902 3903 // Check for a SGPR index. 3904 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3905 MachineBasicBlock::iterator I(&MI); 3906 const DebugLoc &DL = MI.getDebugLoc(); 3907 3908 if (UseGPRIdxMode) { 3909 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3910 3911 const MCInstrDesc &GPRIDXDesc = 3912 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3913 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3914 .addReg(SrcVec->getReg()) 3915 .add(*Val) 3916 .addReg(Idx) 3917 .addImm(SubReg); 3918 } else { 3919 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3920 3921 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3922 TRI.getRegSizeInBits(*VecRC), 32, false); 3923 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3924 .addReg(SrcVec->getReg()) 3925 .add(*Val) 3926 .addImm(SubReg); 3927 } 3928 MI.eraseFromParent(); 3929 return &MBB; 3930 } 3931 3932 // Control flow needs to be inserted if indexing with a VGPR. 3933 if (Val->isReg()) 3934 MRI.clearKillFlags(Val->getReg()); 3935 3936 const DebugLoc &DL = MI.getDebugLoc(); 3937 3938 Register PhiReg = MRI.createVirtualRegister(VecRC); 3939 3940 Register SGPRIdxReg; 3941 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3942 UseGPRIdxMode, SGPRIdxReg); 3943 MachineBasicBlock *LoopBB = InsPt->getParent(); 3944 3945 if (UseGPRIdxMode) { 3946 const MCInstrDesc &GPRIDXDesc = 3947 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3948 3949 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3950 .addReg(PhiReg) 3951 .add(*Val) 3952 .addReg(SGPRIdxReg) 3953 .addImm(AMDGPU::sub0); 3954 } else { 3955 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3956 TRI.getRegSizeInBits(*VecRC), 32, false); 3957 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3958 .addReg(PhiReg) 3959 .add(*Val) 3960 .addImm(AMDGPU::sub0); 3961 } 3962 3963 MI.eraseFromParent(); 3964 return LoopBB; 3965 } 3966 3967 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3968 MachineInstr &MI, MachineBasicBlock *BB) const { 3969 3970 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3971 MachineFunction *MF = BB->getParent(); 3972 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3973 3974 switch (MI.getOpcode()) { 3975 case AMDGPU::S_UADDO_PSEUDO: 3976 case AMDGPU::S_USUBO_PSEUDO: { 3977 const DebugLoc &DL = MI.getDebugLoc(); 3978 MachineOperand &Dest0 = MI.getOperand(0); 3979 MachineOperand &Dest1 = MI.getOperand(1); 3980 MachineOperand &Src0 = MI.getOperand(2); 3981 MachineOperand &Src1 = MI.getOperand(3); 3982 3983 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3984 ? AMDGPU::S_ADD_I32 3985 : AMDGPU::S_SUB_I32; 3986 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3987 3988 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3989 .addImm(1) 3990 .addImm(0); 3991 3992 MI.eraseFromParent(); 3993 return BB; 3994 } 3995 case AMDGPU::S_ADD_U64_PSEUDO: 3996 case AMDGPU::S_SUB_U64_PSEUDO: { 3997 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3998 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3999 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4000 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4001 const DebugLoc &DL = MI.getDebugLoc(); 4002 4003 MachineOperand &Dest = MI.getOperand(0); 4004 MachineOperand &Src0 = MI.getOperand(1); 4005 MachineOperand &Src1 = MI.getOperand(2); 4006 4007 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4008 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4009 4010 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4011 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4012 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4013 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4014 4015 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4016 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4017 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4018 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4019 4020 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4021 4022 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4023 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4024 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4025 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4026 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4027 .addReg(DestSub0) 4028 .addImm(AMDGPU::sub0) 4029 .addReg(DestSub1) 4030 .addImm(AMDGPU::sub1); 4031 MI.eraseFromParent(); 4032 return BB; 4033 } 4034 case AMDGPU::V_ADD_U64_PSEUDO: 4035 case AMDGPU::V_SUB_U64_PSEUDO: { 4036 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4037 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4038 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4039 const DebugLoc &DL = MI.getDebugLoc(); 4040 4041 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4042 4043 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4044 4045 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4046 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4047 4048 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4049 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4050 4051 MachineOperand &Dest = MI.getOperand(0); 4052 MachineOperand &Src0 = MI.getOperand(1); 4053 MachineOperand &Src1 = MI.getOperand(2); 4054 4055 const TargetRegisterClass *Src0RC = Src0.isReg() 4056 ? MRI.getRegClass(Src0.getReg()) 4057 : &AMDGPU::VReg_64RegClass; 4058 const TargetRegisterClass *Src1RC = Src1.isReg() 4059 ? MRI.getRegClass(Src1.getReg()) 4060 : &AMDGPU::VReg_64RegClass; 4061 4062 const TargetRegisterClass *Src0SubRC = 4063 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4064 const TargetRegisterClass *Src1SubRC = 4065 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4066 4067 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4068 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4069 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4070 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4071 4072 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4073 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4074 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4075 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4076 4077 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4078 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4079 .addReg(CarryReg, RegState::Define) 4080 .add(SrcReg0Sub0) 4081 .add(SrcReg1Sub0) 4082 .addImm(0); // clamp bit 4083 4084 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4085 MachineInstr *HiHalf = 4086 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4087 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4088 .add(SrcReg0Sub1) 4089 .add(SrcReg1Sub1) 4090 .addReg(CarryReg, RegState::Kill) 4091 .addImm(0); // clamp bit 4092 4093 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4094 .addReg(DestSub0) 4095 .addImm(AMDGPU::sub0) 4096 .addReg(DestSub1) 4097 .addImm(AMDGPU::sub1); 4098 TII->legalizeOperands(*LoHalf); 4099 TII->legalizeOperands(*HiHalf); 4100 MI.eraseFromParent(); 4101 return BB; 4102 } 4103 case AMDGPU::S_ADD_CO_PSEUDO: 4104 case AMDGPU::S_SUB_CO_PSEUDO: { 4105 // This pseudo has a chance to be selected 4106 // only from uniform add/subcarry node. All the VGPR operands 4107 // therefore assumed to be splat vectors. 4108 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4109 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4110 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4111 MachineBasicBlock::iterator MII = MI; 4112 const DebugLoc &DL = MI.getDebugLoc(); 4113 MachineOperand &Dest = MI.getOperand(0); 4114 MachineOperand &CarryDest = MI.getOperand(1); 4115 MachineOperand &Src0 = MI.getOperand(2); 4116 MachineOperand &Src1 = MI.getOperand(3); 4117 MachineOperand &Src2 = MI.getOperand(4); 4118 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4119 ? AMDGPU::S_ADDC_U32 4120 : AMDGPU::S_SUBB_U32; 4121 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4122 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4123 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4124 .addReg(Src0.getReg()); 4125 Src0.setReg(RegOp0); 4126 } 4127 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4128 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4129 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4130 .addReg(Src1.getReg()); 4131 Src1.setReg(RegOp1); 4132 } 4133 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4134 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4135 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4136 .addReg(Src2.getReg()); 4137 Src2.setReg(RegOp2); 4138 } 4139 4140 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4141 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4142 assert(WaveSize == 64 || WaveSize == 32); 4143 4144 if (WaveSize == 64) { 4145 if (ST.hasScalarCompareEq64()) { 4146 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4147 .addReg(Src2.getReg()) 4148 .addImm(0); 4149 } else { 4150 const TargetRegisterClass *SubRC = 4151 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4152 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4153 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4154 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4155 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4156 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4157 4158 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4159 .add(Src2Sub0) 4160 .add(Src2Sub1); 4161 4162 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4163 .addReg(Src2_32, RegState::Kill) 4164 .addImm(0); 4165 } 4166 } else { 4167 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4168 .addReg(Src2.getReg()) 4169 .addImm(0); 4170 } 4171 4172 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4173 4174 unsigned SelOpc = 4175 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4176 4177 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4178 .addImm(-1) 4179 .addImm(0); 4180 4181 MI.eraseFromParent(); 4182 return BB; 4183 } 4184 case AMDGPU::SI_INIT_M0: { 4185 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4186 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4187 .add(MI.getOperand(0)); 4188 MI.eraseFromParent(); 4189 return BB; 4190 } 4191 case AMDGPU::GET_GROUPSTATICSIZE: { 4192 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4193 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4194 DebugLoc DL = MI.getDebugLoc(); 4195 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4196 .add(MI.getOperand(0)) 4197 .addImm(MFI->getLDSSize()); 4198 MI.eraseFromParent(); 4199 return BB; 4200 } 4201 case AMDGPU::SI_INDIRECT_SRC_V1: 4202 case AMDGPU::SI_INDIRECT_SRC_V2: 4203 case AMDGPU::SI_INDIRECT_SRC_V4: 4204 case AMDGPU::SI_INDIRECT_SRC_V8: 4205 case AMDGPU::SI_INDIRECT_SRC_V16: 4206 case AMDGPU::SI_INDIRECT_SRC_V32: 4207 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4208 case AMDGPU::SI_INDIRECT_DST_V1: 4209 case AMDGPU::SI_INDIRECT_DST_V2: 4210 case AMDGPU::SI_INDIRECT_DST_V4: 4211 case AMDGPU::SI_INDIRECT_DST_V8: 4212 case AMDGPU::SI_INDIRECT_DST_V16: 4213 case AMDGPU::SI_INDIRECT_DST_V32: 4214 return emitIndirectDst(MI, *BB, *getSubtarget()); 4215 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4216 case AMDGPU::SI_KILL_I1_PSEUDO: 4217 return splitKillBlock(MI, BB); 4218 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4219 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4220 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4221 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4222 4223 Register Dst = MI.getOperand(0).getReg(); 4224 Register Src0 = MI.getOperand(1).getReg(); 4225 Register Src1 = MI.getOperand(2).getReg(); 4226 const DebugLoc &DL = MI.getDebugLoc(); 4227 Register SrcCond = MI.getOperand(3).getReg(); 4228 4229 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4230 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4231 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4232 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4233 4234 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4235 .addReg(SrcCond); 4236 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4237 .addImm(0) 4238 .addReg(Src0, 0, AMDGPU::sub0) 4239 .addImm(0) 4240 .addReg(Src1, 0, AMDGPU::sub0) 4241 .addReg(SrcCondCopy); 4242 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4243 .addImm(0) 4244 .addReg(Src0, 0, AMDGPU::sub1) 4245 .addImm(0) 4246 .addReg(Src1, 0, AMDGPU::sub1) 4247 .addReg(SrcCondCopy); 4248 4249 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4250 .addReg(DstLo) 4251 .addImm(AMDGPU::sub0) 4252 .addReg(DstHi) 4253 .addImm(AMDGPU::sub1); 4254 MI.eraseFromParent(); 4255 return BB; 4256 } 4257 case AMDGPU::SI_BR_UNDEF: { 4258 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4259 const DebugLoc &DL = MI.getDebugLoc(); 4260 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4261 .add(MI.getOperand(0)); 4262 Br->getOperand(1).setIsUndef(true); // read undef SCC 4263 MI.eraseFromParent(); 4264 return BB; 4265 } 4266 case AMDGPU::ADJCALLSTACKUP: 4267 case AMDGPU::ADJCALLSTACKDOWN: { 4268 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4269 MachineInstrBuilder MIB(*MF, &MI); 4270 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4271 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4272 return BB; 4273 } 4274 case AMDGPU::SI_CALL_ISEL: { 4275 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4276 const DebugLoc &DL = MI.getDebugLoc(); 4277 4278 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4279 4280 MachineInstrBuilder MIB; 4281 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4282 4283 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4284 MIB.add(MI.getOperand(I)); 4285 4286 MIB.cloneMemRefs(MI); 4287 MI.eraseFromParent(); 4288 return BB; 4289 } 4290 case AMDGPU::V_ADD_CO_U32_e32: 4291 case AMDGPU::V_SUB_CO_U32_e32: 4292 case AMDGPU::V_SUBREV_CO_U32_e32: { 4293 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4294 const DebugLoc &DL = MI.getDebugLoc(); 4295 unsigned Opc = MI.getOpcode(); 4296 4297 bool NeedClampOperand = false; 4298 if (TII->pseudoToMCOpcode(Opc) == -1) { 4299 Opc = AMDGPU::getVOPe64(Opc); 4300 NeedClampOperand = true; 4301 } 4302 4303 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4304 if (TII->isVOP3(*I)) { 4305 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4306 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4307 I.addReg(TRI->getVCC(), RegState::Define); 4308 } 4309 I.add(MI.getOperand(1)) 4310 .add(MI.getOperand(2)); 4311 if (NeedClampOperand) 4312 I.addImm(0); // clamp bit for e64 encoding 4313 4314 TII->legalizeOperands(*I); 4315 4316 MI.eraseFromParent(); 4317 return BB; 4318 } 4319 case AMDGPU::V_ADDC_U32_e32: 4320 case AMDGPU::V_SUBB_U32_e32: 4321 case AMDGPU::V_SUBBREV_U32_e32: 4322 // These instructions have an implicit use of vcc which counts towards the 4323 // constant bus limit. 4324 TII->legalizeOperands(MI); 4325 return BB; 4326 case AMDGPU::DS_GWS_INIT: 4327 case AMDGPU::DS_GWS_SEMA_BR: 4328 case AMDGPU::DS_GWS_BARRIER: 4329 if (Subtarget->needsAlignedVGPRs()) { 4330 // Add implicit aligned super-reg to force alignment on the data operand. 4331 const DebugLoc &DL = MI.getDebugLoc(); 4332 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4333 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4334 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4335 Register DataReg = Op->getReg(); 4336 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4337 Register Undef = MRI.createVirtualRegister( 4338 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4339 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4340 Register NewVR = 4341 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4342 : &AMDGPU::VReg_64_Align2RegClass); 4343 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4344 .addReg(DataReg, 0, Op->getSubReg()) 4345 .addImm(AMDGPU::sub0) 4346 .addReg(Undef) 4347 .addImm(AMDGPU::sub1); 4348 Op->setReg(NewVR); 4349 Op->setSubReg(AMDGPU::sub0); 4350 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4351 } 4352 LLVM_FALLTHROUGH; 4353 case AMDGPU::DS_GWS_SEMA_V: 4354 case AMDGPU::DS_GWS_SEMA_P: 4355 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4356 // A s_waitcnt 0 is required to be the instruction immediately following. 4357 if (getSubtarget()->hasGWSAutoReplay()) { 4358 bundleInstWithWaitcnt(MI); 4359 return BB; 4360 } 4361 4362 return emitGWSMemViolTestLoop(MI, BB); 4363 case AMDGPU::S_SETREG_B32: { 4364 // Try to optimize cases that only set the denormal mode or rounding mode. 4365 // 4366 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4367 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4368 // instead. 4369 // 4370 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4371 // allow you to have a no side effect instruction in the output of a 4372 // sideeffecting pattern. 4373 unsigned ID, Offset, Width; 4374 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4375 if (ID != AMDGPU::Hwreg::ID_MODE) 4376 return BB; 4377 4378 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4379 const unsigned SetMask = WidthMask << Offset; 4380 4381 if (getSubtarget()->hasDenormModeInst()) { 4382 unsigned SetDenormOp = 0; 4383 unsigned SetRoundOp = 0; 4384 4385 // The dedicated instructions can only set the whole denorm or round mode 4386 // at once, not a subset of bits in either. 4387 if (SetMask == 4388 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4389 // If this fully sets both the round and denorm mode, emit the two 4390 // dedicated instructions for these. 4391 SetRoundOp = AMDGPU::S_ROUND_MODE; 4392 SetDenormOp = AMDGPU::S_DENORM_MODE; 4393 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4394 SetRoundOp = AMDGPU::S_ROUND_MODE; 4395 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4396 SetDenormOp = AMDGPU::S_DENORM_MODE; 4397 } 4398 4399 if (SetRoundOp || SetDenormOp) { 4400 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4401 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4402 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4403 unsigned ImmVal = Def->getOperand(1).getImm(); 4404 if (SetRoundOp) { 4405 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4406 .addImm(ImmVal & 0xf); 4407 4408 // If we also have the denorm mode, get just the denorm mode bits. 4409 ImmVal >>= 4; 4410 } 4411 4412 if (SetDenormOp) { 4413 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4414 .addImm(ImmVal & 0xf); 4415 } 4416 4417 MI.eraseFromParent(); 4418 return BB; 4419 } 4420 } 4421 } 4422 4423 // If only FP bits are touched, used the no side effects pseudo. 4424 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4425 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4426 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4427 4428 return BB; 4429 } 4430 default: 4431 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4432 } 4433 } 4434 4435 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4436 return isTypeLegal(VT.getScalarType()); 4437 } 4438 4439 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4440 // This currently forces unfolding various combinations of fsub into fma with 4441 // free fneg'd operands. As long as we have fast FMA (controlled by 4442 // isFMAFasterThanFMulAndFAdd), we should perform these. 4443 4444 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4445 // most of these combines appear to be cycle neutral but save on instruction 4446 // count / code size. 4447 return true; 4448 } 4449 4450 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4451 EVT VT) const { 4452 if (!VT.isVector()) { 4453 return MVT::i1; 4454 } 4455 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4456 } 4457 4458 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4459 // TODO: Should i16 be used always if legal? For now it would force VALU 4460 // shifts. 4461 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4462 } 4463 4464 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4465 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4466 ? Ty.changeElementSize(16) 4467 : Ty.changeElementSize(32); 4468 } 4469 4470 // Answering this is somewhat tricky and depends on the specific device which 4471 // have different rates for fma or all f64 operations. 4472 // 4473 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4474 // regardless of which device (although the number of cycles differs between 4475 // devices), so it is always profitable for f64. 4476 // 4477 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4478 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4479 // which we can always do even without fused FP ops since it returns the same 4480 // result as the separate operations and since it is always full 4481 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4482 // however does not support denormals, so we do report fma as faster if we have 4483 // a fast fma device and require denormals. 4484 // 4485 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4486 EVT VT) const { 4487 VT = VT.getScalarType(); 4488 4489 switch (VT.getSimpleVT().SimpleTy) { 4490 case MVT::f32: { 4491 // If mad is not available this depends only on if f32 fma is full rate. 4492 if (!Subtarget->hasMadMacF32Insts()) 4493 return Subtarget->hasFastFMAF32(); 4494 4495 // Otherwise f32 mad is always full rate and returns the same result as 4496 // the separate operations so should be preferred over fma. 4497 // However does not support denomals. 4498 if (hasFP32Denormals(MF)) 4499 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4500 4501 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4502 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4503 } 4504 case MVT::f64: 4505 return true; 4506 case MVT::f16: 4507 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4508 default: 4509 break; 4510 } 4511 4512 return false; 4513 } 4514 4515 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4516 const SDNode *N) const { 4517 // TODO: Check future ftz flag 4518 // v_mad_f32/v_mac_f32 do not support denormals. 4519 EVT VT = N->getValueType(0); 4520 if (VT == MVT::f32) 4521 return Subtarget->hasMadMacF32Insts() && 4522 !hasFP32Denormals(DAG.getMachineFunction()); 4523 if (VT == MVT::f16) { 4524 return Subtarget->hasMadF16() && 4525 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4526 } 4527 4528 return false; 4529 } 4530 4531 //===----------------------------------------------------------------------===// 4532 // Custom DAG Lowering Operations 4533 //===----------------------------------------------------------------------===// 4534 4535 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4536 // wider vector type is legal. 4537 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4538 SelectionDAG &DAG) const { 4539 unsigned Opc = Op.getOpcode(); 4540 EVT VT = Op.getValueType(); 4541 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4542 4543 SDValue Lo, Hi; 4544 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4545 4546 SDLoc SL(Op); 4547 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4548 Op->getFlags()); 4549 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4550 Op->getFlags()); 4551 4552 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4553 } 4554 4555 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4556 // wider vector type is legal. 4557 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4558 SelectionDAG &DAG) const { 4559 unsigned Opc = Op.getOpcode(); 4560 EVT VT = Op.getValueType(); 4561 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4562 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4563 4564 SDValue Lo0, Hi0; 4565 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4566 SDValue Lo1, Hi1; 4567 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4568 4569 SDLoc SL(Op); 4570 4571 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4572 Op->getFlags()); 4573 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4574 Op->getFlags()); 4575 4576 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4577 } 4578 4579 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4580 SelectionDAG &DAG) const { 4581 unsigned Opc = Op.getOpcode(); 4582 EVT VT = Op.getValueType(); 4583 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4584 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4585 4586 SDValue Lo0, Hi0; 4587 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4588 SDValue Lo1, Hi1; 4589 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4590 SDValue Lo2, Hi2; 4591 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4592 4593 SDLoc SL(Op); 4594 4595 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4596 Op->getFlags()); 4597 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4598 Op->getFlags()); 4599 4600 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4601 } 4602 4603 4604 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4605 switch (Op.getOpcode()) { 4606 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4607 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4608 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4609 case ISD::LOAD: { 4610 SDValue Result = LowerLOAD(Op, DAG); 4611 assert((!Result.getNode() || 4612 Result.getNode()->getNumValues() == 2) && 4613 "Load should return a value and a chain"); 4614 return Result; 4615 } 4616 4617 case ISD::FSIN: 4618 case ISD::FCOS: 4619 return LowerTrig(Op, DAG); 4620 case ISD::SELECT: return LowerSELECT(Op, DAG); 4621 case ISD::FDIV: return LowerFDIV(Op, DAG); 4622 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4623 case ISD::STORE: return LowerSTORE(Op, DAG); 4624 case ISD::GlobalAddress: { 4625 MachineFunction &MF = DAG.getMachineFunction(); 4626 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4627 return LowerGlobalAddress(MFI, Op, DAG); 4628 } 4629 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4630 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4631 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4632 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4633 case ISD::INSERT_SUBVECTOR: 4634 return lowerINSERT_SUBVECTOR(Op, DAG); 4635 case ISD::INSERT_VECTOR_ELT: 4636 return lowerINSERT_VECTOR_ELT(Op, DAG); 4637 case ISD::EXTRACT_VECTOR_ELT: 4638 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4639 case ISD::VECTOR_SHUFFLE: 4640 return lowerVECTOR_SHUFFLE(Op, DAG); 4641 case ISD::BUILD_VECTOR: 4642 return lowerBUILD_VECTOR(Op, DAG); 4643 case ISD::FP_ROUND: 4644 return lowerFP_ROUND(Op, DAG); 4645 case ISD::TRAP: 4646 return lowerTRAP(Op, DAG); 4647 case ISD::DEBUGTRAP: 4648 return lowerDEBUGTRAP(Op, DAG); 4649 case ISD::FABS: 4650 case ISD::FNEG: 4651 case ISD::FCANONICALIZE: 4652 case ISD::BSWAP: 4653 return splitUnaryVectorOp(Op, DAG); 4654 case ISD::FMINNUM: 4655 case ISD::FMAXNUM: 4656 return lowerFMINNUM_FMAXNUM(Op, DAG); 4657 case ISD::FMA: 4658 return splitTernaryVectorOp(Op, DAG); 4659 case ISD::FP_TO_SINT: 4660 case ISD::FP_TO_UINT: 4661 return LowerFP_TO_INT(Op, DAG); 4662 case ISD::SHL: 4663 case ISD::SRA: 4664 case ISD::SRL: 4665 case ISD::ADD: 4666 case ISD::SUB: 4667 case ISD::MUL: 4668 case ISD::SMIN: 4669 case ISD::SMAX: 4670 case ISD::UMIN: 4671 case ISD::UMAX: 4672 case ISD::FADD: 4673 case ISD::FMUL: 4674 case ISD::FMINNUM_IEEE: 4675 case ISD::FMAXNUM_IEEE: 4676 case ISD::UADDSAT: 4677 case ISD::USUBSAT: 4678 case ISD::SADDSAT: 4679 case ISD::SSUBSAT: 4680 return splitBinaryVectorOp(Op, DAG); 4681 case ISD::SMULO: 4682 case ISD::UMULO: 4683 return lowerXMULO(Op, DAG); 4684 case ISD::DYNAMIC_STACKALLOC: 4685 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4686 } 4687 return SDValue(); 4688 } 4689 4690 // Used for D16: Casts the result of an instruction into the right vector, 4691 // packs values if loads return unpacked values. 4692 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4693 const SDLoc &DL, 4694 SelectionDAG &DAG, bool Unpacked) { 4695 if (!LoadVT.isVector()) 4696 return Result; 4697 4698 // Cast back to the original packed type or to a larger type that is a 4699 // multiple of 32 bit for D16. Widening the return type is a required for 4700 // legalization. 4701 EVT FittingLoadVT = LoadVT; 4702 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4703 FittingLoadVT = 4704 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4705 LoadVT.getVectorNumElements() + 1); 4706 } 4707 4708 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4709 // Truncate to v2i16/v4i16. 4710 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4711 4712 // Workaround legalizer not scalarizing truncate after vector op 4713 // legalization but not creating intermediate vector trunc. 4714 SmallVector<SDValue, 4> Elts; 4715 DAG.ExtractVectorElements(Result, Elts); 4716 for (SDValue &Elt : Elts) 4717 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4718 4719 // Pad illegal v1i16/v3fi6 to v4i16 4720 if ((LoadVT.getVectorNumElements() % 2) == 1) 4721 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4722 4723 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4724 4725 // Bitcast to original type (v2f16/v4f16). 4726 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4727 } 4728 4729 // Cast back to the original packed type. 4730 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4731 } 4732 4733 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4734 MemSDNode *M, 4735 SelectionDAG &DAG, 4736 ArrayRef<SDValue> Ops, 4737 bool IsIntrinsic) const { 4738 SDLoc DL(M); 4739 4740 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4741 EVT LoadVT = M->getValueType(0); 4742 4743 EVT EquivLoadVT = LoadVT; 4744 if (LoadVT.isVector()) { 4745 if (Unpacked) { 4746 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4747 LoadVT.getVectorNumElements()); 4748 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4749 // Widen v3f16 to legal type 4750 EquivLoadVT = 4751 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4752 LoadVT.getVectorNumElements() + 1); 4753 } 4754 } 4755 4756 // Change from v4f16/v2f16 to EquivLoadVT. 4757 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4758 4759 SDValue Load 4760 = DAG.getMemIntrinsicNode( 4761 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4762 VTList, Ops, M->getMemoryVT(), 4763 M->getMemOperand()); 4764 4765 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4766 4767 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4768 } 4769 4770 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4771 SelectionDAG &DAG, 4772 ArrayRef<SDValue> Ops) const { 4773 SDLoc DL(M); 4774 EVT LoadVT = M->getValueType(0); 4775 EVT EltType = LoadVT.getScalarType(); 4776 EVT IntVT = LoadVT.changeTypeToInteger(); 4777 4778 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4779 4780 unsigned Opc = 4781 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4782 4783 if (IsD16) { 4784 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4785 } 4786 4787 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4788 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4789 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4790 4791 if (isTypeLegal(LoadVT)) { 4792 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4793 M->getMemOperand(), DAG); 4794 } 4795 4796 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4797 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4798 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4799 M->getMemOperand(), DAG); 4800 return DAG.getMergeValues( 4801 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4802 DL); 4803 } 4804 4805 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4806 SDNode *N, SelectionDAG &DAG) { 4807 EVT VT = N->getValueType(0); 4808 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4809 unsigned CondCode = CD->getZExtValue(); 4810 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4811 return DAG.getUNDEF(VT); 4812 4813 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4814 4815 SDValue LHS = N->getOperand(1); 4816 SDValue RHS = N->getOperand(2); 4817 4818 SDLoc DL(N); 4819 4820 EVT CmpVT = LHS.getValueType(); 4821 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4822 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4823 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4824 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4825 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4826 } 4827 4828 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4829 4830 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4831 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4832 4833 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4834 DAG.getCondCode(CCOpcode)); 4835 if (VT.bitsEq(CCVT)) 4836 return SetCC; 4837 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4838 } 4839 4840 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4841 SDNode *N, SelectionDAG &DAG) { 4842 EVT VT = N->getValueType(0); 4843 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4844 4845 unsigned CondCode = CD->getZExtValue(); 4846 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4847 return DAG.getUNDEF(VT); 4848 4849 SDValue Src0 = N->getOperand(1); 4850 SDValue Src1 = N->getOperand(2); 4851 EVT CmpVT = Src0.getValueType(); 4852 SDLoc SL(N); 4853 4854 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4855 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4856 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4857 } 4858 4859 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4860 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4861 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4862 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4863 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4864 Src1, DAG.getCondCode(CCOpcode)); 4865 if (VT.bitsEq(CCVT)) 4866 return SetCC; 4867 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4868 } 4869 4870 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4871 SelectionDAG &DAG) { 4872 EVT VT = N->getValueType(0); 4873 SDValue Src = N->getOperand(1); 4874 SDLoc SL(N); 4875 4876 if (Src.getOpcode() == ISD::SETCC) { 4877 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4878 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4879 Src.getOperand(1), Src.getOperand(2)); 4880 } 4881 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4882 // (ballot 0) -> 0 4883 if (Arg->isZero()) 4884 return DAG.getConstant(0, SL, VT); 4885 4886 // (ballot 1) -> EXEC/EXEC_LO 4887 if (Arg->isOne()) { 4888 Register Exec; 4889 if (VT.getScalarSizeInBits() == 32) 4890 Exec = AMDGPU::EXEC_LO; 4891 else if (VT.getScalarSizeInBits() == 64) 4892 Exec = AMDGPU::EXEC; 4893 else 4894 return SDValue(); 4895 4896 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4897 } 4898 } 4899 4900 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4901 // ISD::SETNE) 4902 return DAG.getNode( 4903 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4904 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4905 } 4906 4907 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4908 SmallVectorImpl<SDValue> &Results, 4909 SelectionDAG &DAG) const { 4910 switch (N->getOpcode()) { 4911 case ISD::INSERT_VECTOR_ELT: { 4912 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4913 Results.push_back(Res); 4914 return; 4915 } 4916 case ISD::EXTRACT_VECTOR_ELT: { 4917 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4918 Results.push_back(Res); 4919 return; 4920 } 4921 case ISD::INTRINSIC_WO_CHAIN: { 4922 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4923 switch (IID) { 4924 case Intrinsic::amdgcn_cvt_pkrtz: { 4925 SDValue Src0 = N->getOperand(1); 4926 SDValue Src1 = N->getOperand(2); 4927 SDLoc SL(N); 4928 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4929 Src0, Src1); 4930 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4931 return; 4932 } 4933 case Intrinsic::amdgcn_cvt_pknorm_i16: 4934 case Intrinsic::amdgcn_cvt_pknorm_u16: 4935 case Intrinsic::amdgcn_cvt_pk_i16: 4936 case Intrinsic::amdgcn_cvt_pk_u16: { 4937 SDValue Src0 = N->getOperand(1); 4938 SDValue Src1 = N->getOperand(2); 4939 SDLoc SL(N); 4940 unsigned Opcode; 4941 4942 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4943 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4944 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4945 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4946 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4947 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4948 else 4949 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4950 4951 EVT VT = N->getValueType(0); 4952 if (isTypeLegal(VT)) 4953 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4954 else { 4955 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4956 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4957 } 4958 return; 4959 } 4960 } 4961 break; 4962 } 4963 case ISD::INTRINSIC_W_CHAIN: { 4964 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4965 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4966 // FIXME: Hacky 4967 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4968 Results.push_back(Res.getOperand(I)); 4969 } 4970 } else { 4971 Results.push_back(Res); 4972 Results.push_back(Res.getValue(1)); 4973 } 4974 return; 4975 } 4976 4977 break; 4978 } 4979 case ISD::SELECT: { 4980 SDLoc SL(N); 4981 EVT VT = N->getValueType(0); 4982 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4983 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4984 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4985 4986 EVT SelectVT = NewVT; 4987 if (NewVT.bitsLT(MVT::i32)) { 4988 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4989 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4990 SelectVT = MVT::i32; 4991 } 4992 4993 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4994 N->getOperand(0), LHS, RHS); 4995 4996 if (NewVT != SelectVT) 4997 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4998 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4999 return; 5000 } 5001 case ISD::FNEG: { 5002 if (N->getValueType(0) != MVT::v2f16) 5003 break; 5004 5005 SDLoc SL(N); 5006 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5007 5008 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5009 BC, 5010 DAG.getConstant(0x80008000, SL, MVT::i32)); 5011 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5012 return; 5013 } 5014 case ISD::FABS: { 5015 if (N->getValueType(0) != MVT::v2f16) 5016 break; 5017 5018 SDLoc SL(N); 5019 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5020 5021 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5022 BC, 5023 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5024 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5025 return; 5026 } 5027 default: 5028 break; 5029 } 5030 } 5031 5032 /// Helper function for LowerBRCOND 5033 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5034 5035 SDNode *Parent = Value.getNode(); 5036 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5037 I != E; ++I) { 5038 5039 if (I.getUse().get() != Value) 5040 continue; 5041 5042 if (I->getOpcode() == Opcode) 5043 return *I; 5044 } 5045 return nullptr; 5046 } 5047 5048 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5049 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5050 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5051 case Intrinsic::amdgcn_if: 5052 return AMDGPUISD::IF; 5053 case Intrinsic::amdgcn_else: 5054 return AMDGPUISD::ELSE; 5055 case Intrinsic::amdgcn_loop: 5056 return AMDGPUISD::LOOP; 5057 case Intrinsic::amdgcn_end_cf: 5058 llvm_unreachable("should not occur"); 5059 default: 5060 return 0; 5061 } 5062 } 5063 5064 // break, if_break, else_break are all only used as inputs to loop, not 5065 // directly as branch conditions. 5066 return 0; 5067 } 5068 5069 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5070 const Triple &TT = getTargetMachine().getTargetTriple(); 5071 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5072 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5073 AMDGPU::shouldEmitConstantsToTextSection(TT); 5074 } 5075 5076 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5077 // FIXME: Either avoid relying on address space here or change the default 5078 // address space for functions to avoid the explicit check. 5079 return (GV->getValueType()->isFunctionTy() || 5080 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5081 !shouldEmitFixup(GV) && 5082 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5083 } 5084 5085 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5086 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5087 } 5088 5089 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5090 if (!GV->hasExternalLinkage()) 5091 return true; 5092 5093 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5094 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5095 } 5096 5097 /// This transforms the control flow intrinsics to get the branch destination as 5098 /// last parameter, also switches branch target with BR if the need arise 5099 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5100 SelectionDAG &DAG) const { 5101 SDLoc DL(BRCOND); 5102 5103 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5104 SDValue Target = BRCOND.getOperand(2); 5105 SDNode *BR = nullptr; 5106 SDNode *SetCC = nullptr; 5107 5108 if (Intr->getOpcode() == ISD::SETCC) { 5109 // As long as we negate the condition everything is fine 5110 SetCC = Intr; 5111 Intr = SetCC->getOperand(0).getNode(); 5112 5113 } else { 5114 // Get the target from BR if we don't negate the condition 5115 BR = findUser(BRCOND, ISD::BR); 5116 assert(BR && "brcond missing unconditional branch user"); 5117 Target = BR->getOperand(1); 5118 } 5119 5120 unsigned CFNode = isCFIntrinsic(Intr); 5121 if (CFNode == 0) { 5122 // This is a uniform branch so we don't need to legalize. 5123 return BRCOND; 5124 } 5125 5126 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5127 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5128 5129 assert(!SetCC || 5130 (SetCC->getConstantOperandVal(1) == 1 && 5131 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5132 ISD::SETNE)); 5133 5134 // operands of the new intrinsic call 5135 SmallVector<SDValue, 4> Ops; 5136 if (HaveChain) 5137 Ops.push_back(BRCOND.getOperand(0)); 5138 5139 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5140 Ops.push_back(Target); 5141 5142 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5143 5144 // build the new intrinsic call 5145 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5146 5147 if (!HaveChain) { 5148 SDValue Ops[] = { 5149 SDValue(Result, 0), 5150 BRCOND.getOperand(0) 5151 }; 5152 5153 Result = DAG.getMergeValues(Ops, DL).getNode(); 5154 } 5155 5156 if (BR) { 5157 // Give the branch instruction our target 5158 SDValue Ops[] = { 5159 BR->getOperand(0), 5160 BRCOND.getOperand(2) 5161 }; 5162 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5163 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5164 } 5165 5166 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5167 5168 // Copy the intrinsic results to registers 5169 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5170 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5171 if (!CopyToReg) 5172 continue; 5173 5174 Chain = DAG.getCopyToReg( 5175 Chain, DL, 5176 CopyToReg->getOperand(1), 5177 SDValue(Result, i - 1), 5178 SDValue()); 5179 5180 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5181 } 5182 5183 // Remove the old intrinsic from the chain 5184 DAG.ReplaceAllUsesOfValueWith( 5185 SDValue(Intr, Intr->getNumValues() - 1), 5186 Intr->getOperand(0)); 5187 5188 return Chain; 5189 } 5190 5191 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5192 SelectionDAG &DAG) const { 5193 MVT VT = Op.getSimpleValueType(); 5194 SDLoc DL(Op); 5195 // Checking the depth 5196 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5197 return DAG.getConstant(0, DL, VT); 5198 5199 MachineFunction &MF = DAG.getMachineFunction(); 5200 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5201 // Check for kernel and shader functions 5202 if (Info->isEntryFunction()) 5203 return DAG.getConstant(0, DL, VT); 5204 5205 MachineFrameInfo &MFI = MF.getFrameInfo(); 5206 // There is a call to @llvm.returnaddress in this function 5207 MFI.setReturnAddressIsTaken(true); 5208 5209 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5210 // Get the return address reg and mark it as an implicit live-in 5211 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5212 5213 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5214 } 5215 5216 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5217 SDValue Op, 5218 const SDLoc &DL, 5219 EVT VT) const { 5220 return Op.getValueType().bitsLE(VT) ? 5221 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5222 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5223 DAG.getTargetConstant(0, DL, MVT::i32)); 5224 } 5225 5226 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5227 assert(Op.getValueType() == MVT::f16 && 5228 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5229 5230 SDValue Src = Op.getOperand(0); 5231 EVT SrcVT = Src.getValueType(); 5232 if (SrcVT != MVT::f64) 5233 return Op; 5234 5235 SDLoc DL(Op); 5236 5237 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5238 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5239 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5240 } 5241 5242 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5243 SelectionDAG &DAG) const { 5244 EVT VT = Op.getValueType(); 5245 const MachineFunction &MF = DAG.getMachineFunction(); 5246 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5247 bool IsIEEEMode = Info->getMode().IEEE; 5248 5249 // FIXME: Assert during selection that this is only selected for 5250 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5251 // mode functions, but this happens to be OK since it's only done in cases 5252 // where there is known no sNaN. 5253 if (IsIEEEMode) 5254 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5255 5256 if (VT == MVT::v4f16) 5257 return splitBinaryVectorOp(Op, DAG); 5258 return Op; 5259 } 5260 5261 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5262 EVT VT = Op.getValueType(); 5263 SDLoc SL(Op); 5264 SDValue LHS = Op.getOperand(0); 5265 SDValue RHS = Op.getOperand(1); 5266 bool isSigned = Op.getOpcode() == ISD::SMULO; 5267 5268 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5269 const APInt &C = RHSC->getAPIntValue(); 5270 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5271 if (C.isPowerOf2()) { 5272 // smulo(x, signed_min) is same as umulo(x, signed_min). 5273 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5274 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5275 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5276 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5277 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5278 SL, VT, Result, ShiftAmt), 5279 LHS, ISD::SETNE); 5280 return DAG.getMergeValues({ Result, Overflow }, SL); 5281 } 5282 } 5283 5284 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5285 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5286 SL, VT, LHS, RHS); 5287 5288 SDValue Sign = isSigned 5289 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5290 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5291 : DAG.getConstant(0, SL, VT); 5292 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5293 5294 return DAG.getMergeValues({ Result, Overflow }, SL); 5295 } 5296 5297 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5298 if (!Subtarget->isTrapHandlerEnabled() || 5299 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5300 return lowerTrapEndpgm(Op, DAG); 5301 5302 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5303 switch (*HsaAbiVer) { 5304 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5305 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5306 return lowerTrapHsaQueuePtr(Op, DAG); 5307 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5308 return Subtarget->supportsGetDoorbellID() ? 5309 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5310 } 5311 } 5312 5313 llvm_unreachable("Unknown trap handler"); 5314 } 5315 5316 SDValue SITargetLowering::lowerTrapEndpgm( 5317 SDValue Op, SelectionDAG &DAG) const { 5318 SDLoc SL(Op); 5319 SDValue Chain = Op.getOperand(0); 5320 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5321 } 5322 5323 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5324 SDValue Op, SelectionDAG &DAG) const { 5325 SDLoc SL(Op); 5326 SDValue Chain = Op.getOperand(0); 5327 5328 MachineFunction &MF = DAG.getMachineFunction(); 5329 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5330 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5331 5332 SDValue QueuePtr; 5333 if (UserSGPR == AMDGPU::NoRegister) { 5334 // We probably are in a function incorrectly marked with 5335 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5336 // so just use a null pointer. 5337 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5338 } else { 5339 QueuePtr = CreateLiveInRegister( 5340 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5341 } 5342 5343 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5344 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5345 QueuePtr, SDValue()); 5346 5347 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5348 SDValue Ops[] = { 5349 ToReg, 5350 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5351 SGPR01, 5352 ToReg.getValue(1) 5353 }; 5354 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5355 } 5356 5357 SDValue SITargetLowering::lowerTrapHsa( 5358 SDValue Op, SelectionDAG &DAG) const { 5359 SDLoc SL(Op); 5360 SDValue Chain = Op.getOperand(0); 5361 5362 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5363 SDValue Ops[] = { 5364 Chain, 5365 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5366 }; 5367 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5368 } 5369 5370 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5371 SDLoc SL(Op); 5372 SDValue Chain = Op.getOperand(0); 5373 MachineFunction &MF = DAG.getMachineFunction(); 5374 5375 if (!Subtarget->isTrapHandlerEnabled() || 5376 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5377 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5378 "debugtrap handler not supported", 5379 Op.getDebugLoc(), 5380 DS_Warning); 5381 LLVMContext &Ctx = MF.getFunction().getContext(); 5382 Ctx.diagnose(NoTrap); 5383 return Chain; 5384 } 5385 5386 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5387 SDValue Ops[] = { 5388 Chain, 5389 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5390 }; 5391 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5392 } 5393 5394 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5395 SelectionDAG &DAG) const { 5396 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5397 if (Subtarget->hasApertureRegs()) { 5398 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5399 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5400 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5401 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5402 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5403 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5404 unsigned Encoding = 5405 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5406 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5407 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5408 5409 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5410 SDValue ApertureReg = SDValue( 5411 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5412 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5413 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5414 } 5415 5416 MachineFunction &MF = DAG.getMachineFunction(); 5417 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5418 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5419 if (UserSGPR == AMDGPU::NoRegister) { 5420 // We probably are in a function incorrectly marked with 5421 // amdgpu-no-queue-ptr. This is undefined. 5422 return DAG.getUNDEF(MVT::i32); 5423 } 5424 5425 SDValue QueuePtr = CreateLiveInRegister( 5426 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5427 5428 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5429 // private_segment_aperture_base_hi. 5430 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5431 5432 SDValue Ptr = 5433 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5434 5435 // TODO: Use custom target PseudoSourceValue. 5436 // TODO: We should use the value from the IR intrinsic call, but it might not 5437 // be available and how do we get it? 5438 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5439 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5440 commonAlignment(Align(64), StructOffset), 5441 MachineMemOperand::MODereferenceable | 5442 MachineMemOperand::MOInvariant); 5443 } 5444 5445 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5446 SelectionDAG &DAG) const { 5447 SDLoc SL(Op); 5448 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5449 5450 SDValue Src = ASC->getOperand(0); 5451 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5452 5453 const AMDGPUTargetMachine &TM = 5454 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5455 5456 // flat -> local/private 5457 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5458 unsigned DestAS = ASC->getDestAddressSpace(); 5459 5460 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5461 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5462 unsigned NullVal = TM.getNullPointerValue(DestAS); 5463 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5464 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5465 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5466 5467 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5468 NonNull, Ptr, SegmentNullPtr); 5469 } 5470 } 5471 5472 // local/private -> flat 5473 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5474 unsigned SrcAS = ASC->getSrcAddressSpace(); 5475 5476 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5477 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5478 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5479 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5480 5481 SDValue NonNull 5482 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5483 5484 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5485 SDValue CvtPtr 5486 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5487 5488 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5489 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5490 FlatNullPtr); 5491 } 5492 } 5493 5494 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5495 Src.getValueType() == MVT::i64) 5496 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5497 5498 // global <-> flat are no-ops and never emitted. 5499 5500 const MachineFunction &MF = DAG.getMachineFunction(); 5501 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5502 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5503 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5504 5505 return DAG.getUNDEF(ASC->getValueType(0)); 5506 } 5507 5508 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5509 // the small vector and inserting them into the big vector. That is better than 5510 // the default expansion of doing it via a stack slot. Even though the use of 5511 // the stack slot would be optimized away afterwards, the stack slot itself 5512 // remains. 5513 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5514 SelectionDAG &DAG) const { 5515 SDValue Vec = Op.getOperand(0); 5516 SDValue Ins = Op.getOperand(1); 5517 SDValue Idx = Op.getOperand(2); 5518 EVT VecVT = Vec.getValueType(); 5519 EVT InsVT = Ins.getValueType(); 5520 EVT EltVT = VecVT.getVectorElementType(); 5521 unsigned InsNumElts = InsVT.getVectorNumElements(); 5522 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5523 SDLoc SL(Op); 5524 5525 for (unsigned I = 0; I != InsNumElts; ++I) { 5526 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5527 DAG.getConstant(I, SL, MVT::i32)); 5528 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5529 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5530 } 5531 return Vec; 5532 } 5533 5534 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5535 SelectionDAG &DAG) const { 5536 SDValue Vec = Op.getOperand(0); 5537 SDValue InsVal = Op.getOperand(1); 5538 SDValue Idx = Op.getOperand(2); 5539 EVT VecVT = Vec.getValueType(); 5540 EVT EltVT = VecVT.getVectorElementType(); 5541 unsigned VecSize = VecVT.getSizeInBits(); 5542 unsigned EltSize = EltVT.getSizeInBits(); 5543 5544 5545 assert(VecSize <= 64); 5546 5547 unsigned NumElts = VecVT.getVectorNumElements(); 5548 SDLoc SL(Op); 5549 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5550 5551 if (NumElts == 4 && EltSize == 16 && KIdx) { 5552 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5553 5554 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5555 DAG.getConstant(0, SL, MVT::i32)); 5556 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5557 DAG.getConstant(1, SL, MVT::i32)); 5558 5559 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5560 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5561 5562 unsigned Idx = KIdx->getZExtValue(); 5563 bool InsertLo = Idx < 2; 5564 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5565 InsertLo ? LoVec : HiVec, 5566 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5567 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5568 5569 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5570 5571 SDValue Concat = InsertLo ? 5572 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5573 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5574 5575 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5576 } 5577 5578 if (isa<ConstantSDNode>(Idx)) 5579 return SDValue(); 5580 5581 MVT IntVT = MVT::getIntegerVT(VecSize); 5582 5583 // Avoid stack access for dynamic indexing. 5584 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5585 5586 // Create a congruent vector with the target value in each element so that 5587 // the required element can be masked and ORed into the target vector. 5588 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5589 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5590 5591 assert(isPowerOf2_32(EltSize)); 5592 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5593 5594 // Convert vector index to bit-index. 5595 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5596 5597 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5598 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5599 DAG.getConstant(0xffff, SL, IntVT), 5600 ScaledIdx); 5601 5602 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5603 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5604 DAG.getNOT(SL, BFM, IntVT), BCVec); 5605 5606 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5607 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5608 } 5609 5610 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5611 SelectionDAG &DAG) const { 5612 SDLoc SL(Op); 5613 5614 EVT ResultVT = Op.getValueType(); 5615 SDValue Vec = Op.getOperand(0); 5616 SDValue Idx = Op.getOperand(1); 5617 EVT VecVT = Vec.getValueType(); 5618 unsigned VecSize = VecVT.getSizeInBits(); 5619 EVT EltVT = VecVT.getVectorElementType(); 5620 assert(VecSize <= 64); 5621 5622 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5623 5624 // Make sure we do any optimizations that will make it easier to fold 5625 // source modifiers before obscuring it with bit operations. 5626 5627 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5628 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5629 return Combined; 5630 5631 unsigned EltSize = EltVT.getSizeInBits(); 5632 assert(isPowerOf2_32(EltSize)); 5633 5634 MVT IntVT = MVT::getIntegerVT(VecSize); 5635 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5636 5637 // Convert vector index to bit-index (* EltSize) 5638 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5639 5640 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5641 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5642 5643 if (ResultVT == MVT::f16) { 5644 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5645 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5646 } 5647 5648 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5649 } 5650 5651 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5652 assert(Elt % 2 == 0); 5653 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5654 } 5655 5656 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5657 SelectionDAG &DAG) const { 5658 SDLoc SL(Op); 5659 EVT ResultVT = Op.getValueType(); 5660 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5661 5662 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5663 EVT EltVT = PackVT.getVectorElementType(); 5664 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5665 5666 // vector_shuffle <0,1,6,7> lhs, rhs 5667 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5668 // 5669 // vector_shuffle <6,7,2,3> lhs, rhs 5670 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5671 // 5672 // vector_shuffle <6,7,0,1> lhs, rhs 5673 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5674 5675 // Avoid scalarizing when both halves are reading from consecutive elements. 5676 SmallVector<SDValue, 4> Pieces; 5677 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5678 if (elementPairIsContiguous(SVN->getMask(), I)) { 5679 const int Idx = SVN->getMaskElt(I); 5680 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5681 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5682 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5683 PackVT, SVN->getOperand(VecIdx), 5684 DAG.getConstant(EltIdx, SL, MVT::i32)); 5685 Pieces.push_back(SubVec); 5686 } else { 5687 const int Idx0 = SVN->getMaskElt(I); 5688 const int Idx1 = SVN->getMaskElt(I + 1); 5689 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5690 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5691 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5692 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5693 5694 SDValue Vec0 = SVN->getOperand(VecIdx0); 5695 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5696 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5697 5698 SDValue Vec1 = SVN->getOperand(VecIdx1); 5699 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5700 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5701 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5702 } 5703 } 5704 5705 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5706 } 5707 5708 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5709 SelectionDAG &DAG) const { 5710 SDLoc SL(Op); 5711 EVT VT = Op.getValueType(); 5712 5713 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5714 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5715 5716 // Turn into pair of packed build_vectors. 5717 // TODO: Special case for constants that can be materialized with s_mov_b64. 5718 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5719 { Op.getOperand(0), Op.getOperand(1) }); 5720 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5721 { Op.getOperand(2), Op.getOperand(3) }); 5722 5723 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5724 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5725 5726 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5727 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5728 } 5729 5730 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5731 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5732 5733 SDValue Lo = Op.getOperand(0); 5734 SDValue Hi = Op.getOperand(1); 5735 5736 // Avoid adding defined bits with the zero_extend. 5737 if (Hi.isUndef()) { 5738 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5739 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5740 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5741 } 5742 5743 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5744 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5745 5746 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5747 DAG.getConstant(16, SL, MVT::i32)); 5748 if (Lo.isUndef()) 5749 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5750 5751 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5752 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5753 5754 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5755 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5756 } 5757 5758 bool 5759 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5760 // We can fold offsets for anything that doesn't require a GOT relocation. 5761 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5762 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5763 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5764 !shouldEmitGOTReloc(GA->getGlobal()); 5765 } 5766 5767 static SDValue 5768 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5769 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5770 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5771 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5772 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5773 // lowered to the following code sequence: 5774 // 5775 // For constant address space: 5776 // s_getpc_b64 s[0:1] 5777 // s_add_u32 s0, s0, $symbol 5778 // s_addc_u32 s1, s1, 0 5779 // 5780 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5781 // a fixup or relocation is emitted to replace $symbol with a literal 5782 // constant, which is a pc-relative offset from the encoding of the $symbol 5783 // operand to the global variable. 5784 // 5785 // For global address space: 5786 // s_getpc_b64 s[0:1] 5787 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5788 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5789 // 5790 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5791 // fixups or relocations are emitted to replace $symbol@*@lo and 5792 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5793 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5794 // operand to the global variable. 5795 // 5796 // What we want here is an offset from the value returned by s_getpc 5797 // (which is the address of the s_add_u32 instruction) to the global 5798 // variable, but since the encoding of $symbol starts 4 bytes after the start 5799 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5800 // small. This requires us to add 4 to the global variable offset in order to 5801 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5802 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5803 // instruction. 5804 SDValue PtrLo = 5805 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5806 SDValue PtrHi; 5807 if (GAFlags == SIInstrInfo::MO_NONE) { 5808 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5809 } else { 5810 PtrHi = 5811 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5812 } 5813 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5814 } 5815 5816 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5817 SDValue Op, 5818 SelectionDAG &DAG) const { 5819 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5820 SDLoc DL(GSD); 5821 EVT PtrVT = Op.getValueType(); 5822 5823 const GlobalValue *GV = GSD->getGlobal(); 5824 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5825 shouldUseLDSConstAddress(GV)) || 5826 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5827 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5828 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5829 GV->hasExternalLinkage()) { 5830 Type *Ty = GV->getValueType(); 5831 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5832 // zero-sized type in other languages to declare the dynamic shared 5833 // memory which size is not known at the compile time. They will be 5834 // allocated by the runtime and placed directly after the static 5835 // allocated ones. They all share the same offset. 5836 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5837 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5838 // Adjust alignment for that dynamic shared memory array. 5839 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5840 return SDValue( 5841 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5842 } 5843 } 5844 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5845 } 5846 5847 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5848 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5849 SIInstrInfo::MO_ABS32_LO); 5850 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5851 } 5852 5853 if (shouldEmitFixup(GV)) 5854 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5855 else if (shouldEmitPCReloc(GV)) 5856 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5857 SIInstrInfo::MO_REL32); 5858 5859 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5860 SIInstrInfo::MO_GOTPCREL32); 5861 5862 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5863 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5864 const DataLayout &DataLayout = DAG.getDataLayout(); 5865 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5866 MachinePointerInfo PtrInfo 5867 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5868 5869 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5870 MachineMemOperand::MODereferenceable | 5871 MachineMemOperand::MOInvariant); 5872 } 5873 5874 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5875 const SDLoc &DL, SDValue V) const { 5876 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5877 // the destination register. 5878 // 5879 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5880 // so we will end up with redundant moves to m0. 5881 // 5882 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5883 5884 // A Null SDValue creates a glue result. 5885 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5886 V, Chain); 5887 return SDValue(M0, 0); 5888 } 5889 5890 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5891 SDValue Op, 5892 MVT VT, 5893 unsigned Offset) const { 5894 SDLoc SL(Op); 5895 SDValue Param = lowerKernargMemParameter( 5896 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5897 // The local size values will have the hi 16-bits as zero. 5898 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5899 DAG.getValueType(VT)); 5900 } 5901 5902 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5903 EVT VT) { 5904 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5905 "non-hsa intrinsic with hsa target", 5906 DL.getDebugLoc()); 5907 DAG.getContext()->diagnose(BadIntrin); 5908 return DAG.getUNDEF(VT); 5909 } 5910 5911 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5912 EVT VT) { 5913 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5914 "intrinsic not supported on subtarget", 5915 DL.getDebugLoc()); 5916 DAG.getContext()->diagnose(BadIntrin); 5917 return DAG.getUNDEF(VT); 5918 } 5919 5920 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5921 ArrayRef<SDValue> Elts) { 5922 assert(!Elts.empty()); 5923 MVT Type; 5924 unsigned NumElts = Elts.size(); 5925 5926 if (NumElts <= 8) { 5927 Type = MVT::getVectorVT(MVT::f32, NumElts); 5928 } else { 5929 assert(Elts.size() <= 16); 5930 Type = MVT::v16f32; 5931 NumElts = 16; 5932 } 5933 5934 SmallVector<SDValue, 16> VecElts(NumElts); 5935 for (unsigned i = 0; i < Elts.size(); ++i) { 5936 SDValue Elt = Elts[i]; 5937 if (Elt.getValueType() != MVT::f32) 5938 Elt = DAG.getBitcast(MVT::f32, Elt); 5939 VecElts[i] = Elt; 5940 } 5941 for (unsigned i = Elts.size(); i < NumElts; ++i) 5942 VecElts[i] = DAG.getUNDEF(MVT::f32); 5943 5944 if (NumElts == 1) 5945 return VecElts[0]; 5946 return DAG.getBuildVector(Type, DL, VecElts); 5947 } 5948 5949 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5950 SDValue Src, int ExtraElts) { 5951 EVT SrcVT = Src.getValueType(); 5952 5953 SmallVector<SDValue, 8> Elts; 5954 5955 if (SrcVT.isVector()) 5956 DAG.ExtractVectorElements(Src, Elts); 5957 else 5958 Elts.push_back(Src); 5959 5960 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5961 while (ExtraElts--) 5962 Elts.push_back(Undef); 5963 5964 return DAG.getBuildVector(CastVT, DL, Elts); 5965 } 5966 5967 // Re-construct the required return value for a image load intrinsic. 5968 // This is more complicated due to the optional use TexFailCtrl which means the required 5969 // return type is an aggregate 5970 static SDValue constructRetValue(SelectionDAG &DAG, 5971 MachineSDNode *Result, 5972 ArrayRef<EVT> ResultTypes, 5973 bool IsTexFail, bool Unpacked, bool IsD16, 5974 int DMaskPop, int NumVDataDwords, 5975 const SDLoc &DL) { 5976 // Determine the required return type. This is the same regardless of IsTexFail flag 5977 EVT ReqRetVT = ResultTypes[0]; 5978 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5979 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5980 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5981 5982 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5983 DMaskPop : (DMaskPop + 1) / 2; 5984 5985 MVT DataDwordVT = NumDataDwords == 1 ? 5986 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5987 5988 MVT MaskPopVT = MaskPopDwords == 1 ? 5989 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5990 5991 SDValue Data(Result, 0); 5992 SDValue TexFail; 5993 5994 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5995 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5996 if (MaskPopVT.isVector()) { 5997 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5998 SDValue(Result, 0), ZeroIdx); 5999 } else { 6000 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6001 SDValue(Result, 0), ZeroIdx); 6002 } 6003 } 6004 6005 if (DataDwordVT.isVector()) 6006 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6007 NumDataDwords - MaskPopDwords); 6008 6009 if (IsD16) 6010 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6011 6012 EVT LegalReqRetVT = ReqRetVT; 6013 if (!ReqRetVT.isVector()) { 6014 if (!Data.getValueType().isInteger()) 6015 Data = DAG.getNode(ISD::BITCAST, DL, 6016 Data.getValueType().changeTypeToInteger(), Data); 6017 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6018 } else { 6019 // We need to widen the return vector to a legal type 6020 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6021 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6022 LegalReqRetVT = 6023 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6024 ReqRetVT.getVectorNumElements() + 1); 6025 } 6026 } 6027 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6028 6029 if (IsTexFail) { 6030 TexFail = 6031 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6032 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6033 6034 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6035 } 6036 6037 if (Result->getNumValues() == 1) 6038 return Data; 6039 6040 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6041 } 6042 6043 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6044 SDValue *LWE, bool &IsTexFail) { 6045 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6046 6047 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6048 if (Value) { 6049 IsTexFail = true; 6050 } 6051 6052 SDLoc DL(TexFailCtrlConst); 6053 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6054 Value &= ~(uint64_t)0x1; 6055 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6056 Value &= ~(uint64_t)0x2; 6057 6058 return Value == 0; 6059 } 6060 6061 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6062 MVT PackVectorVT, 6063 SmallVectorImpl<SDValue> &PackedAddrs, 6064 unsigned DimIdx, unsigned EndIdx, 6065 unsigned NumGradients) { 6066 SDLoc DL(Op); 6067 for (unsigned I = DimIdx; I < EndIdx; I++) { 6068 SDValue Addr = Op.getOperand(I); 6069 6070 // Gradients are packed with undef for each coordinate. 6071 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6072 // 1D: undef,dx/dh; undef,dx/dv 6073 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6074 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6075 if (((I + 1) >= EndIdx) || 6076 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6077 I == DimIdx + NumGradients - 1))) { 6078 if (Addr.getValueType() != MVT::i16) 6079 Addr = DAG.getBitcast(MVT::i16, Addr); 6080 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6081 } else { 6082 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6083 I++; 6084 } 6085 Addr = DAG.getBitcast(MVT::f32, Addr); 6086 PackedAddrs.push_back(Addr); 6087 } 6088 } 6089 6090 SDValue SITargetLowering::lowerImage(SDValue Op, 6091 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6092 SelectionDAG &DAG, bool WithChain) const { 6093 SDLoc DL(Op); 6094 MachineFunction &MF = DAG.getMachineFunction(); 6095 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6096 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6097 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6098 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6099 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6100 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6101 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6102 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6103 unsigned IntrOpcode = Intr->BaseOpcode; 6104 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6105 6106 SmallVector<EVT, 3> ResultTypes(Op->values()); 6107 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6108 bool IsD16 = false; 6109 bool IsG16 = false; 6110 bool IsA16 = false; 6111 SDValue VData; 6112 int NumVDataDwords; 6113 bool AdjustRetType = false; 6114 6115 // Offset of intrinsic arguments 6116 const unsigned ArgOffset = WithChain ? 2 : 1; 6117 6118 unsigned DMask; 6119 unsigned DMaskLanes = 0; 6120 6121 if (BaseOpcode->Atomic) { 6122 VData = Op.getOperand(2); 6123 6124 bool Is64Bit = VData.getValueType() == MVT::i64; 6125 if (BaseOpcode->AtomicX2) { 6126 SDValue VData2 = Op.getOperand(3); 6127 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6128 {VData, VData2}); 6129 if (Is64Bit) 6130 VData = DAG.getBitcast(MVT::v4i32, VData); 6131 6132 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6133 DMask = Is64Bit ? 0xf : 0x3; 6134 NumVDataDwords = Is64Bit ? 4 : 2; 6135 } else { 6136 DMask = Is64Bit ? 0x3 : 0x1; 6137 NumVDataDwords = Is64Bit ? 2 : 1; 6138 } 6139 } else { 6140 auto *DMaskConst = 6141 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6142 DMask = DMaskConst->getZExtValue(); 6143 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6144 6145 if (BaseOpcode->Store) { 6146 VData = Op.getOperand(2); 6147 6148 MVT StoreVT = VData.getSimpleValueType(); 6149 if (StoreVT.getScalarType() == MVT::f16) { 6150 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6151 return Op; // D16 is unsupported for this instruction 6152 6153 IsD16 = true; 6154 VData = handleD16VData(VData, DAG, true); 6155 } 6156 6157 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6158 } else { 6159 // Work out the num dwords based on the dmask popcount and underlying type 6160 // and whether packing is supported. 6161 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6162 if (LoadVT.getScalarType() == MVT::f16) { 6163 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6164 return Op; // D16 is unsupported for this instruction 6165 6166 IsD16 = true; 6167 } 6168 6169 // Confirm that the return type is large enough for the dmask specified 6170 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6171 (!LoadVT.isVector() && DMaskLanes > 1)) 6172 return Op; 6173 6174 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6175 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6176 // instructions. 6177 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6178 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6179 NumVDataDwords = (DMaskLanes + 1) / 2; 6180 else 6181 NumVDataDwords = DMaskLanes; 6182 6183 AdjustRetType = true; 6184 } 6185 } 6186 6187 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6188 SmallVector<SDValue, 4> VAddrs; 6189 6190 // Optimize _L to _LZ when _L is zero 6191 if (LZMappingInfo) { 6192 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6193 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6194 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6195 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6196 VAddrEnd--; // remove 'lod' 6197 } 6198 } 6199 } 6200 6201 // Optimize _mip away, when 'lod' is zero 6202 if (MIPMappingInfo) { 6203 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6204 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6205 if (ConstantLod->isZero()) { 6206 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6207 VAddrEnd--; // remove 'mip' 6208 } 6209 } 6210 } 6211 6212 // Push back extra arguments. 6213 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6214 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6215 6216 // Check for 16 bit addresses or derivatives and pack if true. 6217 MVT VAddrVT = 6218 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6219 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6220 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6221 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6222 6223 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6224 VAddrScalarVT = VAddrVT.getScalarType(); 6225 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6226 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6227 6228 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6229 // 16 bit gradients are supported, but are tied to the A16 control 6230 // so both gradients and addresses must be 16 bit 6231 LLVM_DEBUG( 6232 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6233 "require 16 bit args for both gradients and addresses"); 6234 return Op; 6235 } 6236 6237 if (IsA16) { 6238 if (!ST->hasA16()) { 6239 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6240 "support 16 bit addresses\n"); 6241 return Op; 6242 } 6243 } 6244 6245 // We've dealt with incorrect input so we know that if IsA16, IsG16 6246 // are set then we have to compress/pack operands (either address, 6247 // gradient or both) 6248 // In the case where a16 and gradients are tied (no G16 support) then we 6249 // have already verified that both IsA16 and IsG16 are true 6250 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6251 // Activate g16 6252 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6253 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6254 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6255 } 6256 6257 // Add gradients (packed or unpacked) 6258 if (IsG16) { 6259 // Pack the gradients 6260 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6261 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6262 ArgOffset + Intr->GradientStart, 6263 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6264 } else { 6265 for (unsigned I = ArgOffset + Intr->GradientStart; 6266 I < ArgOffset + Intr->CoordStart; I++) 6267 VAddrs.push_back(Op.getOperand(I)); 6268 } 6269 6270 // Add addresses (packed or unpacked) 6271 if (IsA16) { 6272 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6273 ArgOffset + Intr->CoordStart, VAddrEnd, 6274 0 /* No gradients */); 6275 } else { 6276 // Add uncompressed address 6277 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6278 VAddrs.push_back(Op.getOperand(I)); 6279 } 6280 6281 // If the register allocator cannot place the address registers contiguously 6282 // without introducing moves, then using the non-sequential address encoding 6283 // is always preferable, since it saves VALU instructions and is usually a 6284 // wash in terms of code size or even better. 6285 // 6286 // However, we currently have no way of hinting to the register allocator that 6287 // MIMG addresses should be placed contiguously when it is possible to do so, 6288 // so force non-NSA for the common 2-address case as a heuristic. 6289 // 6290 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6291 // allocation when possible. 6292 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6293 VAddrs.size() >= 3 && 6294 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6295 SDValue VAddr; 6296 if (!UseNSA) 6297 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6298 6299 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6300 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6301 SDValue Unorm; 6302 if (!BaseOpcode->Sampler) { 6303 Unorm = True; 6304 } else { 6305 auto UnormConst = 6306 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6307 6308 Unorm = UnormConst->getZExtValue() ? True : False; 6309 } 6310 6311 SDValue TFE; 6312 SDValue LWE; 6313 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6314 bool IsTexFail = false; 6315 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6316 return Op; 6317 6318 if (IsTexFail) { 6319 if (!DMaskLanes) { 6320 // Expecting to get an error flag since TFC is on - and dmask is 0 6321 // Force dmask to be at least 1 otherwise the instruction will fail 6322 DMask = 0x1; 6323 DMaskLanes = 1; 6324 NumVDataDwords = 1; 6325 } 6326 NumVDataDwords += 1; 6327 AdjustRetType = true; 6328 } 6329 6330 // Has something earlier tagged that the return type needs adjusting 6331 // This happens if the instruction is a load or has set TexFailCtrl flags 6332 if (AdjustRetType) { 6333 // NumVDataDwords reflects the true number of dwords required in the return type 6334 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6335 // This is a no-op load. This can be eliminated 6336 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6337 if (isa<MemSDNode>(Op)) 6338 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6339 return Undef; 6340 } 6341 6342 EVT NewVT = NumVDataDwords > 1 ? 6343 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6344 : MVT::i32; 6345 6346 ResultTypes[0] = NewVT; 6347 if (ResultTypes.size() == 3) { 6348 // Original result was aggregate type used for TexFailCtrl results 6349 // The actual instruction returns as a vector type which has now been 6350 // created. Remove the aggregate result. 6351 ResultTypes.erase(&ResultTypes[1]); 6352 } 6353 } 6354 6355 unsigned CPol = cast<ConstantSDNode>( 6356 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6357 if (BaseOpcode->Atomic) 6358 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6359 if (CPol & ~AMDGPU::CPol::ALL) 6360 return Op; 6361 6362 SmallVector<SDValue, 26> Ops; 6363 if (BaseOpcode->Store || BaseOpcode->Atomic) 6364 Ops.push_back(VData); // vdata 6365 if (UseNSA) 6366 append_range(Ops, VAddrs); 6367 else 6368 Ops.push_back(VAddr); 6369 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6370 if (BaseOpcode->Sampler) 6371 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6372 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6373 if (IsGFX10Plus) 6374 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6375 Ops.push_back(Unorm); 6376 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6377 Ops.push_back(IsA16 && // r128, a16 for gfx9 6378 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6379 if (IsGFX10Plus) 6380 Ops.push_back(IsA16 ? True : False); 6381 if (!Subtarget->hasGFX90AInsts()) { 6382 Ops.push_back(TFE); //tfe 6383 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6384 report_fatal_error("TFE is not supported on this GPU"); 6385 } 6386 Ops.push_back(LWE); // lwe 6387 if (!IsGFX10Plus) 6388 Ops.push_back(DimInfo->DA ? True : False); 6389 if (BaseOpcode->HasD16) 6390 Ops.push_back(IsD16 ? True : False); 6391 if (isa<MemSDNode>(Op)) 6392 Ops.push_back(Op.getOperand(0)); // chain 6393 6394 int NumVAddrDwords = 6395 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6396 int Opcode = -1; 6397 6398 if (IsGFX10Plus) { 6399 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6400 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6401 : AMDGPU::MIMGEncGfx10Default, 6402 NumVDataDwords, NumVAddrDwords); 6403 } else { 6404 if (Subtarget->hasGFX90AInsts()) { 6405 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6406 NumVDataDwords, NumVAddrDwords); 6407 if (Opcode == -1) 6408 report_fatal_error( 6409 "requested image instruction is not supported on this GPU"); 6410 } 6411 if (Opcode == -1 && 6412 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6413 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6414 NumVDataDwords, NumVAddrDwords); 6415 if (Opcode == -1) 6416 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6417 NumVDataDwords, NumVAddrDwords); 6418 } 6419 assert(Opcode != -1); 6420 6421 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6422 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6423 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6424 DAG.setNodeMemRefs(NewNode, {MemRef}); 6425 } 6426 6427 if (BaseOpcode->AtomicX2) { 6428 SmallVector<SDValue, 1> Elt; 6429 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6430 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6431 } 6432 if (BaseOpcode->Store) 6433 return SDValue(NewNode, 0); 6434 return constructRetValue(DAG, NewNode, 6435 OrigResultTypes, IsTexFail, 6436 Subtarget->hasUnpackedD16VMem(), IsD16, 6437 DMaskLanes, NumVDataDwords, DL); 6438 } 6439 6440 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6441 SDValue Offset, SDValue CachePolicy, 6442 SelectionDAG &DAG) const { 6443 MachineFunction &MF = DAG.getMachineFunction(); 6444 6445 const DataLayout &DataLayout = DAG.getDataLayout(); 6446 Align Alignment = 6447 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6448 6449 MachineMemOperand *MMO = MF.getMachineMemOperand( 6450 MachinePointerInfo(), 6451 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6452 MachineMemOperand::MOInvariant, 6453 VT.getStoreSize(), Alignment); 6454 6455 if (!Offset->isDivergent()) { 6456 SDValue Ops[] = { 6457 Rsrc, 6458 Offset, // Offset 6459 CachePolicy 6460 }; 6461 6462 // Widen vec3 load to vec4. 6463 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6464 EVT WidenedVT = 6465 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6466 auto WidenedOp = DAG.getMemIntrinsicNode( 6467 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6468 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6469 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6470 DAG.getVectorIdxConstant(0, DL)); 6471 return Subvector; 6472 } 6473 6474 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6475 DAG.getVTList(VT), Ops, VT, MMO); 6476 } 6477 6478 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6479 // assume that the buffer is unswizzled. 6480 SmallVector<SDValue, 4> Loads; 6481 unsigned NumLoads = 1; 6482 MVT LoadVT = VT.getSimpleVT(); 6483 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6484 assert((LoadVT.getScalarType() == MVT::i32 || 6485 LoadVT.getScalarType() == MVT::f32)); 6486 6487 if (NumElts == 8 || NumElts == 16) { 6488 NumLoads = NumElts / 4; 6489 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6490 } 6491 6492 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6493 SDValue Ops[] = { 6494 DAG.getEntryNode(), // Chain 6495 Rsrc, // rsrc 6496 DAG.getConstant(0, DL, MVT::i32), // vindex 6497 {}, // voffset 6498 {}, // soffset 6499 {}, // offset 6500 CachePolicy, // cachepolicy 6501 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6502 }; 6503 6504 // Use the alignment to ensure that the required offsets will fit into the 6505 // immediate offsets. 6506 setBufferOffsets(Offset, DAG, &Ops[3], 6507 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6508 6509 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6510 for (unsigned i = 0; i < NumLoads; ++i) { 6511 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6512 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6513 LoadVT, MMO, DAG)); 6514 } 6515 6516 if (NumElts == 8 || NumElts == 16) 6517 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6518 6519 return Loads[0]; 6520 } 6521 6522 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6523 SelectionDAG &DAG) const { 6524 MachineFunction &MF = DAG.getMachineFunction(); 6525 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6526 6527 EVT VT = Op.getValueType(); 6528 SDLoc DL(Op); 6529 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6530 6531 // TODO: Should this propagate fast-math-flags? 6532 6533 switch (IntrinsicID) { 6534 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6535 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6536 return emitNonHSAIntrinsicError(DAG, DL, VT); 6537 return getPreloadedValue(DAG, *MFI, VT, 6538 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6539 } 6540 case Intrinsic::amdgcn_dispatch_ptr: 6541 case Intrinsic::amdgcn_queue_ptr: { 6542 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6543 DiagnosticInfoUnsupported BadIntrin( 6544 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6545 DL.getDebugLoc()); 6546 DAG.getContext()->diagnose(BadIntrin); 6547 return DAG.getUNDEF(VT); 6548 } 6549 6550 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6551 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6552 return getPreloadedValue(DAG, *MFI, VT, RegID); 6553 } 6554 case Intrinsic::amdgcn_implicitarg_ptr: { 6555 if (MFI->isEntryFunction()) 6556 return getImplicitArgPtr(DAG, DL); 6557 return getPreloadedValue(DAG, *MFI, VT, 6558 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6559 } 6560 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6561 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6562 // This only makes sense to call in a kernel, so just lower to null. 6563 return DAG.getConstant(0, DL, VT); 6564 } 6565 6566 return getPreloadedValue(DAG, *MFI, VT, 6567 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6568 } 6569 case Intrinsic::amdgcn_dispatch_id: { 6570 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6571 } 6572 case Intrinsic::amdgcn_rcp: 6573 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6574 case Intrinsic::amdgcn_rsq: 6575 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6576 case Intrinsic::amdgcn_rsq_legacy: 6577 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6578 return emitRemovedIntrinsicError(DAG, DL, VT); 6579 return SDValue(); 6580 case Intrinsic::amdgcn_rcp_legacy: 6581 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6582 return emitRemovedIntrinsicError(DAG, DL, VT); 6583 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6584 case Intrinsic::amdgcn_rsq_clamp: { 6585 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6586 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6587 6588 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6589 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6590 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6591 6592 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6593 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6594 DAG.getConstantFP(Max, DL, VT)); 6595 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6596 DAG.getConstantFP(Min, DL, VT)); 6597 } 6598 case Intrinsic::r600_read_ngroups_x: 6599 if (Subtarget->isAmdHsaOS()) 6600 return emitNonHSAIntrinsicError(DAG, DL, VT); 6601 6602 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6603 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6604 false); 6605 case Intrinsic::r600_read_ngroups_y: 6606 if (Subtarget->isAmdHsaOS()) 6607 return emitNonHSAIntrinsicError(DAG, DL, VT); 6608 6609 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6610 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6611 false); 6612 case Intrinsic::r600_read_ngroups_z: 6613 if (Subtarget->isAmdHsaOS()) 6614 return emitNonHSAIntrinsicError(DAG, DL, VT); 6615 6616 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6617 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6618 false); 6619 case Intrinsic::r600_read_global_size_x: 6620 if (Subtarget->isAmdHsaOS()) 6621 return emitNonHSAIntrinsicError(DAG, DL, VT); 6622 6623 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6624 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6625 Align(4), false); 6626 case Intrinsic::r600_read_global_size_y: 6627 if (Subtarget->isAmdHsaOS()) 6628 return emitNonHSAIntrinsicError(DAG, DL, VT); 6629 6630 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6631 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6632 Align(4), false); 6633 case Intrinsic::r600_read_global_size_z: 6634 if (Subtarget->isAmdHsaOS()) 6635 return emitNonHSAIntrinsicError(DAG, DL, VT); 6636 6637 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6638 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6639 Align(4), false); 6640 case Intrinsic::r600_read_local_size_x: 6641 if (Subtarget->isAmdHsaOS()) 6642 return emitNonHSAIntrinsicError(DAG, DL, VT); 6643 6644 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6645 SI::KernelInputOffsets::LOCAL_SIZE_X); 6646 case Intrinsic::r600_read_local_size_y: 6647 if (Subtarget->isAmdHsaOS()) 6648 return emitNonHSAIntrinsicError(DAG, DL, VT); 6649 6650 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6651 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6652 case Intrinsic::r600_read_local_size_z: 6653 if (Subtarget->isAmdHsaOS()) 6654 return emitNonHSAIntrinsicError(DAG, DL, VT); 6655 6656 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6657 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6658 case Intrinsic::amdgcn_workgroup_id_x: 6659 return getPreloadedValue(DAG, *MFI, VT, 6660 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6661 case Intrinsic::amdgcn_workgroup_id_y: 6662 return getPreloadedValue(DAG, *MFI, VT, 6663 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6664 case Intrinsic::amdgcn_workgroup_id_z: 6665 return getPreloadedValue(DAG, *MFI, VT, 6666 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6667 case Intrinsic::amdgcn_workitem_id_x: 6668 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6669 SDLoc(DAG.getEntryNode()), 6670 MFI->getArgInfo().WorkItemIDX); 6671 case Intrinsic::amdgcn_workitem_id_y: 6672 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6673 SDLoc(DAG.getEntryNode()), 6674 MFI->getArgInfo().WorkItemIDY); 6675 case Intrinsic::amdgcn_workitem_id_z: 6676 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6677 SDLoc(DAG.getEntryNode()), 6678 MFI->getArgInfo().WorkItemIDZ); 6679 case Intrinsic::amdgcn_wavefrontsize: 6680 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6681 SDLoc(Op), MVT::i32); 6682 case Intrinsic::amdgcn_s_buffer_load: { 6683 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6684 if (CPol & ~AMDGPU::CPol::ALL) 6685 return Op; 6686 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6687 DAG); 6688 } 6689 case Intrinsic::amdgcn_fdiv_fast: 6690 return lowerFDIV_FAST(Op, DAG); 6691 case Intrinsic::amdgcn_sin: 6692 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6693 6694 case Intrinsic::amdgcn_cos: 6695 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6696 6697 case Intrinsic::amdgcn_mul_u24: 6698 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6699 case Intrinsic::amdgcn_mul_i24: 6700 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6701 6702 case Intrinsic::amdgcn_log_clamp: { 6703 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6704 return SDValue(); 6705 6706 return emitRemovedIntrinsicError(DAG, DL, VT); 6707 } 6708 case Intrinsic::amdgcn_ldexp: 6709 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6710 Op.getOperand(1), Op.getOperand(2)); 6711 6712 case Intrinsic::amdgcn_fract: 6713 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6714 6715 case Intrinsic::amdgcn_class: 6716 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6717 Op.getOperand(1), Op.getOperand(2)); 6718 case Intrinsic::amdgcn_div_fmas: 6719 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6720 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6721 Op.getOperand(4)); 6722 6723 case Intrinsic::amdgcn_div_fixup: 6724 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6725 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6726 6727 case Intrinsic::amdgcn_div_scale: { 6728 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6729 6730 // Translate to the operands expected by the machine instruction. The 6731 // first parameter must be the same as the first instruction. 6732 SDValue Numerator = Op.getOperand(1); 6733 SDValue Denominator = Op.getOperand(2); 6734 6735 // Note this order is opposite of the machine instruction's operations, 6736 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6737 // intrinsic has the numerator as the first operand to match a normal 6738 // division operation. 6739 6740 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6741 6742 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6743 Denominator, Numerator); 6744 } 6745 case Intrinsic::amdgcn_icmp: { 6746 // There is a Pat that handles this variant, so return it as-is. 6747 if (Op.getOperand(1).getValueType() == MVT::i1 && 6748 Op.getConstantOperandVal(2) == 0 && 6749 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6750 return Op; 6751 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6752 } 6753 case Intrinsic::amdgcn_fcmp: { 6754 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6755 } 6756 case Intrinsic::amdgcn_ballot: 6757 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6758 case Intrinsic::amdgcn_fmed3: 6759 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6760 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6761 case Intrinsic::amdgcn_fdot2: 6762 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6763 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6764 Op.getOperand(4)); 6765 case Intrinsic::amdgcn_fmul_legacy: 6766 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6767 Op.getOperand(1), Op.getOperand(2)); 6768 case Intrinsic::amdgcn_sffbh: 6769 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6770 case Intrinsic::amdgcn_sbfe: 6771 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6772 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6773 case Intrinsic::amdgcn_ubfe: 6774 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6775 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6776 case Intrinsic::amdgcn_cvt_pkrtz: 6777 case Intrinsic::amdgcn_cvt_pknorm_i16: 6778 case Intrinsic::amdgcn_cvt_pknorm_u16: 6779 case Intrinsic::amdgcn_cvt_pk_i16: 6780 case Intrinsic::amdgcn_cvt_pk_u16: { 6781 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6782 EVT VT = Op.getValueType(); 6783 unsigned Opcode; 6784 6785 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6786 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6787 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6788 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6789 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6790 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6791 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6792 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6793 else 6794 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6795 6796 if (isTypeLegal(VT)) 6797 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6798 6799 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6800 Op.getOperand(1), Op.getOperand(2)); 6801 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6802 } 6803 case Intrinsic::amdgcn_fmad_ftz: 6804 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6805 Op.getOperand(2), Op.getOperand(3)); 6806 6807 case Intrinsic::amdgcn_if_break: 6808 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6809 Op->getOperand(1), Op->getOperand(2)), 0); 6810 6811 case Intrinsic::amdgcn_groupstaticsize: { 6812 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6813 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6814 return Op; 6815 6816 const Module *M = MF.getFunction().getParent(); 6817 const GlobalValue *GV = 6818 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6819 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6820 SIInstrInfo::MO_ABS32_LO); 6821 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6822 } 6823 case Intrinsic::amdgcn_is_shared: 6824 case Intrinsic::amdgcn_is_private: { 6825 SDLoc SL(Op); 6826 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6827 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6828 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6829 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6830 Op.getOperand(1)); 6831 6832 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6833 DAG.getConstant(1, SL, MVT::i32)); 6834 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6835 } 6836 case Intrinsic::amdgcn_alignbit: 6837 return DAG.getNode(ISD::FSHR, DL, VT, 6838 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6839 case Intrinsic::amdgcn_perm: 6840 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6841 Op.getOperand(2), Op.getOperand(3)); 6842 case Intrinsic::amdgcn_reloc_constant: { 6843 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6844 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6845 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6846 auto RelocSymbol = cast<GlobalVariable>( 6847 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6848 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6849 SIInstrInfo::MO_ABS32_LO); 6850 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6851 } 6852 default: 6853 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6854 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6855 return lowerImage(Op, ImageDimIntr, DAG, false); 6856 6857 return Op; 6858 } 6859 } 6860 6861 /// Update \p MMO based on the offset inputs to an intrinsic. 6862 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6863 SDValue SOffset, SDValue Offset, 6864 SDValue VIndex = SDValue()) { 6865 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6866 !isa<ConstantSDNode>(Offset)) { 6867 // The combined offset is not known to be constant, so we cannot represent 6868 // it in the MMO. Give up. 6869 MMO->setValue((Value *)nullptr); 6870 return; 6871 } 6872 6873 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6874 !cast<ConstantSDNode>(VIndex)->isZero())) { 6875 // The strided index component of the address is not known to be zero, so we 6876 // cannot represent it in the MMO. Give up. 6877 MMO->setValue((Value *)nullptr); 6878 return; 6879 } 6880 6881 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6882 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6883 cast<ConstantSDNode>(Offset)->getSExtValue()); 6884 } 6885 6886 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6887 SelectionDAG &DAG, 6888 unsigned NewOpcode) const { 6889 SDLoc DL(Op); 6890 6891 SDValue VData = Op.getOperand(2); 6892 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6893 SDValue Ops[] = { 6894 Op.getOperand(0), // Chain 6895 VData, // vdata 6896 Op.getOperand(3), // rsrc 6897 DAG.getConstant(0, DL, MVT::i32), // vindex 6898 Offsets.first, // voffset 6899 Op.getOperand(5), // soffset 6900 Offsets.second, // offset 6901 Op.getOperand(6), // cachepolicy 6902 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6903 }; 6904 6905 auto *M = cast<MemSDNode>(Op); 6906 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 6907 6908 EVT MemVT = VData.getValueType(); 6909 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6910 M->getMemOperand()); 6911 } 6912 6913 // Return a value to use for the idxen operand by examining the vindex operand. 6914 static unsigned getIdxEn(SDValue VIndex) { 6915 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 6916 // No need to set idxen if vindex is known to be zero. 6917 return VIndexC->getZExtValue() != 0; 6918 return 1; 6919 } 6920 6921 SDValue 6922 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6923 unsigned NewOpcode) const { 6924 SDLoc DL(Op); 6925 6926 SDValue VData = Op.getOperand(2); 6927 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6928 SDValue Ops[] = { 6929 Op.getOperand(0), // Chain 6930 VData, // vdata 6931 Op.getOperand(3), // rsrc 6932 Op.getOperand(4), // vindex 6933 Offsets.first, // voffset 6934 Op.getOperand(6), // soffset 6935 Offsets.second, // offset 6936 Op.getOperand(7), // cachepolicy 6937 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6938 }; 6939 6940 auto *M = cast<MemSDNode>(Op); 6941 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 6942 6943 EVT MemVT = VData.getValueType(); 6944 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6945 M->getMemOperand()); 6946 } 6947 6948 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6949 SelectionDAG &DAG) const { 6950 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6951 SDLoc DL(Op); 6952 6953 switch (IntrID) { 6954 case Intrinsic::amdgcn_ds_ordered_add: 6955 case Intrinsic::amdgcn_ds_ordered_swap: { 6956 MemSDNode *M = cast<MemSDNode>(Op); 6957 SDValue Chain = M->getOperand(0); 6958 SDValue M0 = M->getOperand(2); 6959 SDValue Value = M->getOperand(3); 6960 unsigned IndexOperand = M->getConstantOperandVal(7); 6961 unsigned WaveRelease = M->getConstantOperandVal(8); 6962 unsigned WaveDone = M->getConstantOperandVal(9); 6963 6964 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6965 IndexOperand &= ~0x3f; 6966 unsigned CountDw = 0; 6967 6968 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6969 CountDw = (IndexOperand >> 24) & 0xf; 6970 IndexOperand &= ~(0xf << 24); 6971 6972 if (CountDw < 1 || CountDw > 4) { 6973 report_fatal_error( 6974 "ds_ordered_count: dword count must be between 1 and 4"); 6975 } 6976 } 6977 6978 if (IndexOperand) 6979 report_fatal_error("ds_ordered_count: bad index operand"); 6980 6981 if (WaveDone && !WaveRelease) 6982 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6983 6984 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6985 unsigned ShaderType = 6986 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6987 unsigned Offset0 = OrderedCountIndex << 2; 6988 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6989 (Instruction << 4); 6990 6991 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6992 Offset1 |= (CountDw - 1) << 6; 6993 6994 unsigned Offset = Offset0 | (Offset1 << 8); 6995 6996 SDValue Ops[] = { 6997 Chain, 6998 Value, 6999 DAG.getTargetConstant(Offset, DL, MVT::i16), 7000 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7001 }; 7002 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7003 M->getVTList(), Ops, M->getMemoryVT(), 7004 M->getMemOperand()); 7005 } 7006 case Intrinsic::amdgcn_ds_fadd: { 7007 MemSDNode *M = cast<MemSDNode>(Op); 7008 unsigned Opc; 7009 switch (IntrID) { 7010 case Intrinsic::amdgcn_ds_fadd: 7011 Opc = ISD::ATOMIC_LOAD_FADD; 7012 break; 7013 } 7014 7015 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7016 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7017 M->getMemOperand()); 7018 } 7019 case Intrinsic::amdgcn_atomic_inc: 7020 case Intrinsic::amdgcn_atomic_dec: 7021 case Intrinsic::amdgcn_ds_fmin: 7022 case Intrinsic::amdgcn_ds_fmax: { 7023 MemSDNode *M = cast<MemSDNode>(Op); 7024 unsigned Opc; 7025 switch (IntrID) { 7026 case Intrinsic::amdgcn_atomic_inc: 7027 Opc = AMDGPUISD::ATOMIC_INC; 7028 break; 7029 case Intrinsic::amdgcn_atomic_dec: 7030 Opc = AMDGPUISD::ATOMIC_DEC; 7031 break; 7032 case Intrinsic::amdgcn_ds_fmin: 7033 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7034 break; 7035 case Intrinsic::amdgcn_ds_fmax: 7036 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7037 break; 7038 default: 7039 llvm_unreachable("Unknown intrinsic!"); 7040 } 7041 SDValue Ops[] = { 7042 M->getOperand(0), // Chain 7043 M->getOperand(2), // Ptr 7044 M->getOperand(3) // Value 7045 }; 7046 7047 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7048 M->getMemoryVT(), M->getMemOperand()); 7049 } 7050 case Intrinsic::amdgcn_buffer_load: 7051 case Intrinsic::amdgcn_buffer_load_format: { 7052 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7053 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7054 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7055 SDValue Ops[] = { 7056 Op.getOperand(0), // Chain 7057 Op.getOperand(2), // rsrc 7058 Op.getOperand(3), // vindex 7059 SDValue(), // voffset -- will be set by setBufferOffsets 7060 SDValue(), // soffset -- will be set by setBufferOffsets 7061 SDValue(), // offset -- will be set by setBufferOffsets 7062 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7063 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7064 }; 7065 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7066 7067 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7068 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7069 7070 EVT VT = Op.getValueType(); 7071 EVT IntVT = VT.changeTypeToInteger(); 7072 auto *M = cast<MemSDNode>(Op); 7073 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7074 EVT LoadVT = Op.getValueType(); 7075 7076 if (LoadVT.getScalarType() == MVT::f16) 7077 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7078 M, DAG, Ops); 7079 7080 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7081 if (LoadVT.getScalarType() == MVT::i8 || 7082 LoadVT.getScalarType() == MVT::i16) 7083 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7084 7085 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7086 M->getMemOperand(), DAG); 7087 } 7088 case Intrinsic::amdgcn_raw_buffer_load: 7089 case Intrinsic::amdgcn_raw_buffer_load_format: { 7090 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7091 7092 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7093 SDValue Ops[] = { 7094 Op.getOperand(0), // Chain 7095 Op.getOperand(2), // rsrc 7096 DAG.getConstant(0, DL, MVT::i32), // vindex 7097 Offsets.first, // voffset 7098 Op.getOperand(4), // soffset 7099 Offsets.second, // offset 7100 Op.getOperand(5), // cachepolicy, swizzled buffer 7101 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7102 }; 7103 7104 auto *M = cast<MemSDNode>(Op); 7105 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7106 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7107 } 7108 case Intrinsic::amdgcn_struct_buffer_load: 7109 case Intrinsic::amdgcn_struct_buffer_load_format: { 7110 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7111 7112 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7113 SDValue Ops[] = { 7114 Op.getOperand(0), // Chain 7115 Op.getOperand(2), // rsrc 7116 Op.getOperand(3), // vindex 7117 Offsets.first, // voffset 7118 Op.getOperand(5), // soffset 7119 Offsets.second, // offset 7120 Op.getOperand(6), // cachepolicy, swizzled buffer 7121 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7122 }; 7123 7124 auto *M = cast<MemSDNode>(Op); 7125 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7126 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7127 } 7128 case Intrinsic::amdgcn_tbuffer_load: { 7129 MemSDNode *M = cast<MemSDNode>(Op); 7130 EVT LoadVT = Op.getValueType(); 7131 7132 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7133 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7134 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7135 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7136 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7137 SDValue Ops[] = { 7138 Op.getOperand(0), // Chain 7139 Op.getOperand(2), // rsrc 7140 Op.getOperand(3), // vindex 7141 Op.getOperand(4), // voffset 7142 Op.getOperand(5), // soffset 7143 Op.getOperand(6), // offset 7144 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7145 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7146 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7147 }; 7148 7149 if (LoadVT.getScalarType() == MVT::f16) 7150 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7151 M, DAG, Ops); 7152 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7153 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7154 DAG); 7155 } 7156 case Intrinsic::amdgcn_raw_tbuffer_load: { 7157 MemSDNode *M = cast<MemSDNode>(Op); 7158 EVT LoadVT = Op.getValueType(); 7159 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7160 7161 SDValue Ops[] = { 7162 Op.getOperand(0), // Chain 7163 Op.getOperand(2), // rsrc 7164 DAG.getConstant(0, DL, MVT::i32), // vindex 7165 Offsets.first, // voffset 7166 Op.getOperand(4), // soffset 7167 Offsets.second, // offset 7168 Op.getOperand(5), // format 7169 Op.getOperand(6), // cachepolicy, swizzled buffer 7170 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7171 }; 7172 7173 if (LoadVT.getScalarType() == MVT::f16) 7174 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7175 M, DAG, Ops); 7176 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7177 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7178 DAG); 7179 } 7180 case Intrinsic::amdgcn_struct_tbuffer_load: { 7181 MemSDNode *M = cast<MemSDNode>(Op); 7182 EVT LoadVT = Op.getValueType(); 7183 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7184 7185 SDValue Ops[] = { 7186 Op.getOperand(0), // Chain 7187 Op.getOperand(2), // rsrc 7188 Op.getOperand(3), // vindex 7189 Offsets.first, // voffset 7190 Op.getOperand(5), // soffset 7191 Offsets.second, // offset 7192 Op.getOperand(6), // format 7193 Op.getOperand(7), // cachepolicy, swizzled buffer 7194 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7195 }; 7196 7197 if (LoadVT.getScalarType() == MVT::f16) 7198 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7199 M, DAG, Ops); 7200 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7201 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7202 DAG); 7203 } 7204 case Intrinsic::amdgcn_buffer_atomic_swap: 7205 case Intrinsic::amdgcn_buffer_atomic_add: 7206 case Intrinsic::amdgcn_buffer_atomic_sub: 7207 case Intrinsic::amdgcn_buffer_atomic_csub: 7208 case Intrinsic::amdgcn_buffer_atomic_smin: 7209 case Intrinsic::amdgcn_buffer_atomic_umin: 7210 case Intrinsic::amdgcn_buffer_atomic_smax: 7211 case Intrinsic::amdgcn_buffer_atomic_umax: 7212 case Intrinsic::amdgcn_buffer_atomic_and: 7213 case Intrinsic::amdgcn_buffer_atomic_or: 7214 case Intrinsic::amdgcn_buffer_atomic_xor: 7215 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7216 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7217 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7218 SDValue Ops[] = { 7219 Op.getOperand(0), // Chain 7220 Op.getOperand(2), // vdata 7221 Op.getOperand(3), // rsrc 7222 Op.getOperand(4), // vindex 7223 SDValue(), // voffset -- will be set by setBufferOffsets 7224 SDValue(), // soffset -- will be set by setBufferOffsets 7225 SDValue(), // offset -- will be set by setBufferOffsets 7226 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7227 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7228 }; 7229 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7230 7231 EVT VT = Op.getValueType(); 7232 7233 auto *M = cast<MemSDNode>(Op); 7234 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7235 unsigned Opcode = 0; 7236 7237 switch (IntrID) { 7238 case Intrinsic::amdgcn_buffer_atomic_swap: 7239 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7240 break; 7241 case Intrinsic::amdgcn_buffer_atomic_add: 7242 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7243 break; 7244 case Intrinsic::amdgcn_buffer_atomic_sub: 7245 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7246 break; 7247 case Intrinsic::amdgcn_buffer_atomic_csub: 7248 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7249 break; 7250 case Intrinsic::amdgcn_buffer_atomic_smin: 7251 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7252 break; 7253 case Intrinsic::amdgcn_buffer_atomic_umin: 7254 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7255 break; 7256 case Intrinsic::amdgcn_buffer_atomic_smax: 7257 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7258 break; 7259 case Intrinsic::amdgcn_buffer_atomic_umax: 7260 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7261 break; 7262 case Intrinsic::amdgcn_buffer_atomic_and: 7263 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7264 break; 7265 case Intrinsic::amdgcn_buffer_atomic_or: 7266 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7267 break; 7268 case Intrinsic::amdgcn_buffer_atomic_xor: 7269 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7270 break; 7271 case Intrinsic::amdgcn_buffer_atomic_fadd: 7272 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7273 DiagnosticInfoUnsupported 7274 NoFpRet(DAG.getMachineFunction().getFunction(), 7275 "return versions of fp atomics not supported", 7276 DL.getDebugLoc(), DS_Error); 7277 DAG.getContext()->diagnose(NoFpRet); 7278 return SDValue(); 7279 } 7280 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7281 break; 7282 default: 7283 llvm_unreachable("unhandled atomic opcode"); 7284 } 7285 7286 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7287 M->getMemOperand()); 7288 } 7289 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7290 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7291 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7292 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7293 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7294 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7295 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7296 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7297 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7298 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7299 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7300 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7301 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7302 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7303 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7304 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7305 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7306 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7307 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7308 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7309 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7310 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7311 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7312 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7313 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7314 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7315 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7316 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7317 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7318 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7319 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7320 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7321 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7322 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7323 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7324 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7325 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7326 return lowerStructBufferAtomicIntrin(Op, DAG, 7327 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7328 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7329 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7330 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7331 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7332 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7333 return lowerStructBufferAtomicIntrin(Op, DAG, 7334 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7335 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7336 return lowerStructBufferAtomicIntrin(Op, DAG, 7337 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7338 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7339 return lowerStructBufferAtomicIntrin(Op, DAG, 7340 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7341 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7342 return lowerStructBufferAtomicIntrin(Op, DAG, 7343 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7344 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7345 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7346 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7347 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7348 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7349 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7350 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7351 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7352 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7353 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7354 7355 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7356 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7357 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7358 SDValue Ops[] = { 7359 Op.getOperand(0), // Chain 7360 Op.getOperand(2), // src 7361 Op.getOperand(3), // cmp 7362 Op.getOperand(4), // rsrc 7363 Op.getOperand(5), // vindex 7364 SDValue(), // voffset -- will be set by setBufferOffsets 7365 SDValue(), // soffset -- will be set by setBufferOffsets 7366 SDValue(), // offset -- will be set by setBufferOffsets 7367 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7368 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7369 }; 7370 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7371 7372 EVT VT = Op.getValueType(); 7373 auto *M = cast<MemSDNode>(Op); 7374 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7375 7376 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7377 Op->getVTList(), Ops, VT, M->getMemOperand()); 7378 } 7379 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7380 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7381 SDValue Ops[] = { 7382 Op.getOperand(0), // Chain 7383 Op.getOperand(2), // src 7384 Op.getOperand(3), // cmp 7385 Op.getOperand(4), // rsrc 7386 DAG.getConstant(0, DL, MVT::i32), // vindex 7387 Offsets.first, // voffset 7388 Op.getOperand(6), // soffset 7389 Offsets.second, // offset 7390 Op.getOperand(7), // cachepolicy 7391 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7392 }; 7393 EVT VT = Op.getValueType(); 7394 auto *M = cast<MemSDNode>(Op); 7395 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7396 7397 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7398 Op->getVTList(), Ops, VT, M->getMemOperand()); 7399 } 7400 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7401 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7402 SDValue Ops[] = { 7403 Op.getOperand(0), // Chain 7404 Op.getOperand(2), // src 7405 Op.getOperand(3), // cmp 7406 Op.getOperand(4), // rsrc 7407 Op.getOperand(5), // vindex 7408 Offsets.first, // voffset 7409 Op.getOperand(7), // soffset 7410 Offsets.second, // offset 7411 Op.getOperand(8), // cachepolicy 7412 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7413 }; 7414 EVT VT = Op.getValueType(); 7415 auto *M = cast<MemSDNode>(Op); 7416 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7417 7418 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7419 Op->getVTList(), Ops, VT, M->getMemOperand()); 7420 } 7421 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7422 MemSDNode *M = cast<MemSDNode>(Op); 7423 SDValue NodePtr = M->getOperand(2); 7424 SDValue RayExtent = M->getOperand(3); 7425 SDValue RayOrigin = M->getOperand(4); 7426 SDValue RayDir = M->getOperand(5); 7427 SDValue RayInvDir = M->getOperand(6); 7428 SDValue TDescr = M->getOperand(7); 7429 7430 assert(NodePtr.getValueType() == MVT::i32 || 7431 NodePtr.getValueType() == MVT::i64); 7432 assert(RayDir.getValueType() == MVT::v4f16 || 7433 RayDir.getValueType() == MVT::v4f32); 7434 7435 if (!Subtarget->hasGFX10_AEncoding()) { 7436 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7437 return SDValue(); 7438 } 7439 7440 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7441 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7442 const unsigned NumVDataDwords = 4; 7443 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7444 const bool UseNSA = Subtarget->hasNSAEncoding() && 7445 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7446 const unsigned BaseOpcodes[2][2] = { 7447 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7448 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7449 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7450 int Opcode; 7451 if (UseNSA) { 7452 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7453 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7454 NumVAddrDwords); 7455 } else { 7456 Opcode = AMDGPU::getMIMGOpcode( 7457 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7458 PowerOf2Ceil(NumVAddrDwords)); 7459 } 7460 assert(Opcode != -1); 7461 7462 SmallVector<SDValue, 16> Ops; 7463 7464 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7465 SmallVector<SDValue, 3> Lanes; 7466 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7467 if (Lanes[0].getValueSizeInBits() == 32) { 7468 for (unsigned I = 0; I < 3; ++I) 7469 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7470 } else { 7471 if (IsAligned) { 7472 Ops.push_back( 7473 DAG.getBitcast(MVT::i32, 7474 DAG.getBuildVector(MVT::v2f16, DL, 7475 { Lanes[0], Lanes[1] }))); 7476 Ops.push_back(Lanes[2]); 7477 } else { 7478 SDValue Elt0 = Ops.pop_back_val(); 7479 Ops.push_back( 7480 DAG.getBitcast(MVT::i32, 7481 DAG.getBuildVector(MVT::v2f16, DL, 7482 { Elt0, Lanes[0] }))); 7483 Ops.push_back( 7484 DAG.getBitcast(MVT::i32, 7485 DAG.getBuildVector(MVT::v2f16, DL, 7486 { Lanes[1], Lanes[2] }))); 7487 } 7488 } 7489 }; 7490 7491 if (Is64) 7492 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7493 else 7494 Ops.push_back(NodePtr); 7495 7496 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7497 packLanes(RayOrigin, true); 7498 packLanes(RayDir, true); 7499 packLanes(RayInvDir, false); 7500 7501 if (!UseNSA) { 7502 // Build a single vector containing all the operands so far prepared. 7503 if (NumVAddrDwords > 8) { 7504 SDValue Undef = DAG.getUNDEF(MVT::i32); 7505 Ops.append(16 - Ops.size(), Undef); 7506 } 7507 assert(Ops.size() == 8 || Ops.size() == 16); 7508 SDValue MergedOps = DAG.getBuildVector( 7509 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7510 Ops.clear(); 7511 Ops.push_back(MergedOps); 7512 } 7513 7514 Ops.push_back(TDescr); 7515 if (IsA16) 7516 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7517 Ops.push_back(M->getChain()); 7518 7519 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7520 MachineMemOperand *MemRef = M->getMemOperand(); 7521 DAG.setNodeMemRefs(NewNode, {MemRef}); 7522 return SDValue(NewNode, 0); 7523 } 7524 case Intrinsic::amdgcn_global_atomic_fadd: 7525 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7526 DiagnosticInfoUnsupported 7527 NoFpRet(DAG.getMachineFunction().getFunction(), 7528 "return versions of fp atomics not supported", 7529 DL.getDebugLoc(), DS_Error); 7530 DAG.getContext()->diagnose(NoFpRet); 7531 return SDValue(); 7532 } 7533 LLVM_FALLTHROUGH; 7534 case Intrinsic::amdgcn_global_atomic_fmin: 7535 case Intrinsic::amdgcn_global_atomic_fmax: 7536 case Intrinsic::amdgcn_flat_atomic_fadd: 7537 case Intrinsic::amdgcn_flat_atomic_fmin: 7538 case Intrinsic::amdgcn_flat_atomic_fmax: { 7539 MemSDNode *M = cast<MemSDNode>(Op); 7540 SDValue Ops[] = { 7541 M->getOperand(0), // Chain 7542 M->getOperand(2), // Ptr 7543 M->getOperand(3) // Value 7544 }; 7545 unsigned Opcode = 0; 7546 switch (IntrID) { 7547 case Intrinsic::amdgcn_global_atomic_fadd: 7548 case Intrinsic::amdgcn_flat_atomic_fadd: { 7549 EVT VT = Op.getOperand(3).getValueType(); 7550 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7551 DAG.getVTList(VT, MVT::Other), Ops, 7552 M->getMemOperand()); 7553 } 7554 case Intrinsic::amdgcn_global_atomic_fmin: 7555 case Intrinsic::amdgcn_flat_atomic_fmin: { 7556 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7557 break; 7558 } 7559 case Intrinsic::amdgcn_global_atomic_fmax: 7560 case Intrinsic::amdgcn_flat_atomic_fmax: { 7561 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7562 break; 7563 } 7564 default: 7565 llvm_unreachable("unhandled atomic opcode"); 7566 } 7567 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7568 M->getVTList(), Ops, M->getMemoryVT(), 7569 M->getMemOperand()); 7570 } 7571 default: 7572 7573 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7574 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7575 return lowerImage(Op, ImageDimIntr, DAG, true); 7576 7577 return SDValue(); 7578 } 7579 } 7580 7581 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7582 // dwordx4 if on SI. 7583 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7584 SDVTList VTList, 7585 ArrayRef<SDValue> Ops, EVT MemVT, 7586 MachineMemOperand *MMO, 7587 SelectionDAG &DAG) const { 7588 EVT VT = VTList.VTs[0]; 7589 EVT WidenedVT = VT; 7590 EVT WidenedMemVT = MemVT; 7591 if (!Subtarget->hasDwordx3LoadStores() && 7592 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7593 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7594 WidenedVT.getVectorElementType(), 4); 7595 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7596 WidenedMemVT.getVectorElementType(), 4); 7597 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7598 } 7599 7600 assert(VTList.NumVTs == 2); 7601 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7602 7603 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7604 WidenedMemVT, MMO); 7605 if (WidenedVT != VT) { 7606 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7607 DAG.getVectorIdxConstant(0, DL)); 7608 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7609 } 7610 return NewOp; 7611 } 7612 7613 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7614 bool ImageStore) const { 7615 EVT StoreVT = VData.getValueType(); 7616 7617 // No change for f16 and legal vector D16 types. 7618 if (!StoreVT.isVector()) 7619 return VData; 7620 7621 SDLoc DL(VData); 7622 unsigned NumElements = StoreVT.getVectorNumElements(); 7623 7624 if (Subtarget->hasUnpackedD16VMem()) { 7625 // We need to unpack the packed data to store. 7626 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7627 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7628 7629 EVT EquivStoreVT = 7630 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7631 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7632 return DAG.UnrollVectorOp(ZExt.getNode()); 7633 } 7634 7635 // The sq block of gfx8.1 does not estimate register use correctly for d16 7636 // image store instructions. The data operand is computed as if it were not a 7637 // d16 image instruction. 7638 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7639 // Bitcast to i16 7640 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7641 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7642 7643 // Decompose into scalars 7644 SmallVector<SDValue, 4> Elts; 7645 DAG.ExtractVectorElements(IntVData, Elts); 7646 7647 // Group pairs of i16 into v2i16 and bitcast to i32 7648 SmallVector<SDValue, 4> PackedElts; 7649 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7650 SDValue Pair = 7651 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7652 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7653 PackedElts.push_back(IntPair); 7654 } 7655 if ((NumElements % 2) == 1) { 7656 // Handle v3i16 7657 unsigned I = Elts.size() / 2; 7658 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7659 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7660 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7661 PackedElts.push_back(IntPair); 7662 } 7663 7664 // Pad using UNDEF 7665 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7666 7667 // Build final vector 7668 EVT VecVT = 7669 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7670 return DAG.getBuildVector(VecVT, DL, PackedElts); 7671 } 7672 7673 if (NumElements == 3) { 7674 EVT IntStoreVT = 7675 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7676 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7677 7678 EVT WidenedStoreVT = EVT::getVectorVT( 7679 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7680 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7681 WidenedStoreVT.getStoreSizeInBits()); 7682 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7683 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7684 } 7685 7686 assert(isTypeLegal(StoreVT)); 7687 return VData; 7688 } 7689 7690 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7691 SelectionDAG &DAG) const { 7692 SDLoc DL(Op); 7693 SDValue Chain = Op.getOperand(0); 7694 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7695 MachineFunction &MF = DAG.getMachineFunction(); 7696 7697 switch (IntrinsicID) { 7698 case Intrinsic::amdgcn_exp_compr: { 7699 SDValue Src0 = Op.getOperand(4); 7700 SDValue Src1 = Op.getOperand(5); 7701 // Hack around illegal type on SI by directly selecting it. 7702 if (isTypeLegal(Src0.getValueType())) 7703 return SDValue(); 7704 7705 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7706 SDValue Undef = DAG.getUNDEF(MVT::f32); 7707 const SDValue Ops[] = { 7708 Op.getOperand(2), // tgt 7709 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7710 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7711 Undef, // src2 7712 Undef, // src3 7713 Op.getOperand(7), // vm 7714 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7715 Op.getOperand(3), // en 7716 Op.getOperand(0) // Chain 7717 }; 7718 7719 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7720 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7721 } 7722 case Intrinsic::amdgcn_s_barrier: { 7723 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7724 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7725 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7726 if (WGSize <= ST.getWavefrontSize()) 7727 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7728 Op.getOperand(0)), 0); 7729 } 7730 return SDValue(); 7731 }; 7732 case Intrinsic::amdgcn_tbuffer_store: { 7733 SDValue VData = Op.getOperand(2); 7734 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7735 if (IsD16) 7736 VData = handleD16VData(VData, DAG); 7737 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7738 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7739 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7740 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7741 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7742 SDValue Ops[] = { 7743 Chain, 7744 VData, // vdata 7745 Op.getOperand(3), // rsrc 7746 Op.getOperand(4), // vindex 7747 Op.getOperand(5), // voffset 7748 Op.getOperand(6), // soffset 7749 Op.getOperand(7), // offset 7750 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7751 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7752 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7753 }; 7754 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7755 AMDGPUISD::TBUFFER_STORE_FORMAT; 7756 MemSDNode *M = cast<MemSDNode>(Op); 7757 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7758 M->getMemoryVT(), M->getMemOperand()); 7759 } 7760 7761 case Intrinsic::amdgcn_struct_tbuffer_store: { 7762 SDValue VData = Op.getOperand(2); 7763 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7764 if (IsD16) 7765 VData = handleD16VData(VData, DAG); 7766 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7767 SDValue Ops[] = { 7768 Chain, 7769 VData, // vdata 7770 Op.getOperand(3), // rsrc 7771 Op.getOperand(4), // vindex 7772 Offsets.first, // voffset 7773 Op.getOperand(6), // soffset 7774 Offsets.second, // offset 7775 Op.getOperand(7), // format 7776 Op.getOperand(8), // cachepolicy, swizzled buffer 7777 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7778 }; 7779 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7780 AMDGPUISD::TBUFFER_STORE_FORMAT; 7781 MemSDNode *M = cast<MemSDNode>(Op); 7782 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7783 M->getMemoryVT(), M->getMemOperand()); 7784 } 7785 7786 case Intrinsic::amdgcn_raw_tbuffer_store: { 7787 SDValue VData = Op.getOperand(2); 7788 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7789 if (IsD16) 7790 VData = handleD16VData(VData, DAG); 7791 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7792 SDValue Ops[] = { 7793 Chain, 7794 VData, // vdata 7795 Op.getOperand(3), // rsrc 7796 DAG.getConstant(0, DL, MVT::i32), // vindex 7797 Offsets.first, // voffset 7798 Op.getOperand(5), // soffset 7799 Offsets.second, // offset 7800 Op.getOperand(6), // format 7801 Op.getOperand(7), // cachepolicy, swizzled buffer 7802 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7803 }; 7804 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7805 AMDGPUISD::TBUFFER_STORE_FORMAT; 7806 MemSDNode *M = cast<MemSDNode>(Op); 7807 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7808 M->getMemoryVT(), M->getMemOperand()); 7809 } 7810 7811 case Intrinsic::amdgcn_buffer_store: 7812 case Intrinsic::amdgcn_buffer_store_format: { 7813 SDValue VData = Op.getOperand(2); 7814 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7815 if (IsD16) 7816 VData = handleD16VData(VData, DAG); 7817 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7818 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7819 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7820 SDValue Ops[] = { 7821 Chain, 7822 VData, 7823 Op.getOperand(3), // rsrc 7824 Op.getOperand(4), // vindex 7825 SDValue(), // voffset -- will be set by setBufferOffsets 7826 SDValue(), // soffset -- will be set by setBufferOffsets 7827 SDValue(), // offset -- will be set by setBufferOffsets 7828 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7829 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7830 }; 7831 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7832 7833 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7834 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7835 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7836 MemSDNode *M = cast<MemSDNode>(Op); 7837 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7838 7839 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7840 EVT VDataType = VData.getValueType().getScalarType(); 7841 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7842 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7843 7844 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7845 M->getMemoryVT(), M->getMemOperand()); 7846 } 7847 7848 case Intrinsic::amdgcn_raw_buffer_store: 7849 case Intrinsic::amdgcn_raw_buffer_store_format: { 7850 const bool IsFormat = 7851 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7852 7853 SDValue VData = Op.getOperand(2); 7854 EVT VDataVT = VData.getValueType(); 7855 EVT EltType = VDataVT.getScalarType(); 7856 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7857 if (IsD16) { 7858 VData = handleD16VData(VData, DAG); 7859 VDataVT = VData.getValueType(); 7860 } 7861 7862 if (!isTypeLegal(VDataVT)) { 7863 VData = 7864 DAG.getNode(ISD::BITCAST, DL, 7865 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7866 } 7867 7868 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7869 SDValue Ops[] = { 7870 Chain, 7871 VData, 7872 Op.getOperand(3), // rsrc 7873 DAG.getConstant(0, DL, MVT::i32), // vindex 7874 Offsets.first, // voffset 7875 Op.getOperand(5), // soffset 7876 Offsets.second, // offset 7877 Op.getOperand(6), // cachepolicy, swizzled buffer 7878 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7879 }; 7880 unsigned Opc = 7881 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7882 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7883 MemSDNode *M = cast<MemSDNode>(Op); 7884 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7885 7886 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7887 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7888 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7889 7890 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7891 M->getMemoryVT(), M->getMemOperand()); 7892 } 7893 7894 case Intrinsic::amdgcn_struct_buffer_store: 7895 case Intrinsic::amdgcn_struct_buffer_store_format: { 7896 const bool IsFormat = 7897 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7898 7899 SDValue VData = Op.getOperand(2); 7900 EVT VDataVT = VData.getValueType(); 7901 EVT EltType = VDataVT.getScalarType(); 7902 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7903 7904 if (IsD16) { 7905 VData = handleD16VData(VData, DAG); 7906 VDataVT = VData.getValueType(); 7907 } 7908 7909 if (!isTypeLegal(VDataVT)) { 7910 VData = 7911 DAG.getNode(ISD::BITCAST, DL, 7912 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7913 } 7914 7915 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7916 SDValue Ops[] = { 7917 Chain, 7918 VData, 7919 Op.getOperand(3), // rsrc 7920 Op.getOperand(4), // vindex 7921 Offsets.first, // voffset 7922 Op.getOperand(6), // soffset 7923 Offsets.second, // offset 7924 Op.getOperand(7), // cachepolicy, swizzled buffer 7925 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7926 }; 7927 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7928 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7929 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7930 MemSDNode *M = cast<MemSDNode>(Op); 7931 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7932 7933 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7934 EVT VDataType = VData.getValueType().getScalarType(); 7935 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7936 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7937 7938 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7939 M->getMemoryVT(), M->getMemOperand()); 7940 } 7941 case Intrinsic::amdgcn_end_cf: 7942 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7943 Op->getOperand(2), Chain), 0); 7944 7945 default: { 7946 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7947 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7948 return lowerImage(Op, ImageDimIntr, DAG, true); 7949 7950 return Op; 7951 } 7952 } 7953 } 7954 7955 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7956 // offset (the offset that is included in bounds checking and swizzling, to be 7957 // split between the instruction's voffset and immoffset fields) and soffset 7958 // (the offset that is excluded from bounds checking and swizzling, to go in 7959 // the instruction's soffset field). This function takes the first kind of 7960 // offset and figures out how to split it between voffset and immoffset. 7961 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7962 SDValue Offset, SelectionDAG &DAG) const { 7963 SDLoc DL(Offset); 7964 const unsigned MaxImm = 4095; 7965 SDValue N0 = Offset; 7966 ConstantSDNode *C1 = nullptr; 7967 7968 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7969 N0 = SDValue(); 7970 else if (DAG.isBaseWithConstantOffset(N0)) { 7971 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7972 N0 = N0.getOperand(0); 7973 } 7974 7975 if (C1) { 7976 unsigned ImmOffset = C1->getZExtValue(); 7977 // If the immediate value is too big for the immoffset field, put the value 7978 // and -4096 into the immoffset field so that the value that is copied/added 7979 // for the voffset field is a multiple of 4096, and it stands more chance 7980 // of being CSEd with the copy/add for another similar load/store. 7981 // However, do not do that rounding down to a multiple of 4096 if that is a 7982 // negative number, as it appears to be illegal to have a negative offset 7983 // in the vgpr, even if adding the immediate offset makes it positive. 7984 unsigned Overflow = ImmOffset & ~MaxImm; 7985 ImmOffset -= Overflow; 7986 if ((int32_t)Overflow < 0) { 7987 Overflow += ImmOffset; 7988 ImmOffset = 0; 7989 } 7990 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7991 if (Overflow) { 7992 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7993 if (!N0) 7994 N0 = OverflowVal; 7995 else { 7996 SDValue Ops[] = { N0, OverflowVal }; 7997 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7998 } 7999 } 8000 } 8001 if (!N0) 8002 N0 = DAG.getConstant(0, DL, MVT::i32); 8003 if (!C1) 8004 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8005 return {N0, SDValue(C1, 0)}; 8006 } 8007 8008 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8009 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8010 // pointed to by Offsets. 8011 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8012 SelectionDAG &DAG, SDValue *Offsets, 8013 Align Alignment) const { 8014 SDLoc DL(CombinedOffset); 8015 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8016 uint32_t Imm = C->getZExtValue(); 8017 uint32_t SOffset, ImmOffset; 8018 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8019 Alignment)) { 8020 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8021 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8022 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8023 return; 8024 } 8025 } 8026 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8027 SDValue N0 = CombinedOffset.getOperand(0); 8028 SDValue N1 = CombinedOffset.getOperand(1); 8029 uint32_t SOffset, ImmOffset; 8030 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8031 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8032 Subtarget, Alignment)) { 8033 Offsets[0] = N0; 8034 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8035 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8036 return; 8037 } 8038 } 8039 Offsets[0] = CombinedOffset; 8040 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8041 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8042 } 8043 8044 // Handle 8 bit and 16 bit buffer loads 8045 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8046 EVT LoadVT, SDLoc DL, 8047 ArrayRef<SDValue> Ops, 8048 MemSDNode *M) const { 8049 EVT IntVT = LoadVT.changeTypeToInteger(); 8050 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8051 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8052 8053 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8054 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8055 Ops, IntVT, 8056 M->getMemOperand()); 8057 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8058 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8059 8060 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8061 } 8062 8063 // Handle 8 bit and 16 bit buffer stores 8064 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8065 EVT VDataType, SDLoc DL, 8066 SDValue Ops[], 8067 MemSDNode *M) const { 8068 if (VDataType == MVT::f16) 8069 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8070 8071 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8072 Ops[1] = BufferStoreExt; 8073 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8074 AMDGPUISD::BUFFER_STORE_SHORT; 8075 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8076 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8077 M->getMemOperand()); 8078 } 8079 8080 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8081 ISD::LoadExtType ExtType, SDValue Op, 8082 const SDLoc &SL, EVT VT) { 8083 if (VT.bitsLT(Op.getValueType())) 8084 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8085 8086 switch (ExtType) { 8087 case ISD::SEXTLOAD: 8088 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8089 case ISD::ZEXTLOAD: 8090 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8091 case ISD::EXTLOAD: 8092 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8093 case ISD::NON_EXTLOAD: 8094 return Op; 8095 } 8096 8097 llvm_unreachable("invalid ext type"); 8098 } 8099 8100 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8101 SelectionDAG &DAG = DCI.DAG; 8102 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8103 return SDValue(); 8104 8105 // FIXME: Constant loads should all be marked invariant. 8106 unsigned AS = Ld->getAddressSpace(); 8107 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8108 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8109 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8110 return SDValue(); 8111 8112 // Don't do this early, since it may interfere with adjacent load merging for 8113 // illegal types. We can avoid losing alignment information for exotic types 8114 // pre-legalize. 8115 EVT MemVT = Ld->getMemoryVT(); 8116 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8117 MemVT.getSizeInBits() >= 32) 8118 return SDValue(); 8119 8120 SDLoc SL(Ld); 8121 8122 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8123 "unexpected vector extload"); 8124 8125 // TODO: Drop only high part of range. 8126 SDValue Ptr = Ld->getBasePtr(); 8127 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8128 MVT::i32, SL, Ld->getChain(), Ptr, 8129 Ld->getOffset(), 8130 Ld->getPointerInfo(), MVT::i32, 8131 Ld->getAlignment(), 8132 Ld->getMemOperand()->getFlags(), 8133 Ld->getAAInfo(), 8134 nullptr); // Drop ranges 8135 8136 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8137 if (MemVT.isFloatingPoint()) { 8138 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8139 "unexpected fp extload"); 8140 TruncVT = MemVT.changeTypeToInteger(); 8141 } 8142 8143 SDValue Cvt = NewLoad; 8144 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8145 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8146 DAG.getValueType(TruncVT)); 8147 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8148 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8149 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8150 } else { 8151 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8152 } 8153 8154 EVT VT = Ld->getValueType(0); 8155 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8156 8157 DCI.AddToWorklist(Cvt.getNode()); 8158 8159 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8160 // the appropriate extension from the 32-bit load. 8161 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8162 DCI.AddToWorklist(Cvt.getNode()); 8163 8164 // Handle conversion back to floating point if necessary. 8165 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8166 8167 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8168 } 8169 8170 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8171 SDLoc DL(Op); 8172 LoadSDNode *Load = cast<LoadSDNode>(Op); 8173 ISD::LoadExtType ExtType = Load->getExtensionType(); 8174 EVT MemVT = Load->getMemoryVT(); 8175 8176 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8177 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8178 return SDValue(); 8179 8180 // FIXME: Copied from PPC 8181 // First, load into 32 bits, then truncate to 1 bit. 8182 8183 SDValue Chain = Load->getChain(); 8184 SDValue BasePtr = Load->getBasePtr(); 8185 MachineMemOperand *MMO = Load->getMemOperand(); 8186 8187 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8188 8189 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8190 BasePtr, RealMemVT, MMO); 8191 8192 if (!MemVT.isVector()) { 8193 SDValue Ops[] = { 8194 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8195 NewLD.getValue(1) 8196 }; 8197 8198 return DAG.getMergeValues(Ops, DL); 8199 } 8200 8201 SmallVector<SDValue, 3> Elts; 8202 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8203 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8204 DAG.getConstant(I, DL, MVT::i32)); 8205 8206 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8207 } 8208 8209 SDValue Ops[] = { 8210 DAG.getBuildVector(MemVT, DL, Elts), 8211 NewLD.getValue(1) 8212 }; 8213 8214 return DAG.getMergeValues(Ops, DL); 8215 } 8216 8217 if (!MemVT.isVector()) 8218 return SDValue(); 8219 8220 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8221 "Custom lowering for non-i32 vectors hasn't been implemented."); 8222 8223 unsigned Alignment = Load->getAlignment(); 8224 unsigned AS = Load->getAddressSpace(); 8225 if (Subtarget->hasLDSMisalignedBug() && 8226 AS == AMDGPUAS::FLAT_ADDRESS && 8227 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8228 return SplitVectorLoad(Op, DAG); 8229 } 8230 8231 MachineFunction &MF = DAG.getMachineFunction(); 8232 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8233 // If there is a possibilty that flat instruction access scratch memory 8234 // then we need to use the same legalization rules we use for private. 8235 if (AS == AMDGPUAS::FLAT_ADDRESS && 8236 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8237 AS = MFI->hasFlatScratchInit() ? 8238 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8239 8240 unsigned NumElements = MemVT.getVectorNumElements(); 8241 8242 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8243 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8244 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8245 if (MemVT.isPow2VectorType()) 8246 return SDValue(); 8247 return WidenOrSplitVectorLoad(Op, DAG); 8248 } 8249 // Non-uniform loads will be selected to MUBUF instructions, so they 8250 // have the same legalization requirements as global and private 8251 // loads. 8252 // 8253 } 8254 8255 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8256 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8257 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8258 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8259 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8260 Alignment >= 4 && NumElements < 32) { 8261 if (MemVT.isPow2VectorType()) 8262 return SDValue(); 8263 return WidenOrSplitVectorLoad(Op, DAG); 8264 } 8265 // Non-uniform loads will be selected to MUBUF instructions, so they 8266 // have the same legalization requirements as global and private 8267 // loads. 8268 // 8269 } 8270 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8271 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8272 AS == AMDGPUAS::GLOBAL_ADDRESS || 8273 AS == AMDGPUAS::FLAT_ADDRESS) { 8274 if (NumElements > 4) 8275 return SplitVectorLoad(Op, DAG); 8276 // v3 loads not supported on SI. 8277 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8278 return WidenOrSplitVectorLoad(Op, DAG); 8279 8280 // v3 and v4 loads are supported for private and global memory. 8281 return SDValue(); 8282 } 8283 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8284 // Depending on the setting of the private_element_size field in the 8285 // resource descriptor, we can only make private accesses up to a certain 8286 // size. 8287 switch (Subtarget->getMaxPrivateElementSize()) { 8288 case 4: { 8289 SDValue Ops[2]; 8290 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8291 return DAG.getMergeValues(Ops, DL); 8292 } 8293 case 8: 8294 if (NumElements > 2) 8295 return SplitVectorLoad(Op, DAG); 8296 return SDValue(); 8297 case 16: 8298 // Same as global/flat 8299 if (NumElements > 4) 8300 return SplitVectorLoad(Op, DAG); 8301 // v3 loads not supported on SI. 8302 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8303 return WidenOrSplitVectorLoad(Op, DAG); 8304 8305 return SDValue(); 8306 default: 8307 llvm_unreachable("unsupported private_element_size"); 8308 } 8309 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8310 // Use ds_read_b128 or ds_read_b96 when possible. 8311 if (Subtarget->hasDS96AndDS128() && 8312 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8313 MemVT.getStoreSize() == 12) && 8314 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8315 Load->getAlign())) 8316 return SDValue(); 8317 8318 if (NumElements > 2) 8319 return SplitVectorLoad(Op, DAG); 8320 8321 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8322 // address is negative, then the instruction is incorrectly treated as 8323 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8324 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8325 // load later in the SILoadStoreOptimizer. 8326 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8327 NumElements == 2 && MemVT.getStoreSize() == 8 && 8328 Load->getAlignment() < 8) { 8329 return SplitVectorLoad(Op, DAG); 8330 } 8331 } 8332 8333 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8334 MemVT, *Load->getMemOperand())) { 8335 SDValue Ops[2]; 8336 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8337 return DAG.getMergeValues(Ops, DL); 8338 } 8339 8340 return SDValue(); 8341 } 8342 8343 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8344 EVT VT = Op.getValueType(); 8345 assert(VT.getSizeInBits() == 64); 8346 8347 SDLoc DL(Op); 8348 SDValue Cond = Op.getOperand(0); 8349 8350 if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() && 8351 !Op->isDivergent()) { 8352 if (VT == MVT::i64) 8353 return Op; 8354 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1)); 8355 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2)); 8356 return DAG.getNode(ISD::BITCAST, DL, VT, 8357 DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS)); 8358 } 8359 8360 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8361 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8362 8363 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8364 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8365 8366 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8367 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8368 8369 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8370 8371 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8372 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8373 8374 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8375 8376 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8377 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8378 } 8379 8380 // Catch division cases where we can use shortcuts with rcp and rsq 8381 // instructions. 8382 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8383 SelectionDAG &DAG) const { 8384 SDLoc SL(Op); 8385 SDValue LHS = Op.getOperand(0); 8386 SDValue RHS = Op.getOperand(1); 8387 EVT VT = Op.getValueType(); 8388 const SDNodeFlags Flags = Op->getFlags(); 8389 8390 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8391 8392 // Without !fpmath accuracy information, we can't do more because we don't 8393 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8394 if (!AllowInaccurateRcp) 8395 return SDValue(); 8396 8397 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8398 if (CLHS->isExactlyValue(1.0)) { 8399 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8400 // the CI documentation has a worst case error of 1 ulp. 8401 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8402 // use it as long as we aren't trying to use denormals. 8403 // 8404 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8405 8406 // 1.0 / sqrt(x) -> rsq(x) 8407 8408 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8409 // error seems really high at 2^29 ULP. 8410 if (RHS.getOpcode() == ISD::FSQRT) 8411 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8412 8413 // 1.0 / x -> rcp(x) 8414 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8415 } 8416 8417 // Same as for 1.0, but expand the sign out of the constant. 8418 if (CLHS->isExactlyValue(-1.0)) { 8419 // -1.0 / x -> rcp (fneg x) 8420 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8421 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8422 } 8423 } 8424 8425 // Turn into multiply by the reciprocal. 8426 // x / y -> x * (1.0 / y) 8427 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8428 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8429 } 8430 8431 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8432 SelectionDAG &DAG) const { 8433 SDLoc SL(Op); 8434 SDValue X = Op.getOperand(0); 8435 SDValue Y = Op.getOperand(1); 8436 EVT VT = Op.getValueType(); 8437 const SDNodeFlags Flags = Op->getFlags(); 8438 8439 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8440 DAG.getTarget().Options.UnsafeFPMath; 8441 if (!AllowInaccurateDiv) 8442 return SDValue(); 8443 8444 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8445 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8446 8447 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8448 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8449 8450 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8451 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8452 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8453 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8454 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8455 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8456 } 8457 8458 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8459 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8460 SDNodeFlags Flags) { 8461 if (GlueChain->getNumValues() <= 1) { 8462 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8463 } 8464 8465 assert(GlueChain->getNumValues() == 3); 8466 8467 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8468 switch (Opcode) { 8469 default: llvm_unreachable("no chain equivalent for opcode"); 8470 case ISD::FMUL: 8471 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8472 break; 8473 } 8474 8475 return DAG.getNode(Opcode, SL, VTList, 8476 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8477 Flags); 8478 } 8479 8480 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8481 EVT VT, SDValue A, SDValue B, SDValue C, 8482 SDValue GlueChain, SDNodeFlags Flags) { 8483 if (GlueChain->getNumValues() <= 1) { 8484 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8485 } 8486 8487 assert(GlueChain->getNumValues() == 3); 8488 8489 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8490 switch (Opcode) { 8491 default: llvm_unreachable("no chain equivalent for opcode"); 8492 case ISD::FMA: 8493 Opcode = AMDGPUISD::FMA_W_CHAIN; 8494 break; 8495 } 8496 8497 return DAG.getNode(Opcode, SL, VTList, 8498 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8499 Flags); 8500 } 8501 8502 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8503 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8504 return FastLowered; 8505 8506 SDLoc SL(Op); 8507 SDValue Src0 = Op.getOperand(0); 8508 SDValue Src1 = Op.getOperand(1); 8509 8510 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8511 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8512 8513 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8514 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8515 8516 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8517 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8518 8519 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8520 } 8521 8522 // Faster 2.5 ULP division that does not support denormals. 8523 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8524 SDLoc SL(Op); 8525 SDValue LHS = Op.getOperand(1); 8526 SDValue RHS = Op.getOperand(2); 8527 8528 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8529 8530 const APFloat K0Val(BitsToFloat(0x6f800000)); 8531 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8532 8533 const APFloat K1Val(BitsToFloat(0x2f800000)); 8534 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8535 8536 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8537 8538 EVT SetCCVT = 8539 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8540 8541 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8542 8543 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8544 8545 // TODO: Should this propagate fast-math-flags? 8546 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8547 8548 // rcp does not support denormals. 8549 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8550 8551 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8552 8553 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8554 } 8555 8556 // Returns immediate value for setting the F32 denorm mode when using the 8557 // S_DENORM_MODE instruction. 8558 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8559 const SDLoc &SL, const GCNSubtarget *ST) { 8560 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8561 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8562 ? FP_DENORM_FLUSH_NONE 8563 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8564 8565 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8566 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8567 } 8568 8569 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8570 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8571 return FastLowered; 8572 8573 // The selection matcher assumes anything with a chain selecting to a 8574 // mayRaiseFPException machine instruction. Since we're introducing a chain 8575 // here, we need to explicitly report nofpexcept for the regular fdiv 8576 // lowering. 8577 SDNodeFlags Flags = Op->getFlags(); 8578 Flags.setNoFPExcept(true); 8579 8580 SDLoc SL(Op); 8581 SDValue LHS = Op.getOperand(0); 8582 SDValue RHS = Op.getOperand(1); 8583 8584 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8585 8586 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8587 8588 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8589 {RHS, RHS, LHS}, Flags); 8590 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8591 {LHS, RHS, LHS}, Flags); 8592 8593 // Denominator is scaled to not be denormal, so using rcp is ok. 8594 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8595 DenominatorScaled, Flags); 8596 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8597 DenominatorScaled, Flags); 8598 8599 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8600 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8601 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8602 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8603 8604 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8605 8606 if (!HasFP32Denormals) { 8607 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8608 // lowering. The chain dependence is insufficient, and we need glue. We do 8609 // not need the glue variants in a strictfp function. 8610 8611 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8612 8613 SDNode *EnableDenorm; 8614 if (Subtarget->hasDenormModeInst()) { 8615 const SDValue EnableDenormValue = 8616 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8617 8618 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8619 DAG.getEntryNode(), EnableDenormValue).getNode(); 8620 } else { 8621 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8622 SL, MVT::i32); 8623 EnableDenorm = 8624 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8625 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8626 } 8627 8628 SDValue Ops[3] = { 8629 NegDivScale0, 8630 SDValue(EnableDenorm, 0), 8631 SDValue(EnableDenorm, 1) 8632 }; 8633 8634 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8635 } 8636 8637 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8638 ApproxRcp, One, NegDivScale0, Flags); 8639 8640 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8641 ApproxRcp, Fma0, Flags); 8642 8643 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8644 Fma1, Fma1, Flags); 8645 8646 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8647 NumeratorScaled, Mul, Flags); 8648 8649 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8650 Fma2, Fma1, Mul, Fma2, Flags); 8651 8652 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8653 NumeratorScaled, Fma3, Flags); 8654 8655 if (!HasFP32Denormals) { 8656 SDNode *DisableDenorm; 8657 if (Subtarget->hasDenormModeInst()) { 8658 const SDValue DisableDenormValue = 8659 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8660 8661 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8662 Fma4.getValue(1), DisableDenormValue, 8663 Fma4.getValue(2)).getNode(); 8664 } else { 8665 const SDValue DisableDenormValue = 8666 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8667 8668 DisableDenorm = DAG.getMachineNode( 8669 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8670 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8671 } 8672 8673 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8674 SDValue(DisableDenorm, 0), DAG.getRoot()); 8675 DAG.setRoot(OutputChain); 8676 } 8677 8678 SDValue Scale = NumeratorScaled.getValue(1); 8679 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8680 {Fma4, Fma1, Fma3, Scale}, Flags); 8681 8682 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8683 } 8684 8685 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8686 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8687 return FastLowered; 8688 8689 SDLoc SL(Op); 8690 SDValue X = Op.getOperand(0); 8691 SDValue Y = Op.getOperand(1); 8692 8693 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8694 8695 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8696 8697 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8698 8699 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8700 8701 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8702 8703 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8704 8705 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8706 8707 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8708 8709 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8710 8711 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8712 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8713 8714 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8715 NegDivScale0, Mul, DivScale1); 8716 8717 SDValue Scale; 8718 8719 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8720 // Workaround a hardware bug on SI where the condition output from div_scale 8721 // is not usable. 8722 8723 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8724 8725 // Figure out if the scale to use for div_fmas. 8726 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8727 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8728 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8729 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8730 8731 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8732 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8733 8734 SDValue Scale0Hi 8735 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8736 SDValue Scale1Hi 8737 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8738 8739 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8740 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8741 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8742 } else { 8743 Scale = DivScale1.getValue(1); 8744 } 8745 8746 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8747 Fma4, Fma3, Mul, Scale); 8748 8749 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8750 } 8751 8752 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8753 EVT VT = Op.getValueType(); 8754 8755 if (VT == MVT::f32) 8756 return LowerFDIV32(Op, DAG); 8757 8758 if (VT == MVT::f64) 8759 return LowerFDIV64(Op, DAG); 8760 8761 if (VT == MVT::f16) 8762 return LowerFDIV16(Op, DAG); 8763 8764 llvm_unreachable("Unexpected type for fdiv"); 8765 } 8766 8767 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8768 SDLoc DL(Op); 8769 StoreSDNode *Store = cast<StoreSDNode>(Op); 8770 EVT VT = Store->getMemoryVT(); 8771 8772 if (VT == MVT::i1) { 8773 return DAG.getTruncStore(Store->getChain(), DL, 8774 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8775 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8776 } 8777 8778 assert(VT.isVector() && 8779 Store->getValue().getValueType().getScalarType() == MVT::i32); 8780 8781 unsigned AS = Store->getAddressSpace(); 8782 if (Subtarget->hasLDSMisalignedBug() && 8783 AS == AMDGPUAS::FLAT_ADDRESS && 8784 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8785 return SplitVectorStore(Op, DAG); 8786 } 8787 8788 MachineFunction &MF = DAG.getMachineFunction(); 8789 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8790 // If there is a possibilty that flat instruction access scratch memory 8791 // then we need to use the same legalization rules we use for private. 8792 if (AS == AMDGPUAS::FLAT_ADDRESS && 8793 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8794 AS = MFI->hasFlatScratchInit() ? 8795 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8796 8797 unsigned NumElements = VT.getVectorNumElements(); 8798 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8799 AS == AMDGPUAS::FLAT_ADDRESS) { 8800 if (NumElements > 4) 8801 return SplitVectorStore(Op, DAG); 8802 // v3 stores not supported on SI. 8803 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8804 return SplitVectorStore(Op, DAG); 8805 8806 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8807 VT, *Store->getMemOperand())) 8808 return expandUnalignedStore(Store, DAG); 8809 8810 return SDValue(); 8811 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8812 switch (Subtarget->getMaxPrivateElementSize()) { 8813 case 4: 8814 return scalarizeVectorStore(Store, DAG); 8815 case 8: 8816 if (NumElements > 2) 8817 return SplitVectorStore(Op, DAG); 8818 return SDValue(); 8819 case 16: 8820 if (NumElements > 4 || 8821 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8822 return SplitVectorStore(Op, DAG); 8823 return SDValue(); 8824 default: 8825 llvm_unreachable("unsupported private_element_size"); 8826 } 8827 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8828 // Use ds_write_b128 or ds_write_b96 when possible. 8829 if (Subtarget->hasDS96AndDS128() && 8830 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8831 (VT.getStoreSize() == 12)) && 8832 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8833 Store->getAlign())) 8834 return SDValue(); 8835 8836 if (NumElements > 2) 8837 return SplitVectorStore(Op, DAG); 8838 8839 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8840 // address is negative, then the instruction is incorrectly treated as 8841 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8842 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8843 // store later in the SILoadStoreOptimizer. 8844 if (!Subtarget->hasUsableDSOffset() && 8845 NumElements == 2 && VT.getStoreSize() == 8 && 8846 Store->getAlignment() < 8) { 8847 return SplitVectorStore(Op, DAG); 8848 } 8849 8850 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8851 VT, *Store->getMemOperand())) { 8852 if (VT.isVector()) 8853 return SplitVectorStore(Op, DAG); 8854 return expandUnalignedStore(Store, DAG); 8855 } 8856 8857 return SDValue(); 8858 } else { 8859 llvm_unreachable("unhandled address space"); 8860 } 8861 } 8862 8863 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8864 SDLoc DL(Op); 8865 EVT VT = Op.getValueType(); 8866 SDValue Arg = Op.getOperand(0); 8867 SDValue TrigVal; 8868 8869 // Propagate fast-math flags so that the multiply we introduce can be folded 8870 // if Arg is already the result of a multiply by constant. 8871 auto Flags = Op->getFlags(); 8872 8873 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8874 8875 if (Subtarget->hasTrigReducedRange()) { 8876 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8877 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8878 } else { 8879 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8880 } 8881 8882 switch (Op.getOpcode()) { 8883 case ISD::FCOS: 8884 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8885 case ISD::FSIN: 8886 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8887 default: 8888 llvm_unreachable("Wrong trig opcode"); 8889 } 8890 } 8891 8892 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8893 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8894 assert(AtomicNode->isCompareAndSwap()); 8895 unsigned AS = AtomicNode->getAddressSpace(); 8896 8897 // No custom lowering required for local address space 8898 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8899 return Op; 8900 8901 // Non-local address space requires custom lowering for atomic compare 8902 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8903 SDLoc DL(Op); 8904 SDValue ChainIn = Op.getOperand(0); 8905 SDValue Addr = Op.getOperand(1); 8906 SDValue Old = Op.getOperand(2); 8907 SDValue New = Op.getOperand(3); 8908 EVT VT = Op.getValueType(); 8909 MVT SimpleVT = VT.getSimpleVT(); 8910 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8911 8912 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8913 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8914 8915 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8916 Ops, VT, AtomicNode->getMemOperand()); 8917 } 8918 8919 //===----------------------------------------------------------------------===// 8920 // Custom DAG optimizations 8921 //===----------------------------------------------------------------------===// 8922 8923 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8924 DAGCombinerInfo &DCI) const { 8925 EVT VT = N->getValueType(0); 8926 EVT ScalarVT = VT.getScalarType(); 8927 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8928 return SDValue(); 8929 8930 SelectionDAG &DAG = DCI.DAG; 8931 SDLoc DL(N); 8932 8933 SDValue Src = N->getOperand(0); 8934 EVT SrcVT = Src.getValueType(); 8935 8936 // TODO: We could try to match extracting the higher bytes, which would be 8937 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8938 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8939 // about in practice. 8940 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8941 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8942 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8943 DCI.AddToWorklist(Cvt.getNode()); 8944 8945 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8946 if (ScalarVT != MVT::f32) { 8947 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8948 DAG.getTargetConstant(0, DL, MVT::i32)); 8949 } 8950 return Cvt; 8951 } 8952 } 8953 8954 return SDValue(); 8955 } 8956 8957 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8958 8959 // This is a variant of 8960 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8961 // 8962 // The normal DAG combiner will do this, but only if the add has one use since 8963 // that would increase the number of instructions. 8964 // 8965 // This prevents us from seeing a constant offset that can be folded into a 8966 // memory instruction's addressing mode. If we know the resulting add offset of 8967 // a pointer can be folded into an addressing offset, we can replace the pointer 8968 // operand with the add of new constant offset. This eliminates one of the uses, 8969 // and may allow the remaining use to also be simplified. 8970 // 8971 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8972 unsigned AddrSpace, 8973 EVT MemVT, 8974 DAGCombinerInfo &DCI) const { 8975 SDValue N0 = N->getOperand(0); 8976 SDValue N1 = N->getOperand(1); 8977 8978 // We only do this to handle cases where it's profitable when there are 8979 // multiple uses of the add, so defer to the standard combine. 8980 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8981 N0->hasOneUse()) 8982 return SDValue(); 8983 8984 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8985 if (!CN1) 8986 return SDValue(); 8987 8988 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8989 if (!CAdd) 8990 return SDValue(); 8991 8992 // If the resulting offset is too large, we can't fold it into the addressing 8993 // mode offset. 8994 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8995 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8996 8997 AddrMode AM; 8998 AM.HasBaseReg = true; 8999 AM.BaseOffs = Offset.getSExtValue(); 9000 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9001 return SDValue(); 9002 9003 SelectionDAG &DAG = DCI.DAG; 9004 SDLoc SL(N); 9005 EVT VT = N->getValueType(0); 9006 9007 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9008 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9009 9010 SDNodeFlags Flags; 9011 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9012 (N0.getOpcode() == ISD::OR || 9013 N0->getFlags().hasNoUnsignedWrap())); 9014 9015 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9016 } 9017 9018 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9019 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9020 /// specific intrinsic, but they all place the pointer operand first. 9021 static unsigned getBasePtrIndex(const MemSDNode *N) { 9022 switch (N->getOpcode()) { 9023 case ISD::STORE: 9024 case ISD::INTRINSIC_W_CHAIN: 9025 case ISD::INTRINSIC_VOID: 9026 return 2; 9027 default: 9028 return 1; 9029 } 9030 } 9031 9032 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9033 DAGCombinerInfo &DCI) const { 9034 SelectionDAG &DAG = DCI.DAG; 9035 SDLoc SL(N); 9036 9037 unsigned PtrIdx = getBasePtrIndex(N); 9038 SDValue Ptr = N->getOperand(PtrIdx); 9039 9040 // TODO: We could also do this for multiplies. 9041 if (Ptr.getOpcode() == ISD::SHL) { 9042 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9043 N->getMemoryVT(), DCI); 9044 if (NewPtr) { 9045 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9046 9047 NewOps[PtrIdx] = NewPtr; 9048 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9049 } 9050 } 9051 9052 return SDValue(); 9053 } 9054 9055 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9056 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9057 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9058 (Opc == ISD::XOR && Val == 0); 9059 } 9060 9061 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9062 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9063 // integer combine opportunities since most 64-bit operations are decomposed 9064 // this way. TODO: We won't want this for SALU especially if it is an inline 9065 // immediate. 9066 SDValue SITargetLowering::splitBinaryBitConstantOp( 9067 DAGCombinerInfo &DCI, 9068 const SDLoc &SL, 9069 unsigned Opc, SDValue LHS, 9070 const ConstantSDNode *CRHS) const { 9071 uint64_t Val = CRHS->getZExtValue(); 9072 uint32_t ValLo = Lo_32(Val); 9073 uint32_t ValHi = Hi_32(Val); 9074 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9075 9076 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9077 bitOpWithConstantIsReducible(Opc, ValHi)) || 9078 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9079 // If we need to materialize a 64-bit immediate, it will be split up later 9080 // anyway. Avoid creating the harder to understand 64-bit immediate 9081 // materialization. 9082 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9083 } 9084 9085 return SDValue(); 9086 } 9087 9088 // Returns true if argument is a boolean value which is not serialized into 9089 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9090 static bool isBoolSGPR(SDValue V) { 9091 if (V.getValueType() != MVT::i1) 9092 return false; 9093 switch (V.getOpcode()) { 9094 default: 9095 break; 9096 case ISD::SETCC: 9097 case AMDGPUISD::FP_CLASS: 9098 return true; 9099 case ISD::AND: 9100 case ISD::OR: 9101 case ISD::XOR: 9102 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9103 } 9104 return false; 9105 } 9106 9107 // If a constant has all zeroes or all ones within each byte return it. 9108 // Otherwise return 0. 9109 static uint32_t getConstantPermuteMask(uint32_t C) { 9110 // 0xff for any zero byte in the mask 9111 uint32_t ZeroByteMask = 0; 9112 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9113 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9114 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9115 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9116 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9117 if ((NonZeroByteMask & C) != NonZeroByteMask) 9118 return 0; // Partial bytes selected. 9119 return C; 9120 } 9121 9122 // Check if a node selects whole bytes from its operand 0 starting at a byte 9123 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9124 // or -1 if not succeeded. 9125 // Note byte select encoding: 9126 // value 0-3 selects corresponding source byte; 9127 // value 0xc selects zero; 9128 // value 0xff selects 0xff. 9129 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9130 assert(V.getValueSizeInBits() == 32); 9131 9132 if (V.getNumOperands() != 2) 9133 return ~0; 9134 9135 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9136 if (!N1) 9137 return ~0; 9138 9139 uint32_t C = N1->getZExtValue(); 9140 9141 switch (V.getOpcode()) { 9142 default: 9143 break; 9144 case ISD::AND: 9145 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9146 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9147 } 9148 break; 9149 9150 case ISD::OR: 9151 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9152 return (0x03020100 & ~ConstMask) | ConstMask; 9153 } 9154 break; 9155 9156 case ISD::SHL: 9157 if (C % 8) 9158 return ~0; 9159 9160 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9161 9162 case ISD::SRL: 9163 if (C % 8) 9164 return ~0; 9165 9166 return uint32_t(0x0c0c0c0c03020100ull >> C); 9167 } 9168 9169 return ~0; 9170 } 9171 9172 SDValue SITargetLowering::performAndCombine(SDNode *N, 9173 DAGCombinerInfo &DCI) const { 9174 if (DCI.isBeforeLegalize()) 9175 return SDValue(); 9176 9177 SelectionDAG &DAG = DCI.DAG; 9178 EVT VT = N->getValueType(0); 9179 SDValue LHS = N->getOperand(0); 9180 SDValue RHS = N->getOperand(1); 9181 9182 9183 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9184 if (VT == MVT::i64 && CRHS) { 9185 if (SDValue Split 9186 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9187 return Split; 9188 } 9189 9190 if (CRHS && VT == MVT::i32) { 9191 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9192 // nb = number of trailing zeroes in mask 9193 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9194 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9195 uint64_t Mask = CRHS->getZExtValue(); 9196 unsigned Bits = countPopulation(Mask); 9197 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9198 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9199 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9200 unsigned Shift = CShift->getZExtValue(); 9201 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9202 unsigned Offset = NB + Shift; 9203 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9204 SDLoc SL(N); 9205 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9206 LHS->getOperand(0), 9207 DAG.getConstant(Offset, SL, MVT::i32), 9208 DAG.getConstant(Bits, SL, MVT::i32)); 9209 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9210 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9211 DAG.getValueType(NarrowVT)); 9212 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9213 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9214 return Shl; 9215 } 9216 } 9217 } 9218 9219 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9220 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9221 isa<ConstantSDNode>(LHS.getOperand(2))) { 9222 uint32_t Sel = getConstantPermuteMask(Mask); 9223 if (!Sel) 9224 return SDValue(); 9225 9226 // Select 0xc for all zero bytes 9227 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9228 SDLoc DL(N); 9229 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9230 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9231 } 9232 } 9233 9234 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9235 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9236 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9237 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9238 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9239 9240 SDValue X = LHS.getOperand(0); 9241 SDValue Y = RHS.getOperand(0); 9242 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9243 return SDValue(); 9244 9245 if (LCC == ISD::SETO) { 9246 if (X != LHS.getOperand(1)) 9247 return SDValue(); 9248 9249 if (RCC == ISD::SETUNE) { 9250 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9251 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9252 return SDValue(); 9253 9254 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9255 SIInstrFlags::N_SUBNORMAL | 9256 SIInstrFlags::N_ZERO | 9257 SIInstrFlags::P_ZERO | 9258 SIInstrFlags::P_SUBNORMAL | 9259 SIInstrFlags::P_NORMAL; 9260 9261 static_assert(((~(SIInstrFlags::S_NAN | 9262 SIInstrFlags::Q_NAN | 9263 SIInstrFlags::N_INFINITY | 9264 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9265 "mask not equal"); 9266 9267 SDLoc DL(N); 9268 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9269 X, DAG.getConstant(Mask, DL, MVT::i32)); 9270 } 9271 } 9272 } 9273 9274 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9275 std::swap(LHS, RHS); 9276 9277 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9278 RHS.hasOneUse()) { 9279 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9280 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9281 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9282 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9283 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9284 (RHS.getOperand(0) == LHS.getOperand(0) && 9285 LHS.getOperand(0) == LHS.getOperand(1))) { 9286 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9287 unsigned NewMask = LCC == ISD::SETO ? 9288 Mask->getZExtValue() & ~OrdMask : 9289 Mask->getZExtValue() & OrdMask; 9290 9291 SDLoc DL(N); 9292 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9293 DAG.getConstant(NewMask, DL, MVT::i32)); 9294 } 9295 } 9296 9297 if (VT == MVT::i32 && 9298 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9299 // and x, (sext cc from i1) => select cc, x, 0 9300 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9301 std::swap(LHS, RHS); 9302 if (isBoolSGPR(RHS.getOperand(0))) 9303 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9304 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9305 } 9306 9307 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9308 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9309 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9310 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9311 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9312 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9313 if (LHSMask != ~0u && RHSMask != ~0u) { 9314 // Canonicalize the expression in an attempt to have fewer unique masks 9315 // and therefore fewer registers used to hold the masks. 9316 if (LHSMask > RHSMask) { 9317 std::swap(LHSMask, RHSMask); 9318 std::swap(LHS, RHS); 9319 } 9320 9321 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9322 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9323 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9324 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9325 9326 // Check of we need to combine values from two sources within a byte. 9327 if (!(LHSUsedLanes & RHSUsedLanes) && 9328 // If we select high and lower word keep it for SDWA. 9329 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9330 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9331 // Each byte in each mask is either selector mask 0-3, or has higher 9332 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9333 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9334 // mask which is not 0xff wins. By anding both masks we have a correct 9335 // result except that 0x0c shall be corrected to give 0x0c only. 9336 uint32_t Mask = LHSMask & RHSMask; 9337 for (unsigned I = 0; I < 32; I += 8) { 9338 uint32_t ByteSel = 0xff << I; 9339 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9340 Mask &= (0x0c << I) & 0xffffffff; 9341 } 9342 9343 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9344 // or 0x0c. 9345 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9346 SDLoc DL(N); 9347 9348 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9349 LHS.getOperand(0), RHS.getOperand(0), 9350 DAG.getConstant(Sel, DL, MVT::i32)); 9351 } 9352 } 9353 } 9354 9355 return SDValue(); 9356 } 9357 9358 SDValue SITargetLowering::performOrCombine(SDNode *N, 9359 DAGCombinerInfo &DCI) const { 9360 SelectionDAG &DAG = DCI.DAG; 9361 SDValue LHS = N->getOperand(0); 9362 SDValue RHS = N->getOperand(1); 9363 9364 EVT VT = N->getValueType(0); 9365 if (VT == MVT::i1) { 9366 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9367 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9368 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9369 SDValue Src = LHS.getOperand(0); 9370 if (Src != RHS.getOperand(0)) 9371 return SDValue(); 9372 9373 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9374 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9375 if (!CLHS || !CRHS) 9376 return SDValue(); 9377 9378 // Only 10 bits are used. 9379 static const uint32_t MaxMask = 0x3ff; 9380 9381 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9382 SDLoc DL(N); 9383 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9384 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9385 } 9386 9387 return SDValue(); 9388 } 9389 9390 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9391 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9392 LHS.getOpcode() == AMDGPUISD::PERM && 9393 isa<ConstantSDNode>(LHS.getOperand(2))) { 9394 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9395 if (!Sel) 9396 return SDValue(); 9397 9398 Sel |= LHS.getConstantOperandVal(2); 9399 SDLoc DL(N); 9400 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9401 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9402 } 9403 9404 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9405 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9406 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9407 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9408 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9409 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9410 if (LHSMask != ~0u && RHSMask != ~0u) { 9411 // Canonicalize the expression in an attempt to have fewer unique masks 9412 // and therefore fewer registers used to hold the masks. 9413 if (LHSMask > RHSMask) { 9414 std::swap(LHSMask, RHSMask); 9415 std::swap(LHS, RHS); 9416 } 9417 9418 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9419 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9420 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9421 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9422 9423 // Check of we need to combine values from two sources within a byte. 9424 if (!(LHSUsedLanes & RHSUsedLanes) && 9425 // If we select high and lower word keep it for SDWA. 9426 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9427 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9428 // Kill zero bytes selected by other mask. Zero value is 0xc. 9429 LHSMask &= ~RHSUsedLanes; 9430 RHSMask &= ~LHSUsedLanes; 9431 // Add 4 to each active LHS lane 9432 LHSMask |= LHSUsedLanes & 0x04040404; 9433 // Combine masks 9434 uint32_t Sel = LHSMask | RHSMask; 9435 SDLoc DL(N); 9436 9437 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9438 LHS.getOperand(0), RHS.getOperand(0), 9439 DAG.getConstant(Sel, DL, MVT::i32)); 9440 } 9441 } 9442 } 9443 9444 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9445 return SDValue(); 9446 9447 // TODO: This could be a generic combine with a predicate for extracting the 9448 // high half of an integer being free. 9449 9450 // (or i64:x, (zero_extend i32:y)) -> 9451 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9452 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9453 RHS.getOpcode() != ISD::ZERO_EXTEND) 9454 std::swap(LHS, RHS); 9455 9456 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9457 SDValue ExtSrc = RHS.getOperand(0); 9458 EVT SrcVT = ExtSrc.getValueType(); 9459 if (SrcVT == MVT::i32) { 9460 SDLoc SL(N); 9461 SDValue LowLHS, HiBits; 9462 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9463 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9464 9465 DCI.AddToWorklist(LowOr.getNode()); 9466 DCI.AddToWorklist(HiBits.getNode()); 9467 9468 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9469 LowOr, HiBits); 9470 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9471 } 9472 } 9473 9474 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9475 if (CRHS) { 9476 if (SDValue Split 9477 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9478 return Split; 9479 } 9480 9481 return SDValue(); 9482 } 9483 9484 SDValue SITargetLowering::performXorCombine(SDNode *N, 9485 DAGCombinerInfo &DCI) const { 9486 EVT VT = N->getValueType(0); 9487 if (VT != MVT::i64) 9488 return SDValue(); 9489 9490 SDValue LHS = N->getOperand(0); 9491 SDValue RHS = N->getOperand(1); 9492 9493 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9494 if (CRHS) { 9495 if (SDValue Split 9496 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9497 return Split; 9498 } 9499 9500 return SDValue(); 9501 } 9502 9503 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9504 DAGCombinerInfo &DCI) const { 9505 if (!Subtarget->has16BitInsts() || 9506 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9507 return SDValue(); 9508 9509 EVT VT = N->getValueType(0); 9510 if (VT != MVT::i32) 9511 return SDValue(); 9512 9513 SDValue Src = N->getOperand(0); 9514 if (Src.getValueType() != MVT::i16) 9515 return SDValue(); 9516 9517 return SDValue(); 9518 } 9519 9520 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9521 DAGCombinerInfo &DCI) 9522 const { 9523 SDValue Src = N->getOperand(0); 9524 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9525 9526 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9527 VTSign->getVT() == MVT::i8) || 9528 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9529 VTSign->getVT() == MVT::i16)) && 9530 Src.hasOneUse()) { 9531 auto *M = cast<MemSDNode>(Src); 9532 SDValue Ops[] = { 9533 Src.getOperand(0), // Chain 9534 Src.getOperand(1), // rsrc 9535 Src.getOperand(2), // vindex 9536 Src.getOperand(3), // voffset 9537 Src.getOperand(4), // soffset 9538 Src.getOperand(5), // offset 9539 Src.getOperand(6), 9540 Src.getOperand(7) 9541 }; 9542 // replace with BUFFER_LOAD_BYTE/SHORT 9543 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9544 Src.getOperand(0).getValueType()); 9545 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9546 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9547 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9548 ResList, 9549 Ops, M->getMemoryVT(), 9550 M->getMemOperand()); 9551 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9552 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9553 } 9554 return SDValue(); 9555 } 9556 9557 SDValue SITargetLowering::performClassCombine(SDNode *N, 9558 DAGCombinerInfo &DCI) const { 9559 SelectionDAG &DAG = DCI.DAG; 9560 SDValue Mask = N->getOperand(1); 9561 9562 // fp_class x, 0 -> false 9563 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9564 if (CMask->isZero()) 9565 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9566 } 9567 9568 if (N->getOperand(0).isUndef()) 9569 return DAG.getUNDEF(MVT::i1); 9570 9571 return SDValue(); 9572 } 9573 9574 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9575 DAGCombinerInfo &DCI) const { 9576 EVT VT = N->getValueType(0); 9577 SDValue N0 = N->getOperand(0); 9578 9579 if (N0.isUndef()) 9580 return N0; 9581 9582 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9583 N0.getOpcode() == ISD::SINT_TO_FP)) { 9584 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9585 N->getFlags()); 9586 } 9587 9588 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9589 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9590 N0.getOperand(0), N->getFlags()); 9591 } 9592 9593 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9594 } 9595 9596 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9597 unsigned MaxDepth) const { 9598 unsigned Opcode = Op.getOpcode(); 9599 if (Opcode == ISD::FCANONICALIZE) 9600 return true; 9601 9602 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9603 auto F = CFP->getValueAPF(); 9604 if (F.isNaN() && F.isSignaling()) 9605 return false; 9606 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9607 } 9608 9609 // If source is a result of another standard FP operation it is already in 9610 // canonical form. 9611 if (MaxDepth == 0) 9612 return false; 9613 9614 switch (Opcode) { 9615 // These will flush denorms if required. 9616 case ISD::FADD: 9617 case ISD::FSUB: 9618 case ISD::FMUL: 9619 case ISD::FCEIL: 9620 case ISD::FFLOOR: 9621 case ISD::FMA: 9622 case ISD::FMAD: 9623 case ISD::FSQRT: 9624 case ISD::FDIV: 9625 case ISD::FREM: 9626 case ISD::FP_ROUND: 9627 case ISD::FP_EXTEND: 9628 case AMDGPUISD::FMUL_LEGACY: 9629 case AMDGPUISD::FMAD_FTZ: 9630 case AMDGPUISD::RCP: 9631 case AMDGPUISD::RSQ: 9632 case AMDGPUISD::RSQ_CLAMP: 9633 case AMDGPUISD::RCP_LEGACY: 9634 case AMDGPUISD::RCP_IFLAG: 9635 case AMDGPUISD::DIV_SCALE: 9636 case AMDGPUISD::DIV_FMAS: 9637 case AMDGPUISD::DIV_FIXUP: 9638 case AMDGPUISD::FRACT: 9639 case AMDGPUISD::LDEXP: 9640 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9641 case AMDGPUISD::CVT_F32_UBYTE0: 9642 case AMDGPUISD::CVT_F32_UBYTE1: 9643 case AMDGPUISD::CVT_F32_UBYTE2: 9644 case AMDGPUISD::CVT_F32_UBYTE3: 9645 return true; 9646 9647 // It can/will be lowered or combined as a bit operation. 9648 // Need to check their input recursively to handle. 9649 case ISD::FNEG: 9650 case ISD::FABS: 9651 case ISD::FCOPYSIGN: 9652 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9653 9654 case ISD::FSIN: 9655 case ISD::FCOS: 9656 case ISD::FSINCOS: 9657 return Op.getValueType().getScalarType() != MVT::f16; 9658 9659 case ISD::FMINNUM: 9660 case ISD::FMAXNUM: 9661 case ISD::FMINNUM_IEEE: 9662 case ISD::FMAXNUM_IEEE: 9663 case AMDGPUISD::CLAMP: 9664 case AMDGPUISD::FMED3: 9665 case AMDGPUISD::FMAX3: 9666 case AMDGPUISD::FMIN3: { 9667 // FIXME: Shouldn't treat the generic operations different based these. 9668 // However, we aren't really required to flush the result from 9669 // minnum/maxnum.. 9670 9671 // snans will be quieted, so we only need to worry about denormals. 9672 if (Subtarget->supportsMinMaxDenormModes() || 9673 denormalsEnabledForType(DAG, Op.getValueType())) 9674 return true; 9675 9676 // Flushing may be required. 9677 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9678 // targets need to check their input recursively. 9679 9680 // FIXME: Does this apply with clamp? It's implemented with max. 9681 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9682 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9683 return false; 9684 } 9685 9686 return true; 9687 } 9688 case ISD::SELECT: { 9689 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9690 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9691 } 9692 case ISD::BUILD_VECTOR: { 9693 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9694 SDValue SrcOp = Op.getOperand(i); 9695 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9696 return false; 9697 } 9698 9699 return true; 9700 } 9701 case ISD::EXTRACT_VECTOR_ELT: 9702 case ISD::EXTRACT_SUBVECTOR: { 9703 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9704 } 9705 case ISD::INSERT_VECTOR_ELT: { 9706 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9707 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9708 } 9709 case ISD::UNDEF: 9710 // Could be anything. 9711 return false; 9712 9713 case ISD::BITCAST: 9714 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9715 case ISD::TRUNCATE: { 9716 // Hack round the mess we make when legalizing extract_vector_elt 9717 if (Op.getValueType() == MVT::i16) { 9718 SDValue TruncSrc = Op.getOperand(0); 9719 if (TruncSrc.getValueType() == MVT::i32 && 9720 TruncSrc.getOpcode() == ISD::BITCAST && 9721 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9722 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9723 } 9724 } 9725 return false; 9726 } 9727 case ISD::INTRINSIC_WO_CHAIN: { 9728 unsigned IntrinsicID 9729 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9730 // TODO: Handle more intrinsics 9731 switch (IntrinsicID) { 9732 case Intrinsic::amdgcn_cvt_pkrtz: 9733 case Intrinsic::amdgcn_cubeid: 9734 case Intrinsic::amdgcn_frexp_mant: 9735 case Intrinsic::amdgcn_fdot2: 9736 case Intrinsic::amdgcn_rcp: 9737 case Intrinsic::amdgcn_rsq: 9738 case Intrinsic::amdgcn_rsq_clamp: 9739 case Intrinsic::amdgcn_rcp_legacy: 9740 case Intrinsic::amdgcn_rsq_legacy: 9741 case Intrinsic::amdgcn_trig_preop: 9742 return true; 9743 default: 9744 break; 9745 } 9746 9747 LLVM_FALLTHROUGH; 9748 } 9749 default: 9750 return denormalsEnabledForType(DAG, Op.getValueType()) && 9751 DAG.isKnownNeverSNaN(Op); 9752 } 9753 9754 llvm_unreachable("invalid operation"); 9755 } 9756 9757 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9758 unsigned MaxDepth) const { 9759 MachineRegisterInfo &MRI = MF.getRegInfo(); 9760 MachineInstr *MI = MRI.getVRegDef(Reg); 9761 unsigned Opcode = MI->getOpcode(); 9762 9763 if (Opcode == AMDGPU::G_FCANONICALIZE) 9764 return true; 9765 9766 if (Opcode == AMDGPU::G_FCONSTANT) { 9767 auto F = MI->getOperand(1).getFPImm()->getValueAPF(); 9768 if (F.isNaN() && F.isSignaling()) 9769 return false; 9770 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF); 9771 } 9772 9773 if (MaxDepth == 0) 9774 return false; 9775 9776 switch (Opcode) { 9777 case AMDGPU::G_FMINNUM_IEEE: 9778 case AMDGPU::G_FMAXNUM_IEEE: { 9779 if (Subtarget->supportsMinMaxDenormModes() || 9780 denormalsEnabledForType(MRI.getType(Reg), MF)) 9781 return true; 9782 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) { 9783 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1)) 9784 return false; 9785 } 9786 return true; 9787 } 9788 default: 9789 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9790 isKnownNeverSNaN(Reg, MRI); 9791 } 9792 9793 llvm_unreachable("invalid operation"); 9794 } 9795 9796 // Constant fold canonicalize. 9797 SDValue SITargetLowering::getCanonicalConstantFP( 9798 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9799 // Flush denormals to 0 if not enabled. 9800 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9801 return DAG.getConstantFP(0.0, SL, VT); 9802 9803 if (C.isNaN()) { 9804 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9805 if (C.isSignaling()) { 9806 // Quiet a signaling NaN. 9807 // FIXME: Is this supposed to preserve payload bits? 9808 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9809 } 9810 9811 // Make sure it is the canonical NaN bitpattern. 9812 // 9813 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9814 // immediate? 9815 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9816 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9817 } 9818 9819 // Already canonical. 9820 return DAG.getConstantFP(C, SL, VT); 9821 } 9822 9823 static bool vectorEltWillFoldAway(SDValue Op) { 9824 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9825 } 9826 9827 SDValue SITargetLowering::performFCanonicalizeCombine( 9828 SDNode *N, 9829 DAGCombinerInfo &DCI) const { 9830 SelectionDAG &DAG = DCI.DAG; 9831 SDValue N0 = N->getOperand(0); 9832 EVT VT = N->getValueType(0); 9833 9834 // fcanonicalize undef -> qnan 9835 if (N0.isUndef()) { 9836 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9837 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9838 } 9839 9840 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9841 EVT VT = N->getValueType(0); 9842 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9843 } 9844 9845 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9846 // (fcanonicalize k) 9847 // 9848 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9849 9850 // TODO: This could be better with wider vectors that will be split to v2f16, 9851 // and to consider uses since there aren't that many packed operations. 9852 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9853 isTypeLegal(MVT::v2f16)) { 9854 SDLoc SL(N); 9855 SDValue NewElts[2]; 9856 SDValue Lo = N0.getOperand(0); 9857 SDValue Hi = N0.getOperand(1); 9858 EVT EltVT = Lo.getValueType(); 9859 9860 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9861 for (unsigned I = 0; I != 2; ++I) { 9862 SDValue Op = N0.getOperand(I); 9863 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9864 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9865 CFP->getValueAPF()); 9866 } else if (Op.isUndef()) { 9867 // Handled below based on what the other operand is. 9868 NewElts[I] = Op; 9869 } else { 9870 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9871 } 9872 } 9873 9874 // If one half is undef, and one is constant, perfer a splat vector rather 9875 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9876 // cheaper to use and may be free with a packed operation. 9877 if (NewElts[0].isUndef()) { 9878 if (isa<ConstantFPSDNode>(NewElts[1])) 9879 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9880 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9881 } 9882 9883 if (NewElts[1].isUndef()) { 9884 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9885 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9886 } 9887 9888 return DAG.getBuildVector(VT, SL, NewElts); 9889 } 9890 } 9891 9892 unsigned SrcOpc = N0.getOpcode(); 9893 9894 // If it's free to do so, push canonicalizes further up the source, which may 9895 // find a canonical source. 9896 // 9897 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9898 // sNaNs. 9899 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9900 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9901 if (CRHS && N0.hasOneUse()) { 9902 SDLoc SL(N); 9903 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9904 N0.getOperand(0)); 9905 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9906 DCI.AddToWorklist(Canon0.getNode()); 9907 9908 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9909 } 9910 } 9911 9912 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9913 } 9914 9915 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9916 switch (Opc) { 9917 case ISD::FMAXNUM: 9918 case ISD::FMAXNUM_IEEE: 9919 return AMDGPUISD::FMAX3; 9920 case ISD::SMAX: 9921 return AMDGPUISD::SMAX3; 9922 case ISD::UMAX: 9923 return AMDGPUISD::UMAX3; 9924 case ISD::FMINNUM: 9925 case ISD::FMINNUM_IEEE: 9926 return AMDGPUISD::FMIN3; 9927 case ISD::SMIN: 9928 return AMDGPUISD::SMIN3; 9929 case ISD::UMIN: 9930 return AMDGPUISD::UMIN3; 9931 default: 9932 llvm_unreachable("Not a min/max opcode"); 9933 } 9934 } 9935 9936 SDValue SITargetLowering::performIntMed3ImmCombine( 9937 SelectionDAG &DAG, const SDLoc &SL, 9938 SDValue Op0, SDValue Op1, bool Signed) const { 9939 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9940 if (!K1) 9941 return SDValue(); 9942 9943 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9944 if (!K0) 9945 return SDValue(); 9946 9947 if (Signed) { 9948 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9949 return SDValue(); 9950 } else { 9951 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9952 return SDValue(); 9953 } 9954 9955 EVT VT = K0->getValueType(0); 9956 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9957 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9958 return DAG.getNode(Med3Opc, SL, VT, 9959 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9960 } 9961 9962 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9963 if (VT == MVT::i16) { 9964 MVT NVT = MVT::i32; 9965 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9966 9967 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9968 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9969 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9970 9971 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9972 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9973 } 9974 9975 return SDValue(); 9976 } 9977 9978 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9979 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9980 return C; 9981 9982 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9983 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9984 return C; 9985 } 9986 9987 return nullptr; 9988 } 9989 9990 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9991 const SDLoc &SL, 9992 SDValue Op0, 9993 SDValue Op1) const { 9994 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9995 if (!K1) 9996 return SDValue(); 9997 9998 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9999 if (!K0) 10000 return SDValue(); 10001 10002 // Ordered >= (although NaN inputs should have folded away by now). 10003 if (K0->getValueAPF() > K1->getValueAPF()) 10004 return SDValue(); 10005 10006 const MachineFunction &MF = DAG.getMachineFunction(); 10007 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10008 10009 // TODO: Check IEEE bit enabled? 10010 EVT VT = Op0.getValueType(); 10011 if (Info->getMode().DX10Clamp) { 10012 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10013 // hardware fmed3 behavior converting to a min. 10014 // FIXME: Should this be allowing -0.0? 10015 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10016 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10017 } 10018 10019 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10020 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10021 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10022 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10023 // then give the other result, which is different from med3 with a NaN 10024 // input. 10025 SDValue Var = Op0.getOperand(0); 10026 if (!DAG.isKnownNeverSNaN(Var)) 10027 return SDValue(); 10028 10029 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10030 10031 if ((!K0->hasOneUse() || 10032 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10033 (!K1->hasOneUse() || 10034 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10035 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10036 Var, SDValue(K0, 0), SDValue(K1, 0)); 10037 } 10038 } 10039 10040 return SDValue(); 10041 } 10042 10043 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10044 DAGCombinerInfo &DCI) const { 10045 SelectionDAG &DAG = DCI.DAG; 10046 10047 EVT VT = N->getValueType(0); 10048 unsigned Opc = N->getOpcode(); 10049 SDValue Op0 = N->getOperand(0); 10050 SDValue Op1 = N->getOperand(1); 10051 10052 // Only do this if the inner op has one use since this will just increases 10053 // register pressure for no benefit. 10054 10055 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10056 !VT.isVector() && 10057 (VT == MVT::i32 || VT == MVT::f32 || 10058 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10059 // max(max(a, b), c) -> max3(a, b, c) 10060 // min(min(a, b), c) -> min3(a, b, c) 10061 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10062 SDLoc DL(N); 10063 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10064 DL, 10065 N->getValueType(0), 10066 Op0.getOperand(0), 10067 Op0.getOperand(1), 10068 Op1); 10069 } 10070 10071 // Try commuted. 10072 // max(a, max(b, c)) -> max3(a, b, c) 10073 // min(a, min(b, c)) -> min3(a, b, c) 10074 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10075 SDLoc DL(N); 10076 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10077 DL, 10078 N->getValueType(0), 10079 Op0, 10080 Op1.getOperand(0), 10081 Op1.getOperand(1)); 10082 } 10083 } 10084 10085 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10086 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10087 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10088 return Med3; 10089 } 10090 10091 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10092 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10093 return Med3; 10094 } 10095 10096 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10097 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10098 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10099 (Opc == AMDGPUISD::FMIN_LEGACY && 10100 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10101 (VT == MVT::f32 || VT == MVT::f64 || 10102 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10103 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10104 Op0.hasOneUse()) { 10105 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10106 return Res; 10107 } 10108 10109 return SDValue(); 10110 } 10111 10112 static bool isClampZeroToOne(SDValue A, SDValue B) { 10113 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10114 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10115 // FIXME: Should this be allowing -0.0? 10116 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10117 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10118 } 10119 } 10120 10121 return false; 10122 } 10123 10124 // FIXME: Should only worry about snans for version with chain. 10125 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10126 DAGCombinerInfo &DCI) const { 10127 EVT VT = N->getValueType(0); 10128 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10129 // NaNs. With a NaN input, the order of the operands may change the result. 10130 10131 SelectionDAG &DAG = DCI.DAG; 10132 SDLoc SL(N); 10133 10134 SDValue Src0 = N->getOperand(0); 10135 SDValue Src1 = N->getOperand(1); 10136 SDValue Src2 = N->getOperand(2); 10137 10138 if (isClampZeroToOne(Src0, Src1)) { 10139 // const_a, const_b, x -> clamp is safe in all cases including signaling 10140 // nans. 10141 // FIXME: Should this be allowing -0.0? 10142 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10143 } 10144 10145 const MachineFunction &MF = DAG.getMachineFunction(); 10146 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10147 10148 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10149 // handling no dx10-clamp? 10150 if (Info->getMode().DX10Clamp) { 10151 // If NaNs is clamped to 0, we are free to reorder the inputs. 10152 10153 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10154 std::swap(Src0, Src1); 10155 10156 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10157 std::swap(Src1, Src2); 10158 10159 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10160 std::swap(Src0, Src1); 10161 10162 if (isClampZeroToOne(Src1, Src2)) 10163 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10164 } 10165 10166 return SDValue(); 10167 } 10168 10169 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10170 DAGCombinerInfo &DCI) const { 10171 SDValue Src0 = N->getOperand(0); 10172 SDValue Src1 = N->getOperand(1); 10173 if (Src0.isUndef() && Src1.isUndef()) 10174 return DCI.DAG.getUNDEF(N->getValueType(0)); 10175 return SDValue(); 10176 } 10177 10178 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10179 // expanded into a set of cmp/select instructions. 10180 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10181 unsigned NumElem, 10182 bool IsDivergentIdx) { 10183 if (UseDivergentRegisterIndexing) 10184 return false; 10185 10186 unsigned VecSize = EltSize * NumElem; 10187 10188 // Sub-dword vectors of size 2 dword or less have better implementation. 10189 if (VecSize <= 64 && EltSize < 32) 10190 return false; 10191 10192 // Always expand the rest of sub-dword instructions, otherwise it will be 10193 // lowered via memory. 10194 if (EltSize < 32) 10195 return true; 10196 10197 // Always do this if var-idx is divergent, otherwise it will become a loop. 10198 if (IsDivergentIdx) 10199 return true; 10200 10201 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10202 unsigned NumInsts = NumElem /* Number of compares */ + 10203 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10204 return NumInsts <= 16; 10205 } 10206 10207 static bool shouldExpandVectorDynExt(SDNode *N) { 10208 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10209 if (isa<ConstantSDNode>(Idx)) 10210 return false; 10211 10212 SDValue Vec = N->getOperand(0); 10213 EVT VecVT = Vec.getValueType(); 10214 EVT EltVT = VecVT.getVectorElementType(); 10215 unsigned EltSize = EltVT.getSizeInBits(); 10216 unsigned NumElem = VecVT.getVectorNumElements(); 10217 10218 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10219 Idx->isDivergent()); 10220 } 10221 10222 SDValue SITargetLowering::performExtractVectorEltCombine( 10223 SDNode *N, DAGCombinerInfo &DCI) const { 10224 SDValue Vec = N->getOperand(0); 10225 SelectionDAG &DAG = DCI.DAG; 10226 10227 EVT VecVT = Vec.getValueType(); 10228 EVT EltVT = VecVT.getVectorElementType(); 10229 10230 if ((Vec.getOpcode() == ISD::FNEG || 10231 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10232 SDLoc SL(N); 10233 EVT EltVT = N->getValueType(0); 10234 SDValue Idx = N->getOperand(1); 10235 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10236 Vec.getOperand(0), Idx); 10237 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10238 } 10239 10240 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10241 // => 10242 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10243 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10244 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10245 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10246 SDLoc SL(N); 10247 EVT EltVT = N->getValueType(0); 10248 SDValue Idx = N->getOperand(1); 10249 unsigned Opc = Vec.getOpcode(); 10250 10251 switch(Opc) { 10252 default: 10253 break; 10254 // TODO: Support other binary operations. 10255 case ISD::FADD: 10256 case ISD::FSUB: 10257 case ISD::FMUL: 10258 case ISD::ADD: 10259 case ISD::UMIN: 10260 case ISD::UMAX: 10261 case ISD::SMIN: 10262 case ISD::SMAX: 10263 case ISD::FMAXNUM: 10264 case ISD::FMINNUM: 10265 case ISD::FMAXNUM_IEEE: 10266 case ISD::FMINNUM_IEEE: { 10267 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10268 Vec.getOperand(0), Idx); 10269 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10270 Vec.getOperand(1), Idx); 10271 10272 DCI.AddToWorklist(Elt0.getNode()); 10273 DCI.AddToWorklist(Elt1.getNode()); 10274 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10275 } 10276 } 10277 } 10278 10279 unsigned VecSize = VecVT.getSizeInBits(); 10280 unsigned EltSize = EltVT.getSizeInBits(); 10281 10282 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10283 if (::shouldExpandVectorDynExt(N)) { 10284 SDLoc SL(N); 10285 SDValue Idx = N->getOperand(1); 10286 SDValue V; 10287 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10288 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10289 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10290 if (I == 0) 10291 V = Elt; 10292 else 10293 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10294 } 10295 return V; 10296 } 10297 10298 if (!DCI.isBeforeLegalize()) 10299 return SDValue(); 10300 10301 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10302 // elements. This exposes more load reduction opportunities by replacing 10303 // multiple small extract_vector_elements with a single 32-bit extract. 10304 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10305 if (isa<MemSDNode>(Vec) && 10306 EltSize <= 16 && 10307 EltVT.isByteSized() && 10308 VecSize > 32 && 10309 VecSize % 32 == 0 && 10310 Idx) { 10311 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10312 10313 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10314 unsigned EltIdx = BitIndex / 32; 10315 unsigned LeftoverBitIdx = BitIndex % 32; 10316 SDLoc SL(N); 10317 10318 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10319 DCI.AddToWorklist(Cast.getNode()); 10320 10321 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10322 DAG.getConstant(EltIdx, SL, MVT::i32)); 10323 DCI.AddToWorklist(Elt.getNode()); 10324 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10325 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10326 DCI.AddToWorklist(Srl.getNode()); 10327 10328 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10329 DCI.AddToWorklist(Trunc.getNode()); 10330 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10331 } 10332 10333 return SDValue(); 10334 } 10335 10336 SDValue 10337 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10338 DAGCombinerInfo &DCI) const { 10339 SDValue Vec = N->getOperand(0); 10340 SDValue Idx = N->getOperand(2); 10341 EVT VecVT = Vec.getValueType(); 10342 EVT EltVT = VecVT.getVectorElementType(); 10343 10344 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10345 // => BUILD_VECTOR n x select (e, const-idx) 10346 if (!::shouldExpandVectorDynExt(N)) 10347 return SDValue(); 10348 10349 SelectionDAG &DAG = DCI.DAG; 10350 SDLoc SL(N); 10351 SDValue Ins = N->getOperand(1); 10352 EVT IdxVT = Idx.getValueType(); 10353 10354 SmallVector<SDValue, 16> Ops; 10355 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10356 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10357 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10358 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10359 Ops.push_back(V); 10360 } 10361 10362 return DAG.getBuildVector(VecVT, SL, Ops); 10363 } 10364 10365 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10366 const SDNode *N0, 10367 const SDNode *N1) const { 10368 EVT VT = N0->getValueType(0); 10369 10370 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10371 // support denormals ever. 10372 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10373 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10374 getSubtarget()->hasMadF16())) && 10375 isOperationLegal(ISD::FMAD, VT)) 10376 return ISD::FMAD; 10377 10378 const TargetOptions &Options = DAG.getTarget().Options; 10379 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10380 (N0->getFlags().hasAllowContract() && 10381 N1->getFlags().hasAllowContract())) && 10382 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10383 return ISD::FMA; 10384 } 10385 10386 return 0; 10387 } 10388 10389 // For a reassociatable opcode perform: 10390 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10391 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10392 SelectionDAG &DAG) const { 10393 EVT VT = N->getValueType(0); 10394 if (VT != MVT::i32 && VT != MVT::i64) 10395 return SDValue(); 10396 10397 unsigned Opc = N->getOpcode(); 10398 SDValue Op0 = N->getOperand(0); 10399 SDValue Op1 = N->getOperand(1); 10400 10401 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10402 return SDValue(); 10403 10404 if (Op0->isDivergent()) 10405 std::swap(Op0, Op1); 10406 10407 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10408 return SDValue(); 10409 10410 SDValue Op2 = Op1.getOperand(1); 10411 Op1 = Op1.getOperand(0); 10412 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10413 return SDValue(); 10414 10415 if (Op1->isDivergent()) 10416 std::swap(Op1, Op2); 10417 10418 // If either operand is constant this will conflict with 10419 // DAGCombiner::ReassociateOps(). 10420 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10421 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10422 return SDValue(); 10423 10424 SDLoc SL(N); 10425 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10426 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10427 } 10428 10429 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10430 EVT VT, 10431 SDValue N0, SDValue N1, SDValue N2, 10432 bool Signed) { 10433 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10434 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10435 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10436 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10437 } 10438 10439 SDValue SITargetLowering::performAddCombine(SDNode *N, 10440 DAGCombinerInfo &DCI) const { 10441 SelectionDAG &DAG = DCI.DAG; 10442 EVT VT = N->getValueType(0); 10443 SDLoc SL(N); 10444 SDValue LHS = N->getOperand(0); 10445 SDValue RHS = N->getOperand(1); 10446 10447 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10448 && Subtarget->hasMad64_32() && 10449 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10450 VT.getScalarSizeInBits() <= 64) { 10451 if (LHS.getOpcode() != ISD::MUL) 10452 std::swap(LHS, RHS); 10453 10454 SDValue MulLHS = LHS.getOperand(0); 10455 SDValue MulRHS = LHS.getOperand(1); 10456 SDValue AddRHS = RHS; 10457 10458 // TODO: Maybe restrict if SGPR inputs. 10459 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10460 numBitsUnsigned(MulRHS, DAG) <= 32) { 10461 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10462 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10463 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10464 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10465 } 10466 10467 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10468 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10469 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10470 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10471 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10472 } 10473 10474 return SDValue(); 10475 } 10476 10477 if (SDValue V = reassociateScalarOps(N, DAG)) { 10478 return V; 10479 } 10480 10481 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10482 return SDValue(); 10483 10484 // add x, zext (setcc) => addcarry x, 0, setcc 10485 // add x, sext (setcc) => subcarry x, 0, setcc 10486 unsigned Opc = LHS.getOpcode(); 10487 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10488 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10489 std::swap(RHS, LHS); 10490 10491 Opc = RHS.getOpcode(); 10492 switch (Opc) { 10493 default: break; 10494 case ISD::ZERO_EXTEND: 10495 case ISD::SIGN_EXTEND: 10496 case ISD::ANY_EXTEND: { 10497 auto Cond = RHS.getOperand(0); 10498 // If this won't be a real VOPC output, we would still need to insert an 10499 // extra instruction anyway. 10500 if (!isBoolSGPR(Cond)) 10501 break; 10502 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10503 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10504 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10505 return DAG.getNode(Opc, SL, VTList, Args); 10506 } 10507 case ISD::ADDCARRY: { 10508 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10509 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10510 if (!C || C->getZExtValue() != 0) break; 10511 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10512 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10513 } 10514 } 10515 return SDValue(); 10516 } 10517 10518 SDValue SITargetLowering::performSubCombine(SDNode *N, 10519 DAGCombinerInfo &DCI) const { 10520 SelectionDAG &DAG = DCI.DAG; 10521 EVT VT = N->getValueType(0); 10522 10523 if (VT != MVT::i32) 10524 return SDValue(); 10525 10526 SDLoc SL(N); 10527 SDValue LHS = N->getOperand(0); 10528 SDValue RHS = N->getOperand(1); 10529 10530 // sub x, zext (setcc) => subcarry x, 0, setcc 10531 // sub x, sext (setcc) => addcarry x, 0, setcc 10532 unsigned Opc = RHS.getOpcode(); 10533 switch (Opc) { 10534 default: break; 10535 case ISD::ZERO_EXTEND: 10536 case ISD::SIGN_EXTEND: 10537 case ISD::ANY_EXTEND: { 10538 auto Cond = RHS.getOperand(0); 10539 // If this won't be a real VOPC output, we would still need to insert an 10540 // extra instruction anyway. 10541 if (!isBoolSGPR(Cond)) 10542 break; 10543 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10544 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10545 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10546 return DAG.getNode(Opc, SL, VTList, Args); 10547 } 10548 } 10549 10550 if (LHS.getOpcode() == ISD::SUBCARRY) { 10551 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10552 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10553 if (!C || !C->isZero()) 10554 return SDValue(); 10555 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10556 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10557 } 10558 return SDValue(); 10559 } 10560 10561 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10562 DAGCombinerInfo &DCI) const { 10563 10564 if (N->getValueType(0) != MVT::i32) 10565 return SDValue(); 10566 10567 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10568 if (!C || C->getZExtValue() != 0) 10569 return SDValue(); 10570 10571 SelectionDAG &DAG = DCI.DAG; 10572 SDValue LHS = N->getOperand(0); 10573 10574 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10575 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10576 unsigned LHSOpc = LHS.getOpcode(); 10577 unsigned Opc = N->getOpcode(); 10578 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10579 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10580 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10581 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10582 } 10583 return SDValue(); 10584 } 10585 10586 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10587 DAGCombinerInfo &DCI) const { 10588 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10589 return SDValue(); 10590 10591 SelectionDAG &DAG = DCI.DAG; 10592 EVT VT = N->getValueType(0); 10593 10594 SDLoc SL(N); 10595 SDValue LHS = N->getOperand(0); 10596 SDValue RHS = N->getOperand(1); 10597 10598 // These should really be instruction patterns, but writing patterns with 10599 // source modiifiers is a pain. 10600 10601 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10602 if (LHS.getOpcode() == ISD::FADD) { 10603 SDValue A = LHS.getOperand(0); 10604 if (A == LHS.getOperand(1)) { 10605 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10606 if (FusedOp != 0) { 10607 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10608 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10609 } 10610 } 10611 } 10612 10613 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10614 if (RHS.getOpcode() == ISD::FADD) { 10615 SDValue A = RHS.getOperand(0); 10616 if (A == RHS.getOperand(1)) { 10617 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10618 if (FusedOp != 0) { 10619 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10620 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10621 } 10622 } 10623 } 10624 10625 return SDValue(); 10626 } 10627 10628 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10629 DAGCombinerInfo &DCI) const { 10630 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10631 return SDValue(); 10632 10633 SelectionDAG &DAG = DCI.DAG; 10634 SDLoc SL(N); 10635 EVT VT = N->getValueType(0); 10636 assert(!VT.isVector()); 10637 10638 // Try to get the fneg to fold into the source modifier. This undoes generic 10639 // DAG combines and folds them into the mad. 10640 // 10641 // Only do this if we are not trying to support denormals. v_mad_f32 does 10642 // not support denormals ever. 10643 SDValue LHS = N->getOperand(0); 10644 SDValue RHS = N->getOperand(1); 10645 if (LHS.getOpcode() == ISD::FADD) { 10646 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10647 SDValue A = LHS.getOperand(0); 10648 if (A == LHS.getOperand(1)) { 10649 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10650 if (FusedOp != 0){ 10651 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10652 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10653 10654 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10655 } 10656 } 10657 } 10658 10659 if (RHS.getOpcode() == ISD::FADD) { 10660 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10661 10662 SDValue A = RHS.getOperand(0); 10663 if (A == RHS.getOperand(1)) { 10664 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10665 if (FusedOp != 0){ 10666 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10667 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10668 } 10669 } 10670 } 10671 10672 return SDValue(); 10673 } 10674 10675 SDValue SITargetLowering::performFMACombine(SDNode *N, 10676 DAGCombinerInfo &DCI) const { 10677 SelectionDAG &DAG = DCI.DAG; 10678 EVT VT = N->getValueType(0); 10679 SDLoc SL(N); 10680 10681 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10682 return SDValue(); 10683 10684 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10685 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10686 SDValue Op1 = N->getOperand(0); 10687 SDValue Op2 = N->getOperand(1); 10688 SDValue FMA = N->getOperand(2); 10689 10690 if (FMA.getOpcode() != ISD::FMA || 10691 Op1.getOpcode() != ISD::FP_EXTEND || 10692 Op2.getOpcode() != ISD::FP_EXTEND) 10693 return SDValue(); 10694 10695 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10696 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10697 // is sufficient to allow generaing fdot2. 10698 const TargetOptions &Options = DAG.getTarget().Options; 10699 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10700 (N->getFlags().hasAllowContract() && 10701 FMA->getFlags().hasAllowContract())) { 10702 Op1 = Op1.getOperand(0); 10703 Op2 = Op2.getOperand(0); 10704 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10705 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10706 return SDValue(); 10707 10708 SDValue Vec1 = Op1.getOperand(0); 10709 SDValue Idx1 = Op1.getOperand(1); 10710 SDValue Vec2 = Op2.getOperand(0); 10711 10712 SDValue FMAOp1 = FMA.getOperand(0); 10713 SDValue FMAOp2 = FMA.getOperand(1); 10714 SDValue FMAAcc = FMA.getOperand(2); 10715 10716 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10717 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10718 return SDValue(); 10719 10720 FMAOp1 = FMAOp1.getOperand(0); 10721 FMAOp2 = FMAOp2.getOperand(0); 10722 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10723 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10724 return SDValue(); 10725 10726 SDValue Vec3 = FMAOp1.getOperand(0); 10727 SDValue Vec4 = FMAOp2.getOperand(0); 10728 SDValue Idx2 = FMAOp1.getOperand(1); 10729 10730 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10731 // Idx1 and Idx2 cannot be the same. 10732 Idx1 == Idx2) 10733 return SDValue(); 10734 10735 if (Vec1 == Vec2 || Vec3 == Vec4) 10736 return SDValue(); 10737 10738 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10739 return SDValue(); 10740 10741 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10742 (Vec1 == Vec4 && Vec2 == Vec3)) { 10743 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10744 DAG.getTargetConstant(0, SL, MVT::i1)); 10745 } 10746 } 10747 return SDValue(); 10748 } 10749 10750 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10751 DAGCombinerInfo &DCI) const { 10752 SelectionDAG &DAG = DCI.DAG; 10753 SDLoc SL(N); 10754 10755 SDValue LHS = N->getOperand(0); 10756 SDValue RHS = N->getOperand(1); 10757 EVT VT = LHS.getValueType(); 10758 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10759 10760 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10761 if (!CRHS) { 10762 CRHS = dyn_cast<ConstantSDNode>(LHS); 10763 if (CRHS) { 10764 std::swap(LHS, RHS); 10765 CC = getSetCCSwappedOperands(CC); 10766 } 10767 } 10768 10769 if (CRHS) { 10770 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10771 isBoolSGPR(LHS.getOperand(0))) { 10772 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10773 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10774 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10775 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10776 if ((CRHS->isAllOnes() && 10777 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10778 (CRHS->isZero() && 10779 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10780 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10781 DAG.getConstant(-1, SL, MVT::i1)); 10782 if ((CRHS->isAllOnes() && 10783 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10784 (CRHS->isZero() && 10785 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10786 return LHS.getOperand(0); 10787 } 10788 10789 uint64_t CRHSVal = CRHS->getZExtValue(); 10790 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10791 LHS.getOpcode() == ISD::SELECT && 10792 isa<ConstantSDNode>(LHS.getOperand(1)) && 10793 isa<ConstantSDNode>(LHS.getOperand(2)) && 10794 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10795 isBoolSGPR(LHS.getOperand(0))) { 10796 // Given CT != FT: 10797 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10798 // setcc (select cc, CT, CF), CF, ne => cc 10799 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10800 // setcc (select cc, CT, CF), CT, eq => cc 10801 uint64_t CT = LHS.getConstantOperandVal(1); 10802 uint64_t CF = LHS.getConstantOperandVal(2); 10803 10804 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10805 (CT == CRHSVal && CC == ISD::SETNE)) 10806 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10807 DAG.getConstant(-1, SL, MVT::i1)); 10808 if ((CF == CRHSVal && CC == ISD::SETNE) || 10809 (CT == CRHSVal && CC == ISD::SETEQ)) 10810 return LHS.getOperand(0); 10811 } 10812 } 10813 10814 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10815 VT != MVT::f16)) 10816 return SDValue(); 10817 10818 // Match isinf/isfinite pattern 10819 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10820 // (fcmp one (fabs x), inf) -> (fp_class x, 10821 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10822 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10823 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10824 if (!CRHS) 10825 return SDValue(); 10826 10827 const APFloat &APF = CRHS->getValueAPF(); 10828 if (APF.isInfinity() && !APF.isNegative()) { 10829 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10830 SIInstrFlags::N_INFINITY; 10831 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10832 SIInstrFlags::P_ZERO | 10833 SIInstrFlags::N_NORMAL | 10834 SIInstrFlags::P_NORMAL | 10835 SIInstrFlags::N_SUBNORMAL | 10836 SIInstrFlags::P_SUBNORMAL; 10837 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10838 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10839 DAG.getConstant(Mask, SL, MVT::i32)); 10840 } 10841 } 10842 10843 return SDValue(); 10844 } 10845 10846 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10847 DAGCombinerInfo &DCI) const { 10848 SelectionDAG &DAG = DCI.DAG; 10849 SDLoc SL(N); 10850 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10851 10852 SDValue Src = N->getOperand(0); 10853 SDValue Shift = N->getOperand(0); 10854 10855 // TODO: Extend type shouldn't matter (assuming legal types). 10856 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10857 Shift = Shift.getOperand(0); 10858 10859 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10860 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10861 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10862 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10863 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10864 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10865 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10866 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10867 SDLoc(Shift.getOperand(0)), MVT::i32); 10868 10869 unsigned ShiftOffset = 8 * Offset; 10870 if (Shift.getOpcode() == ISD::SHL) 10871 ShiftOffset -= C->getZExtValue(); 10872 else 10873 ShiftOffset += C->getZExtValue(); 10874 10875 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10876 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10877 MVT::f32, Shift); 10878 } 10879 } 10880 } 10881 10882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10883 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10884 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10885 // We simplified Src. If this node is not dead, visit it again so it is 10886 // folded properly. 10887 if (N->getOpcode() != ISD::DELETED_NODE) 10888 DCI.AddToWorklist(N); 10889 return SDValue(N, 0); 10890 } 10891 10892 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10893 if (SDValue DemandedSrc = 10894 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10895 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10896 10897 return SDValue(); 10898 } 10899 10900 SDValue SITargetLowering::performClampCombine(SDNode *N, 10901 DAGCombinerInfo &DCI) const { 10902 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10903 if (!CSrc) 10904 return SDValue(); 10905 10906 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10907 const APFloat &F = CSrc->getValueAPF(); 10908 APFloat Zero = APFloat::getZero(F.getSemantics()); 10909 if (F < Zero || 10910 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10911 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10912 } 10913 10914 APFloat One(F.getSemantics(), "1.0"); 10915 if (F > One) 10916 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10917 10918 return SDValue(CSrc, 0); 10919 } 10920 10921 10922 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10923 DAGCombinerInfo &DCI) const { 10924 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10925 return SDValue(); 10926 switch (N->getOpcode()) { 10927 case ISD::ADD: 10928 return performAddCombine(N, DCI); 10929 case ISD::SUB: 10930 return performSubCombine(N, DCI); 10931 case ISD::ADDCARRY: 10932 case ISD::SUBCARRY: 10933 return performAddCarrySubCarryCombine(N, DCI); 10934 case ISD::FADD: 10935 return performFAddCombine(N, DCI); 10936 case ISD::FSUB: 10937 return performFSubCombine(N, DCI); 10938 case ISD::SETCC: 10939 return performSetCCCombine(N, DCI); 10940 case ISD::FMAXNUM: 10941 case ISD::FMINNUM: 10942 case ISD::FMAXNUM_IEEE: 10943 case ISD::FMINNUM_IEEE: 10944 case ISD::SMAX: 10945 case ISD::SMIN: 10946 case ISD::UMAX: 10947 case ISD::UMIN: 10948 case AMDGPUISD::FMIN_LEGACY: 10949 case AMDGPUISD::FMAX_LEGACY: 10950 return performMinMaxCombine(N, DCI); 10951 case ISD::FMA: 10952 return performFMACombine(N, DCI); 10953 case ISD::AND: 10954 return performAndCombine(N, DCI); 10955 case ISD::OR: 10956 return performOrCombine(N, DCI); 10957 case ISD::XOR: 10958 return performXorCombine(N, DCI); 10959 case ISD::ZERO_EXTEND: 10960 return performZeroExtendCombine(N, DCI); 10961 case ISD::SIGN_EXTEND_INREG: 10962 return performSignExtendInRegCombine(N , DCI); 10963 case AMDGPUISD::FP_CLASS: 10964 return performClassCombine(N, DCI); 10965 case ISD::FCANONICALIZE: 10966 return performFCanonicalizeCombine(N, DCI); 10967 case AMDGPUISD::RCP: 10968 return performRcpCombine(N, DCI); 10969 case AMDGPUISD::FRACT: 10970 case AMDGPUISD::RSQ: 10971 case AMDGPUISD::RCP_LEGACY: 10972 case AMDGPUISD::RCP_IFLAG: 10973 case AMDGPUISD::RSQ_CLAMP: 10974 case AMDGPUISD::LDEXP: { 10975 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10976 SDValue Src = N->getOperand(0); 10977 if (Src.isUndef()) 10978 return Src; 10979 break; 10980 } 10981 case ISD::SINT_TO_FP: 10982 case ISD::UINT_TO_FP: 10983 return performUCharToFloatCombine(N, DCI); 10984 case AMDGPUISD::CVT_F32_UBYTE0: 10985 case AMDGPUISD::CVT_F32_UBYTE1: 10986 case AMDGPUISD::CVT_F32_UBYTE2: 10987 case AMDGPUISD::CVT_F32_UBYTE3: 10988 return performCvtF32UByteNCombine(N, DCI); 10989 case AMDGPUISD::FMED3: 10990 return performFMed3Combine(N, DCI); 10991 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10992 return performCvtPkRTZCombine(N, DCI); 10993 case AMDGPUISD::CLAMP: 10994 return performClampCombine(N, DCI); 10995 case ISD::SCALAR_TO_VECTOR: { 10996 SelectionDAG &DAG = DCI.DAG; 10997 EVT VT = N->getValueType(0); 10998 10999 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11000 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11001 SDLoc SL(N); 11002 SDValue Src = N->getOperand(0); 11003 EVT EltVT = Src.getValueType(); 11004 if (EltVT == MVT::f16) 11005 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11006 11007 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11008 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11009 } 11010 11011 break; 11012 } 11013 case ISD::EXTRACT_VECTOR_ELT: 11014 return performExtractVectorEltCombine(N, DCI); 11015 case ISD::INSERT_VECTOR_ELT: 11016 return performInsertVectorEltCombine(N, DCI); 11017 case ISD::LOAD: { 11018 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11019 return Widended; 11020 LLVM_FALLTHROUGH; 11021 } 11022 default: { 11023 if (!DCI.isBeforeLegalize()) { 11024 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11025 return performMemSDNodeCombine(MemNode, DCI); 11026 } 11027 11028 break; 11029 } 11030 } 11031 11032 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11033 } 11034 11035 /// Helper function for adjustWritemask 11036 static unsigned SubIdx2Lane(unsigned Idx) { 11037 switch (Idx) { 11038 default: return ~0u; 11039 case AMDGPU::sub0: return 0; 11040 case AMDGPU::sub1: return 1; 11041 case AMDGPU::sub2: return 2; 11042 case AMDGPU::sub3: return 3; 11043 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11044 } 11045 } 11046 11047 /// Adjust the writemask of MIMG instructions 11048 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11049 SelectionDAG &DAG) const { 11050 unsigned Opcode = Node->getMachineOpcode(); 11051 11052 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11053 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11054 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11055 return Node; // not implemented for D16 11056 11057 SDNode *Users[5] = { nullptr }; 11058 unsigned Lane = 0; 11059 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11060 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11061 unsigned NewDmask = 0; 11062 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11063 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11064 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11065 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 11066 unsigned TFCLane = 0; 11067 bool HasChain = Node->getNumValues() > 1; 11068 11069 if (OldDmask == 0) { 11070 // These are folded out, but on the chance it happens don't assert. 11071 return Node; 11072 } 11073 11074 unsigned OldBitsSet = countPopulation(OldDmask); 11075 // Work out which is the TFE/LWE lane if that is enabled. 11076 if (UsesTFC) { 11077 TFCLane = OldBitsSet; 11078 } 11079 11080 // Try to figure out the used register components 11081 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11082 I != E; ++I) { 11083 11084 // Don't look at users of the chain. 11085 if (I.getUse().getResNo() != 0) 11086 continue; 11087 11088 // Abort if we can't understand the usage 11089 if (!I->isMachineOpcode() || 11090 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11091 return Node; 11092 11093 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11094 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11095 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11096 // set, etc. 11097 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11098 if (Lane == ~0u) 11099 return Node; 11100 11101 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11102 if (UsesTFC && Lane == TFCLane) { 11103 Users[Lane] = *I; 11104 } else { 11105 // Set which texture component corresponds to the lane. 11106 unsigned Comp; 11107 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11108 Comp = countTrailingZeros(Dmask); 11109 Dmask &= ~(1 << Comp); 11110 } 11111 11112 // Abort if we have more than one user per component. 11113 if (Users[Lane]) 11114 return Node; 11115 11116 Users[Lane] = *I; 11117 NewDmask |= 1 << Comp; 11118 } 11119 } 11120 11121 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11122 bool NoChannels = !NewDmask; 11123 if (NoChannels) { 11124 if (!UsesTFC) { 11125 // No uses of the result and not using TFC. Then do nothing. 11126 return Node; 11127 } 11128 // If the original dmask has one channel - then nothing to do 11129 if (OldBitsSet == 1) 11130 return Node; 11131 // Use an arbitrary dmask - required for the instruction to work 11132 NewDmask = 1; 11133 } 11134 // Abort if there's no change 11135 if (NewDmask == OldDmask) 11136 return Node; 11137 11138 unsigned BitsSet = countPopulation(NewDmask); 11139 11140 // Check for TFE or LWE - increase the number of channels by one to account 11141 // for the extra return value 11142 // This will need adjustment for D16 if this is also included in 11143 // adjustWriteMask (this function) but at present D16 are excluded. 11144 unsigned NewChannels = BitsSet + UsesTFC; 11145 11146 int NewOpcode = 11147 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11148 assert(NewOpcode != -1 && 11149 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11150 "failed to find equivalent MIMG op"); 11151 11152 // Adjust the writemask in the node 11153 SmallVector<SDValue, 12> Ops; 11154 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11155 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11156 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11157 11158 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11159 11160 MVT ResultVT = NewChannels == 1 ? 11161 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11162 NewChannels == 5 ? 8 : NewChannels); 11163 SDVTList NewVTList = HasChain ? 11164 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11165 11166 11167 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11168 NewVTList, Ops); 11169 11170 if (HasChain) { 11171 // Update chain. 11172 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11173 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11174 } 11175 11176 if (NewChannels == 1) { 11177 assert(Node->hasNUsesOfValue(1, 0)); 11178 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11179 SDLoc(Node), Users[Lane]->getValueType(0), 11180 SDValue(NewNode, 0)); 11181 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11182 return nullptr; 11183 } 11184 11185 // Update the users of the node with the new indices 11186 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11187 SDNode *User = Users[i]; 11188 if (!User) { 11189 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11190 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11191 if (i || !NoChannels) 11192 continue; 11193 } else { 11194 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11195 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11196 } 11197 11198 switch (Idx) { 11199 default: break; 11200 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11201 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11202 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11203 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11204 } 11205 } 11206 11207 DAG.RemoveDeadNode(Node); 11208 return nullptr; 11209 } 11210 11211 static bool isFrameIndexOp(SDValue Op) { 11212 if (Op.getOpcode() == ISD::AssertZext) 11213 Op = Op.getOperand(0); 11214 11215 return isa<FrameIndexSDNode>(Op); 11216 } 11217 11218 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11219 /// with frame index operands. 11220 /// LLVM assumes that inputs are to these instructions are registers. 11221 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11222 SelectionDAG &DAG) const { 11223 if (Node->getOpcode() == ISD::CopyToReg) { 11224 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11225 SDValue SrcVal = Node->getOperand(2); 11226 11227 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11228 // to try understanding copies to physical registers. 11229 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11230 SDLoc SL(Node); 11231 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11232 SDValue VReg = DAG.getRegister( 11233 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11234 11235 SDNode *Glued = Node->getGluedNode(); 11236 SDValue ToVReg 11237 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11238 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11239 SDValue ToResultReg 11240 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11241 VReg, ToVReg.getValue(1)); 11242 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11243 DAG.RemoveDeadNode(Node); 11244 return ToResultReg.getNode(); 11245 } 11246 } 11247 11248 SmallVector<SDValue, 8> Ops; 11249 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11250 if (!isFrameIndexOp(Node->getOperand(i))) { 11251 Ops.push_back(Node->getOperand(i)); 11252 continue; 11253 } 11254 11255 SDLoc DL(Node); 11256 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11257 Node->getOperand(i).getValueType(), 11258 Node->getOperand(i)), 0)); 11259 } 11260 11261 return DAG.UpdateNodeOperands(Node, Ops); 11262 } 11263 11264 /// Fold the instructions after selecting them. 11265 /// Returns null if users were already updated. 11266 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11267 SelectionDAG &DAG) const { 11268 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11269 unsigned Opcode = Node->getMachineOpcode(); 11270 11271 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11272 !TII->isGather4(Opcode) && 11273 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11274 return adjustWritemask(Node, DAG); 11275 } 11276 11277 if (Opcode == AMDGPU::INSERT_SUBREG || 11278 Opcode == AMDGPU::REG_SEQUENCE) { 11279 legalizeTargetIndependentNode(Node, DAG); 11280 return Node; 11281 } 11282 11283 switch (Opcode) { 11284 case AMDGPU::V_DIV_SCALE_F32_e64: 11285 case AMDGPU::V_DIV_SCALE_F64_e64: { 11286 // Satisfy the operand register constraint when one of the inputs is 11287 // undefined. Ordinarily each undef value will have its own implicit_def of 11288 // a vreg, so force these to use a single register. 11289 SDValue Src0 = Node->getOperand(1); 11290 SDValue Src1 = Node->getOperand(3); 11291 SDValue Src2 = Node->getOperand(5); 11292 11293 if ((Src0.isMachineOpcode() && 11294 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11295 (Src0 == Src1 || Src0 == Src2)) 11296 break; 11297 11298 MVT VT = Src0.getValueType().getSimpleVT(); 11299 const TargetRegisterClass *RC = 11300 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11301 11302 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11303 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11304 11305 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11306 UndefReg, Src0, SDValue()); 11307 11308 // src0 must be the same register as src1 or src2, even if the value is 11309 // undefined, so make sure we don't violate this constraint. 11310 if (Src0.isMachineOpcode() && 11311 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11312 if (Src1.isMachineOpcode() && 11313 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11314 Src0 = Src1; 11315 else if (Src2.isMachineOpcode() && 11316 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11317 Src0 = Src2; 11318 else { 11319 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11320 Src0 = UndefReg; 11321 Src1 = UndefReg; 11322 } 11323 } else 11324 break; 11325 11326 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11327 Ops[1] = Src0; 11328 Ops[3] = Src1; 11329 Ops[5] = Src2; 11330 Ops.push_back(ImpDef.getValue(1)); 11331 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11332 } 11333 default: 11334 break; 11335 } 11336 11337 return Node; 11338 } 11339 11340 // Any MIMG instructions that use tfe or lwe require an initialization of the 11341 // result register that will be written in the case of a memory access failure. 11342 // The required code is also added to tie this init code to the result of the 11343 // img instruction. 11344 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11345 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11346 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11347 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11348 MachineBasicBlock &MBB = *MI.getParent(); 11349 11350 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11351 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11352 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11353 11354 if (!TFE && !LWE) // intersect_ray 11355 return; 11356 11357 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11358 unsigned LWEVal = LWE->getImm(); 11359 unsigned D16Val = D16 ? D16->getImm() : 0; 11360 11361 if (!TFEVal && !LWEVal) 11362 return; 11363 11364 // At least one of TFE or LWE are non-zero 11365 // We have to insert a suitable initialization of the result value and 11366 // tie this to the dest of the image instruction. 11367 11368 const DebugLoc &DL = MI.getDebugLoc(); 11369 11370 int DstIdx = 11371 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11372 11373 // Calculate which dword we have to initialize to 0. 11374 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11375 11376 // check that dmask operand is found. 11377 assert(MO_Dmask && "Expected dmask operand in instruction"); 11378 11379 unsigned dmask = MO_Dmask->getImm(); 11380 // Determine the number of active lanes taking into account the 11381 // Gather4 special case 11382 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11383 11384 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11385 11386 unsigned InitIdx = 11387 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11388 11389 // Abandon attempt if the dst size isn't large enough 11390 // - this is in fact an error but this is picked up elsewhere and 11391 // reported correctly. 11392 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11393 if (DstSize < InitIdx) 11394 return; 11395 11396 // Create a register for the intialization value. 11397 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11398 unsigned NewDst = 0; // Final initialized value will be in here 11399 11400 // If PRTStrictNull feature is enabled (the default) then initialize 11401 // all the result registers to 0, otherwise just the error indication 11402 // register (VGPRn+1) 11403 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11404 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11405 11406 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11407 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11408 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11409 // Initialize dword 11410 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11411 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11412 .addImm(0); 11413 // Insert into the super-reg 11414 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11415 .addReg(PrevDst) 11416 .addReg(SubReg) 11417 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11418 11419 PrevDst = NewDst; 11420 } 11421 11422 // Add as an implicit operand 11423 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11424 11425 // Tie the just added implicit operand to the dst 11426 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11427 } 11428 11429 /// Assign the register class depending on the number of 11430 /// bits set in the writemask 11431 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11432 SDNode *Node) const { 11433 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11434 11435 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11436 11437 if (TII->isVOP3(MI.getOpcode())) { 11438 // Make sure constant bus requirements are respected. 11439 TII->legalizeOperandsVOP3(MRI, MI); 11440 11441 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11442 // This saves a chain-copy of registers and better ballance register 11443 // use between vgpr and agpr as agpr tuples tend to be big. 11444 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11445 unsigned Opc = MI.getOpcode(); 11446 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11447 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11448 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11449 if (I == -1) 11450 break; 11451 MachineOperand &Op = MI.getOperand(I); 11452 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11453 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11454 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11455 continue; 11456 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11457 if (!Src || !Src->isCopy() || 11458 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11459 continue; 11460 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11461 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11462 // All uses of agpr64 and agpr32 can also accept vgpr except for 11463 // v_accvgpr_read, but we do not produce agpr reads during selection, 11464 // so no use checks are needed. 11465 MRI.setRegClass(Op.getReg(), NewRC); 11466 } 11467 } 11468 11469 return; 11470 } 11471 11472 // Replace unused atomics with the no return version. 11473 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11474 if (NoRetAtomicOp != -1) { 11475 if (!Node->hasAnyUseOfValue(0)) { 11476 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11477 AMDGPU::OpName::cpol); 11478 if (CPolIdx != -1) { 11479 MachineOperand &CPol = MI.getOperand(CPolIdx); 11480 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11481 } 11482 MI.RemoveOperand(0); 11483 MI.setDesc(TII->get(NoRetAtomicOp)); 11484 return; 11485 } 11486 11487 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11488 // instruction, because the return type of these instructions is a vec2 of 11489 // the memory type, so it can be tied to the input operand. 11490 // This means these instructions always have a use, so we need to add a 11491 // special case to check if the atomic has only one extract_subreg use, 11492 // which itself has no uses. 11493 if ((Node->hasNUsesOfValue(1, 0) && 11494 Node->use_begin()->isMachineOpcode() && 11495 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11496 !Node->use_begin()->hasAnyUseOfValue(0))) { 11497 Register Def = MI.getOperand(0).getReg(); 11498 11499 // Change this into a noret atomic. 11500 MI.setDesc(TII->get(NoRetAtomicOp)); 11501 MI.RemoveOperand(0); 11502 11503 // If we only remove the def operand from the atomic instruction, the 11504 // extract_subreg will be left with a use of a vreg without a def. 11505 // So we need to insert an implicit_def to avoid machine verifier 11506 // errors. 11507 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11508 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11509 } 11510 return; 11511 } 11512 11513 if (TII->isMIMG(MI) && !MI.mayStore()) 11514 AddIMGInit(MI); 11515 } 11516 11517 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11518 uint64_t Val) { 11519 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11520 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11521 } 11522 11523 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11524 const SDLoc &DL, 11525 SDValue Ptr) const { 11526 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11527 11528 // Build the half of the subregister with the constants before building the 11529 // full 128-bit register. If we are building multiple resource descriptors, 11530 // this will allow CSEing of the 2-component register. 11531 const SDValue Ops0[] = { 11532 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11533 buildSMovImm32(DAG, DL, 0), 11534 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11535 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11536 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11537 }; 11538 11539 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11540 MVT::v2i32, Ops0), 0); 11541 11542 // Combine the constants and the pointer. 11543 const SDValue Ops1[] = { 11544 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11545 Ptr, 11546 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11547 SubRegHi, 11548 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11549 }; 11550 11551 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11552 } 11553 11554 /// Return a resource descriptor with the 'Add TID' bit enabled 11555 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11556 /// of the resource descriptor) to create an offset, which is added to 11557 /// the resource pointer. 11558 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11559 SDValue Ptr, uint32_t RsrcDword1, 11560 uint64_t RsrcDword2And3) const { 11561 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11562 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11563 if (RsrcDword1) { 11564 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11565 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11566 0); 11567 } 11568 11569 SDValue DataLo = buildSMovImm32(DAG, DL, 11570 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11571 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11572 11573 const SDValue Ops[] = { 11574 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11575 PtrLo, 11576 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11577 PtrHi, 11578 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11579 DataLo, 11580 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11581 DataHi, 11582 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11583 }; 11584 11585 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11586 } 11587 11588 //===----------------------------------------------------------------------===// 11589 // SI Inline Assembly Support 11590 //===----------------------------------------------------------------------===// 11591 11592 std::pair<unsigned, const TargetRegisterClass *> 11593 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11594 StringRef Constraint, 11595 MVT VT) const { 11596 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11597 11598 const TargetRegisterClass *RC = nullptr; 11599 if (Constraint.size() == 1) { 11600 const unsigned BitWidth = VT.getSizeInBits(); 11601 switch (Constraint[0]) { 11602 default: 11603 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11604 case 's': 11605 case 'r': 11606 switch (BitWidth) { 11607 case 16: 11608 RC = &AMDGPU::SReg_32RegClass; 11609 break; 11610 case 64: 11611 RC = &AMDGPU::SGPR_64RegClass; 11612 break; 11613 default: 11614 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11615 if (!RC) 11616 return std::make_pair(0U, nullptr); 11617 break; 11618 } 11619 break; 11620 case 'v': 11621 switch (BitWidth) { 11622 case 16: 11623 RC = &AMDGPU::VGPR_32RegClass; 11624 break; 11625 default: 11626 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11627 if (!RC) 11628 return std::make_pair(0U, nullptr); 11629 break; 11630 } 11631 break; 11632 case 'a': 11633 if (!Subtarget->hasMAIInsts()) 11634 break; 11635 switch (BitWidth) { 11636 case 16: 11637 RC = &AMDGPU::AGPR_32RegClass; 11638 break; 11639 default: 11640 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11641 if (!RC) 11642 return std::make_pair(0U, nullptr); 11643 break; 11644 } 11645 break; 11646 } 11647 // We actually support i128, i16 and f16 as inline parameters 11648 // even if they are not reported as legal 11649 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11650 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11651 return std::make_pair(0U, RC); 11652 } 11653 11654 if (Constraint.size() > 1) { 11655 if (Constraint[1] == 'v') { 11656 RC = &AMDGPU::VGPR_32RegClass; 11657 } else if (Constraint[1] == 's') { 11658 RC = &AMDGPU::SGPR_32RegClass; 11659 } else if (Constraint[1] == 'a') { 11660 RC = &AMDGPU::AGPR_32RegClass; 11661 } 11662 11663 if (RC) { 11664 uint32_t Idx; 11665 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11666 if (!Failed && Idx < RC->getNumRegs()) 11667 return std::make_pair(RC->getRegister(Idx), RC); 11668 } 11669 } 11670 11671 // FIXME: Returns VS_32 for physical SGPR constraints 11672 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11673 } 11674 11675 static bool isImmConstraint(StringRef Constraint) { 11676 if (Constraint.size() == 1) { 11677 switch (Constraint[0]) { 11678 default: break; 11679 case 'I': 11680 case 'J': 11681 case 'A': 11682 case 'B': 11683 case 'C': 11684 return true; 11685 } 11686 } else if (Constraint == "DA" || 11687 Constraint == "DB") { 11688 return true; 11689 } 11690 return false; 11691 } 11692 11693 SITargetLowering::ConstraintType 11694 SITargetLowering::getConstraintType(StringRef Constraint) const { 11695 if (Constraint.size() == 1) { 11696 switch (Constraint[0]) { 11697 default: break; 11698 case 's': 11699 case 'v': 11700 case 'a': 11701 return C_RegisterClass; 11702 } 11703 } 11704 if (isImmConstraint(Constraint)) { 11705 return C_Other; 11706 } 11707 return TargetLowering::getConstraintType(Constraint); 11708 } 11709 11710 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11711 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11712 Val = Val & maskTrailingOnes<uint64_t>(Size); 11713 } 11714 return Val; 11715 } 11716 11717 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11718 std::string &Constraint, 11719 std::vector<SDValue> &Ops, 11720 SelectionDAG &DAG) const { 11721 if (isImmConstraint(Constraint)) { 11722 uint64_t Val; 11723 if (getAsmOperandConstVal(Op, Val) && 11724 checkAsmConstraintVal(Op, Constraint, Val)) { 11725 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11726 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11727 } 11728 } else { 11729 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11730 } 11731 } 11732 11733 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11734 unsigned Size = Op.getScalarValueSizeInBits(); 11735 if (Size > 64) 11736 return false; 11737 11738 if (Size == 16 && !Subtarget->has16BitInsts()) 11739 return false; 11740 11741 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11742 Val = C->getSExtValue(); 11743 return true; 11744 } 11745 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11746 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11747 return true; 11748 } 11749 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11750 if (Size != 16 || Op.getNumOperands() != 2) 11751 return false; 11752 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11753 return false; 11754 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11755 Val = C->getSExtValue(); 11756 return true; 11757 } 11758 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11759 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11760 return true; 11761 } 11762 } 11763 11764 return false; 11765 } 11766 11767 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11768 const std::string &Constraint, 11769 uint64_t Val) const { 11770 if (Constraint.size() == 1) { 11771 switch (Constraint[0]) { 11772 case 'I': 11773 return AMDGPU::isInlinableIntLiteral(Val); 11774 case 'J': 11775 return isInt<16>(Val); 11776 case 'A': 11777 return checkAsmConstraintValA(Op, Val); 11778 case 'B': 11779 return isInt<32>(Val); 11780 case 'C': 11781 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11782 AMDGPU::isInlinableIntLiteral(Val); 11783 default: 11784 break; 11785 } 11786 } else if (Constraint.size() == 2) { 11787 if (Constraint == "DA") { 11788 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11789 int64_t LoBits = static_cast<int32_t>(Val); 11790 return checkAsmConstraintValA(Op, HiBits, 32) && 11791 checkAsmConstraintValA(Op, LoBits, 32); 11792 } 11793 if (Constraint == "DB") { 11794 return true; 11795 } 11796 } 11797 llvm_unreachable("Invalid asm constraint"); 11798 } 11799 11800 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11801 uint64_t Val, 11802 unsigned MaxSize) const { 11803 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11804 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11805 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11806 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11807 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11808 return true; 11809 } 11810 return false; 11811 } 11812 11813 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11814 switch (UnalignedClassID) { 11815 case AMDGPU::VReg_64RegClassID: 11816 return AMDGPU::VReg_64_Align2RegClassID; 11817 case AMDGPU::VReg_96RegClassID: 11818 return AMDGPU::VReg_96_Align2RegClassID; 11819 case AMDGPU::VReg_128RegClassID: 11820 return AMDGPU::VReg_128_Align2RegClassID; 11821 case AMDGPU::VReg_160RegClassID: 11822 return AMDGPU::VReg_160_Align2RegClassID; 11823 case AMDGPU::VReg_192RegClassID: 11824 return AMDGPU::VReg_192_Align2RegClassID; 11825 case AMDGPU::VReg_224RegClassID: 11826 return AMDGPU::VReg_224_Align2RegClassID; 11827 case AMDGPU::VReg_256RegClassID: 11828 return AMDGPU::VReg_256_Align2RegClassID; 11829 case AMDGPU::VReg_512RegClassID: 11830 return AMDGPU::VReg_512_Align2RegClassID; 11831 case AMDGPU::VReg_1024RegClassID: 11832 return AMDGPU::VReg_1024_Align2RegClassID; 11833 case AMDGPU::AReg_64RegClassID: 11834 return AMDGPU::AReg_64_Align2RegClassID; 11835 case AMDGPU::AReg_96RegClassID: 11836 return AMDGPU::AReg_96_Align2RegClassID; 11837 case AMDGPU::AReg_128RegClassID: 11838 return AMDGPU::AReg_128_Align2RegClassID; 11839 case AMDGPU::AReg_160RegClassID: 11840 return AMDGPU::AReg_160_Align2RegClassID; 11841 case AMDGPU::AReg_192RegClassID: 11842 return AMDGPU::AReg_192_Align2RegClassID; 11843 case AMDGPU::AReg_256RegClassID: 11844 return AMDGPU::AReg_256_Align2RegClassID; 11845 case AMDGPU::AReg_512RegClassID: 11846 return AMDGPU::AReg_512_Align2RegClassID; 11847 case AMDGPU::AReg_1024RegClassID: 11848 return AMDGPU::AReg_1024_Align2RegClassID; 11849 default: 11850 return -1; 11851 } 11852 } 11853 11854 // Figure out which registers should be reserved for stack access. Only after 11855 // the function is legalized do we know all of the non-spill stack objects or if 11856 // calls are present. 11857 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11858 MachineRegisterInfo &MRI = MF.getRegInfo(); 11859 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11860 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11861 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11862 const SIInstrInfo *TII = ST.getInstrInfo(); 11863 11864 if (Info->isEntryFunction()) { 11865 // Callable functions have fixed registers used for stack access. 11866 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11867 } 11868 11869 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11870 Info->getStackPtrOffsetReg())); 11871 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11872 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11873 11874 // We need to worry about replacing the default register with itself in case 11875 // of MIR testcases missing the MFI. 11876 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11877 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11878 11879 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11880 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11881 11882 Info->limitOccupancy(MF); 11883 11884 if (ST.isWave32() && !MF.empty()) { 11885 for (auto &MBB : MF) { 11886 for (auto &MI : MBB) { 11887 TII->fixImplicitOperands(MI); 11888 } 11889 } 11890 } 11891 11892 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11893 // classes if required. Ideally the register class constraints would differ 11894 // per-subtarget, but there's no easy way to achieve that right now. This is 11895 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11896 // from using them as the register class for legal types. 11897 if (ST.needsAlignedVGPRs()) { 11898 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11899 const Register Reg = Register::index2VirtReg(I); 11900 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11901 if (!RC) 11902 continue; 11903 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11904 if (NewClassID != -1) 11905 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11906 } 11907 } 11908 11909 TargetLoweringBase::finalizeLowering(MF); 11910 11911 // Allocate a VGPR for future SGPR Spill if 11912 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11913 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11914 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11915 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11916 Info->reserveVGPRforSGPRSpills(MF); 11917 } 11918 11919 void SITargetLowering::computeKnownBitsForFrameIndex( 11920 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11921 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11922 11923 // Set the high bits to zero based on the maximum allowed scratch size per 11924 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11925 // calculation won't overflow, so assume the sign bit is never set. 11926 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11927 } 11928 11929 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11930 KnownBits &Known, unsigned Dim) { 11931 unsigned MaxValue = 11932 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11933 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11934 } 11935 11936 void SITargetLowering::computeKnownBitsForTargetInstr( 11937 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11938 const MachineRegisterInfo &MRI, unsigned Depth) const { 11939 const MachineInstr *MI = MRI.getVRegDef(R); 11940 switch (MI->getOpcode()) { 11941 case AMDGPU::G_INTRINSIC: { 11942 switch (MI->getIntrinsicID()) { 11943 case Intrinsic::amdgcn_workitem_id_x: 11944 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11945 break; 11946 case Intrinsic::amdgcn_workitem_id_y: 11947 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11948 break; 11949 case Intrinsic::amdgcn_workitem_id_z: 11950 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11951 break; 11952 case Intrinsic::amdgcn_mbcnt_lo: 11953 case Intrinsic::amdgcn_mbcnt_hi: { 11954 // These return at most the wavefront size - 1. 11955 unsigned Size = MRI.getType(R).getSizeInBits(); 11956 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11957 break; 11958 } 11959 case Intrinsic::amdgcn_groupstaticsize: { 11960 // We can report everything over the maximum size as 0. We can't report 11961 // based on the actual size because we don't know if it's accurate or not 11962 // at any given point. 11963 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11964 break; 11965 } 11966 } 11967 break; 11968 } 11969 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11970 Known.Zero.setHighBits(24); 11971 break; 11972 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11973 Known.Zero.setHighBits(16); 11974 break; 11975 } 11976 } 11977 11978 Align SITargetLowering::computeKnownAlignForTargetInstr( 11979 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11980 unsigned Depth) const { 11981 const MachineInstr *MI = MRI.getVRegDef(R); 11982 switch (MI->getOpcode()) { 11983 case AMDGPU::G_INTRINSIC: 11984 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11985 // FIXME: Can this move to generic code? What about the case where the call 11986 // site specifies a lower alignment? 11987 Intrinsic::ID IID = MI->getIntrinsicID(); 11988 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11989 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11990 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11991 return *RetAlign; 11992 return Align(1); 11993 } 11994 default: 11995 return Align(1); 11996 } 11997 } 11998 11999 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12000 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12001 const Align CacheLineAlign = Align(64); 12002 12003 // Pre-GFX10 target did not benefit from loop alignment 12004 if (!ML || DisableLoopAlignment || 12005 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12006 getSubtarget()->hasInstFwdPrefetchBug()) 12007 return PrefAlign; 12008 12009 // On GFX10 I$ is 4 x 64 bytes cache lines. 12010 // By default prefetcher keeps one cache line behind and reads two ahead. 12011 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12012 // behind and one ahead. 12013 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12014 // If loop fits 64 bytes it always spans no more than two cache lines and 12015 // does not need an alignment. 12016 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12017 // Else if loop is less or equal 192 bytes we need two lines behind. 12018 12019 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12020 const MachineBasicBlock *Header = ML->getHeader(); 12021 if (Header->getAlignment() != PrefAlign) 12022 return Header->getAlignment(); // Already processed. 12023 12024 unsigned LoopSize = 0; 12025 for (const MachineBasicBlock *MBB : ML->blocks()) { 12026 // If inner loop block is aligned assume in average half of the alignment 12027 // size to be added as nops. 12028 if (MBB != Header) 12029 LoopSize += MBB->getAlignment().value() / 2; 12030 12031 for (const MachineInstr &MI : *MBB) { 12032 LoopSize += TII->getInstSizeInBytes(MI); 12033 if (LoopSize > 192) 12034 return PrefAlign; 12035 } 12036 } 12037 12038 if (LoopSize <= 64) 12039 return PrefAlign; 12040 12041 if (LoopSize <= 128) 12042 return CacheLineAlign; 12043 12044 // If any of parent loops is surrounded by prefetch instructions do not 12045 // insert new for inner loop, which would reset parent's settings. 12046 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12047 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12048 auto I = Exit->getFirstNonDebugInstr(); 12049 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12050 return CacheLineAlign; 12051 } 12052 } 12053 12054 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12055 MachineBasicBlock *Exit = ML->getExitBlock(); 12056 12057 if (Pre && Exit) { 12058 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12059 TII->get(AMDGPU::S_INST_PREFETCH)) 12060 .addImm(1); // prefetch 2 lines behind PC 12061 12062 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12063 TII->get(AMDGPU::S_INST_PREFETCH)) 12064 .addImm(2); // prefetch 1 line behind PC 12065 } 12066 12067 return CacheLineAlign; 12068 } 12069 12070 LLVM_ATTRIBUTE_UNUSED 12071 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12072 assert(N->getOpcode() == ISD::CopyFromReg); 12073 do { 12074 // Follow the chain until we find an INLINEASM node. 12075 N = N->getOperand(0).getNode(); 12076 if (N->getOpcode() == ISD::INLINEASM || 12077 N->getOpcode() == ISD::INLINEASM_BR) 12078 return true; 12079 } while (N->getOpcode() == ISD::CopyFromReg); 12080 return false; 12081 } 12082 12083 bool SITargetLowering::isSDNodeSourceOfDivergence( 12084 const SDNode *N, FunctionLoweringInfo *FLI, 12085 LegacyDivergenceAnalysis *KDA) const { 12086 switch (N->getOpcode()) { 12087 case ISD::CopyFromReg: { 12088 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12089 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12090 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12091 Register Reg = R->getReg(); 12092 12093 // FIXME: Why does this need to consider isLiveIn? 12094 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12095 return !TRI->isSGPRReg(MRI, Reg); 12096 12097 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12098 return KDA->isDivergent(V); 12099 12100 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12101 return !TRI->isSGPRReg(MRI, Reg); 12102 } 12103 case ISD::LOAD: { 12104 const LoadSDNode *L = cast<LoadSDNode>(N); 12105 unsigned AS = L->getAddressSpace(); 12106 // A flat load may access private memory. 12107 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12108 } 12109 case ISD::CALLSEQ_END: 12110 return true; 12111 case ISD::INTRINSIC_WO_CHAIN: 12112 return AMDGPU::isIntrinsicSourceOfDivergence( 12113 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12114 case ISD::INTRINSIC_W_CHAIN: 12115 return AMDGPU::isIntrinsicSourceOfDivergence( 12116 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12117 case AMDGPUISD::ATOMIC_CMP_SWAP: 12118 case AMDGPUISD::ATOMIC_INC: 12119 case AMDGPUISD::ATOMIC_DEC: 12120 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12121 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12122 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12123 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12124 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12125 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12126 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12127 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12128 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12129 case AMDGPUISD::BUFFER_ATOMIC_AND: 12130 case AMDGPUISD::BUFFER_ATOMIC_OR: 12131 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12132 case AMDGPUISD::BUFFER_ATOMIC_INC: 12133 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12134 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12135 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12136 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12137 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12138 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12139 // Target-specific read-modify-write atomics are sources of divergence. 12140 return true; 12141 default: 12142 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12143 // Generic read-modify-write atomics are sources of divergence. 12144 return A->readMem() && A->writeMem(); 12145 } 12146 return false; 12147 } 12148 } 12149 12150 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12151 EVT VT) const { 12152 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12153 case MVT::f32: 12154 return hasFP32Denormals(DAG.getMachineFunction()); 12155 case MVT::f64: 12156 case MVT::f16: 12157 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12158 default: 12159 return false; 12160 } 12161 } 12162 12163 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12164 MachineFunction &MF) const { 12165 switch (Ty.getScalarSizeInBits()) { 12166 case 32: 12167 return hasFP32Denormals(MF); 12168 case 64: 12169 case 16: 12170 return hasFP64FP16Denormals(MF); 12171 default: 12172 return false; 12173 } 12174 } 12175 12176 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12177 const SelectionDAG &DAG, 12178 bool SNaN, 12179 unsigned Depth) const { 12180 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12181 const MachineFunction &MF = DAG.getMachineFunction(); 12182 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12183 12184 if (Info->getMode().DX10Clamp) 12185 return true; // Clamped to 0. 12186 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12187 } 12188 12189 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12190 SNaN, Depth); 12191 } 12192 12193 // Global FP atomic instructions have a hardcoded FP mode and do not support 12194 // FP32 denormals, and only support v2f16 denormals. 12195 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12196 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12197 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12198 if (&Flt == &APFloat::IEEEsingle()) 12199 return DenormMode == DenormalMode::getPreserveSign(); 12200 return DenormMode == DenormalMode::getIEEE(); 12201 } 12202 12203 TargetLowering::AtomicExpansionKind 12204 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12205 12206 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12207 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12208 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12209 SmallVector<StringRef> SSNs; 12210 Ctx.getSyncScopeNames(SSNs); 12211 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12212 ? "system" 12213 : SSNs[RMW->getSyncScopeID()]; 12214 ORE.emit([&]() { 12215 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12216 << "Hardware instruction generated for atomic " 12217 << RMW->getOperationName(RMW->getOperation()) 12218 << " operation at memory scope " << MemScope 12219 << " due to an unsafe request."; 12220 }); 12221 return Kind; 12222 }; 12223 12224 switch (RMW->getOperation()) { 12225 case AtomicRMWInst::FAdd: { 12226 Type *Ty = RMW->getType(); 12227 12228 // We don't have a way to support 16-bit atomics now, so just leave them 12229 // as-is. 12230 if (Ty->isHalfTy()) 12231 return AtomicExpansionKind::None; 12232 12233 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12234 return AtomicExpansionKind::CmpXChg; 12235 12236 unsigned AS = RMW->getPointerAddressSpace(); 12237 12238 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12239 Subtarget->hasAtomicFaddInsts()) { 12240 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12241 // floating point atomic instructions. May generate more efficient code, 12242 // but may not respect rounding and denormal modes, and may give incorrect 12243 // results for certain memory destinations. 12244 if (RMW->getFunction() 12245 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12246 .getValueAsString() != "true") 12247 return AtomicExpansionKind::CmpXChg; 12248 12249 if (Subtarget->hasGFX90AInsts()) { 12250 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12251 return AtomicExpansionKind::CmpXChg; 12252 12253 auto SSID = RMW->getSyncScopeID(); 12254 if (SSID == SyncScope::System || 12255 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12256 return AtomicExpansionKind::CmpXChg; 12257 12258 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12259 } 12260 12261 if (AS == AMDGPUAS::FLAT_ADDRESS) 12262 return AtomicExpansionKind::CmpXChg; 12263 12264 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12265 : AtomicExpansionKind::CmpXChg; 12266 } 12267 12268 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12269 // to round-to-nearest-even. 12270 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12271 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12272 if (!Ty->isDoubleTy()) 12273 return AtomicExpansionKind::None; 12274 12275 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12276 return AtomicExpansionKind::None; 12277 12278 return RMW->getFunction() 12279 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12280 .getValueAsString() == "true" 12281 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12282 : AtomicExpansionKind::CmpXChg; 12283 } 12284 12285 return AtomicExpansionKind::CmpXChg; 12286 } 12287 default: 12288 break; 12289 } 12290 12291 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12292 } 12293 12294 const TargetRegisterClass * 12295 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12296 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12297 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12298 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12299 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12300 : &AMDGPU::SReg_32RegClass; 12301 if (!TRI->isSGPRClass(RC) && !isDivergent) 12302 return TRI->getEquivalentSGPRClass(RC); 12303 else if (TRI->isSGPRClass(RC) && isDivergent) 12304 return TRI->getEquivalentVGPRClass(RC); 12305 12306 return RC; 12307 } 12308 12309 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12310 // uniform values (as produced by the mask results of control flow intrinsics) 12311 // used outside of divergent blocks. The phi users need to also be treated as 12312 // always uniform. 12313 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12314 unsigned WaveSize) { 12315 // FIXME: We asssume we never cast the mask results of a control flow 12316 // intrinsic. 12317 // Early exit if the type won't be consistent as a compile time hack. 12318 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12319 if (!IT || IT->getBitWidth() != WaveSize) 12320 return false; 12321 12322 if (!isa<Instruction>(V)) 12323 return false; 12324 if (!Visited.insert(V).second) 12325 return false; 12326 bool Result = false; 12327 for (auto U : V->users()) { 12328 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12329 if (V == U->getOperand(1)) { 12330 switch (Intrinsic->getIntrinsicID()) { 12331 default: 12332 Result = false; 12333 break; 12334 case Intrinsic::amdgcn_if_break: 12335 case Intrinsic::amdgcn_if: 12336 case Intrinsic::amdgcn_else: 12337 Result = true; 12338 break; 12339 } 12340 } 12341 if (V == U->getOperand(0)) { 12342 switch (Intrinsic->getIntrinsicID()) { 12343 default: 12344 Result = false; 12345 break; 12346 case Intrinsic::amdgcn_end_cf: 12347 case Intrinsic::amdgcn_loop: 12348 Result = true; 12349 break; 12350 } 12351 } 12352 } else { 12353 Result = hasCFUser(U, Visited, WaveSize); 12354 } 12355 if (Result) 12356 break; 12357 } 12358 return Result; 12359 } 12360 12361 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12362 const Value *V) const { 12363 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12364 if (CI->isInlineAsm()) { 12365 // FIXME: This cannot give a correct answer. This should only trigger in 12366 // the case where inline asm returns mixed SGPR and VGPR results, used 12367 // outside the defining block. We don't have a specific result to 12368 // consider, so this assumes if any value is SGPR, the overall register 12369 // also needs to be SGPR. 12370 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12371 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12372 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12373 for (auto &TC : TargetConstraints) { 12374 if (TC.Type == InlineAsm::isOutput) { 12375 ComputeConstraintToUse(TC, SDValue()); 12376 unsigned AssignedReg; 12377 const TargetRegisterClass *RC; 12378 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12379 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12380 if (RC) { 12381 MachineRegisterInfo &MRI = MF.getRegInfo(); 12382 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12383 return true; 12384 else if (SIRI->isSGPRClass(RC)) 12385 return true; 12386 } 12387 } 12388 } 12389 } 12390 } 12391 SmallPtrSet<const Value *, 16> Visited; 12392 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12393 } 12394 12395 std::pair<InstructionCost, MVT> 12396 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12397 Type *Ty) const { 12398 std::pair<InstructionCost, MVT> Cost = 12399 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12400 auto Size = DL.getTypeSizeInBits(Ty); 12401 // Maximum load or store can handle 8 dwords for scalar and 4 for 12402 // vector ALU. Let's assume anything above 8 dwords is expensive 12403 // even if legal. 12404 if (Size <= 256) 12405 return Cost; 12406 12407 Cost.first = (Size + 255) / 256; 12408 return Cost; 12409 } 12410