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/BinaryFormat/ELF.h" 23 #include "llvm/CodeGen/Analysis.h" 24 #include "llvm/CodeGen/FunctionLoweringInfo.h" 25 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 26 #include "llvm/CodeGen/MachineLoopInfo.h" 27 #include "llvm/IR/DiagnosticInfo.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/IntrinsicsAMDGPU.h" 30 #include "llvm/IR/IntrinsicsR600.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/KnownBits.h" 33 34 using namespace llvm; 35 36 #define DEBUG_TYPE "si-lower" 37 38 STATISTIC(NumTailCalls, "Number of tail calls"); 39 40 static cl::opt<bool> DisableLoopAlignment( 41 "amdgpu-disable-loop-alignment", 42 cl::desc("Do not align and prefetch loops"), 43 cl::init(false)); 44 45 static cl::opt<bool> VGPRReserveforSGPRSpill( 46 "amdgpu-reserve-vgpr-for-sgpr-spill", 47 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 48 49 static cl::opt<bool> UseDivergentRegisterIndexing( 50 "amdgpu-use-divergent-register-indexing", 51 cl::Hidden, 52 cl::desc("Use indirect register addressing for divergent indexes"), 53 cl::init(false)); 54 55 static bool hasFP32Denormals(const MachineFunction &MF) { 56 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 57 return Info->getMode().allFP32Denormals(); 58 } 59 60 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 61 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 62 return Info->getMode().allFP64FP16Denormals(); 63 } 64 65 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 66 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 67 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 68 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 69 return AMDGPU::SGPR0 + Reg; 70 } 71 } 72 llvm_unreachable("Cannot allocate sgpr"); 73 } 74 75 SITargetLowering::SITargetLowering(const TargetMachine &TM, 76 const GCNSubtarget &STI) 77 : AMDGPUTargetLowering(TM, STI), 78 Subtarget(&STI) { 79 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 80 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 81 82 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 83 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 84 85 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 86 87 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 88 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 89 90 addRegisterClass(MVT::f64, V64RegClass); 91 addRegisterClass(MVT::v2f32, V64RegClass); 92 93 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 94 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 95 96 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 97 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 98 99 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 100 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 101 102 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 103 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 104 105 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 106 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 107 108 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 109 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 110 111 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 112 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 113 114 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 115 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 116 117 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 118 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 119 120 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 121 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 122 123 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 124 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 125 126 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 127 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 128 129 if (Subtarget->has16BitInsts()) { 130 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 131 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 132 133 // Unless there are also VOP3P operations, not operations are really legal. 134 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 135 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 137 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 138 } 139 140 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 141 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 142 143 computeRegisterProperties(Subtarget->getRegisterInfo()); 144 145 // The boolean content concept here is too inflexible. Compares only ever 146 // really produce a 1-bit result. Any copy/extend from these will turn into a 147 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 148 // it's what most targets use. 149 setBooleanContents(ZeroOrOneBooleanContent); 150 setBooleanVectorContents(ZeroOrOneBooleanContent); 151 152 // We need to custom lower vector stores from local memory 153 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 154 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 155 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::i1, Custom); 162 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 163 164 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 165 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 166 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 172 setOperationAction(ISD::STORE, MVT::i1, Custom); 173 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 174 175 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 176 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 177 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 178 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 179 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 180 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 181 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 182 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 183 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 184 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 185 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 186 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 187 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 188 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 189 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 190 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 191 192 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 193 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 194 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 195 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 196 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 197 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 198 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 199 200 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 201 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 202 203 setOperationAction(ISD::SELECT, MVT::i1, Promote); 204 setOperationAction(ISD::SELECT, MVT::i64, Custom); 205 setOperationAction(ISD::SELECT, MVT::f64, Promote); 206 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 207 208 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 209 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 210 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 213 214 setOperationAction(ISD::SETCC, MVT::i1, Promote); 215 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 216 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 217 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 218 219 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 220 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 221 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 222 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 223 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 224 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 225 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 227 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 228 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 229 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 230 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 231 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 232 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 233 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 234 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 235 236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 244 245 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 246 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 247 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 248 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 249 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 250 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 251 252 setOperationAction(ISD::UADDO, MVT::i32, Legal); 253 setOperationAction(ISD::USUBO, MVT::i32, Legal); 254 255 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 256 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 257 258 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 259 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 260 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 261 262 #if 0 263 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 264 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 265 #endif 266 267 // We only support LOAD/STORE and vector manipulation ops for vectors 268 // with > 4 elements. 269 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 270 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 271 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 272 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 273 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 274 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 275 switch (Op) { 276 case ISD::LOAD: 277 case ISD::STORE: 278 case ISD::BUILD_VECTOR: 279 case ISD::BITCAST: 280 case ISD::EXTRACT_VECTOR_ELT: 281 case ISD::INSERT_VECTOR_ELT: 282 case ISD::INSERT_SUBVECTOR: 283 case ISD::EXTRACT_SUBVECTOR: 284 case ISD::SCALAR_TO_VECTOR: 285 break; 286 case ISD::CONCAT_VECTORS: 287 setOperationAction(Op, VT, Custom); 288 break; 289 default: 290 setOperationAction(Op, VT, Expand); 291 break; 292 } 293 } 294 } 295 296 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 297 298 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 299 // is expanded to avoid having two separate loops in case the index is a VGPR. 300 301 // Most operations are naturally 32-bit vector operations. We only support 302 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 303 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 304 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 305 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 306 307 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 308 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 309 310 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 311 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 312 313 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 314 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 315 } 316 317 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 318 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 319 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 320 321 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 322 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 323 324 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 325 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 326 327 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 328 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 329 } 330 331 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 332 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 333 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 334 335 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 336 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 337 338 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 339 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 340 341 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 342 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 343 } 344 345 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 346 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 347 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 348 349 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 350 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 351 352 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 353 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 354 355 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 356 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 357 } 358 359 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 360 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 361 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 362 363 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 364 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 365 366 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 367 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 368 369 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 370 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 371 } 372 373 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 374 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 377 378 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 379 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 380 381 // Avoid stack access for these. 382 // TODO: Generalize to more vector types. 383 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 384 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 385 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 386 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 387 388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 394 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 398 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 399 400 // Deal with vec3 vector operations when widened to vec4. 401 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 402 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 405 406 // Deal with vec5/6/7 vector operations when widened to vec8. 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 408 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 415 416 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 417 // and output demarshalling 418 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 419 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 420 421 // We can't return success/failure, only the old value, 422 // let LLVM add the comparison 423 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 424 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 425 426 if (Subtarget->hasFlatAddressSpace()) { 427 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 428 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 429 } 430 431 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 432 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 433 434 // FIXME: This should be narrowed to i32, but that only happens if i64 is 435 // illegal. 436 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 437 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 438 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 439 440 // On SI this is s_memtime and s_memrealtime on VI. 441 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 442 setOperationAction(ISD::TRAP, MVT::Other, Custom); 443 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 444 445 if (Subtarget->has16BitInsts()) { 446 setOperationAction(ISD::FPOW, MVT::f16, Promote); 447 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 448 setOperationAction(ISD::FLOG, MVT::f16, Custom); 449 setOperationAction(ISD::FEXP, MVT::f16, Custom); 450 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 451 } 452 453 if (Subtarget->hasMadMacF32Insts()) 454 setOperationAction(ISD::FMAD, MVT::f32, Legal); 455 456 if (!Subtarget->hasBFI()) { 457 // fcopysign can be done in a single instruction with BFI. 458 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 459 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 460 } 461 462 if (!Subtarget->hasBCNT(32)) 463 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 464 465 if (!Subtarget->hasBCNT(64)) 466 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 467 468 if (Subtarget->hasFFBH()) 469 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 470 471 if (Subtarget->hasFFBL()) 472 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 473 474 // We only really have 32-bit BFE instructions (and 16-bit on VI). 475 // 476 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 477 // effort to match them now. We want this to be false for i64 cases when the 478 // extraction isn't restricted to the upper or lower half. Ideally we would 479 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 480 // span the midpoint are probably relatively rare, so don't worry about them 481 // for now. 482 if (Subtarget->hasBFE()) 483 setHasExtractBitsInsn(true); 484 485 // Clamp modifier on add/sub 486 if (Subtarget->hasIntClamp()) { 487 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 488 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 489 } 490 491 if (Subtarget->hasAddNoCarry()) { 492 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 493 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 494 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 495 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 496 } 497 498 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 499 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 500 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 501 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 502 503 504 // These are really only legal for ieee_mode functions. We should be avoiding 505 // them for functions that don't have ieee_mode enabled, so just say they are 506 // legal. 507 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 508 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 509 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 510 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 511 512 513 if (Subtarget->haveRoundOpsF64()) { 514 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 515 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 516 setOperationAction(ISD::FRINT, MVT::f64, Legal); 517 } else { 518 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 519 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 520 setOperationAction(ISD::FRINT, MVT::f64, Custom); 521 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 522 } 523 524 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 525 526 setOperationAction(ISD::FSIN, MVT::f32, Custom); 527 setOperationAction(ISD::FCOS, MVT::f32, Custom); 528 setOperationAction(ISD::FDIV, MVT::f32, Custom); 529 setOperationAction(ISD::FDIV, MVT::f64, Custom); 530 531 if (Subtarget->has16BitInsts()) { 532 setOperationAction(ISD::Constant, MVT::i16, Legal); 533 534 setOperationAction(ISD::SMIN, MVT::i16, Legal); 535 setOperationAction(ISD::SMAX, MVT::i16, Legal); 536 537 setOperationAction(ISD::UMIN, MVT::i16, Legal); 538 setOperationAction(ISD::UMAX, MVT::i16, Legal); 539 540 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 541 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 542 543 setOperationAction(ISD::ROTR, MVT::i16, Expand); 544 setOperationAction(ISD::ROTL, MVT::i16, Expand); 545 546 setOperationAction(ISD::SDIV, MVT::i16, Promote); 547 setOperationAction(ISD::UDIV, MVT::i16, Promote); 548 setOperationAction(ISD::SREM, MVT::i16, Promote); 549 setOperationAction(ISD::UREM, MVT::i16, Promote); 550 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 551 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 552 553 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 554 555 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 557 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 558 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 559 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 560 561 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 562 563 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 564 565 setOperationAction(ISD::LOAD, MVT::i16, Custom); 566 567 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 568 569 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 570 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 571 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 572 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 573 574 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 575 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 576 577 // F16 - Constant Actions. 578 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 579 580 // F16 - Load/Store Actions. 581 setOperationAction(ISD::LOAD, MVT::f16, Promote); 582 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 583 setOperationAction(ISD::STORE, MVT::f16, Promote); 584 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 585 586 // F16 - VOP1 Actions. 587 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 588 setOperationAction(ISD::FCOS, MVT::f16, Custom); 589 setOperationAction(ISD::FSIN, MVT::f16, Custom); 590 591 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 592 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 593 594 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 595 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 596 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 597 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 598 setOperationAction(ISD::FROUND, MVT::f16, Custom); 599 600 // F16 - VOP2 Actions. 601 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 602 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 603 604 setOperationAction(ISD::FDIV, MVT::f16, Custom); 605 606 // F16 - VOP3 Actions. 607 setOperationAction(ISD::FMA, MVT::f16, Legal); 608 if (STI.hasMadF16()) 609 setOperationAction(ISD::FMAD, MVT::f16, Legal); 610 611 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 612 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 613 switch (Op) { 614 case ISD::LOAD: 615 case ISD::STORE: 616 case ISD::BUILD_VECTOR: 617 case ISD::BITCAST: 618 case ISD::EXTRACT_VECTOR_ELT: 619 case ISD::INSERT_VECTOR_ELT: 620 case ISD::INSERT_SUBVECTOR: 621 case ISD::EXTRACT_SUBVECTOR: 622 case ISD::SCALAR_TO_VECTOR: 623 break; 624 case ISD::CONCAT_VECTORS: 625 setOperationAction(Op, VT, Custom); 626 break; 627 default: 628 setOperationAction(Op, VT, Expand); 629 break; 630 } 631 } 632 } 633 634 // v_perm_b32 can handle either of these. 635 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 636 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 637 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 638 639 // XXX - Do these do anything? Vector constants turn into build_vector. 640 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 641 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 642 643 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 644 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 645 646 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 647 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 648 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 649 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 650 651 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 652 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 653 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 654 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 655 656 setOperationAction(ISD::AND, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::OR, MVT::v2i16, Promote); 659 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 660 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 661 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 662 663 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 664 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 665 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 666 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 667 668 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 669 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 670 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 671 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 672 673 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 674 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 675 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 676 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 677 678 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 679 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 680 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 681 682 if (!Subtarget->hasVOP3PInsts()) { 683 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 684 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 685 } 686 687 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 688 // This isn't really legal, but this avoids the legalizer unrolling it (and 689 // allows matching fneg (fabs x) patterns) 690 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 691 692 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 693 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 694 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 695 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 696 697 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 698 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 699 700 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 701 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 702 } 703 704 if (Subtarget->hasVOP3PInsts()) { 705 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 706 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 707 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 708 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 709 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 710 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 711 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 712 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 713 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 714 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 715 716 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 717 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 718 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 719 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 720 721 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 722 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 723 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 724 725 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 726 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 727 728 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 729 730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 731 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 732 733 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 734 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 735 736 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 737 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 738 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 739 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 740 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 741 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 742 743 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 744 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 745 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 746 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 747 748 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 749 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 750 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 751 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 752 753 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 754 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 755 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 756 757 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 758 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 759 760 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 762 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 763 764 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 765 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 766 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 767 768 if (Subtarget->hasPackedFP32Ops()) { 769 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 770 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 771 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 772 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 773 774 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 775 setOperationAction(ISD::FADD, VT, Custom); 776 setOperationAction(ISD::FMUL, VT, Custom); 777 setOperationAction(ISD::FMA, VT, Custom); 778 } 779 } 780 } 781 782 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 783 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 784 785 if (Subtarget->has16BitInsts()) { 786 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 787 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 788 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 789 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 790 } else { 791 // Legalization hack. 792 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 793 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 794 795 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 796 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 797 } 798 799 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 800 setOperationAction(ISD::SELECT, VT, Custom); 801 } 802 803 setOperationAction(ISD::SMULO, MVT::i64, Custom); 804 setOperationAction(ISD::UMULO, MVT::i64, Custom); 805 806 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 807 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 808 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 809 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 810 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 811 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 812 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 813 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 815 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 816 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 817 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 818 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 819 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 820 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 821 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 822 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 823 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 824 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 825 826 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 827 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 828 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 829 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 830 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 831 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 832 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 833 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 834 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 835 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 836 837 setTargetDAGCombine(ISD::ADD); 838 setTargetDAGCombine(ISD::ADDCARRY); 839 setTargetDAGCombine(ISD::SUB); 840 setTargetDAGCombine(ISD::SUBCARRY); 841 setTargetDAGCombine(ISD::FADD); 842 setTargetDAGCombine(ISD::FSUB); 843 setTargetDAGCombine(ISD::FMINNUM); 844 setTargetDAGCombine(ISD::FMAXNUM); 845 setTargetDAGCombine(ISD::FMINNUM_IEEE); 846 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 847 setTargetDAGCombine(ISD::FMA); 848 setTargetDAGCombine(ISD::SMIN); 849 setTargetDAGCombine(ISD::SMAX); 850 setTargetDAGCombine(ISD::UMIN); 851 setTargetDAGCombine(ISD::UMAX); 852 setTargetDAGCombine(ISD::SETCC); 853 setTargetDAGCombine(ISD::AND); 854 setTargetDAGCombine(ISD::OR); 855 setTargetDAGCombine(ISD::XOR); 856 setTargetDAGCombine(ISD::SINT_TO_FP); 857 setTargetDAGCombine(ISD::UINT_TO_FP); 858 setTargetDAGCombine(ISD::FCANONICALIZE); 859 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 860 setTargetDAGCombine(ISD::ZERO_EXTEND); 861 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 862 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 863 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 864 865 // All memory operations. Some folding on the pointer operand is done to help 866 // matching the constant offsets in the addressing modes. 867 setTargetDAGCombine(ISD::LOAD); 868 setTargetDAGCombine(ISD::STORE); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD); 870 setTargetDAGCombine(ISD::ATOMIC_STORE); 871 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 872 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 873 setTargetDAGCombine(ISD::ATOMIC_SWAP); 874 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 875 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 876 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 877 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 878 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 879 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 880 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 881 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 882 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 883 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 884 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 885 setTargetDAGCombine(ISD::INTRINSIC_VOID); 886 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 887 888 // FIXME: In other contexts we pretend this is a per-function property. 889 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 890 891 setSchedulingPreference(Sched::RegPressure); 892 } 893 894 const GCNSubtarget *SITargetLowering::getSubtarget() const { 895 return Subtarget; 896 } 897 898 //===----------------------------------------------------------------------===// 899 // TargetLowering queries 900 //===----------------------------------------------------------------------===// 901 902 // v_mad_mix* support a conversion from f16 to f32. 903 // 904 // There is only one special case when denormals are enabled we don't currently, 905 // where this is OK to use. 906 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 907 EVT DestVT, EVT SrcVT) const { 908 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 909 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 910 DestVT.getScalarType() == MVT::f32 && 911 SrcVT.getScalarType() == MVT::f16 && 912 // TODO: This probably only requires no input flushing? 913 !hasFP32Denormals(DAG.getMachineFunction()); 914 } 915 916 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 917 // SI has some legal vector types, but no legal vector operations. Say no 918 // shuffles are legal in order to prefer scalarizing some vector operations. 919 return false; 920 } 921 922 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 923 CallingConv::ID CC, 924 EVT VT) const { 925 if (CC == CallingConv::AMDGPU_KERNEL) 926 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 927 928 if (VT.isVector()) { 929 EVT ScalarVT = VT.getScalarType(); 930 unsigned Size = ScalarVT.getSizeInBits(); 931 if (Size == 16) { 932 if (Subtarget->has16BitInsts()) 933 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 934 return VT.isInteger() ? MVT::i32 : MVT::f32; 935 } 936 937 if (Size < 16) 938 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 939 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 940 } 941 942 if (VT.getSizeInBits() > 32) 943 return MVT::i32; 944 945 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 946 } 947 948 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 949 CallingConv::ID CC, 950 EVT VT) const { 951 if (CC == CallingConv::AMDGPU_KERNEL) 952 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 953 954 if (VT.isVector()) { 955 unsigned NumElts = VT.getVectorNumElements(); 956 EVT ScalarVT = VT.getScalarType(); 957 unsigned Size = ScalarVT.getSizeInBits(); 958 959 // FIXME: Should probably promote 8-bit vectors to i16. 960 if (Size == 16 && Subtarget->has16BitInsts()) 961 return (NumElts + 1) / 2; 962 963 if (Size <= 32) 964 return NumElts; 965 966 if (Size > 32) 967 return NumElts * ((Size + 31) / 32); 968 } else if (VT.getSizeInBits() > 32) 969 return (VT.getSizeInBits() + 31) / 32; 970 971 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 972 } 973 974 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 975 LLVMContext &Context, CallingConv::ID CC, 976 EVT VT, EVT &IntermediateVT, 977 unsigned &NumIntermediates, MVT &RegisterVT) const { 978 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 979 unsigned NumElts = VT.getVectorNumElements(); 980 EVT ScalarVT = VT.getScalarType(); 981 unsigned Size = ScalarVT.getSizeInBits(); 982 // FIXME: We should fix the ABI to be the same on targets without 16-bit 983 // support, but unless we can properly handle 3-vectors, it will be still be 984 // inconsistent. 985 if (Size == 16 && Subtarget->has16BitInsts()) { 986 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 987 IntermediateVT = RegisterVT; 988 NumIntermediates = (NumElts + 1) / 2; 989 return NumIntermediates; 990 } 991 992 if (Size == 32) { 993 RegisterVT = ScalarVT.getSimpleVT(); 994 IntermediateVT = RegisterVT; 995 NumIntermediates = NumElts; 996 return NumIntermediates; 997 } 998 999 if (Size < 16 && Subtarget->has16BitInsts()) { 1000 // FIXME: Should probably form v2i16 pieces 1001 RegisterVT = MVT::i16; 1002 IntermediateVT = ScalarVT; 1003 NumIntermediates = NumElts; 1004 return NumIntermediates; 1005 } 1006 1007 1008 if (Size != 16 && Size <= 32) { 1009 RegisterVT = MVT::i32; 1010 IntermediateVT = ScalarVT; 1011 NumIntermediates = NumElts; 1012 return NumIntermediates; 1013 } 1014 1015 if (Size > 32) { 1016 RegisterVT = MVT::i32; 1017 IntermediateVT = RegisterVT; 1018 NumIntermediates = NumElts * ((Size + 31) / 32); 1019 return NumIntermediates; 1020 } 1021 } 1022 1023 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1024 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1025 } 1026 1027 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1028 assert(DMaskLanes != 0); 1029 1030 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1031 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1032 return EVT::getVectorVT(Ty->getContext(), 1033 EVT::getEVT(VT->getElementType()), 1034 NumElts); 1035 } 1036 1037 return EVT::getEVT(Ty); 1038 } 1039 1040 // Peek through TFE struct returns to only use the data size. 1041 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1042 auto *ST = dyn_cast<StructType>(Ty); 1043 if (!ST) 1044 return memVTFromImageData(Ty, DMaskLanes); 1045 1046 // Some intrinsics return an aggregate type - special case to work out the 1047 // correct memVT. 1048 // 1049 // Only limited forms of aggregate type currently expected. 1050 if (ST->getNumContainedTypes() != 2 || 1051 !ST->getContainedType(1)->isIntegerTy(32)) 1052 return EVT(); 1053 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1054 } 1055 1056 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1057 const CallInst &CI, 1058 MachineFunction &MF, 1059 unsigned IntrID) const { 1060 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1061 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1062 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1063 (Intrinsic::ID)IntrID); 1064 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1065 return false; 1066 1067 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1068 1069 if (RsrcIntr->IsImage) { 1070 Info.ptrVal = 1071 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1072 Info.align.reset(); 1073 } else { 1074 Info.ptrVal = 1075 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1076 } 1077 1078 Info.flags = MachineMemOperand::MODereferenceable; 1079 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1080 unsigned DMaskLanes = 4; 1081 1082 if (RsrcIntr->IsImage) { 1083 const AMDGPU::ImageDimIntrinsicInfo *Intr 1084 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1085 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1086 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1087 1088 if (!BaseOpcode->Gather4) { 1089 // If this isn't a gather, we may have excess loaded elements in the 1090 // IR type. Check the dmask for the real number of elements loaded. 1091 unsigned DMask 1092 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1093 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1094 } 1095 1096 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1097 } else 1098 Info.memVT = EVT::getEVT(CI.getType()); 1099 1100 // FIXME: What does alignment mean for an image? 1101 Info.opc = ISD::INTRINSIC_W_CHAIN; 1102 Info.flags |= MachineMemOperand::MOLoad; 1103 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1104 Info.opc = ISD::INTRINSIC_VOID; 1105 1106 Type *DataTy = CI.getArgOperand(0)->getType(); 1107 if (RsrcIntr->IsImage) { 1108 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1109 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1110 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1111 } else 1112 Info.memVT = EVT::getEVT(DataTy); 1113 1114 Info.flags |= MachineMemOperand::MOStore; 1115 } else { 1116 // Atomic 1117 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1118 ISD::INTRINSIC_W_CHAIN; 1119 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1120 Info.flags = MachineMemOperand::MOLoad | 1121 MachineMemOperand::MOStore | 1122 MachineMemOperand::MODereferenceable; 1123 1124 // XXX - Should this be volatile without known ordering? 1125 Info.flags |= MachineMemOperand::MOVolatile; 1126 } 1127 return true; 1128 } 1129 1130 switch (IntrID) { 1131 case Intrinsic::amdgcn_atomic_inc: 1132 case Intrinsic::amdgcn_atomic_dec: 1133 case Intrinsic::amdgcn_ds_ordered_add: 1134 case Intrinsic::amdgcn_ds_ordered_swap: 1135 case Intrinsic::amdgcn_ds_fadd: 1136 case Intrinsic::amdgcn_ds_fmin: 1137 case Intrinsic::amdgcn_ds_fmax: { 1138 Info.opc = ISD::INTRINSIC_W_CHAIN; 1139 Info.memVT = MVT::getVT(CI.getType()); 1140 Info.ptrVal = CI.getOperand(0); 1141 Info.align.reset(); 1142 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1143 1144 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1145 if (!Vol->isZero()) 1146 Info.flags |= MachineMemOperand::MOVolatile; 1147 1148 return true; 1149 } 1150 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1151 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1152 1153 Info.opc = ISD::INTRINSIC_W_CHAIN; 1154 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1155 Info.ptrVal = 1156 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1157 Info.align.reset(); 1158 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1159 1160 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1161 if (!Vol || !Vol->isZero()) 1162 Info.flags |= MachineMemOperand::MOVolatile; 1163 1164 return true; 1165 } 1166 case Intrinsic::amdgcn_ds_append: 1167 case Intrinsic::amdgcn_ds_consume: { 1168 Info.opc = ISD::INTRINSIC_W_CHAIN; 1169 Info.memVT = MVT::getVT(CI.getType()); 1170 Info.ptrVal = CI.getOperand(0); 1171 Info.align.reset(); 1172 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1173 1174 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1175 if (!Vol->isZero()) 1176 Info.flags |= MachineMemOperand::MOVolatile; 1177 1178 return true; 1179 } 1180 case Intrinsic::amdgcn_global_atomic_csub: { 1181 Info.opc = ISD::INTRINSIC_W_CHAIN; 1182 Info.memVT = MVT::getVT(CI.getType()); 1183 Info.ptrVal = CI.getOperand(0); 1184 Info.align.reset(); 1185 Info.flags = MachineMemOperand::MOLoad | 1186 MachineMemOperand::MOStore | 1187 MachineMemOperand::MOVolatile; 1188 return true; 1189 } 1190 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1191 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1192 Info.opc = ISD::INTRINSIC_W_CHAIN; 1193 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1194 Info.ptrVal = 1195 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1196 Info.align.reset(); 1197 Info.flags = MachineMemOperand::MOLoad | 1198 MachineMemOperand::MODereferenceable; 1199 return true; 1200 } 1201 case Intrinsic::amdgcn_global_atomic_fadd: 1202 case Intrinsic::amdgcn_global_atomic_fmin: 1203 case Intrinsic::amdgcn_global_atomic_fmax: 1204 case Intrinsic::amdgcn_flat_atomic_fadd: 1205 case Intrinsic::amdgcn_flat_atomic_fmin: 1206 case Intrinsic::amdgcn_flat_atomic_fmax: { 1207 Info.opc = ISD::INTRINSIC_W_CHAIN; 1208 Info.memVT = MVT::getVT(CI.getType()); 1209 Info.ptrVal = CI.getOperand(0); 1210 Info.align.reset(); 1211 Info.flags = MachineMemOperand::MOLoad | 1212 MachineMemOperand::MOStore | 1213 MachineMemOperand::MODereferenceable | 1214 MachineMemOperand::MOVolatile; 1215 return true; 1216 } 1217 case Intrinsic::amdgcn_ds_gws_init: 1218 case Intrinsic::amdgcn_ds_gws_barrier: 1219 case Intrinsic::amdgcn_ds_gws_sema_v: 1220 case Intrinsic::amdgcn_ds_gws_sema_br: 1221 case Intrinsic::amdgcn_ds_gws_sema_p: 1222 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1223 Info.opc = ISD::INTRINSIC_VOID; 1224 1225 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1226 Info.ptrVal = 1227 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1228 1229 // This is an abstract access, but we need to specify a type and size. 1230 Info.memVT = MVT::i32; 1231 Info.size = 4; 1232 Info.align = Align(4); 1233 1234 Info.flags = MachineMemOperand::MOStore; 1235 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1236 Info.flags = MachineMemOperand::MOLoad; 1237 return true; 1238 } 1239 default: 1240 return false; 1241 } 1242 } 1243 1244 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1245 SmallVectorImpl<Value*> &Ops, 1246 Type *&AccessTy) const { 1247 switch (II->getIntrinsicID()) { 1248 case Intrinsic::amdgcn_atomic_inc: 1249 case Intrinsic::amdgcn_atomic_dec: 1250 case Intrinsic::amdgcn_ds_ordered_add: 1251 case Intrinsic::amdgcn_ds_ordered_swap: 1252 case Intrinsic::amdgcn_ds_append: 1253 case Intrinsic::amdgcn_ds_consume: 1254 case Intrinsic::amdgcn_ds_fadd: 1255 case Intrinsic::amdgcn_ds_fmin: 1256 case Intrinsic::amdgcn_ds_fmax: 1257 case Intrinsic::amdgcn_global_atomic_fadd: 1258 case Intrinsic::amdgcn_flat_atomic_fadd: 1259 case Intrinsic::amdgcn_flat_atomic_fmin: 1260 case Intrinsic::amdgcn_flat_atomic_fmax: 1261 case Intrinsic::amdgcn_global_atomic_csub: { 1262 Value *Ptr = II->getArgOperand(0); 1263 AccessTy = II->getType(); 1264 Ops.push_back(Ptr); 1265 return true; 1266 } 1267 default: 1268 return false; 1269 } 1270 } 1271 1272 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1273 if (!Subtarget->hasFlatInstOffsets()) { 1274 // Flat instructions do not have offsets, and only have the register 1275 // address. 1276 return AM.BaseOffs == 0 && AM.Scale == 0; 1277 } 1278 1279 return AM.Scale == 0 && 1280 (AM.BaseOffs == 0 || 1281 Subtarget->getInstrInfo()->isLegalFLATOffset( 1282 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1283 } 1284 1285 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1286 if (Subtarget->hasFlatGlobalInsts()) 1287 return AM.Scale == 0 && 1288 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1289 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1290 SIInstrFlags::FlatGlobal)); 1291 1292 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1293 // Assume the we will use FLAT for all global memory accesses 1294 // on VI. 1295 // FIXME: This assumption is currently wrong. On VI we still use 1296 // MUBUF instructions for the r + i addressing mode. As currently 1297 // implemented, the MUBUF instructions only work on buffer < 4GB. 1298 // It may be possible to support > 4GB buffers with MUBUF instructions, 1299 // by setting the stride value in the resource descriptor which would 1300 // increase the size limit to (stride * 4GB). However, this is risky, 1301 // because it has never been validated. 1302 return isLegalFlatAddressingMode(AM); 1303 } 1304 1305 return isLegalMUBUFAddressingMode(AM); 1306 } 1307 1308 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1309 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1310 // additionally can do r + r + i with addr64. 32-bit has more addressing 1311 // mode options. Depending on the resource constant, it can also do 1312 // (i64 r0) + (i32 r1) * (i14 i). 1313 // 1314 // Private arrays end up using a scratch buffer most of the time, so also 1315 // assume those use MUBUF instructions. Scratch loads / stores are currently 1316 // implemented as mubuf instructions with offen bit set, so slightly 1317 // different than the normal addr64. 1318 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1319 return false; 1320 1321 // FIXME: Since we can split immediate into soffset and immediate offset, 1322 // would it make sense to allow any immediate? 1323 1324 switch (AM.Scale) { 1325 case 0: // r + i or just i, depending on HasBaseReg. 1326 return true; 1327 case 1: 1328 return true; // We have r + r or r + i. 1329 case 2: 1330 if (AM.HasBaseReg) { 1331 // Reject 2 * r + r. 1332 return false; 1333 } 1334 1335 // Allow 2 * r as r + r 1336 // Or 2 * r + i is allowed as r + r + i. 1337 return true; 1338 default: // Don't allow n * r 1339 return false; 1340 } 1341 } 1342 1343 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1344 const AddrMode &AM, Type *Ty, 1345 unsigned AS, Instruction *I) const { 1346 // No global is ever allowed as a base. 1347 if (AM.BaseGV) 1348 return false; 1349 1350 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1351 return isLegalGlobalAddressingMode(AM); 1352 1353 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1354 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1355 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1356 // If the offset isn't a multiple of 4, it probably isn't going to be 1357 // correctly aligned. 1358 // FIXME: Can we get the real alignment here? 1359 if (AM.BaseOffs % 4 != 0) 1360 return isLegalMUBUFAddressingMode(AM); 1361 1362 // There are no SMRD extloads, so if we have to do a small type access we 1363 // will use a MUBUF load. 1364 // FIXME?: We also need to do this if unaligned, but we don't know the 1365 // alignment here. 1366 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1367 return isLegalGlobalAddressingMode(AM); 1368 1369 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1370 // SMRD instructions have an 8-bit, dword offset on SI. 1371 if (!isUInt<8>(AM.BaseOffs / 4)) 1372 return false; 1373 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1374 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1375 // in 8-bits, it can use a smaller encoding. 1376 if (!isUInt<32>(AM.BaseOffs / 4)) 1377 return false; 1378 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1379 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1380 if (!isUInt<20>(AM.BaseOffs)) 1381 return false; 1382 } else 1383 llvm_unreachable("unhandled generation"); 1384 1385 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1386 return true; 1387 1388 if (AM.Scale == 1 && AM.HasBaseReg) 1389 return true; 1390 1391 return false; 1392 1393 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1394 return isLegalMUBUFAddressingMode(AM); 1395 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1396 AS == AMDGPUAS::REGION_ADDRESS) { 1397 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1398 // field. 1399 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1400 // an 8-bit dword offset but we don't know the alignment here. 1401 if (!isUInt<16>(AM.BaseOffs)) 1402 return false; 1403 1404 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1405 return true; 1406 1407 if (AM.Scale == 1 && AM.HasBaseReg) 1408 return true; 1409 1410 return false; 1411 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1412 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1413 // For an unknown address space, this usually means that this is for some 1414 // reason being used for pure arithmetic, and not based on some addressing 1415 // computation. We don't have instructions that compute pointers with any 1416 // addressing modes, so treat them as having no offset like flat 1417 // instructions. 1418 return isLegalFlatAddressingMode(AM); 1419 } 1420 1421 // Assume a user alias of global for unknown address spaces. 1422 return isLegalGlobalAddressingMode(AM); 1423 } 1424 1425 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1426 const SelectionDAG &DAG) const { 1427 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1428 return (MemVT.getSizeInBits() <= 4 * 32); 1429 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1430 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1431 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1432 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1433 return (MemVT.getSizeInBits() <= 2 * 32); 1434 } 1435 return true; 1436 } 1437 1438 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1439 unsigned Size, unsigned AddrSpace, Align Alignment, 1440 MachineMemOperand::Flags Flags, bool *IsFast) const { 1441 if (IsFast) 1442 *IsFast = false; 1443 1444 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1445 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1446 // Check if alignment requirements for ds_read/write instructions are 1447 // disabled. 1448 if (Subtarget->hasUnalignedDSAccessEnabled() && 1449 !Subtarget->hasLDSMisalignedBug()) { 1450 if (IsFast) 1451 *IsFast = Alignment != Align(2); 1452 return true; 1453 } 1454 1455 // Either, the alignment requirements are "enabled", or there is an 1456 // unaligned LDS access related hardware bug though alignment requirements 1457 // are "disabled". In either case, we need to check for proper alignment 1458 // requirements. 1459 // 1460 if (Size == 64) { 1461 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1462 // can do a 4 byte aligned, 8 byte access in a single operation using 1463 // ds_read2/write2_b32 with adjacent offsets. 1464 bool AlignedBy4 = Alignment >= Align(4); 1465 if (IsFast) 1466 *IsFast = AlignedBy4; 1467 1468 return AlignedBy4; 1469 } 1470 if (Size == 96) { 1471 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1472 // gfx8 and older. 1473 bool AlignedBy16 = Alignment >= Align(16); 1474 if (IsFast) 1475 *IsFast = AlignedBy16; 1476 1477 return AlignedBy16; 1478 } 1479 if (Size == 128) { 1480 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1481 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1482 // single operation using ds_read2/write2_b64. 1483 bool AlignedBy8 = Alignment >= Align(8); 1484 if (IsFast) 1485 *IsFast = AlignedBy8; 1486 1487 return AlignedBy8; 1488 } 1489 } 1490 1491 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1492 bool AlignedBy4 = Alignment >= Align(4); 1493 if (IsFast) 1494 *IsFast = AlignedBy4; 1495 1496 return AlignedBy4 || 1497 Subtarget->enableFlatScratch() || 1498 Subtarget->hasUnalignedScratchAccess(); 1499 } 1500 1501 // FIXME: We have to be conservative here and assume that flat operations 1502 // will access scratch. If we had access to the IR function, then we 1503 // could determine if any private memory was used in the function. 1504 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1505 !Subtarget->hasUnalignedScratchAccess()) { 1506 bool AlignedBy4 = Alignment >= Align(4); 1507 if (IsFast) 1508 *IsFast = AlignedBy4; 1509 1510 return AlignedBy4; 1511 } 1512 1513 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1514 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1515 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1516 // If we have an uniform constant load, it still requires using a slow 1517 // buffer instruction if unaligned. 1518 if (IsFast) { 1519 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1520 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1521 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1522 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1523 Alignment >= Align(4) : Alignment != Align(2); 1524 } 1525 1526 return true; 1527 } 1528 1529 // Smaller than dword value must be aligned. 1530 if (Size < 32) 1531 return false; 1532 1533 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1534 // byte-address are ignored, thus forcing Dword alignment. 1535 // This applies to private, global, and constant memory. 1536 if (IsFast) 1537 *IsFast = true; 1538 1539 return Size >= 32 && Alignment >= Align(4); 1540 } 1541 1542 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1543 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1544 bool *IsFast) const { 1545 if (IsFast) 1546 *IsFast = false; 1547 1548 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1549 // which isn't a simple VT. 1550 // Until MVT is extended to handle this, simply check for the size and 1551 // rely on the condition below: allow accesses if the size is a multiple of 4. 1552 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1553 VT.getStoreSize() > 16)) { 1554 return false; 1555 } 1556 1557 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1558 Alignment, Flags, IsFast); 1559 } 1560 1561 EVT SITargetLowering::getOptimalMemOpType( 1562 const MemOp &Op, const AttributeList &FuncAttributes) const { 1563 // FIXME: Should account for address space here. 1564 1565 // The default fallback uses the private pointer size as a guess for a type to 1566 // use. Make sure we switch these to 64-bit accesses. 1567 1568 if (Op.size() >= 16 && 1569 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1570 return MVT::v4i32; 1571 1572 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1573 return MVT::v2i32; 1574 1575 // Use the default. 1576 return MVT::Other; 1577 } 1578 1579 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1580 const MemSDNode *MemNode = cast<MemSDNode>(N); 1581 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1582 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1583 return I && I->getMetadata("amdgpu.noclobber"); 1584 } 1585 1586 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1587 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1588 AS == AMDGPUAS::PRIVATE_ADDRESS; 1589 } 1590 1591 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1592 unsigned DestAS) const { 1593 // Flat -> private/local is a simple truncate. 1594 // Flat -> global is no-op 1595 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1596 return true; 1597 1598 const GCNTargetMachine &TM = 1599 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1600 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1601 } 1602 1603 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1604 const MemSDNode *MemNode = cast<MemSDNode>(N); 1605 1606 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1607 } 1608 1609 TargetLoweringBase::LegalizeTypeAction 1610 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1611 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1612 VT.getScalarType().bitsLE(MVT::i16)) 1613 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1614 return TargetLoweringBase::getPreferredVectorAction(VT); 1615 } 1616 1617 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1618 Type *Ty) const { 1619 // FIXME: Could be smarter if called for vector constants. 1620 return true; 1621 } 1622 1623 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1624 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1625 switch (Op) { 1626 case ISD::LOAD: 1627 case ISD::STORE: 1628 1629 // These operations are done with 32-bit instructions anyway. 1630 case ISD::AND: 1631 case ISD::OR: 1632 case ISD::XOR: 1633 case ISD::SELECT: 1634 // TODO: Extensions? 1635 return true; 1636 default: 1637 return false; 1638 } 1639 } 1640 1641 // SimplifySetCC uses this function to determine whether or not it should 1642 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1643 if (VT == MVT::i1 && Op == ISD::SETCC) 1644 return false; 1645 1646 return TargetLowering::isTypeDesirableForOp(Op, VT); 1647 } 1648 1649 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1650 const SDLoc &SL, 1651 SDValue Chain, 1652 uint64_t Offset) const { 1653 const DataLayout &DL = DAG.getDataLayout(); 1654 MachineFunction &MF = DAG.getMachineFunction(); 1655 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1656 1657 const ArgDescriptor *InputPtrReg; 1658 const TargetRegisterClass *RC; 1659 LLT ArgTy; 1660 1661 std::tie(InputPtrReg, RC, ArgTy) = 1662 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1663 1664 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1665 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1666 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1667 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1668 1669 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1670 } 1671 1672 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1673 const SDLoc &SL) const { 1674 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1675 FIRST_IMPLICIT); 1676 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1677 } 1678 1679 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1680 const SDLoc &SL, SDValue Val, 1681 bool Signed, 1682 const ISD::InputArg *Arg) const { 1683 // First, if it is a widened vector, narrow it. 1684 if (VT.isVector() && 1685 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1686 EVT NarrowedVT = 1687 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1688 VT.getVectorNumElements()); 1689 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1690 DAG.getConstant(0, SL, MVT::i32)); 1691 } 1692 1693 // Then convert the vector elements or scalar value. 1694 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1695 VT.bitsLT(MemVT)) { 1696 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1697 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1698 } 1699 1700 if (MemVT.isFloatingPoint()) 1701 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1702 else if (Signed) 1703 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1704 else 1705 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1706 1707 return Val; 1708 } 1709 1710 SDValue SITargetLowering::lowerKernargMemParameter( 1711 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1712 uint64_t Offset, Align Alignment, bool Signed, 1713 const ISD::InputArg *Arg) const { 1714 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1715 1716 // Try to avoid using an extload by loading earlier than the argument address, 1717 // and extracting the relevant bits. The load should hopefully be merged with 1718 // the previous argument. 1719 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1720 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1721 int64_t AlignDownOffset = alignDown(Offset, 4); 1722 int64_t OffsetDiff = Offset - AlignDownOffset; 1723 1724 EVT IntVT = MemVT.changeTypeToInteger(); 1725 1726 // TODO: If we passed in the base kernel offset we could have a better 1727 // alignment than 4, but we don't really need it. 1728 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1729 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1730 MachineMemOperand::MODereferenceable | 1731 MachineMemOperand::MOInvariant); 1732 1733 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1734 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1735 1736 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1737 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1738 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1739 1740 1741 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1742 } 1743 1744 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1745 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1746 MachineMemOperand::MODereferenceable | 1747 MachineMemOperand::MOInvariant); 1748 1749 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1750 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1751 } 1752 1753 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1754 const SDLoc &SL, SDValue Chain, 1755 const ISD::InputArg &Arg) const { 1756 MachineFunction &MF = DAG.getMachineFunction(); 1757 MachineFrameInfo &MFI = MF.getFrameInfo(); 1758 1759 if (Arg.Flags.isByVal()) { 1760 unsigned Size = Arg.Flags.getByValSize(); 1761 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1762 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1763 } 1764 1765 unsigned ArgOffset = VA.getLocMemOffset(); 1766 unsigned ArgSize = VA.getValVT().getStoreSize(); 1767 1768 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1769 1770 // Create load nodes to retrieve arguments from the stack. 1771 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1772 SDValue ArgValue; 1773 1774 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1775 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1776 MVT MemVT = VA.getValVT(); 1777 1778 switch (VA.getLocInfo()) { 1779 default: 1780 break; 1781 case CCValAssign::BCvt: 1782 MemVT = VA.getLocVT(); 1783 break; 1784 case CCValAssign::SExt: 1785 ExtType = ISD::SEXTLOAD; 1786 break; 1787 case CCValAssign::ZExt: 1788 ExtType = ISD::ZEXTLOAD; 1789 break; 1790 case CCValAssign::AExt: 1791 ExtType = ISD::EXTLOAD; 1792 break; 1793 } 1794 1795 ArgValue = DAG.getExtLoad( 1796 ExtType, SL, VA.getLocVT(), Chain, FIN, 1797 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1798 MemVT); 1799 return ArgValue; 1800 } 1801 1802 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1803 const SIMachineFunctionInfo &MFI, 1804 EVT VT, 1805 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1806 const ArgDescriptor *Reg; 1807 const TargetRegisterClass *RC; 1808 LLT Ty; 1809 1810 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1811 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1812 } 1813 1814 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1815 CallingConv::ID CallConv, 1816 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1817 FunctionType *FType, 1818 SIMachineFunctionInfo *Info) { 1819 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1820 const ISD::InputArg *Arg = &Ins[I]; 1821 1822 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1823 "vector type argument should have been split"); 1824 1825 // First check if it's a PS input addr. 1826 if (CallConv == CallingConv::AMDGPU_PS && 1827 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1828 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1829 1830 // Inconveniently only the first part of the split is marked as isSplit, 1831 // so skip to the end. We only want to increment PSInputNum once for the 1832 // entire split argument. 1833 if (Arg->Flags.isSplit()) { 1834 while (!Arg->Flags.isSplitEnd()) { 1835 assert((!Arg->VT.isVector() || 1836 Arg->VT.getScalarSizeInBits() == 16) && 1837 "unexpected vector split in ps argument type"); 1838 if (!SkipArg) 1839 Splits.push_back(*Arg); 1840 Arg = &Ins[++I]; 1841 } 1842 } 1843 1844 if (SkipArg) { 1845 // We can safely skip PS inputs. 1846 Skipped.set(Arg->getOrigArgIndex()); 1847 ++PSInputNum; 1848 continue; 1849 } 1850 1851 Info->markPSInputAllocated(PSInputNum); 1852 if (Arg->Used) 1853 Info->markPSInputEnabled(PSInputNum); 1854 1855 ++PSInputNum; 1856 } 1857 1858 Splits.push_back(*Arg); 1859 } 1860 } 1861 1862 // Allocate special inputs passed in VGPRs. 1863 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1864 MachineFunction &MF, 1865 const SIRegisterInfo &TRI, 1866 SIMachineFunctionInfo &Info) const { 1867 const LLT S32 = LLT::scalar(32); 1868 MachineRegisterInfo &MRI = MF.getRegInfo(); 1869 1870 if (Info.hasWorkItemIDX()) { 1871 Register Reg = AMDGPU::VGPR0; 1872 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1873 1874 CCInfo.AllocateReg(Reg); 1875 unsigned Mask = (Subtarget->hasPackedTID() && 1876 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1877 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1878 } 1879 1880 if (Info.hasWorkItemIDY()) { 1881 assert(Info.hasWorkItemIDX()); 1882 if (Subtarget->hasPackedTID()) { 1883 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1884 0x3ff << 10)); 1885 } else { 1886 unsigned Reg = AMDGPU::VGPR1; 1887 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1888 1889 CCInfo.AllocateReg(Reg); 1890 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1891 } 1892 } 1893 1894 if (Info.hasWorkItemIDZ()) { 1895 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1896 if (Subtarget->hasPackedTID()) { 1897 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1898 0x3ff << 20)); 1899 } else { 1900 unsigned Reg = AMDGPU::VGPR2; 1901 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1902 1903 CCInfo.AllocateReg(Reg); 1904 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1905 } 1906 } 1907 } 1908 1909 // Try to allocate a VGPR at the end of the argument list, or if no argument 1910 // VGPRs are left allocating a stack slot. 1911 // If \p Mask is is given it indicates bitfield position in the register. 1912 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1913 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1914 ArgDescriptor Arg = ArgDescriptor()) { 1915 if (Arg.isSet()) 1916 return ArgDescriptor::createArg(Arg, Mask); 1917 1918 ArrayRef<MCPhysReg> ArgVGPRs 1919 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1920 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1921 if (RegIdx == ArgVGPRs.size()) { 1922 // Spill to stack required. 1923 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1924 1925 return ArgDescriptor::createStack(Offset, Mask); 1926 } 1927 1928 unsigned Reg = ArgVGPRs[RegIdx]; 1929 Reg = CCInfo.AllocateReg(Reg); 1930 assert(Reg != AMDGPU::NoRegister); 1931 1932 MachineFunction &MF = CCInfo.getMachineFunction(); 1933 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1934 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1935 return ArgDescriptor::createRegister(Reg, Mask); 1936 } 1937 1938 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1939 const TargetRegisterClass *RC, 1940 unsigned NumArgRegs) { 1941 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1942 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1943 if (RegIdx == ArgSGPRs.size()) 1944 report_fatal_error("ran out of SGPRs for arguments"); 1945 1946 unsigned Reg = ArgSGPRs[RegIdx]; 1947 Reg = CCInfo.AllocateReg(Reg); 1948 assert(Reg != AMDGPU::NoRegister); 1949 1950 MachineFunction &MF = CCInfo.getMachineFunction(); 1951 MF.addLiveIn(Reg, RC); 1952 return ArgDescriptor::createRegister(Reg); 1953 } 1954 1955 // If this has a fixed position, we still should allocate the register in the 1956 // CCInfo state. Technically we could get away with this for values passed 1957 // outside of the normal argument range. 1958 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1959 const TargetRegisterClass *RC, 1960 MCRegister Reg) { 1961 Reg = CCInfo.AllocateReg(Reg); 1962 assert(Reg != AMDGPU::NoRegister); 1963 MachineFunction &MF = CCInfo.getMachineFunction(); 1964 MF.addLiveIn(Reg, RC); 1965 } 1966 1967 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1968 if (Arg) { 1969 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1970 Arg.getRegister()); 1971 } else 1972 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1973 } 1974 1975 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1976 if (Arg) { 1977 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1978 Arg.getRegister()); 1979 } else 1980 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1981 } 1982 1983 /// Allocate implicit function VGPR arguments at the end of allocated user 1984 /// arguments. 1985 void SITargetLowering::allocateSpecialInputVGPRs( 1986 CCState &CCInfo, MachineFunction &MF, 1987 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1988 const unsigned Mask = 0x3ff; 1989 ArgDescriptor Arg; 1990 1991 if (Info.hasWorkItemIDX()) { 1992 Arg = allocateVGPR32Input(CCInfo, Mask); 1993 Info.setWorkItemIDX(Arg); 1994 } 1995 1996 if (Info.hasWorkItemIDY()) { 1997 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1998 Info.setWorkItemIDY(Arg); 1999 } 2000 2001 if (Info.hasWorkItemIDZ()) 2002 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2003 } 2004 2005 /// Allocate implicit function VGPR arguments in fixed registers. 2006 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2007 CCState &CCInfo, MachineFunction &MF, 2008 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2009 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2010 if (!Reg) 2011 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2012 2013 const unsigned Mask = 0x3ff; 2014 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2015 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2016 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2017 } 2018 2019 void SITargetLowering::allocateSpecialInputSGPRs( 2020 CCState &CCInfo, 2021 MachineFunction &MF, 2022 const SIRegisterInfo &TRI, 2023 SIMachineFunctionInfo &Info) const { 2024 auto &ArgInfo = Info.getArgInfo(); 2025 2026 // TODO: Unify handling with private memory pointers. 2027 2028 if (Info.hasDispatchPtr()) 2029 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2030 2031 if (Info.hasQueuePtr()) 2032 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2033 2034 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2035 // constant offset from the kernarg segment. 2036 if (Info.hasImplicitArgPtr()) 2037 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2038 2039 if (Info.hasDispatchID()) 2040 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2041 2042 // flat_scratch_init is not applicable for non-kernel functions. 2043 2044 if (Info.hasWorkGroupIDX()) 2045 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2046 2047 if (Info.hasWorkGroupIDY()) 2048 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2049 2050 if (Info.hasWorkGroupIDZ()) 2051 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2052 } 2053 2054 // Allocate special inputs passed in user SGPRs. 2055 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2056 MachineFunction &MF, 2057 const SIRegisterInfo &TRI, 2058 SIMachineFunctionInfo &Info) const { 2059 if (Info.hasImplicitBufferPtr()) { 2060 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2061 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2062 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2063 } 2064 2065 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2066 if (Info.hasPrivateSegmentBuffer()) { 2067 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2068 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2069 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2070 } 2071 2072 if (Info.hasDispatchPtr()) { 2073 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2074 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2075 CCInfo.AllocateReg(DispatchPtrReg); 2076 } 2077 2078 if (Info.hasQueuePtr()) { 2079 Register QueuePtrReg = Info.addQueuePtr(TRI); 2080 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2081 CCInfo.AllocateReg(QueuePtrReg); 2082 } 2083 2084 if (Info.hasKernargSegmentPtr()) { 2085 MachineRegisterInfo &MRI = MF.getRegInfo(); 2086 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2087 CCInfo.AllocateReg(InputPtrReg); 2088 2089 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2090 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2091 } 2092 2093 if (Info.hasDispatchID()) { 2094 Register DispatchIDReg = Info.addDispatchID(TRI); 2095 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2096 CCInfo.AllocateReg(DispatchIDReg); 2097 } 2098 2099 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2100 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2101 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2102 CCInfo.AllocateReg(FlatScratchInitReg); 2103 } 2104 2105 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2106 // these from the dispatch pointer. 2107 } 2108 2109 // Allocate special input registers that are initialized per-wave. 2110 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2111 MachineFunction &MF, 2112 SIMachineFunctionInfo &Info, 2113 CallingConv::ID CallConv, 2114 bool IsShader) const { 2115 if (Info.hasWorkGroupIDX()) { 2116 Register Reg = Info.addWorkGroupIDX(); 2117 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2118 CCInfo.AllocateReg(Reg); 2119 } 2120 2121 if (Info.hasWorkGroupIDY()) { 2122 Register Reg = Info.addWorkGroupIDY(); 2123 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2124 CCInfo.AllocateReg(Reg); 2125 } 2126 2127 if (Info.hasWorkGroupIDZ()) { 2128 Register Reg = Info.addWorkGroupIDZ(); 2129 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2130 CCInfo.AllocateReg(Reg); 2131 } 2132 2133 if (Info.hasWorkGroupInfo()) { 2134 Register Reg = Info.addWorkGroupInfo(); 2135 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2136 CCInfo.AllocateReg(Reg); 2137 } 2138 2139 if (Info.hasPrivateSegmentWaveByteOffset()) { 2140 // Scratch wave offset passed in system SGPR. 2141 unsigned PrivateSegmentWaveByteOffsetReg; 2142 2143 if (IsShader) { 2144 PrivateSegmentWaveByteOffsetReg = 2145 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2146 2147 // This is true if the scratch wave byte offset doesn't have a fixed 2148 // location. 2149 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2150 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2151 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2152 } 2153 } else 2154 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2155 2156 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2157 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2158 } 2159 } 2160 2161 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2162 MachineFunction &MF, 2163 const SIRegisterInfo &TRI, 2164 SIMachineFunctionInfo &Info) { 2165 // Now that we've figured out where the scratch register inputs are, see if 2166 // should reserve the arguments and use them directly. 2167 MachineFrameInfo &MFI = MF.getFrameInfo(); 2168 bool HasStackObjects = MFI.hasStackObjects(); 2169 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2170 2171 // Record that we know we have non-spill stack objects so we don't need to 2172 // check all stack objects later. 2173 if (HasStackObjects) 2174 Info.setHasNonSpillStackObjects(true); 2175 2176 // Everything live out of a block is spilled with fast regalloc, so it's 2177 // almost certain that spilling will be required. 2178 if (TM.getOptLevel() == CodeGenOpt::None) 2179 HasStackObjects = true; 2180 2181 // For now assume stack access is needed in any callee functions, so we need 2182 // the scratch registers to pass in. 2183 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2184 2185 if (!ST.enableFlatScratch()) { 2186 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2187 // If we have stack objects, we unquestionably need the private buffer 2188 // resource. For the Code Object V2 ABI, this will be the first 4 user 2189 // SGPR inputs. We can reserve those and use them directly. 2190 2191 Register PrivateSegmentBufferReg = 2192 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2193 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2194 } else { 2195 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2196 // We tentatively reserve the last registers (skipping the last registers 2197 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2198 // we'll replace these with the ones immediately after those which were 2199 // really allocated. In the prologue copies will be inserted from the 2200 // argument to these reserved registers. 2201 2202 // Without HSA, relocations are used for the scratch pointer and the 2203 // buffer resource setup is always inserted in the prologue. Scratch wave 2204 // offset is still in an input SGPR. 2205 Info.setScratchRSrcReg(ReservedBufferReg); 2206 } 2207 } 2208 2209 MachineRegisterInfo &MRI = MF.getRegInfo(); 2210 2211 // For entry functions we have to set up the stack pointer if we use it, 2212 // whereas non-entry functions get this "for free". This means there is no 2213 // intrinsic advantage to using S32 over S34 in cases where we do not have 2214 // calls but do need a frame pointer (i.e. if we are requested to have one 2215 // because frame pointer elimination is disabled). To keep things simple we 2216 // only ever use S32 as the call ABI stack pointer, and so using it does not 2217 // imply we need a separate frame pointer. 2218 // 2219 // Try to use s32 as the SP, but move it if it would interfere with input 2220 // arguments. This won't work with calls though. 2221 // 2222 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2223 // registers. 2224 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2225 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2226 } else { 2227 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2228 2229 if (MFI.hasCalls()) 2230 report_fatal_error("call in graphics shader with too many input SGPRs"); 2231 2232 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2233 if (!MRI.isLiveIn(Reg)) { 2234 Info.setStackPtrOffsetReg(Reg); 2235 break; 2236 } 2237 } 2238 2239 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2240 report_fatal_error("failed to find register for SP"); 2241 } 2242 2243 // hasFP should be accurate for entry functions even before the frame is 2244 // finalized, because it does not rely on the known stack size, only 2245 // properties like whether variable sized objects are present. 2246 if (ST.getFrameLowering()->hasFP(MF)) { 2247 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2248 } 2249 } 2250 2251 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2252 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2253 return !Info->isEntryFunction(); 2254 } 2255 2256 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2257 2258 } 2259 2260 void SITargetLowering::insertCopiesSplitCSR( 2261 MachineBasicBlock *Entry, 2262 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2263 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2264 2265 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2266 if (!IStart) 2267 return; 2268 2269 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2270 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2271 MachineBasicBlock::iterator MBBI = Entry->begin(); 2272 for (const MCPhysReg *I = IStart; *I; ++I) { 2273 const TargetRegisterClass *RC = nullptr; 2274 if (AMDGPU::SReg_64RegClass.contains(*I)) 2275 RC = &AMDGPU::SGPR_64RegClass; 2276 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2277 RC = &AMDGPU::SGPR_32RegClass; 2278 else 2279 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2280 2281 Register NewVR = MRI->createVirtualRegister(RC); 2282 // Create copy from CSR to a virtual register. 2283 Entry->addLiveIn(*I); 2284 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2285 .addReg(*I); 2286 2287 // Insert the copy-back instructions right before the terminator. 2288 for (auto *Exit : Exits) 2289 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2290 TII->get(TargetOpcode::COPY), *I) 2291 .addReg(NewVR); 2292 } 2293 } 2294 2295 SDValue SITargetLowering::LowerFormalArguments( 2296 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2297 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2298 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2299 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2300 2301 MachineFunction &MF = DAG.getMachineFunction(); 2302 const Function &Fn = MF.getFunction(); 2303 FunctionType *FType = MF.getFunction().getFunctionType(); 2304 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2305 2306 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2307 DiagnosticInfoUnsupported NoGraphicsHSA( 2308 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2309 DAG.getContext()->diagnose(NoGraphicsHSA); 2310 return DAG.getEntryNode(); 2311 } 2312 2313 Info->allocateModuleLDSGlobal(Fn.getParent()); 2314 2315 SmallVector<ISD::InputArg, 16> Splits; 2316 SmallVector<CCValAssign, 16> ArgLocs; 2317 BitVector Skipped(Ins.size()); 2318 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2319 *DAG.getContext()); 2320 2321 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2322 bool IsKernel = AMDGPU::isKernel(CallConv); 2323 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2324 2325 if (IsGraphics) { 2326 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2327 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2328 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2329 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2330 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2331 !Info->hasWorkItemIDZ()); 2332 } 2333 2334 if (CallConv == CallingConv::AMDGPU_PS) { 2335 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2336 2337 // At least one interpolation mode must be enabled or else the GPU will 2338 // hang. 2339 // 2340 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2341 // set PSInputAddr, the user wants to enable some bits after the compilation 2342 // based on run-time states. Since we can't know what the final PSInputEna 2343 // will look like, so we shouldn't do anything here and the user should take 2344 // responsibility for the correct programming. 2345 // 2346 // Otherwise, the following restrictions apply: 2347 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2348 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2349 // enabled too. 2350 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2351 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2352 CCInfo.AllocateReg(AMDGPU::VGPR0); 2353 CCInfo.AllocateReg(AMDGPU::VGPR1); 2354 Info->markPSInputAllocated(0); 2355 Info->markPSInputEnabled(0); 2356 } 2357 if (Subtarget->isAmdPalOS()) { 2358 // For isAmdPalOS, the user does not enable some bits after compilation 2359 // based on run-time states; the register values being generated here are 2360 // the final ones set in hardware. Therefore we need to apply the 2361 // workaround to PSInputAddr and PSInputEnable together. (The case where 2362 // a bit is set in PSInputAddr but not PSInputEnable is where the 2363 // frontend set up an input arg for a particular interpolation mode, but 2364 // nothing uses that input arg. Really we should have an earlier pass 2365 // that removes such an arg.) 2366 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2367 if ((PsInputBits & 0x7F) == 0 || 2368 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2369 Info->markPSInputEnabled( 2370 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2371 } 2372 } else if (IsKernel) { 2373 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2374 } else { 2375 Splits.append(Ins.begin(), Ins.end()); 2376 } 2377 2378 if (IsEntryFunc) { 2379 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2380 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2381 } else { 2382 // For the fixed ABI, pass workitem IDs in the last argument register. 2383 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2384 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2385 } 2386 2387 if (IsKernel) { 2388 analyzeFormalArgumentsCompute(CCInfo, Ins); 2389 } else { 2390 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2391 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2392 } 2393 2394 SmallVector<SDValue, 16> Chains; 2395 2396 // FIXME: This is the minimum kernel argument alignment. We should improve 2397 // this to the maximum alignment of the arguments. 2398 // 2399 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2400 // kern arg offset. 2401 const Align KernelArgBaseAlign = Align(16); 2402 2403 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2404 const ISD::InputArg &Arg = Ins[i]; 2405 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2406 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2407 continue; 2408 } 2409 2410 CCValAssign &VA = ArgLocs[ArgIdx++]; 2411 MVT VT = VA.getLocVT(); 2412 2413 if (IsEntryFunc && VA.isMemLoc()) { 2414 VT = Ins[i].VT; 2415 EVT MemVT = VA.getLocVT(); 2416 2417 const uint64_t Offset = VA.getLocMemOffset(); 2418 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2419 2420 if (Arg.Flags.isByRef()) { 2421 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2422 2423 const GCNTargetMachine &TM = 2424 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2425 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2426 Arg.Flags.getPointerAddrSpace())) { 2427 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2428 Arg.Flags.getPointerAddrSpace()); 2429 } 2430 2431 InVals.push_back(Ptr); 2432 continue; 2433 } 2434 2435 SDValue Arg = lowerKernargMemParameter( 2436 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2437 Chains.push_back(Arg.getValue(1)); 2438 2439 auto *ParamTy = 2440 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2441 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2442 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2443 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2444 // On SI local pointers are just offsets into LDS, so they are always 2445 // less than 16-bits. On CI and newer they could potentially be 2446 // real pointers, so we can't guarantee their size. 2447 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2448 DAG.getValueType(MVT::i16)); 2449 } 2450 2451 InVals.push_back(Arg); 2452 continue; 2453 } else if (!IsEntryFunc && VA.isMemLoc()) { 2454 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2455 InVals.push_back(Val); 2456 if (!Arg.Flags.isByVal()) 2457 Chains.push_back(Val.getValue(1)); 2458 continue; 2459 } 2460 2461 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2462 2463 Register Reg = VA.getLocReg(); 2464 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2465 EVT ValVT = VA.getValVT(); 2466 2467 Reg = MF.addLiveIn(Reg, RC); 2468 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2469 2470 if (Arg.Flags.isSRet()) { 2471 // The return object should be reasonably addressable. 2472 2473 // FIXME: This helps when the return is a real sret. If it is a 2474 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2475 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2476 unsigned NumBits 2477 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2478 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2479 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2480 } 2481 2482 // If this is an 8 or 16-bit value, it is really passed promoted 2483 // to 32 bits. Insert an assert[sz]ext to capture this, then 2484 // truncate to the right size. 2485 switch (VA.getLocInfo()) { 2486 case CCValAssign::Full: 2487 break; 2488 case CCValAssign::BCvt: 2489 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2490 break; 2491 case CCValAssign::SExt: 2492 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2493 DAG.getValueType(ValVT)); 2494 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2495 break; 2496 case CCValAssign::ZExt: 2497 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2498 DAG.getValueType(ValVT)); 2499 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2500 break; 2501 case CCValAssign::AExt: 2502 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2503 break; 2504 default: 2505 llvm_unreachable("Unknown loc info!"); 2506 } 2507 2508 InVals.push_back(Val); 2509 } 2510 2511 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2512 // Special inputs come after user arguments. 2513 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2514 } 2515 2516 // Start adding system SGPRs. 2517 if (IsEntryFunc) { 2518 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2519 } else { 2520 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2521 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2522 } 2523 2524 auto &ArgUsageInfo = 2525 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2526 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2527 2528 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2529 Info->setBytesInStackArgArea(StackArgSize); 2530 2531 return Chains.empty() ? Chain : 2532 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2533 } 2534 2535 // TODO: If return values can't fit in registers, we should return as many as 2536 // possible in registers before passing on stack. 2537 bool SITargetLowering::CanLowerReturn( 2538 CallingConv::ID CallConv, 2539 MachineFunction &MF, bool IsVarArg, 2540 const SmallVectorImpl<ISD::OutputArg> &Outs, 2541 LLVMContext &Context) const { 2542 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2543 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2544 // for shaders. Vector types should be explicitly handled by CC. 2545 if (AMDGPU::isEntryFunctionCC(CallConv)) 2546 return true; 2547 2548 SmallVector<CCValAssign, 16> RVLocs; 2549 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2550 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2551 } 2552 2553 SDValue 2554 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2555 bool isVarArg, 2556 const SmallVectorImpl<ISD::OutputArg> &Outs, 2557 const SmallVectorImpl<SDValue> &OutVals, 2558 const SDLoc &DL, SelectionDAG &DAG) const { 2559 MachineFunction &MF = DAG.getMachineFunction(); 2560 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2561 2562 if (AMDGPU::isKernel(CallConv)) { 2563 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2564 OutVals, DL, DAG); 2565 } 2566 2567 bool IsShader = AMDGPU::isShader(CallConv); 2568 2569 Info->setIfReturnsVoid(Outs.empty()); 2570 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2571 2572 // CCValAssign - represent the assignment of the return value to a location. 2573 SmallVector<CCValAssign, 48> RVLocs; 2574 SmallVector<ISD::OutputArg, 48> Splits; 2575 2576 // CCState - Info about the registers and stack slots. 2577 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2578 *DAG.getContext()); 2579 2580 // Analyze outgoing return values. 2581 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2582 2583 SDValue Flag; 2584 SmallVector<SDValue, 48> RetOps; 2585 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2586 2587 // Add return address for callable functions. 2588 if (!Info->isEntryFunction()) { 2589 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2590 SDValue ReturnAddrReg = CreateLiveInRegister( 2591 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2592 2593 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2594 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2595 MVT::i64); 2596 Chain = 2597 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2598 Flag = Chain.getValue(1); 2599 RetOps.push_back(ReturnAddrVirtualReg); 2600 } 2601 2602 // Copy the result values into the output registers. 2603 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2604 ++I, ++RealRVLocIdx) { 2605 CCValAssign &VA = RVLocs[I]; 2606 assert(VA.isRegLoc() && "Can only return in registers!"); 2607 // TODO: Partially return in registers if return values don't fit. 2608 SDValue Arg = OutVals[RealRVLocIdx]; 2609 2610 // Copied from other backends. 2611 switch (VA.getLocInfo()) { 2612 case CCValAssign::Full: 2613 break; 2614 case CCValAssign::BCvt: 2615 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2616 break; 2617 case CCValAssign::SExt: 2618 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2619 break; 2620 case CCValAssign::ZExt: 2621 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2622 break; 2623 case CCValAssign::AExt: 2624 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2625 break; 2626 default: 2627 llvm_unreachable("Unknown loc info!"); 2628 } 2629 2630 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2631 Flag = Chain.getValue(1); 2632 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2633 } 2634 2635 // FIXME: Does sret work properly? 2636 if (!Info->isEntryFunction()) { 2637 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2638 const MCPhysReg *I = 2639 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2640 if (I) { 2641 for (; *I; ++I) { 2642 if (AMDGPU::SReg_64RegClass.contains(*I)) 2643 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2644 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2645 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2646 else 2647 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2648 } 2649 } 2650 } 2651 2652 // Update chain and glue. 2653 RetOps[0] = Chain; 2654 if (Flag.getNode()) 2655 RetOps.push_back(Flag); 2656 2657 unsigned Opc = AMDGPUISD::ENDPGM; 2658 if (!IsWaveEnd) 2659 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2660 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2661 } 2662 2663 SDValue SITargetLowering::LowerCallResult( 2664 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2665 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2666 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2667 SDValue ThisVal) const { 2668 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2669 2670 // Assign locations to each value returned by this call. 2671 SmallVector<CCValAssign, 16> RVLocs; 2672 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2673 *DAG.getContext()); 2674 CCInfo.AnalyzeCallResult(Ins, RetCC); 2675 2676 // Copy all of the result registers out of their specified physreg. 2677 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2678 CCValAssign VA = RVLocs[i]; 2679 SDValue Val; 2680 2681 if (VA.isRegLoc()) { 2682 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2683 Chain = Val.getValue(1); 2684 InFlag = Val.getValue(2); 2685 } else if (VA.isMemLoc()) { 2686 report_fatal_error("TODO: return values in memory"); 2687 } else 2688 llvm_unreachable("unknown argument location type"); 2689 2690 switch (VA.getLocInfo()) { 2691 case CCValAssign::Full: 2692 break; 2693 case CCValAssign::BCvt: 2694 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2695 break; 2696 case CCValAssign::ZExt: 2697 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2698 DAG.getValueType(VA.getValVT())); 2699 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2700 break; 2701 case CCValAssign::SExt: 2702 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2703 DAG.getValueType(VA.getValVT())); 2704 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2705 break; 2706 case CCValAssign::AExt: 2707 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2708 break; 2709 default: 2710 llvm_unreachable("Unknown loc info!"); 2711 } 2712 2713 InVals.push_back(Val); 2714 } 2715 2716 return Chain; 2717 } 2718 2719 // Add code to pass special inputs required depending on used features separate 2720 // from the explicit user arguments present in the IR. 2721 void SITargetLowering::passSpecialInputs( 2722 CallLoweringInfo &CLI, 2723 CCState &CCInfo, 2724 const SIMachineFunctionInfo &Info, 2725 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2726 SmallVectorImpl<SDValue> &MemOpChains, 2727 SDValue Chain) const { 2728 // If we don't have a call site, this was a call inserted by 2729 // legalization. These can never use special inputs. 2730 if (!CLI.CB) 2731 return; 2732 2733 SelectionDAG &DAG = CLI.DAG; 2734 const SDLoc &DL = CLI.DL; 2735 2736 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2737 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2738 2739 const AMDGPUFunctionArgInfo *CalleeArgInfo 2740 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2741 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2742 auto &ArgUsageInfo = 2743 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2744 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2745 } 2746 2747 // TODO: Unify with private memory register handling. This is complicated by 2748 // the fact that at least in kernels, the input argument is not necessarily 2749 // in the same location as the input. 2750 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2751 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2752 AMDGPUFunctionArgInfo::QUEUE_PTR, 2753 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2754 AMDGPUFunctionArgInfo::DISPATCH_ID, 2755 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2756 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2757 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2758 }; 2759 2760 for (auto InputID : InputRegs) { 2761 const ArgDescriptor *OutgoingArg; 2762 const TargetRegisterClass *ArgRC; 2763 LLT ArgTy; 2764 2765 std::tie(OutgoingArg, ArgRC, ArgTy) = 2766 CalleeArgInfo->getPreloadedValue(InputID); 2767 if (!OutgoingArg) 2768 continue; 2769 2770 const ArgDescriptor *IncomingArg; 2771 const TargetRegisterClass *IncomingArgRC; 2772 LLT Ty; 2773 std::tie(IncomingArg, IncomingArgRC, Ty) = 2774 CallerArgInfo.getPreloadedValue(InputID); 2775 assert(IncomingArgRC == ArgRC); 2776 2777 // All special arguments are ints for now. 2778 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2779 SDValue InputReg; 2780 2781 if (IncomingArg) { 2782 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2783 } else { 2784 // The implicit arg ptr is special because it doesn't have a corresponding 2785 // input for kernels, and is computed from the kernarg segment pointer. 2786 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2787 InputReg = getImplicitArgPtr(DAG, DL); 2788 } 2789 2790 if (OutgoingArg->isRegister()) { 2791 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2792 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2793 report_fatal_error("failed to allocate implicit input argument"); 2794 } else { 2795 unsigned SpecialArgOffset = 2796 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2797 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2798 SpecialArgOffset); 2799 MemOpChains.push_back(ArgStore); 2800 } 2801 } 2802 2803 // Pack workitem IDs into a single register or pass it as is if already 2804 // packed. 2805 const ArgDescriptor *OutgoingArg; 2806 const TargetRegisterClass *ArgRC; 2807 LLT Ty; 2808 2809 std::tie(OutgoingArg, ArgRC, Ty) = 2810 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2811 if (!OutgoingArg) 2812 std::tie(OutgoingArg, ArgRC, Ty) = 2813 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2814 if (!OutgoingArg) 2815 std::tie(OutgoingArg, ArgRC, Ty) = 2816 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2817 if (!OutgoingArg) 2818 return; 2819 2820 const ArgDescriptor *IncomingArgX = std::get<0>( 2821 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2822 const ArgDescriptor *IncomingArgY = std::get<0>( 2823 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2824 const ArgDescriptor *IncomingArgZ = std::get<0>( 2825 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2826 2827 SDValue InputReg; 2828 SDLoc SL; 2829 2830 // If incoming ids are not packed we need to pack them. 2831 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2832 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2833 2834 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2835 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2836 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2837 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2838 InputReg = InputReg.getNode() ? 2839 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2840 } 2841 2842 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2843 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2844 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2845 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2846 InputReg = InputReg.getNode() ? 2847 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2848 } 2849 2850 if (!InputReg.getNode()) { 2851 // Workitem ids are already packed, any of present incoming arguments 2852 // will carry all required fields. 2853 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2854 IncomingArgX ? *IncomingArgX : 2855 IncomingArgY ? *IncomingArgY : 2856 *IncomingArgZ, ~0u); 2857 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2858 } 2859 2860 if (OutgoingArg->isRegister()) { 2861 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2862 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2863 } else { 2864 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2865 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2866 SpecialArgOffset); 2867 MemOpChains.push_back(ArgStore); 2868 } 2869 } 2870 2871 static bool canGuaranteeTCO(CallingConv::ID CC) { 2872 return CC == CallingConv::Fast; 2873 } 2874 2875 /// Return true if we might ever do TCO for calls with this calling convention. 2876 static bool mayTailCallThisCC(CallingConv::ID CC) { 2877 switch (CC) { 2878 case CallingConv::C: 2879 case CallingConv::AMDGPU_Gfx: 2880 return true; 2881 default: 2882 return canGuaranteeTCO(CC); 2883 } 2884 } 2885 2886 bool SITargetLowering::isEligibleForTailCallOptimization( 2887 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2888 const SmallVectorImpl<ISD::OutputArg> &Outs, 2889 const SmallVectorImpl<SDValue> &OutVals, 2890 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2891 if (!mayTailCallThisCC(CalleeCC)) 2892 return false; 2893 2894 // For a divergent call target, we need to do a waterfall loop over the 2895 // possible callees which precludes us from using a simple jump. 2896 if (Callee->isDivergent()) 2897 return false; 2898 2899 MachineFunction &MF = DAG.getMachineFunction(); 2900 const Function &CallerF = MF.getFunction(); 2901 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2902 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2903 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2904 2905 // Kernels aren't callable, and don't have a live in return address so it 2906 // doesn't make sense to do a tail call with entry functions. 2907 if (!CallerPreserved) 2908 return false; 2909 2910 bool CCMatch = CallerCC == CalleeCC; 2911 2912 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2913 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2914 return true; 2915 return false; 2916 } 2917 2918 // TODO: Can we handle var args? 2919 if (IsVarArg) 2920 return false; 2921 2922 for (const Argument &Arg : CallerF.args()) { 2923 if (Arg.hasByValAttr()) 2924 return false; 2925 } 2926 2927 LLVMContext &Ctx = *DAG.getContext(); 2928 2929 // Check that the call results are passed in the same way. 2930 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2931 CCAssignFnForCall(CalleeCC, IsVarArg), 2932 CCAssignFnForCall(CallerCC, IsVarArg))) 2933 return false; 2934 2935 // The callee has to preserve all registers the caller needs to preserve. 2936 if (!CCMatch) { 2937 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2938 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2939 return false; 2940 } 2941 2942 // Nothing more to check if the callee is taking no arguments. 2943 if (Outs.empty()) 2944 return true; 2945 2946 SmallVector<CCValAssign, 16> ArgLocs; 2947 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2948 2949 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2950 2951 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2952 // If the stack arguments for this call do not fit into our own save area then 2953 // the call cannot be made tail. 2954 // TODO: Is this really necessary? 2955 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2956 return false; 2957 2958 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2959 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2960 } 2961 2962 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2963 if (!CI->isTailCall()) 2964 return false; 2965 2966 const Function *ParentFn = CI->getParent()->getParent(); 2967 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2968 return false; 2969 return true; 2970 } 2971 2972 // The wave scratch offset register is used as the global base pointer. 2973 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2974 SmallVectorImpl<SDValue> &InVals) const { 2975 SelectionDAG &DAG = CLI.DAG; 2976 const SDLoc &DL = CLI.DL; 2977 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2978 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2979 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2980 SDValue Chain = CLI.Chain; 2981 SDValue Callee = CLI.Callee; 2982 bool &IsTailCall = CLI.IsTailCall; 2983 CallingConv::ID CallConv = CLI.CallConv; 2984 bool IsVarArg = CLI.IsVarArg; 2985 bool IsSibCall = false; 2986 bool IsThisReturn = false; 2987 MachineFunction &MF = DAG.getMachineFunction(); 2988 2989 if (Callee.isUndef() || isNullConstant(Callee)) { 2990 if (!CLI.IsTailCall) { 2991 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2992 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2993 } 2994 2995 return Chain; 2996 } 2997 2998 if (IsVarArg) { 2999 return lowerUnhandledCall(CLI, InVals, 3000 "unsupported call to variadic function "); 3001 } 3002 3003 if (!CLI.CB) 3004 report_fatal_error("unsupported libcall legalization"); 3005 3006 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3007 return lowerUnhandledCall(CLI, InVals, 3008 "unsupported required tail call to function "); 3009 } 3010 3011 if (AMDGPU::isShader(CallConv)) { 3012 // Note the issue is with the CC of the called function, not of the call 3013 // itself. 3014 return lowerUnhandledCall(CLI, InVals, 3015 "unsupported call to a shader function "); 3016 } 3017 3018 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3019 CallConv != CallingConv::AMDGPU_Gfx) { 3020 // Only allow calls with specific calling conventions. 3021 return lowerUnhandledCall(CLI, InVals, 3022 "unsupported calling convention for call from " 3023 "graphics shader of function "); 3024 } 3025 3026 if (IsTailCall) { 3027 IsTailCall = isEligibleForTailCallOptimization( 3028 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3029 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3030 report_fatal_error("failed to perform tail call elimination on a call " 3031 "site marked musttail"); 3032 } 3033 3034 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3035 3036 // A sibling call is one where we're under the usual C ABI and not planning 3037 // to change that but can still do a tail call: 3038 if (!TailCallOpt && IsTailCall) 3039 IsSibCall = true; 3040 3041 if (IsTailCall) 3042 ++NumTailCalls; 3043 } 3044 3045 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3046 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3047 SmallVector<SDValue, 8> MemOpChains; 3048 3049 // Analyze operands of the call, assigning locations to each operand. 3050 SmallVector<CCValAssign, 16> ArgLocs; 3051 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3052 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3053 3054 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3055 CallConv != CallingConv::AMDGPU_Gfx) { 3056 // With a fixed ABI, allocate fixed registers before user arguments. 3057 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3058 } 3059 3060 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3061 3062 // Get a count of how many bytes are to be pushed on the stack. 3063 unsigned NumBytes = CCInfo.getNextStackOffset(); 3064 3065 if (IsSibCall) { 3066 // Since we're not changing the ABI to make this a tail call, the memory 3067 // operands are already available in the caller's incoming argument space. 3068 NumBytes = 0; 3069 } 3070 3071 // FPDiff is the byte offset of the call's argument area from the callee's. 3072 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3073 // by this amount for a tail call. In a sibling call it must be 0 because the 3074 // caller will deallocate the entire stack and the callee still expects its 3075 // arguments to begin at SP+0. Completely unused for non-tail calls. 3076 int32_t FPDiff = 0; 3077 MachineFrameInfo &MFI = MF.getFrameInfo(); 3078 3079 // Adjust the stack pointer for the new arguments... 3080 // These operations are automatically eliminated by the prolog/epilog pass 3081 if (!IsSibCall) { 3082 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3083 3084 if (!Subtarget->enableFlatScratch()) { 3085 SmallVector<SDValue, 4> CopyFromChains; 3086 3087 // In the HSA case, this should be an identity copy. 3088 SDValue ScratchRSrcReg 3089 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3090 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3091 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3092 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3093 } 3094 } 3095 3096 MVT PtrVT = MVT::i32; 3097 3098 // Walk the register/memloc assignments, inserting copies/loads. 3099 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3100 CCValAssign &VA = ArgLocs[i]; 3101 SDValue Arg = OutVals[i]; 3102 3103 // Promote the value if needed. 3104 switch (VA.getLocInfo()) { 3105 case CCValAssign::Full: 3106 break; 3107 case CCValAssign::BCvt: 3108 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3109 break; 3110 case CCValAssign::ZExt: 3111 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3112 break; 3113 case CCValAssign::SExt: 3114 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3115 break; 3116 case CCValAssign::AExt: 3117 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3118 break; 3119 case CCValAssign::FPExt: 3120 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3121 break; 3122 default: 3123 llvm_unreachable("Unknown loc info!"); 3124 } 3125 3126 if (VA.isRegLoc()) { 3127 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3128 } else { 3129 assert(VA.isMemLoc()); 3130 3131 SDValue DstAddr; 3132 MachinePointerInfo DstInfo; 3133 3134 unsigned LocMemOffset = VA.getLocMemOffset(); 3135 int32_t Offset = LocMemOffset; 3136 3137 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3138 MaybeAlign Alignment; 3139 3140 if (IsTailCall) { 3141 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3142 unsigned OpSize = Flags.isByVal() ? 3143 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3144 3145 // FIXME: We can have better than the minimum byval required alignment. 3146 Alignment = 3147 Flags.isByVal() 3148 ? Flags.getNonZeroByValAlign() 3149 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3150 3151 Offset = Offset + FPDiff; 3152 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3153 3154 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3155 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3156 3157 // Make sure any stack arguments overlapping with where we're storing 3158 // are loaded before this eventual operation. Otherwise they'll be 3159 // clobbered. 3160 3161 // FIXME: Why is this really necessary? This seems to just result in a 3162 // lot of code to copy the stack and write them back to the same 3163 // locations, which are supposed to be immutable? 3164 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3165 } else { 3166 // Stores to the argument stack area are relative to the stack pointer. 3167 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3168 MVT::i32); 3169 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3170 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3171 Alignment = 3172 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3173 } 3174 3175 if (Outs[i].Flags.isByVal()) { 3176 SDValue SizeNode = 3177 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3178 SDValue Cpy = 3179 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3180 Outs[i].Flags.getNonZeroByValAlign(), 3181 /*isVol = */ false, /*AlwaysInline = */ true, 3182 /*isTailCall = */ false, DstInfo, 3183 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3184 3185 MemOpChains.push_back(Cpy); 3186 } else { 3187 SDValue Store = 3188 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3189 MemOpChains.push_back(Store); 3190 } 3191 } 3192 } 3193 3194 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3195 CallConv != CallingConv::AMDGPU_Gfx) { 3196 // Copy special input registers after user input arguments. 3197 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3198 } 3199 3200 if (!MemOpChains.empty()) 3201 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3202 3203 // Build a sequence of copy-to-reg nodes chained together with token chain 3204 // and flag operands which copy the outgoing args into the appropriate regs. 3205 SDValue InFlag; 3206 for (auto &RegToPass : RegsToPass) { 3207 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3208 RegToPass.second, InFlag); 3209 InFlag = Chain.getValue(1); 3210 } 3211 3212 3213 SDValue PhysReturnAddrReg; 3214 if (IsTailCall) { 3215 // Since the return is being combined with the call, we need to pass on the 3216 // return address. 3217 3218 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3219 SDValue ReturnAddrReg = CreateLiveInRegister( 3220 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3221 3222 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3223 MVT::i64); 3224 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3225 InFlag = Chain.getValue(1); 3226 } 3227 3228 // We don't usually want to end the call-sequence here because we would tidy 3229 // the frame up *after* the call, however in the ABI-changing tail-call case 3230 // we've carefully laid out the parameters so that when sp is reset they'll be 3231 // in the correct location. 3232 if (IsTailCall && !IsSibCall) { 3233 Chain = DAG.getCALLSEQ_END(Chain, 3234 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3235 DAG.getTargetConstant(0, DL, MVT::i32), 3236 InFlag, DL); 3237 InFlag = Chain.getValue(1); 3238 } 3239 3240 std::vector<SDValue> Ops; 3241 Ops.push_back(Chain); 3242 Ops.push_back(Callee); 3243 // Add a redundant copy of the callee global which will not be legalized, as 3244 // we need direct access to the callee later. 3245 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3246 const GlobalValue *GV = GSD->getGlobal(); 3247 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3248 } else { 3249 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3250 } 3251 3252 if (IsTailCall) { 3253 // Each tail call may have to adjust the stack by a different amount, so 3254 // this information must travel along with the operation for eventual 3255 // consumption by emitEpilogue. 3256 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3257 3258 Ops.push_back(PhysReturnAddrReg); 3259 } 3260 3261 // Add argument registers to the end of the list so that they are known live 3262 // into the call. 3263 for (auto &RegToPass : RegsToPass) { 3264 Ops.push_back(DAG.getRegister(RegToPass.first, 3265 RegToPass.second.getValueType())); 3266 } 3267 3268 // Add a register mask operand representing the call-preserved registers. 3269 3270 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3271 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3272 assert(Mask && "Missing call preserved mask for calling convention"); 3273 Ops.push_back(DAG.getRegisterMask(Mask)); 3274 3275 if (InFlag.getNode()) 3276 Ops.push_back(InFlag); 3277 3278 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3279 3280 // If we're doing a tall call, use a TC_RETURN here rather than an 3281 // actual call instruction. 3282 if (IsTailCall) { 3283 MFI.setHasTailCall(); 3284 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3285 } 3286 3287 // Returns a chain and a flag for retval copy to use. 3288 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3289 Chain = Call.getValue(0); 3290 InFlag = Call.getValue(1); 3291 3292 uint64_t CalleePopBytes = NumBytes; 3293 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3294 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3295 InFlag, DL); 3296 if (!Ins.empty()) 3297 InFlag = Chain.getValue(1); 3298 3299 // Handle result values, copying them out of physregs into vregs that we 3300 // return. 3301 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3302 InVals, IsThisReturn, 3303 IsThisReturn ? OutVals[0] : SDValue()); 3304 } 3305 3306 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3307 // except for applying the wave size scale to the increment amount. 3308 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3309 SDValue Op, SelectionDAG &DAG) const { 3310 const MachineFunction &MF = DAG.getMachineFunction(); 3311 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3312 3313 SDLoc dl(Op); 3314 EVT VT = Op.getValueType(); 3315 SDValue Tmp1 = Op; 3316 SDValue Tmp2 = Op.getValue(1); 3317 SDValue Tmp3 = Op.getOperand(2); 3318 SDValue Chain = Tmp1.getOperand(0); 3319 3320 Register SPReg = Info->getStackPtrOffsetReg(); 3321 3322 // Chain the dynamic stack allocation so that it doesn't modify the stack 3323 // pointer when other instructions are using the stack. 3324 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3325 3326 SDValue Size = Tmp2.getOperand(1); 3327 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3328 Chain = SP.getValue(1); 3329 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3330 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3331 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3332 unsigned Opc = 3333 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3334 ISD::ADD : ISD::SUB; 3335 3336 SDValue ScaledSize = DAG.getNode( 3337 ISD::SHL, dl, VT, Size, 3338 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3339 3340 Align StackAlign = TFL->getStackAlign(); 3341 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3342 if (Alignment && *Alignment > StackAlign) { 3343 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3344 DAG.getConstant(-(uint64_t)Alignment->value() 3345 << ST.getWavefrontSizeLog2(), 3346 dl, VT)); 3347 } 3348 3349 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3350 Tmp2 = DAG.getCALLSEQ_END( 3351 Chain, DAG.getIntPtrConstant(0, dl, true), 3352 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3353 3354 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3355 } 3356 3357 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3358 SelectionDAG &DAG) const { 3359 // We only handle constant sizes here to allow non-entry block, static sized 3360 // allocas. A truly dynamic value is more difficult to support because we 3361 // don't know if the size value is uniform or not. If the size isn't uniform, 3362 // we would need to do a wave reduction to get the maximum size to know how 3363 // much to increment the uniform stack pointer. 3364 SDValue Size = Op.getOperand(1); 3365 if (isa<ConstantSDNode>(Size)) 3366 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3367 3368 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3369 } 3370 3371 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3372 const MachineFunction &MF) const { 3373 Register Reg = StringSwitch<Register>(RegName) 3374 .Case("m0", AMDGPU::M0) 3375 .Case("exec", AMDGPU::EXEC) 3376 .Case("exec_lo", AMDGPU::EXEC_LO) 3377 .Case("exec_hi", AMDGPU::EXEC_HI) 3378 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3379 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3380 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3381 .Default(Register()); 3382 3383 if (Reg == AMDGPU::NoRegister) { 3384 report_fatal_error(Twine("invalid register name \"" 3385 + StringRef(RegName) + "\".")); 3386 3387 } 3388 3389 if (!Subtarget->hasFlatScrRegister() && 3390 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3391 report_fatal_error(Twine("invalid register \"" 3392 + StringRef(RegName) + "\" for subtarget.")); 3393 } 3394 3395 switch (Reg) { 3396 case AMDGPU::M0: 3397 case AMDGPU::EXEC_LO: 3398 case AMDGPU::EXEC_HI: 3399 case AMDGPU::FLAT_SCR_LO: 3400 case AMDGPU::FLAT_SCR_HI: 3401 if (VT.getSizeInBits() == 32) 3402 return Reg; 3403 break; 3404 case AMDGPU::EXEC: 3405 case AMDGPU::FLAT_SCR: 3406 if (VT.getSizeInBits() == 64) 3407 return Reg; 3408 break; 3409 default: 3410 llvm_unreachable("missing register type checking"); 3411 } 3412 3413 report_fatal_error(Twine("invalid type for register \"" 3414 + StringRef(RegName) + "\".")); 3415 } 3416 3417 // If kill is not the last instruction, split the block so kill is always a 3418 // proper terminator. 3419 MachineBasicBlock * 3420 SITargetLowering::splitKillBlock(MachineInstr &MI, 3421 MachineBasicBlock *BB) const { 3422 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3423 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3424 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3425 return SplitBB; 3426 } 3427 3428 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3429 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3430 // be the first instruction in the remainder block. 3431 // 3432 /// \returns { LoopBody, Remainder } 3433 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3434 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3435 MachineFunction *MF = MBB.getParent(); 3436 MachineBasicBlock::iterator I(&MI); 3437 3438 // To insert the loop we need to split the block. Move everything after this 3439 // point to a new block, and insert a new empty block between the two. 3440 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3441 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3442 MachineFunction::iterator MBBI(MBB); 3443 ++MBBI; 3444 3445 MF->insert(MBBI, LoopBB); 3446 MF->insert(MBBI, RemainderBB); 3447 3448 LoopBB->addSuccessor(LoopBB); 3449 LoopBB->addSuccessor(RemainderBB); 3450 3451 // Move the rest of the block into a new block. 3452 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3453 3454 if (InstInLoop) { 3455 auto Next = std::next(I); 3456 3457 // Move instruction to loop body. 3458 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3459 3460 // Move the rest of the block. 3461 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3462 } else { 3463 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3464 } 3465 3466 MBB.addSuccessor(LoopBB); 3467 3468 return std::make_pair(LoopBB, RemainderBB); 3469 } 3470 3471 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3472 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3473 MachineBasicBlock *MBB = MI.getParent(); 3474 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3475 auto I = MI.getIterator(); 3476 auto E = std::next(I); 3477 3478 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3479 .addImm(0); 3480 3481 MIBundleBuilder Bundler(*MBB, I, E); 3482 finalizeBundle(*MBB, Bundler.begin()); 3483 } 3484 3485 MachineBasicBlock * 3486 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3487 MachineBasicBlock *BB) const { 3488 const DebugLoc &DL = MI.getDebugLoc(); 3489 3490 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3491 3492 MachineBasicBlock *LoopBB; 3493 MachineBasicBlock *RemainderBB; 3494 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3495 3496 // Apparently kill flags are only valid if the def is in the same block? 3497 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3498 Src->setIsKill(false); 3499 3500 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3501 3502 MachineBasicBlock::iterator I = LoopBB->end(); 3503 3504 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3505 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3506 3507 // Clear TRAP_STS.MEM_VIOL 3508 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3509 .addImm(0) 3510 .addImm(EncodedReg); 3511 3512 bundleInstWithWaitcnt(MI); 3513 3514 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3515 3516 // Load and check TRAP_STS.MEM_VIOL 3517 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3518 .addImm(EncodedReg); 3519 3520 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3521 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3522 .addReg(Reg, RegState::Kill) 3523 .addImm(0); 3524 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3525 .addMBB(LoopBB); 3526 3527 return RemainderBB; 3528 } 3529 3530 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3531 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3532 // will only do one iteration. In the worst case, this will loop 64 times. 3533 // 3534 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3535 static MachineBasicBlock::iterator 3536 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3537 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3538 const DebugLoc &DL, const MachineOperand &Idx, 3539 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3540 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3541 Register &SGPRIdxReg) { 3542 3543 MachineFunction *MF = OrigBB.getParent(); 3544 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3545 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3546 MachineBasicBlock::iterator I = LoopBB.begin(); 3547 3548 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3549 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3550 Register NewExec = MRI.createVirtualRegister(BoolRC); 3551 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3552 Register CondReg = MRI.createVirtualRegister(BoolRC); 3553 3554 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3555 .addReg(InitReg) 3556 .addMBB(&OrigBB) 3557 .addReg(ResultReg) 3558 .addMBB(&LoopBB); 3559 3560 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3561 .addReg(InitSaveExecReg) 3562 .addMBB(&OrigBB) 3563 .addReg(NewExec) 3564 .addMBB(&LoopBB); 3565 3566 // Read the next variant <- also loop target. 3567 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3568 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3569 3570 // Compare the just read M0 value to all possible Idx values. 3571 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3572 .addReg(CurrentIdxReg) 3573 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3574 3575 // Update EXEC, save the original EXEC value to VCC. 3576 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3577 : AMDGPU::S_AND_SAVEEXEC_B64), 3578 NewExec) 3579 .addReg(CondReg, RegState::Kill); 3580 3581 MRI.setSimpleHint(NewExec, CondReg); 3582 3583 if (UseGPRIdxMode) { 3584 if (Offset == 0) { 3585 SGPRIdxReg = CurrentIdxReg; 3586 } else { 3587 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3588 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3589 .addReg(CurrentIdxReg, RegState::Kill) 3590 .addImm(Offset); 3591 } 3592 } else { 3593 // Move index from VCC into M0 3594 if (Offset == 0) { 3595 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3596 .addReg(CurrentIdxReg, RegState::Kill); 3597 } else { 3598 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3599 .addReg(CurrentIdxReg, RegState::Kill) 3600 .addImm(Offset); 3601 } 3602 } 3603 3604 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3605 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3606 MachineInstr *InsertPt = 3607 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3608 : AMDGPU::S_XOR_B64_term), Exec) 3609 .addReg(Exec) 3610 .addReg(NewExec); 3611 3612 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3613 // s_cbranch_scc0? 3614 3615 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3616 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3617 .addMBB(&LoopBB); 3618 3619 return InsertPt->getIterator(); 3620 } 3621 3622 // This has slightly sub-optimal regalloc when the source vector is killed by 3623 // the read. The register allocator does not understand that the kill is 3624 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3625 // subregister from it, using 1 more VGPR than necessary. This was saved when 3626 // this was expanded after register allocation. 3627 static MachineBasicBlock::iterator 3628 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3629 unsigned InitResultReg, unsigned PhiReg, int Offset, 3630 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3631 MachineFunction *MF = MBB.getParent(); 3632 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3633 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3634 MachineRegisterInfo &MRI = MF->getRegInfo(); 3635 const DebugLoc &DL = MI.getDebugLoc(); 3636 MachineBasicBlock::iterator I(&MI); 3637 3638 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3639 Register DstReg = MI.getOperand(0).getReg(); 3640 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3641 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3642 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3643 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3644 3645 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3646 3647 // Save the EXEC mask 3648 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3649 .addReg(Exec); 3650 3651 MachineBasicBlock *LoopBB; 3652 MachineBasicBlock *RemainderBB; 3653 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3654 3655 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3656 3657 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3658 InitResultReg, DstReg, PhiReg, TmpExec, 3659 Offset, UseGPRIdxMode, SGPRIdxReg); 3660 3661 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3662 MachineFunction::iterator MBBI(LoopBB); 3663 ++MBBI; 3664 MF->insert(MBBI, LandingPad); 3665 LoopBB->removeSuccessor(RemainderBB); 3666 LandingPad->addSuccessor(RemainderBB); 3667 LoopBB->addSuccessor(LandingPad); 3668 MachineBasicBlock::iterator First = LandingPad->begin(); 3669 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3670 .addReg(SaveExec); 3671 3672 return InsPt; 3673 } 3674 3675 // Returns subreg index, offset 3676 static std::pair<unsigned, int> 3677 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3678 const TargetRegisterClass *SuperRC, 3679 unsigned VecReg, 3680 int Offset) { 3681 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3682 3683 // Skip out of bounds offsets, or else we would end up using an undefined 3684 // register. 3685 if (Offset >= NumElts || Offset < 0) 3686 return std::make_pair(AMDGPU::sub0, Offset); 3687 3688 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3689 } 3690 3691 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3692 MachineRegisterInfo &MRI, MachineInstr &MI, 3693 int Offset) { 3694 MachineBasicBlock *MBB = MI.getParent(); 3695 const DebugLoc &DL = MI.getDebugLoc(); 3696 MachineBasicBlock::iterator I(&MI); 3697 3698 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3699 3700 assert(Idx->getReg() != AMDGPU::NoRegister); 3701 3702 if (Offset == 0) { 3703 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3704 } else { 3705 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3706 .add(*Idx) 3707 .addImm(Offset); 3708 } 3709 } 3710 3711 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3712 MachineRegisterInfo &MRI, MachineInstr &MI, 3713 int Offset) { 3714 MachineBasicBlock *MBB = MI.getParent(); 3715 const DebugLoc &DL = MI.getDebugLoc(); 3716 MachineBasicBlock::iterator I(&MI); 3717 3718 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3719 3720 if (Offset == 0) 3721 return Idx->getReg(); 3722 3723 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3724 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3725 .add(*Idx) 3726 .addImm(Offset); 3727 return Tmp; 3728 } 3729 3730 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3731 MachineBasicBlock &MBB, 3732 const GCNSubtarget &ST) { 3733 const SIInstrInfo *TII = ST.getInstrInfo(); 3734 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3735 MachineFunction *MF = MBB.getParent(); 3736 MachineRegisterInfo &MRI = MF->getRegInfo(); 3737 3738 Register Dst = MI.getOperand(0).getReg(); 3739 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3740 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3741 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3742 3743 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3744 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3745 3746 unsigned SubReg; 3747 std::tie(SubReg, Offset) 3748 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3749 3750 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3751 3752 // Check for a SGPR index. 3753 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3754 MachineBasicBlock::iterator I(&MI); 3755 const DebugLoc &DL = MI.getDebugLoc(); 3756 3757 if (UseGPRIdxMode) { 3758 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3759 // to avoid interfering with other uses, so probably requires a new 3760 // optimization pass. 3761 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3762 3763 const MCInstrDesc &GPRIDXDesc = 3764 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3765 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3766 .addReg(SrcReg) 3767 .addReg(Idx) 3768 .addImm(SubReg); 3769 } else { 3770 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3771 3772 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3773 .addReg(SrcReg, 0, SubReg) 3774 .addReg(SrcReg, RegState::Implicit); 3775 } 3776 3777 MI.eraseFromParent(); 3778 3779 return &MBB; 3780 } 3781 3782 // Control flow needs to be inserted if indexing with a VGPR. 3783 const DebugLoc &DL = MI.getDebugLoc(); 3784 MachineBasicBlock::iterator I(&MI); 3785 3786 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3787 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3788 3789 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3790 3791 Register SGPRIdxReg; 3792 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3793 UseGPRIdxMode, SGPRIdxReg); 3794 3795 MachineBasicBlock *LoopBB = InsPt->getParent(); 3796 3797 if (UseGPRIdxMode) { 3798 const MCInstrDesc &GPRIDXDesc = 3799 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3800 3801 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3802 .addReg(SrcReg) 3803 .addReg(SGPRIdxReg) 3804 .addImm(SubReg); 3805 } else { 3806 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3807 .addReg(SrcReg, 0, SubReg) 3808 .addReg(SrcReg, RegState::Implicit); 3809 } 3810 3811 MI.eraseFromParent(); 3812 3813 return LoopBB; 3814 } 3815 3816 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3817 MachineBasicBlock &MBB, 3818 const GCNSubtarget &ST) { 3819 const SIInstrInfo *TII = ST.getInstrInfo(); 3820 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3821 MachineFunction *MF = MBB.getParent(); 3822 MachineRegisterInfo &MRI = MF->getRegInfo(); 3823 3824 Register Dst = MI.getOperand(0).getReg(); 3825 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3826 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3827 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3828 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3829 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3830 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3831 3832 // This can be an immediate, but will be folded later. 3833 assert(Val->getReg()); 3834 3835 unsigned SubReg; 3836 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3837 SrcVec->getReg(), 3838 Offset); 3839 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3840 3841 if (Idx->getReg() == AMDGPU::NoRegister) { 3842 MachineBasicBlock::iterator I(&MI); 3843 const DebugLoc &DL = MI.getDebugLoc(); 3844 3845 assert(Offset == 0); 3846 3847 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3848 .add(*SrcVec) 3849 .add(*Val) 3850 .addImm(SubReg); 3851 3852 MI.eraseFromParent(); 3853 return &MBB; 3854 } 3855 3856 // Check for a SGPR index. 3857 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3858 MachineBasicBlock::iterator I(&MI); 3859 const DebugLoc &DL = MI.getDebugLoc(); 3860 3861 if (UseGPRIdxMode) { 3862 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3863 3864 const MCInstrDesc &GPRIDXDesc = 3865 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3866 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3867 .addReg(SrcVec->getReg()) 3868 .add(*Val) 3869 .addReg(Idx) 3870 .addImm(SubReg); 3871 } else { 3872 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3873 3874 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3875 TRI.getRegSizeInBits(*VecRC), 32, false); 3876 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3877 .addReg(SrcVec->getReg()) 3878 .add(*Val) 3879 .addImm(SubReg); 3880 } 3881 MI.eraseFromParent(); 3882 return &MBB; 3883 } 3884 3885 // Control flow needs to be inserted if indexing with a VGPR. 3886 if (Val->isReg()) 3887 MRI.clearKillFlags(Val->getReg()); 3888 3889 const DebugLoc &DL = MI.getDebugLoc(); 3890 3891 Register PhiReg = MRI.createVirtualRegister(VecRC); 3892 3893 Register SGPRIdxReg; 3894 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3895 UseGPRIdxMode, SGPRIdxReg); 3896 MachineBasicBlock *LoopBB = InsPt->getParent(); 3897 3898 if (UseGPRIdxMode) { 3899 const MCInstrDesc &GPRIDXDesc = 3900 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3901 3902 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3903 .addReg(PhiReg) 3904 .add(*Val) 3905 .addReg(SGPRIdxReg) 3906 .addImm(AMDGPU::sub0); 3907 } else { 3908 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3909 TRI.getRegSizeInBits(*VecRC), 32, false); 3910 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3911 .addReg(PhiReg) 3912 .add(*Val) 3913 .addImm(AMDGPU::sub0); 3914 } 3915 3916 MI.eraseFromParent(); 3917 return LoopBB; 3918 } 3919 3920 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3921 MachineInstr &MI, MachineBasicBlock *BB) const { 3922 3923 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3924 MachineFunction *MF = BB->getParent(); 3925 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3926 3927 switch (MI.getOpcode()) { 3928 case AMDGPU::S_UADDO_PSEUDO: 3929 case AMDGPU::S_USUBO_PSEUDO: { 3930 const DebugLoc &DL = MI.getDebugLoc(); 3931 MachineOperand &Dest0 = MI.getOperand(0); 3932 MachineOperand &Dest1 = MI.getOperand(1); 3933 MachineOperand &Src0 = MI.getOperand(2); 3934 MachineOperand &Src1 = MI.getOperand(3); 3935 3936 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3937 ? AMDGPU::S_ADD_I32 3938 : AMDGPU::S_SUB_I32; 3939 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3940 3941 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3942 .addImm(1) 3943 .addImm(0); 3944 3945 MI.eraseFromParent(); 3946 return BB; 3947 } 3948 case AMDGPU::S_ADD_U64_PSEUDO: 3949 case AMDGPU::S_SUB_U64_PSEUDO: { 3950 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3951 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3952 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3953 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3954 const DebugLoc &DL = MI.getDebugLoc(); 3955 3956 MachineOperand &Dest = MI.getOperand(0); 3957 MachineOperand &Src0 = MI.getOperand(1); 3958 MachineOperand &Src1 = MI.getOperand(2); 3959 3960 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3961 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3962 3963 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3964 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3965 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3966 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3967 3968 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3969 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3970 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3971 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3972 3973 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3974 3975 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3976 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3977 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3978 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3979 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3980 .addReg(DestSub0) 3981 .addImm(AMDGPU::sub0) 3982 .addReg(DestSub1) 3983 .addImm(AMDGPU::sub1); 3984 MI.eraseFromParent(); 3985 return BB; 3986 } 3987 case AMDGPU::V_ADD_U64_PSEUDO: 3988 case AMDGPU::V_SUB_U64_PSEUDO: { 3989 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3990 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3991 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3992 const DebugLoc &DL = MI.getDebugLoc(); 3993 3994 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3995 3996 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3997 3998 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3999 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4000 4001 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4002 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4003 4004 MachineOperand &Dest = MI.getOperand(0); 4005 MachineOperand &Src0 = MI.getOperand(1); 4006 MachineOperand &Src1 = MI.getOperand(2); 4007 4008 const TargetRegisterClass *Src0RC = Src0.isReg() 4009 ? MRI.getRegClass(Src0.getReg()) 4010 : &AMDGPU::VReg_64RegClass; 4011 const TargetRegisterClass *Src1RC = Src1.isReg() 4012 ? MRI.getRegClass(Src1.getReg()) 4013 : &AMDGPU::VReg_64RegClass; 4014 4015 const TargetRegisterClass *Src0SubRC = 4016 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4017 const TargetRegisterClass *Src1SubRC = 4018 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4019 4020 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4021 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4022 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4023 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4024 4025 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4026 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4027 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4028 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4029 4030 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4031 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4032 .addReg(CarryReg, RegState::Define) 4033 .add(SrcReg0Sub0) 4034 .add(SrcReg1Sub0) 4035 .addImm(0); // clamp bit 4036 4037 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4038 MachineInstr *HiHalf = 4039 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4040 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4041 .add(SrcReg0Sub1) 4042 .add(SrcReg1Sub1) 4043 .addReg(CarryReg, RegState::Kill) 4044 .addImm(0); // clamp bit 4045 4046 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4047 .addReg(DestSub0) 4048 .addImm(AMDGPU::sub0) 4049 .addReg(DestSub1) 4050 .addImm(AMDGPU::sub1); 4051 TII->legalizeOperands(*LoHalf); 4052 TII->legalizeOperands(*HiHalf); 4053 MI.eraseFromParent(); 4054 return BB; 4055 } 4056 case AMDGPU::S_ADD_CO_PSEUDO: 4057 case AMDGPU::S_SUB_CO_PSEUDO: { 4058 // This pseudo has a chance to be selected 4059 // only from uniform add/subcarry node. All the VGPR operands 4060 // therefore assumed to be splat vectors. 4061 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4062 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4063 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4064 MachineBasicBlock::iterator MII = MI; 4065 const DebugLoc &DL = MI.getDebugLoc(); 4066 MachineOperand &Dest = MI.getOperand(0); 4067 MachineOperand &CarryDest = MI.getOperand(1); 4068 MachineOperand &Src0 = MI.getOperand(2); 4069 MachineOperand &Src1 = MI.getOperand(3); 4070 MachineOperand &Src2 = MI.getOperand(4); 4071 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4072 ? AMDGPU::S_ADDC_U32 4073 : AMDGPU::S_SUBB_U32; 4074 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4075 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4076 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4077 .addReg(Src0.getReg()); 4078 Src0.setReg(RegOp0); 4079 } 4080 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4081 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4082 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4083 .addReg(Src1.getReg()); 4084 Src1.setReg(RegOp1); 4085 } 4086 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4087 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4088 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4089 .addReg(Src2.getReg()); 4090 Src2.setReg(RegOp2); 4091 } 4092 4093 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4094 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4095 if (ST.hasScalarCompareEq64()) { 4096 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4097 .addReg(Src2.getReg()) 4098 .addImm(0); 4099 } else { 4100 const TargetRegisterClass *SubRC = 4101 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4102 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4103 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4104 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4105 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4106 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4107 4108 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4109 .add(Src2Sub0) 4110 .add(Src2Sub1); 4111 4112 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4113 .addReg(Src2_32, RegState::Kill) 4114 .addImm(0); 4115 } 4116 } else { 4117 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4118 .addReg(Src2.getReg()) 4119 .addImm(0); 4120 } 4121 4122 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4123 4124 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4125 .addReg(AMDGPU::SCC); 4126 MI.eraseFromParent(); 4127 return BB; 4128 } 4129 case AMDGPU::SI_INIT_M0: { 4130 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4131 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4132 .add(MI.getOperand(0)); 4133 MI.eraseFromParent(); 4134 return BB; 4135 } 4136 case AMDGPU::GET_GROUPSTATICSIZE: { 4137 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4138 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4139 DebugLoc DL = MI.getDebugLoc(); 4140 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4141 .add(MI.getOperand(0)) 4142 .addImm(MFI->getLDSSize()); 4143 MI.eraseFromParent(); 4144 return BB; 4145 } 4146 case AMDGPU::SI_INDIRECT_SRC_V1: 4147 case AMDGPU::SI_INDIRECT_SRC_V2: 4148 case AMDGPU::SI_INDIRECT_SRC_V4: 4149 case AMDGPU::SI_INDIRECT_SRC_V8: 4150 case AMDGPU::SI_INDIRECT_SRC_V16: 4151 case AMDGPU::SI_INDIRECT_SRC_V32: 4152 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4153 case AMDGPU::SI_INDIRECT_DST_V1: 4154 case AMDGPU::SI_INDIRECT_DST_V2: 4155 case AMDGPU::SI_INDIRECT_DST_V4: 4156 case AMDGPU::SI_INDIRECT_DST_V8: 4157 case AMDGPU::SI_INDIRECT_DST_V16: 4158 case AMDGPU::SI_INDIRECT_DST_V32: 4159 return emitIndirectDst(MI, *BB, *getSubtarget()); 4160 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4161 case AMDGPU::SI_KILL_I1_PSEUDO: 4162 return splitKillBlock(MI, BB); 4163 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4164 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4165 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4166 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4167 4168 Register Dst = MI.getOperand(0).getReg(); 4169 Register Src0 = MI.getOperand(1).getReg(); 4170 Register Src1 = MI.getOperand(2).getReg(); 4171 const DebugLoc &DL = MI.getDebugLoc(); 4172 Register SrcCond = MI.getOperand(3).getReg(); 4173 4174 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4175 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4176 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4177 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4178 4179 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4180 .addReg(SrcCond); 4181 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4182 .addImm(0) 4183 .addReg(Src0, 0, AMDGPU::sub0) 4184 .addImm(0) 4185 .addReg(Src1, 0, AMDGPU::sub0) 4186 .addReg(SrcCondCopy); 4187 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4188 .addImm(0) 4189 .addReg(Src0, 0, AMDGPU::sub1) 4190 .addImm(0) 4191 .addReg(Src1, 0, AMDGPU::sub1) 4192 .addReg(SrcCondCopy); 4193 4194 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4195 .addReg(DstLo) 4196 .addImm(AMDGPU::sub0) 4197 .addReg(DstHi) 4198 .addImm(AMDGPU::sub1); 4199 MI.eraseFromParent(); 4200 return BB; 4201 } 4202 case AMDGPU::SI_BR_UNDEF: { 4203 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4204 const DebugLoc &DL = MI.getDebugLoc(); 4205 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4206 .add(MI.getOperand(0)); 4207 Br->getOperand(1).setIsUndef(true); // read undef SCC 4208 MI.eraseFromParent(); 4209 return BB; 4210 } 4211 case AMDGPU::ADJCALLSTACKUP: 4212 case AMDGPU::ADJCALLSTACKDOWN: { 4213 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4214 MachineInstrBuilder MIB(*MF, &MI); 4215 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4216 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4217 return BB; 4218 } 4219 case AMDGPU::SI_CALL_ISEL: { 4220 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4221 const DebugLoc &DL = MI.getDebugLoc(); 4222 4223 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4224 4225 MachineInstrBuilder MIB; 4226 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4227 4228 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4229 MIB.add(MI.getOperand(I)); 4230 4231 MIB.cloneMemRefs(MI); 4232 MI.eraseFromParent(); 4233 return BB; 4234 } 4235 case AMDGPU::V_ADD_CO_U32_e32: 4236 case AMDGPU::V_SUB_CO_U32_e32: 4237 case AMDGPU::V_SUBREV_CO_U32_e32: { 4238 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4239 const DebugLoc &DL = MI.getDebugLoc(); 4240 unsigned Opc = MI.getOpcode(); 4241 4242 bool NeedClampOperand = false; 4243 if (TII->pseudoToMCOpcode(Opc) == -1) { 4244 Opc = AMDGPU::getVOPe64(Opc); 4245 NeedClampOperand = true; 4246 } 4247 4248 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4249 if (TII->isVOP3(*I)) { 4250 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4251 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4252 I.addReg(TRI->getVCC(), RegState::Define); 4253 } 4254 I.add(MI.getOperand(1)) 4255 .add(MI.getOperand(2)); 4256 if (NeedClampOperand) 4257 I.addImm(0); // clamp bit for e64 encoding 4258 4259 TII->legalizeOperands(*I); 4260 4261 MI.eraseFromParent(); 4262 return BB; 4263 } 4264 case AMDGPU::DS_GWS_INIT: 4265 case AMDGPU::DS_GWS_SEMA_BR: 4266 case AMDGPU::DS_GWS_BARRIER: 4267 if (Subtarget->needsAlignedVGPRs()) { 4268 // Add implicit aligned super-reg to force alignment on the data operand. 4269 const DebugLoc &DL = MI.getDebugLoc(); 4270 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4271 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4272 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4273 Register DataReg = Op->getReg(); 4274 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4275 Register Undef = MRI.createVirtualRegister( 4276 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4277 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4278 Register NewVR = 4279 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4280 : &AMDGPU::VReg_64_Align2RegClass); 4281 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4282 .addReg(DataReg, 0, Op->getSubReg()) 4283 .addImm(AMDGPU::sub0) 4284 .addReg(Undef) 4285 .addImm(AMDGPU::sub1); 4286 Op->setReg(NewVR); 4287 Op->setSubReg(AMDGPU::sub0); 4288 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4289 } 4290 LLVM_FALLTHROUGH; 4291 case AMDGPU::DS_GWS_SEMA_V: 4292 case AMDGPU::DS_GWS_SEMA_P: 4293 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4294 // A s_waitcnt 0 is required to be the instruction immediately following. 4295 if (getSubtarget()->hasGWSAutoReplay()) { 4296 bundleInstWithWaitcnt(MI); 4297 return BB; 4298 } 4299 4300 return emitGWSMemViolTestLoop(MI, BB); 4301 case AMDGPU::S_SETREG_B32: { 4302 // Try to optimize cases that only set the denormal mode or rounding mode. 4303 // 4304 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4305 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4306 // instead. 4307 // 4308 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4309 // allow you to have a no side effect instruction in the output of a 4310 // sideeffecting pattern. 4311 unsigned ID, Offset, Width; 4312 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4313 if (ID != AMDGPU::Hwreg::ID_MODE) 4314 return BB; 4315 4316 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4317 const unsigned SetMask = WidthMask << Offset; 4318 4319 if (getSubtarget()->hasDenormModeInst()) { 4320 unsigned SetDenormOp = 0; 4321 unsigned SetRoundOp = 0; 4322 4323 // The dedicated instructions can only set the whole denorm or round mode 4324 // at once, not a subset of bits in either. 4325 if (SetMask == 4326 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4327 // If this fully sets both the round and denorm mode, emit the two 4328 // dedicated instructions for these. 4329 SetRoundOp = AMDGPU::S_ROUND_MODE; 4330 SetDenormOp = AMDGPU::S_DENORM_MODE; 4331 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4332 SetRoundOp = AMDGPU::S_ROUND_MODE; 4333 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4334 SetDenormOp = AMDGPU::S_DENORM_MODE; 4335 } 4336 4337 if (SetRoundOp || SetDenormOp) { 4338 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4339 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4340 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4341 unsigned ImmVal = Def->getOperand(1).getImm(); 4342 if (SetRoundOp) { 4343 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4344 .addImm(ImmVal & 0xf); 4345 4346 // If we also have the denorm mode, get just the denorm mode bits. 4347 ImmVal >>= 4; 4348 } 4349 4350 if (SetDenormOp) { 4351 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4352 .addImm(ImmVal & 0xf); 4353 } 4354 4355 MI.eraseFromParent(); 4356 return BB; 4357 } 4358 } 4359 } 4360 4361 // If only FP bits are touched, used the no side effects pseudo. 4362 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4363 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4364 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4365 4366 return BB; 4367 } 4368 default: 4369 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4370 } 4371 } 4372 4373 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4374 return isTypeLegal(VT.getScalarType()); 4375 } 4376 4377 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4378 // This currently forces unfolding various combinations of fsub into fma with 4379 // free fneg'd operands. As long as we have fast FMA (controlled by 4380 // isFMAFasterThanFMulAndFAdd), we should perform these. 4381 4382 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4383 // most of these combines appear to be cycle neutral but save on instruction 4384 // count / code size. 4385 return true; 4386 } 4387 4388 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4389 EVT VT) const { 4390 if (!VT.isVector()) { 4391 return MVT::i1; 4392 } 4393 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4394 } 4395 4396 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4397 // TODO: Should i16 be used always if legal? For now it would force VALU 4398 // shifts. 4399 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4400 } 4401 4402 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4403 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4404 ? Ty.changeElementSize(16) 4405 : Ty.changeElementSize(32); 4406 } 4407 4408 // Answering this is somewhat tricky and depends on the specific device which 4409 // have different rates for fma or all f64 operations. 4410 // 4411 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4412 // regardless of which device (although the number of cycles differs between 4413 // devices), so it is always profitable for f64. 4414 // 4415 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4416 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4417 // which we can always do even without fused FP ops since it returns the same 4418 // result as the separate operations and since it is always full 4419 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4420 // however does not support denormals, so we do report fma as faster if we have 4421 // a fast fma device and require denormals. 4422 // 4423 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4424 EVT VT) const { 4425 VT = VT.getScalarType(); 4426 4427 switch (VT.getSimpleVT().SimpleTy) { 4428 case MVT::f32: { 4429 // If mad is not available this depends only on if f32 fma is full rate. 4430 if (!Subtarget->hasMadMacF32Insts()) 4431 return Subtarget->hasFastFMAF32(); 4432 4433 // Otherwise f32 mad is always full rate and returns the same result as 4434 // the separate operations so should be preferred over fma. 4435 // However does not support denomals. 4436 if (hasFP32Denormals(MF)) 4437 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4438 4439 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4440 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4441 } 4442 case MVT::f64: 4443 return true; 4444 case MVT::f16: 4445 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4446 default: 4447 break; 4448 } 4449 4450 return false; 4451 } 4452 4453 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4454 const SDNode *N) const { 4455 // TODO: Check future ftz flag 4456 // v_mad_f32/v_mac_f32 do not support denormals. 4457 EVT VT = N->getValueType(0); 4458 if (VT == MVT::f32) 4459 return Subtarget->hasMadMacF32Insts() && 4460 !hasFP32Denormals(DAG.getMachineFunction()); 4461 if (VT == MVT::f16) { 4462 return Subtarget->hasMadF16() && 4463 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4464 } 4465 4466 return false; 4467 } 4468 4469 //===----------------------------------------------------------------------===// 4470 // Custom DAG Lowering Operations 4471 //===----------------------------------------------------------------------===// 4472 4473 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4474 // wider vector type is legal. 4475 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4476 SelectionDAG &DAG) const { 4477 unsigned Opc = Op.getOpcode(); 4478 EVT VT = Op.getValueType(); 4479 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4480 4481 SDValue Lo, Hi; 4482 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4483 4484 SDLoc SL(Op); 4485 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4486 Op->getFlags()); 4487 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4488 Op->getFlags()); 4489 4490 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4491 } 4492 4493 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4494 // wider vector type is legal. 4495 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4496 SelectionDAG &DAG) const { 4497 unsigned Opc = Op.getOpcode(); 4498 EVT VT = Op.getValueType(); 4499 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4500 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4501 4502 SDValue Lo0, Hi0; 4503 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4504 SDValue Lo1, Hi1; 4505 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4506 4507 SDLoc SL(Op); 4508 4509 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4510 Op->getFlags()); 4511 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4512 Op->getFlags()); 4513 4514 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4515 } 4516 4517 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4518 SelectionDAG &DAG) const { 4519 unsigned Opc = Op.getOpcode(); 4520 EVT VT = Op.getValueType(); 4521 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4522 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4523 4524 SDValue Lo0, Hi0; 4525 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4526 SDValue Lo1, Hi1; 4527 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4528 SDValue Lo2, Hi2; 4529 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4530 4531 SDLoc SL(Op); 4532 4533 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4534 Op->getFlags()); 4535 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4536 Op->getFlags()); 4537 4538 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4539 } 4540 4541 4542 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4543 switch (Op.getOpcode()) { 4544 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4545 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4546 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4547 case ISD::LOAD: { 4548 SDValue Result = LowerLOAD(Op, DAG); 4549 assert((!Result.getNode() || 4550 Result.getNode()->getNumValues() == 2) && 4551 "Load should return a value and a chain"); 4552 return Result; 4553 } 4554 4555 case ISD::FSIN: 4556 case ISD::FCOS: 4557 return LowerTrig(Op, DAG); 4558 case ISD::SELECT: return LowerSELECT(Op, DAG); 4559 case ISD::FDIV: return LowerFDIV(Op, DAG); 4560 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4561 case ISD::STORE: return LowerSTORE(Op, DAG); 4562 case ISD::GlobalAddress: { 4563 MachineFunction &MF = DAG.getMachineFunction(); 4564 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4565 return LowerGlobalAddress(MFI, Op, DAG); 4566 } 4567 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4568 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4569 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4570 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4571 case ISD::INSERT_SUBVECTOR: 4572 return lowerINSERT_SUBVECTOR(Op, DAG); 4573 case ISD::INSERT_VECTOR_ELT: 4574 return lowerINSERT_VECTOR_ELT(Op, DAG); 4575 case ISD::EXTRACT_VECTOR_ELT: 4576 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4577 case ISD::VECTOR_SHUFFLE: 4578 return lowerVECTOR_SHUFFLE(Op, DAG); 4579 case ISD::BUILD_VECTOR: 4580 return lowerBUILD_VECTOR(Op, DAG); 4581 case ISD::FP_ROUND: 4582 return lowerFP_ROUND(Op, DAG); 4583 case ISD::TRAP: 4584 return lowerTRAP(Op, DAG); 4585 case ISD::DEBUGTRAP: 4586 return lowerDEBUGTRAP(Op, DAG); 4587 case ISD::FABS: 4588 case ISD::FNEG: 4589 case ISD::FCANONICALIZE: 4590 case ISD::BSWAP: 4591 return splitUnaryVectorOp(Op, DAG); 4592 case ISD::FMINNUM: 4593 case ISD::FMAXNUM: 4594 return lowerFMINNUM_FMAXNUM(Op, DAG); 4595 case ISD::FMA: 4596 return splitTernaryVectorOp(Op, DAG); 4597 case ISD::FP_TO_SINT: 4598 case ISD::FP_TO_UINT: 4599 return LowerFP_TO_INT(Op, DAG); 4600 case ISD::SHL: 4601 case ISD::SRA: 4602 case ISD::SRL: 4603 case ISD::ADD: 4604 case ISD::SUB: 4605 case ISD::MUL: 4606 case ISD::SMIN: 4607 case ISD::SMAX: 4608 case ISD::UMIN: 4609 case ISD::UMAX: 4610 case ISD::FADD: 4611 case ISD::FMUL: 4612 case ISD::FMINNUM_IEEE: 4613 case ISD::FMAXNUM_IEEE: 4614 case ISD::UADDSAT: 4615 case ISD::USUBSAT: 4616 case ISD::SADDSAT: 4617 case ISD::SSUBSAT: 4618 return splitBinaryVectorOp(Op, DAG); 4619 case ISD::SMULO: 4620 case ISD::UMULO: 4621 return lowerXMULO(Op, DAG); 4622 case ISD::DYNAMIC_STACKALLOC: 4623 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4624 } 4625 return SDValue(); 4626 } 4627 4628 // Used for D16: Casts the result of an instruction into the right vector, 4629 // packs values if loads return unpacked values. 4630 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4631 const SDLoc &DL, 4632 SelectionDAG &DAG, bool Unpacked) { 4633 if (!LoadVT.isVector()) 4634 return Result; 4635 4636 // Cast back to the original packed type or to a larger type that is a 4637 // multiple of 32 bit for D16. Widening the return type is a required for 4638 // legalization. 4639 EVT FittingLoadVT = LoadVT; 4640 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4641 FittingLoadVT = 4642 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4643 LoadVT.getVectorNumElements() + 1); 4644 } 4645 4646 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4647 // Truncate to v2i16/v4i16. 4648 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4649 4650 // Workaround legalizer not scalarizing truncate after vector op 4651 // legalization but not creating intermediate vector trunc. 4652 SmallVector<SDValue, 4> Elts; 4653 DAG.ExtractVectorElements(Result, Elts); 4654 for (SDValue &Elt : Elts) 4655 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4656 4657 // Pad illegal v1i16/v3fi6 to v4i16 4658 if ((LoadVT.getVectorNumElements() % 2) == 1) 4659 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4660 4661 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4662 4663 // Bitcast to original type (v2f16/v4f16). 4664 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4665 } 4666 4667 // Cast back to the original packed type. 4668 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4669 } 4670 4671 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4672 MemSDNode *M, 4673 SelectionDAG &DAG, 4674 ArrayRef<SDValue> Ops, 4675 bool IsIntrinsic) const { 4676 SDLoc DL(M); 4677 4678 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4679 EVT LoadVT = M->getValueType(0); 4680 4681 EVT EquivLoadVT = LoadVT; 4682 if (LoadVT.isVector()) { 4683 if (Unpacked) { 4684 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4685 LoadVT.getVectorNumElements()); 4686 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4687 // Widen v3f16 to legal type 4688 EquivLoadVT = 4689 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4690 LoadVT.getVectorNumElements() + 1); 4691 } 4692 } 4693 4694 // Change from v4f16/v2f16 to EquivLoadVT. 4695 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4696 4697 SDValue Load 4698 = DAG.getMemIntrinsicNode( 4699 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4700 VTList, Ops, M->getMemoryVT(), 4701 M->getMemOperand()); 4702 4703 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4704 4705 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4706 } 4707 4708 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4709 SelectionDAG &DAG, 4710 ArrayRef<SDValue> Ops) const { 4711 SDLoc DL(M); 4712 EVT LoadVT = M->getValueType(0); 4713 EVT EltType = LoadVT.getScalarType(); 4714 EVT IntVT = LoadVT.changeTypeToInteger(); 4715 4716 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4717 4718 unsigned Opc = 4719 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4720 4721 if (IsD16) { 4722 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4723 } 4724 4725 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4726 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4727 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4728 4729 if (isTypeLegal(LoadVT)) { 4730 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4731 M->getMemOperand(), DAG); 4732 } 4733 4734 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4735 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4736 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4737 M->getMemOperand(), DAG); 4738 return DAG.getMergeValues( 4739 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4740 DL); 4741 } 4742 4743 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4744 SDNode *N, SelectionDAG &DAG) { 4745 EVT VT = N->getValueType(0); 4746 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4747 unsigned CondCode = CD->getZExtValue(); 4748 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4749 return DAG.getUNDEF(VT); 4750 4751 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4752 4753 SDValue LHS = N->getOperand(1); 4754 SDValue RHS = N->getOperand(2); 4755 4756 SDLoc DL(N); 4757 4758 EVT CmpVT = LHS.getValueType(); 4759 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4760 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4761 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4762 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4763 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4764 } 4765 4766 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4767 4768 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4769 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4770 4771 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4772 DAG.getCondCode(CCOpcode)); 4773 if (VT.bitsEq(CCVT)) 4774 return SetCC; 4775 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4776 } 4777 4778 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4779 SDNode *N, SelectionDAG &DAG) { 4780 EVT VT = N->getValueType(0); 4781 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4782 4783 unsigned CondCode = CD->getZExtValue(); 4784 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4785 return DAG.getUNDEF(VT); 4786 4787 SDValue Src0 = N->getOperand(1); 4788 SDValue Src1 = N->getOperand(2); 4789 EVT CmpVT = Src0.getValueType(); 4790 SDLoc SL(N); 4791 4792 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4793 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4794 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4795 } 4796 4797 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4798 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4799 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4800 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4801 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4802 Src1, DAG.getCondCode(CCOpcode)); 4803 if (VT.bitsEq(CCVT)) 4804 return SetCC; 4805 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4806 } 4807 4808 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4809 SelectionDAG &DAG) { 4810 EVT VT = N->getValueType(0); 4811 SDValue Src = N->getOperand(1); 4812 SDLoc SL(N); 4813 4814 if (Src.getOpcode() == ISD::SETCC) { 4815 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4816 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4817 Src.getOperand(1), Src.getOperand(2)); 4818 } 4819 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4820 // (ballot 0) -> 0 4821 if (Arg->isNullValue()) 4822 return DAG.getConstant(0, SL, VT); 4823 4824 // (ballot 1) -> EXEC/EXEC_LO 4825 if (Arg->isOne()) { 4826 Register Exec; 4827 if (VT.getScalarSizeInBits() == 32) 4828 Exec = AMDGPU::EXEC_LO; 4829 else if (VT.getScalarSizeInBits() == 64) 4830 Exec = AMDGPU::EXEC; 4831 else 4832 return SDValue(); 4833 4834 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4835 } 4836 } 4837 4838 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4839 // ISD::SETNE) 4840 return DAG.getNode( 4841 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4842 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4843 } 4844 4845 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4846 SmallVectorImpl<SDValue> &Results, 4847 SelectionDAG &DAG) const { 4848 switch (N->getOpcode()) { 4849 case ISD::INSERT_VECTOR_ELT: { 4850 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4851 Results.push_back(Res); 4852 return; 4853 } 4854 case ISD::EXTRACT_VECTOR_ELT: { 4855 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4856 Results.push_back(Res); 4857 return; 4858 } 4859 case ISD::INTRINSIC_WO_CHAIN: { 4860 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4861 switch (IID) { 4862 case Intrinsic::amdgcn_cvt_pkrtz: { 4863 SDValue Src0 = N->getOperand(1); 4864 SDValue Src1 = N->getOperand(2); 4865 SDLoc SL(N); 4866 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4867 Src0, Src1); 4868 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4869 return; 4870 } 4871 case Intrinsic::amdgcn_cvt_pknorm_i16: 4872 case Intrinsic::amdgcn_cvt_pknorm_u16: 4873 case Intrinsic::amdgcn_cvt_pk_i16: 4874 case Intrinsic::amdgcn_cvt_pk_u16: { 4875 SDValue Src0 = N->getOperand(1); 4876 SDValue Src1 = N->getOperand(2); 4877 SDLoc SL(N); 4878 unsigned Opcode; 4879 4880 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4881 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4882 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4883 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4884 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4885 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4886 else 4887 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4888 4889 EVT VT = N->getValueType(0); 4890 if (isTypeLegal(VT)) 4891 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4892 else { 4893 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4894 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4895 } 4896 return; 4897 } 4898 } 4899 break; 4900 } 4901 case ISD::INTRINSIC_W_CHAIN: { 4902 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4903 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4904 // FIXME: Hacky 4905 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4906 Results.push_back(Res.getOperand(I)); 4907 } 4908 } else { 4909 Results.push_back(Res); 4910 Results.push_back(Res.getValue(1)); 4911 } 4912 return; 4913 } 4914 4915 break; 4916 } 4917 case ISD::SELECT: { 4918 SDLoc SL(N); 4919 EVT VT = N->getValueType(0); 4920 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4921 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4922 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4923 4924 EVT SelectVT = NewVT; 4925 if (NewVT.bitsLT(MVT::i32)) { 4926 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4927 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4928 SelectVT = MVT::i32; 4929 } 4930 4931 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4932 N->getOperand(0), LHS, RHS); 4933 4934 if (NewVT != SelectVT) 4935 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4936 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4937 return; 4938 } 4939 case ISD::FNEG: { 4940 if (N->getValueType(0) != MVT::v2f16) 4941 break; 4942 4943 SDLoc SL(N); 4944 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4945 4946 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4947 BC, 4948 DAG.getConstant(0x80008000, SL, MVT::i32)); 4949 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4950 return; 4951 } 4952 case ISD::FABS: { 4953 if (N->getValueType(0) != MVT::v2f16) 4954 break; 4955 4956 SDLoc SL(N); 4957 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4958 4959 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4960 BC, 4961 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4962 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4963 return; 4964 } 4965 default: 4966 break; 4967 } 4968 } 4969 4970 /// Helper function for LowerBRCOND 4971 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4972 4973 SDNode *Parent = Value.getNode(); 4974 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4975 I != E; ++I) { 4976 4977 if (I.getUse().get() != Value) 4978 continue; 4979 4980 if (I->getOpcode() == Opcode) 4981 return *I; 4982 } 4983 return nullptr; 4984 } 4985 4986 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4987 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4988 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4989 case Intrinsic::amdgcn_if: 4990 return AMDGPUISD::IF; 4991 case Intrinsic::amdgcn_else: 4992 return AMDGPUISD::ELSE; 4993 case Intrinsic::amdgcn_loop: 4994 return AMDGPUISD::LOOP; 4995 case Intrinsic::amdgcn_end_cf: 4996 llvm_unreachable("should not occur"); 4997 default: 4998 return 0; 4999 } 5000 } 5001 5002 // break, if_break, else_break are all only used as inputs to loop, not 5003 // directly as branch conditions. 5004 return 0; 5005 } 5006 5007 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5008 const Triple &TT = getTargetMachine().getTargetTriple(); 5009 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5010 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5011 AMDGPU::shouldEmitConstantsToTextSection(TT); 5012 } 5013 5014 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5015 // FIXME: Either avoid relying on address space here or change the default 5016 // address space for functions to avoid the explicit check. 5017 return (GV->getValueType()->isFunctionTy() || 5018 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5019 !shouldEmitFixup(GV) && 5020 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5021 } 5022 5023 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5024 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5025 } 5026 5027 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5028 if (!GV->hasExternalLinkage()) 5029 return true; 5030 5031 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5032 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5033 } 5034 5035 /// This transforms the control flow intrinsics to get the branch destination as 5036 /// last parameter, also switches branch target with BR if the need arise 5037 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5038 SelectionDAG &DAG) const { 5039 SDLoc DL(BRCOND); 5040 5041 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5042 SDValue Target = BRCOND.getOperand(2); 5043 SDNode *BR = nullptr; 5044 SDNode *SetCC = nullptr; 5045 5046 if (Intr->getOpcode() == ISD::SETCC) { 5047 // As long as we negate the condition everything is fine 5048 SetCC = Intr; 5049 Intr = SetCC->getOperand(0).getNode(); 5050 5051 } else { 5052 // Get the target from BR if we don't negate the condition 5053 BR = findUser(BRCOND, ISD::BR); 5054 assert(BR && "brcond missing unconditional branch user"); 5055 Target = BR->getOperand(1); 5056 } 5057 5058 unsigned CFNode = isCFIntrinsic(Intr); 5059 if (CFNode == 0) { 5060 // This is a uniform branch so we don't need to legalize. 5061 return BRCOND; 5062 } 5063 5064 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5065 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5066 5067 assert(!SetCC || 5068 (SetCC->getConstantOperandVal(1) == 1 && 5069 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5070 ISD::SETNE)); 5071 5072 // operands of the new intrinsic call 5073 SmallVector<SDValue, 4> Ops; 5074 if (HaveChain) 5075 Ops.push_back(BRCOND.getOperand(0)); 5076 5077 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5078 Ops.push_back(Target); 5079 5080 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5081 5082 // build the new intrinsic call 5083 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5084 5085 if (!HaveChain) { 5086 SDValue Ops[] = { 5087 SDValue(Result, 0), 5088 BRCOND.getOperand(0) 5089 }; 5090 5091 Result = DAG.getMergeValues(Ops, DL).getNode(); 5092 } 5093 5094 if (BR) { 5095 // Give the branch instruction our target 5096 SDValue Ops[] = { 5097 BR->getOperand(0), 5098 BRCOND.getOperand(2) 5099 }; 5100 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5101 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5102 } 5103 5104 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5105 5106 // Copy the intrinsic results to registers 5107 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5108 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5109 if (!CopyToReg) 5110 continue; 5111 5112 Chain = DAG.getCopyToReg( 5113 Chain, DL, 5114 CopyToReg->getOperand(1), 5115 SDValue(Result, i - 1), 5116 SDValue()); 5117 5118 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5119 } 5120 5121 // Remove the old intrinsic from the chain 5122 DAG.ReplaceAllUsesOfValueWith( 5123 SDValue(Intr, Intr->getNumValues() - 1), 5124 Intr->getOperand(0)); 5125 5126 return Chain; 5127 } 5128 5129 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5130 SelectionDAG &DAG) const { 5131 MVT VT = Op.getSimpleValueType(); 5132 SDLoc DL(Op); 5133 // Checking the depth 5134 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5135 return DAG.getConstant(0, DL, VT); 5136 5137 MachineFunction &MF = DAG.getMachineFunction(); 5138 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5139 // Check for kernel and shader functions 5140 if (Info->isEntryFunction()) 5141 return DAG.getConstant(0, DL, VT); 5142 5143 MachineFrameInfo &MFI = MF.getFrameInfo(); 5144 // There is a call to @llvm.returnaddress in this function 5145 MFI.setReturnAddressIsTaken(true); 5146 5147 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5148 // Get the return address reg and mark it as an implicit live-in 5149 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5150 5151 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5152 } 5153 5154 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5155 SDValue Op, 5156 const SDLoc &DL, 5157 EVT VT) const { 5158 return Op.getValueType().bitsLE(VT) ? 5159 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5160 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5161 DAG.getTargetConstant(0, DL, MVT::i32)); 5162 } 5163 5164 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5165 assert(Op.getValueType() == MVT::f16 && 5166 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5167 5168 SDValue Src = Op.getOperand(0); 5169 EVT SrcVT = Src.getValueType(); 5170 if (SrcVT != MVT::f64) 5171 return Op; 5172 5173 SDLoc DL(Op); 5174 5175 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5176 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5177 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5178 } 5179 5180 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5181 SelectionDAG &DAG) const { 5182 EVT VT = Op.getValueType(); 5183 const MachineFunction &MF = DAG.getMachineFunction(); 5184 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5185 bool IsIEEEMode = Info->getMode().IEEE; 5186 5187 // FIXME: Assert during selection that this is only selected for 5188 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5189 // mode functions, but this happens to be OK since it's only done in cases 5190 // where there is known no sNaN. 5191 if (IsIEEEMode) 5192 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5193 5194 if (VT == MVT::v4f16) 5195 return splitBinaryVectorOp(Op, DAG); 5196 return Op; 5197 } 5198 5199 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5200 EVT VT = Op.getValueType(); 5201 SDLoc SL(Op); 5202 SDValue LHS = Op.getOperand(0); 5203 SDValue RHS = Op.getOperand(1); 5204 bool isSigned = Op.getOpcode() == ISD::SMULO; 5205 5206 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5207 const APInt &C = RHSC->getAPIntValue(); 5208 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5209 if (C.isPowerOf2()) { 5210 // smulo(x, signed_min) is same as umulo(x, signed_min). 5211 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5212 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5213 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5214 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5215 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5216 SL, VT, Result, ShiftAmt), 5217 LHS, ISD::SETNE); 5218 return DAG.getMergeValues({ Result, Overflow }, SL); 5219 } 5220 } 5221 5222 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5223 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5224 SL, VT, LHS, RHS); 5225 5226 SDValue Sign = isSigned 5227 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5228 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5229 : DAG.getConstant(0, SL, VT); 5230 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5231 5232 return DAG.getMergeValues({ Result, Overflow }, SL); 5233 } 5234 5235 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5236 if (!Subtarget->isTrapHandlerEnabled() || 5237 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5238 return lowerTrapEndpgm(Op, DAG); 5239 5240 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5241 switch (*HsaAbiVer) { 5242 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5243 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5244 return lowerTrapHsaQueuePtr(Op, DAG); 5245 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5246 return Subtarget->supportsGetDoorbellID() ? 5247 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5248 } 5249 } 5250 5251 llvm_unreachable("Unknown trap handler"); 5252 } 5253 5254 SDValue SITargetLowering::lowerTrapEndpgm( 5255 SDValue Op, SelectionDAG &DAG) const { 5256 SDLoc SL(Op); 5257 SDValue Chain = Op.getOperand(0); 5258 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5259 } 5260 5261 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5262 SDValue Op, SelectionDAG &DAG) const { 5263 SDLoc SL(Op); 5264 SDValue Chain = Op.getOperand(0); 5265 5266 MachineFunction &MF = DAG.getMachineFunction(); 5267 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5268 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5269 assert(UserSGPR != AMDGPU::NoRegister); 5270 SDValue QueuePtr = CreateLiveInRegister( 5271 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5272 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5273 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5274 QueuePtr, SDValue()); 5275 5276 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5277 SDValue Ops[] = { 5278 ToReg, 5279 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5280 SGPR01, 5281 ToReg.getValue(1) 5282 }; 5283 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5284 } 5285 5286 SDValue SITargetLowering::lowerTrapHsa( 5287 SDValue Op, SelectionDAG &DAG) const { 5288 SDLoc SL(Op); 5289 SDValue Chain = Op.getOperand(0); 5290 5291 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5292 SDValue Ops[] = { 5293 Chain, 5294 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5295 }; 5296 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5297 } 5298 5299 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5300 SDLoc SL(Op); 5301 SDValue Chain = Op.getOperand(0); 5302 MachineFunction &MF = DAG.getMachineFunction(); 5303 5304 if (!Subtarget->isTrapHandlerEnabled() || 5305 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5306 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5307 "debugtrap handler not supported", 5308 Op.getDebugLoc(), 5309 DS_Warning); 5310 LLVMContext &Ctx = MF.getFunction().getContext(); 5311 Ctx.diagnose(NoTrap); 5312 return Chain; 5313 } 5314 5315 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5316 SDValue Ops[] = { 5317 Chain, 5318 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5319 }; 5320 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5321 } 5322 5323 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5324 SelectionDAG &DAG) const { 5325 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5326 if (Subtarget->hasApertureRegs()) { 5327 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5328 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5329 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5330 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5331 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5332 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5333 unsigned Encoding = 5334 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5335 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5336 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5337 5338 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5339 SDValue ApertureReg = SDValue( 5340 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5341 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5342 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5343 } 5344 5345 MachineFunction &MF = DAG.getMachineFunction(); 5346 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5347 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5348 assert(UserSGPR != AMDGPU::NoRegister); 5349 5350 SDValue QueuePtr = CreateLiveInRegister( 5351 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5352 5353 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5354 // private_segment_aperture_base_hi. 5355 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5356 5357 SDValue Ptr = 5358 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5359 5360 // TODO: Use custom target PseudoSourceValue. 5361 // TODO: We should use the value from the IR intrinsic call, but it might not 5362 // be available and how do we get it? 5363 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5364 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5365 commonAlignment(Align(64), StructOffset), 5366 MachineMemOperand::MODereferenceable | 5367 MachineMemOperand::MOInvariant); 5368 } 5369 5370 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5371 SelectionDAG &DAG) const { 5372 SDLoc SL(Op); 5373 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5374 5375 SDValue Src = ASC->getOperand(0); 5376 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5377 5378 const AMDGPUTargetMachine &TM = 5379 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5380 5381 // flat -> local/private 5382 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5383 unsigned DestAS = ASC->getDestAddressSpace(); 5384 5385 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5386 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5387 unsigned NullVal = TM.getNullPointerValue(DestAS); 5388 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5389 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5390 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5391 5392 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5393 NonNull, Ptr, SegmentNullPtr); 5394 } 5395 } 5396 5397 // local/private -> flat 5398 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5399 unsigned SrcAS = ASC->getSrcAddressSpace(); 5400 5401 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5402 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5403 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5404 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5405 5406 SDValue NonNull 5407 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5408 5409 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5410 SDValue CvtPtr 5411 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5412 5413 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5414 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5415 FlatNullPtr); 5416 } 5417 } 5418 5419 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5420 Src.getValueType() == MVT::i64) 5421 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5422 5423 // global <-> flat are no-ops and never emitted. 5424 5425 const MachineFunction &MF = DAG.getMachineFunction(); 5426 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5427 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5428 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5429 5430 return DAG.getUNDEF(ASC->getValueType(0)); 5431 } 5432 5433 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5434 // the small vector and inserting them into the big vector. That is better than 5435 // the default expansion of doing it via a stack slot. Even though the use of 5436 // the stack slot would be optimized away afterwards, the stack slot itself 5437 // remains. 5438 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5439 SelectionDAG &DAG) const { 5440 SDValue Vec = Op.getOperand(0); 5441 SDValue Ins = Op.getOperand(1); 5442 SDValue Idx = Op.getOperand(2); 5443 EVT VecVT = Vec.getValueType(); 5444 EVT InsVT = Ins.getValueType(); 5445 EVT EltVT = VecVT.getVectorElementType(); 5446 unsigned InsNumElts = InsVT.getVectorNumElements(); 5447 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5448 SDLoc SL(Op); 5449 5450 for (unsigned I = 0; I != InsNumElts; ++I) { 5451 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5452 DAG.getConstant(I, SL, MVT::i32)); 5453 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5454 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5455 } 5456 return Vec; 5457 } 5458 5459 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5460 SelectionDAG &DAG) const { 5461 SDValue Vec = Op.getOperand(0); 5462 SDValue InsVal = Op.getOperand(1); 5463 SDValue Idx = Op.getOperand(2); 5464 EVT VecVT = Vec.getValueType(); 5465 EVT EltVT = VecVT.getVectorElementType(); 5466 unsigned VecSize = VecVT.getSizeInBits(); 5467 unsigned EltSize = EltVT.getSizeInBits(); 5468 5469 5470 assert(VecSize <= 64); 5471 5472 unsigned NumElts = VecVT.getVectorNumElements(); 5473 SDLoc SL(Op); 5474 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5475 5476 if (NumElts == 4 && EltSize == 16 && KIdx) { 5477 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5478 5479 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5480 DAG.getConstant(0, SL, MVT::i32)); 5481 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5482 DAG.getConstant(1, SL, MVT::i32)); 5483 5484 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5485 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5486 5487 unsigned Idx = KIdx->getZExtValue(); 5488 bool InsertLo = Idx < 2; 5489 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5490 InsertLo ? LoVec : HiVec, 5491 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5492 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5493 5494 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5495 5496 SDValue Concat = InsertLo ? 5497 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5498 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5499 5500 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5501 } 5502 5503 if (isa<ConstantSDNode>(Idx)) 5504 return SDValue(); 5505 5506 MVT IntVT = MVT::getIntegerVT(VecSize); 5507 5508 // Avoid stack access for dynamic indexing. 5509 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5510 5511 // Create a congruent vector with the target value in each element so that 5512 // the required element can be masked and ORed into the target vector. 5513 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5514 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5515 5516 assert(isPowerOf2_32(EltSize)); 5517 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5518 5519 // Convert vector index to bit-index. 5520 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5521 5522 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5523 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5524 DAG.getConstant(0xffff, SL, IntVT), 5525 ScaledIdx); 5526 5527 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5528 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5529 DAG.getNOT(SL, BFM, IntVT), BCVec); 5530 5531 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5532 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5533 } 5534 5535 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5536 SelectionDAG &DAG) const { 5537 SDLoc SL(Op); 5538 5539 EVT ResultVT = Op.getValueType(); 5540 SDValue Vec = Op.getOperand(0); 5541 SDValue Idx = Op.getOperand(1); 5542 EVT VecVT = Vec.getValueType(); 5543 unsigned VecSize = VecVT.getSizeInBits(); 5544 EVT EltVT = VecVT.getVectorElementType(); 5545 assert(VecSize <= 64); 5546 5547 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5548 5549 // Make sure we do any optimizations that will make it easier to fold 5550 // source modifiers before obscuring it with bit operations. 5551 5552 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5553 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5554 return Combined; 5555 5556 unsigned EltSize = EltVT.getSizeInBits(); 5557 assert(isPowerOf2_32(EltSize)); 5558 5559 MVT IntVT = MVT::getIntegerVT(VecSize); 5560 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5561 5562 // Convert vector index to bit-index (* EltSize) 5563 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5564 5565 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5566 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5567 5568 if (ResultVT == MVT::f16) { 5569 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5570 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5571 } 5572 5573 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5574 } 5575 5576 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5577 assert(Elt % 2 == 0); 5578 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5579 } 5580 5581 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5582 SelectionDAG &DAG) const { 5583 SDLoc SL(Op); 5584 EVT ResultVT = Op.getValueType(); 5585 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5586 5587 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5588 EVT EltVT = PackVT.getVectorElementType(); 5589 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5590 5591 // vector_shuffle <0,1,6,7> lhs, rhs 5592 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5593 // 5594 // vector_shuffle <6,7,2,3> lhs, rhs 5595 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5596 // 5597 // vector_shuffle <6,7,0,1> lhs, rhs 5598 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5599 5600 // Avoid scalarizing when both halves are reading from consecutive elements. 5601 SmallVector<SDValue, 4> Pieces; 5602 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5603 if (elementPairIsContiguous(SVN->getMask(), I)) { 5604 const int Idx = SVN->getMaskElt(I); 5605 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5606 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5607 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5608 PackVT, SVN->getOperand(VecIdx), 5609 DAG.getConstant(EltIdx, SL, MVT::i32)); 5610 Pieces.push_back(SubVec); 5611 } else { 5612 const int Idx0 = SVN->getMaskElt(I); 5613 const int Idx1 = SVN->getMaskElt(I + 1); 5614 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5615 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5616 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5617 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5618 5619 SDValue Vec0 = SVN->getOperand(VecIdx0); 5620 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5621 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5622 5623 SDValue Vec1 = SVN->getOperand(VecIdx1); 5624 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5625 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5626 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5627 } 5628 } 5629 5630 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5631 } 5632 5633 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5634 SelectionDAG &DAG) const { 5635 SDLoc SL(Op); 5636 EVT VT = Op.getValueType(); 5637 5638 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5639 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5640 5641 // Turn into pair of packed build_vectors. 5642 // TODO: Special case for constants that can be materialized with s_mov_b64. 5643 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5644 { Op.getOperand(0), Op.getOperand(1) }); 5645 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5646 { Op.getOperand(2), Op.getOperand(3) }); 5647 5648 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5649 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5650 5651 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5652 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5653 } 5654 5655 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5656 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5657 5658 SDValue Lo = Op.getOperand(0); 5659 SDValue Hi = Op.getOperand(1); 5660 5661 // Avoid adding defined bits with the zero_extend. 5662 if (Hi.isUndef()) { 5663 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5664 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5665 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5666 } 5667 5668 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5669 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5670 5671 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5672 DAG.getConstant(16, SL, MVT::i32)); 5673 if (Lo.isUndef()) 5674 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5675 5676 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5677 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5678 5679 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5680 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5681 } 5682 5683 bool 5684 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5685 // We can fold offsets for anything that doesn't require a GOT relocation. 5686 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5687 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5688 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5689 !shouldEmitGOTReloc(GA->getGlobal()); 5690 } 5691 5692 static SDValue 5693 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5694 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5695 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5696 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5697 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5698 // lowered to the following code sequence: 5699 // 5700 // For constant address space: 5701 // s_getpc_b64 s[0:1] 5702 // s_add_u32 s0, s0, $symbol 5703 // s_addc_u32 s1, s1, 0 5704 // 5705 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5706 // a fixup or relocation is emitted to replace $symbol with a literal 5707 // constant, which is a pc-relative offset from the encoding of the $symbol 5708 // operand to the global variable. 5709 // 5710 // For global address space: 5711 // s_getpc_b64 s[0:1] 5712 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5713 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5714 // 5715 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5716 // fixups or relocations are emitted to replace $symbol@*@lo and 5717 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5718 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5719 // operand to the global variable. 5720 // 5721 // What we want here is an offset from the value returned by s_getpc 5722 // (which is the address of the s_add_u32 instruction) to the global 5723 // variable, but since the encoding of $symbol starts 4 bytes after the start 5724 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5725 // small. This requires us to add 4 to the global variable offset in order to 5726 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5727 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5728 // instruction. 5729 SDValue PtrLo = 5730 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5731 SDValue PtrHi; 5732 if (GAFlags == SIInstrInfo::MO_NONE) { 5733 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5734 } else { 5735 PtrHi = 5736 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5737 } 5738 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5739 } 5740 5741 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5742 SDValue Op, 5743 SelectionDAG &DAG) const { 5744 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5745 SDLoc DL(GSD); 5746 EVT PtrVT = Op.getValueType(); 5747 5748 const GlobalValue *GV = GSD->getGlobal(); 5749 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5750 shouldUseLDSConstAddress(GV)) || 5751 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5752 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5753 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5754 GV->hasExternalLinkage()) { 5755 Type *Ty = GV->getValueType(); 5756 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5757 // zero-sized type in other languages to declare the dynamic shared 5758 // memory which size is not known at the compile time. They will be 5759 // allocated by the runtime and placed directly after the static 5760 // allocated ones. They all share the same offset. 5761 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5762 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5763 // Adjust alignment for that dynamic shared memory array. 5764 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5765 return SDValue( 5766 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5767 } 5768 } 5769 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5770 } 5771 5772 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5773 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5774 SIInstrInfo::MO_ABS32_LO); 5775 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5776 } 5777 5778 if (shouldEmitFixup(GV)) 5779 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5780 else if (shouldEmitPCReloc(GV)) 5781 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5782 SIInstrInfo::MO_REL32); 5783 5784 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5785 SIInstrInfo::MO_GOTPCREL32); 5786 5787 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5788 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5789 const DataLayout &DataLayout = DAG.getDataLayout(); 5790 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5791 MachinePointerInfo PtrInfo 5792 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5793 5794 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5795 MachineMemOperand::MODereferenceable | 5796 MachineMemOperand::MOInvariant); 5797 } 5798 5799 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5800 const SDLoc &DL, SDValue V) const { 5801 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5802 // the destination register. 5803 // 5804 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5805 // so we will end up with redundant moves to m0. 5806 // 5807 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5808 5809 // A Null SDValue creates a glue result. 5810 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5811 V, Chain); 5812 return SDValue(M0, 0); 5813 } 5814 5815 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5816 SDValue Op, 5817 MVT VT, 5818 unsigned Offset) const { 5819 SDLoc SL(Op); 5820 SDValue Param = lowerKernargMemParameter( 5821 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5822 // The local size values will have the hi 16-bits as zero. 5823 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5824 DAG.getValueType(VT)); 5825 } 5826 5827 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5828 EVT VT) { 5829 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5830 "non-hsa intrinsic with hsa target", 5831 DL.getDebugLoc()); 5832 DAG.getContext()->diagnose(BadIntrin); 5833 return DAG.getUNDEF(VT); 5834 } 5835 5836 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5837 EVT VT) { 5838 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5839 "intrinsic not supported on subtarget", 5840 DL.getDebugLoc()); 5841 DAG.getContext()->diagnose(BadIntrin); 5842 return DAG.getUNDEF(VT); 5843 } 5844 5845 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5846 ArrayRef<SDValue> Elts) { 5847 assert(!Elts.empty()); 5848 MVT Type; 5849 unsigned NumElts; 5850 5851 if (Elts.size() == 1) { 5852 Type = MVT::f32; 5853 NumElts = 1; 5854 } else if (Elts.size() == 2) { 5855 Type = MVT::v2f32; 5856 NumElts = 2; 5857 } else if (Elts.size() == 3) { 5858 Type = MVT::v3f32; 5859 NumElts = 3; 5860 } else if (Elts.size() <= 4) { 5861 Type = MVT::v4f32; 5862 NumElts = 4; 5863 } else if (Elts.size() <= 5) { 5864 Type = MVT::v5f32; 5865 NumElts = 5; 5866 } else if (Elts.size() <= 8) { 5867 Type = MVT::v8f32; 5868 NumElts = 8; 5869 } else { 5870 assert(Elts.size() <= 16); 5871 Type = MVT::v16f32; 5872 NumElts = 16; 5873 } 5874 5875 SmallVector<SDValue, 16> VecElts(NumElts); 5876 for (unsigned i = 0; i < Elts.size(); ++i) { 5877 SDValue Elt = Elts[i]; 5878 if (Elt.getValueType() != MVT::f32) 5879 Elt = DAG.getBitcast(MVT::f32, Elt); 5880 VecElts[i] = Elt; 5881 } 5882 for (unsigned i = Elts.size(); i < NumElts; ++i) 5883 VecElts[i] = DAG.getUNDEF(MVT::f32); 5884 5885 if (NumElts == 1) 5886 return VecElts[0]; 5887 return DAG.getBuildVector(Type, DL, VecElts); 5888 } 5889 5890 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5891 SDValue Src, int ExtraElts) { 5892 EVT SrcVT = Src.getValueType(); 5893 5894 SmallVector<SDValue, 8> Elts; 5895 5896 if (SrcVT.isVector()) 5897 DAG.ExtractVectorElements(Src, Elts); 5898 else 5899 Elts.push_back(Src); 5900 5901 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5902 while (ExtraElts--) 5903 Elts.push_back(Undef); 5904 5905 return DAG.getBuildVector(CastVT, DL, Elts); 5906 } 5907 5908 // Re-construct the required return value for a image load intrinsic. 5909 // This is more complicated due to the optional use TexFailCtrl which means the required 5910 // return type is an aggregate 5911 static SDValue constructRetValue(SelectionDAG &DAG, 5912 MachineSDNode *Result, 5913 ArrayRef<EVT> ResultTypes, 5914 bool IsTexFail, bool Unpacked, bool IsD16, 5915 int DMaskPop, int NumVDataDwords, 5916 const SDLoc &DL) { 5917 // Determine the required return type. This is the same regardless of IsTexFail flag 5918 EVT ReqRetVT = ResultTypes[0]; 5919 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5920 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5921 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5922 5923 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5924 DMaskPop : (DMaskPop + 1) / 2; 5925 5926 MVT DataDwordVT = NumDataDwords == 1 ? 5927 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5928 5929 MVT MaskPopVT = MaskPopDwords == 1 ? 5930 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5931 5932 SDValue Data(Result, 0); 5933 SDValue TexFail; 5934 5935 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5936 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5937 if (MaskPopVT.isVector()) { 5938 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5939 SDValue(Result, 0), ZeroIdx); 5940 } else { 5941 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5942 SDValue(Result, 0), ZeroIdx); 5943 } 5944 } 5945 5946 if (DataDwordVT.isVector()) 5947 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5948 NumDataDwords - MaskPopDwords); 5949 5950 if (IsD16) 5951 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5952 5953 EVT LegalReqRetVT = ReqRetVT; 5954 if (!ReqRetVT.isVector()) { 5955 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5956 } else { 5957 // We need to widen the return vector to a legal type 5958 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5959 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5960 LegalReqRetVT = 5961 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5962 ReqRetVT.getVectorNumElements() + 1); 5963 } 5964 } 5965 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5966 5967 if (IsTexFail) { 5968 TexFail = 5969 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5970 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5971 5972 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5973 } 5974 5975 if (Result->getNumValues() == 1) 5976 return Data; 5977 5978 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5979 } 5980 5981 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5982 SDValue *LWE, bool &IsTexFail) { 5983 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5984 5985 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5986 if (Value) { 5987 IsTexFail = true; 5988 } 5989 5990 SDLoc DL(TexFailCtrlConst); 5991 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5992 Value &= ~(uint64_t)0x1; 5993 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5994 Value &= ~(uint64_t)0x2; 5995 5996 return Value == 0; 5997 } 5998 5999 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6000 MVT PackVectorVT, 6001 SmallVectorImpl<SDValue> &PackedAddrs, 6002 unsigned DimIdx, unsigned EndIdx, 6003 unsigned NumGradients) { 6004 SDLoc DL(Op); 6005 for (unsigned I = DimIdx; I < EndIdx; I++) { 6006 SDValue Addr = Op.getOperand(I); 6007 6008 // Gradients are packed with undef for each coordinate. 6009 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6010 // 1D: undef,dx/dh; undef,dx/dv 6011 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6012 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6013 if (((I + 1) >= EndIdx) || 6014 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6015 I == DimIdx + NumGradients - 1))) { 6016 if (Addr.getValueType() != MVT::i16) 6017 Addr = DAG.getBitcast(MVT::i16, Addr); 6018 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6019 } else { 6020 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6021 I++; 6022 } 6023 Addr = DAG.getBitcast(MVT::f32, Addr); 6024 PackedAddrs.push_back(Addr); 6025 } 6026 } 6027 6028 SDValue SITargetLowering::lowerImage(SDValue Op, 6029 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6030 SelectionDAG &DAG, bool WithChain) const { 6031 SDLoc DL(Op); 6032 MachineFunction &MF = DAG.getMachineFunction(); 6033 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6034 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6035 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6036 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6037 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6038 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6039 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6040 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6041 unsigned IntrOpcode = Intr->BaseOpcode; 6042 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6043 6044 SmallVector<EVT, 3> ResultTypes(Op->values()); 6045 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6046 bool IsD16 = false; 6047 bool IsG16 = false; 6048 bool IsA16 = false; 6049 SDValue VData; 6050 int NumVDataDwords; 6051 bool AdjustRetType = false; 6052 6053 // Offset of intrinsic arguments 6054 const unsigned ArgOffset = WithChain ? 2 : 1; 6055 6056 unsigned DMask; 6057 unsigned DMaskLanes = 0; 6058 6059 if (BaseOpcode->Atomic) { 6060 VData = Op.getOperand(2); 6061 6062 bool Is64Bit = VData.getValueType() == MVT::i64; 6063 if (BaseOpcode->AtomicX2) { 6064 SDValue VData2 = Op.getOperand(3); 6065 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6066 {VData, VData2}); 6067 if (Is64Bit) 6068 VData = DAG.getBitcast(MVT::v4i32, VData); 6069 6070 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6071 DMask = Is64Bit ? 0xf : 0x3; 6072 NumVDataDwords = Is64Bit ? 4 : 2; 6073 } else { 6074 DMask = Is64Bit ? 0x3 : 0x1; 6075 NumVDataDwords = Is64Bit ? 2 : 1; 6076 } 6077 } else { 6078 auto *DMaskConst = 6079 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6080 DMask = DMaskConst->getZExtValue(); 6081 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6082 6083 if (BaseOpcode->Store) { 6084 VData = Op.getOperand(2); 6085 6086 MVT StoreVT = VData.getSimpleValueType(); 6087 if (StoreVT.getScalarType() == MVT::f16) { 6088 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6089 return Op; // D16 is unsupported for this instruction 6090 6091 IsD16 = true; 6092 VData = handleD16VData(VData, DAG, true); 6093 } 6094 6095 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6096 } else { 6097 // Work out the num dwords based on the dmask popcount and underlying type 6098 // and whether packing is supported. 6099 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6100 if (LoadVT.getScalarType() == MVT::f16) { 6101 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6102 return Op; // D16 is unsupported for this instruction 6103 6104 IsD16 = true; 6105 } 6106 6107 // Confirm that the return type is large enough for the dmask specified 6108 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6109 (!LoadVT.isVector() && DMaskLanes > 1)) 6110 return Op; 6111 6112 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6113 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6114 // instructions. 6115 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6116 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6117 NumVDataDwords = (DMaskLanes + 1) / 2; 6118 else 6119 NumVDataDwords = DMaskLanes; 6120 6121 AdjustRetType = true; 6122 } 6123 } 6124 6125 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6126 SmallVector<SDValue, 4> VAddrs; 6127 6128 // Optimize _L to _LZ when _L is zero 6129 if (LZMappingInfo) { 6130 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6131 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6132 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6133 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6134 VAddrEnd--; // remove 'lod' 6135 } 6136 } 6137 } 6138 6139 // Optimize _mip away, when 'lod' is zero 6140 if (MIPMappingInfo) { 6141 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6142 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6143 if (ConstantLod->isNullValue()) { 6144 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6145 VAddrEnd--; // remove 'mip' 6146 } 6147 } 6148 } 6149 6150 // Push back extra arguments. 6151 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6152 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6153 6154 // Check for 16 bit addresses or derivatives and pack if true. 6155 MVT VAddrVT = 6156 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6157 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6158 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6159 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6160 6161 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6162 VAddrScalarVT = VAddrVT.getScalarType(); 6163 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6164 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6165 6166 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6167 // 16 bit gradients are supported, but are tied to the A16 control 6168 // so both gradients and addresses must be 16 bit 6169 LLVM_DEBUG( 6170 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6171 "require 16 bit args for both gradients and addresses"); 6172 return Op; 6173 } 6174 6175 if (IsA16) { 6176 if (!ST->hasA16()) { 6177 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6178 "support 16 bit addresses\n"); 6179 return Op; 6180 } 6181 } 6182 6183 // We've dealt with incorrect input so we know that if IsA16, IsG16 6184 // are set then we have to compress/pack operands (either address, 6185 // gradient or both) 6186 // In the case where a16 and gradients are tied (no G16 support) then we 6187 // have already verified that both IsA16 and IsG16 are true 6188 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6189 // Activate g16 6190 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6191 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6192 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6193 } 6194 6195 // Add gradients (packed or unpacked) 6196 if (IsG16) { 6197 // Pack the gradients 6198 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6199 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6200 ArgOffset + Intr->GradientStart, 6201 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6202 } else { 6203 for (unsigned I = ArgOffset + Intr->GradientStart; 6204 I < ArgOffset + Intr->CoordStart; I++) 6205 VAddrs.push_back(Op.getOperand(I)); 6206 } 6207 6208 // Add addresses (packed or unpacked) 6209 if (IsA16) { 6210 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6211 ArgOffset + Intr->CoordStart, VAddrEnd, 6212 0 /* No gradients */); 6213 } else { 6214 // Add uncompressed address 6215 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6216 VAddrs.push_back(Op.getOperand(I)); 6217 } 6218 6219 // If the register allocator cannot place the address registers contiguously 6220 // without introducing moves, then using the non-sequential address encoding 6221 // is always preferable, since it saves VALU instructions and is usually a 6222 // wash in terms of code size or even better. 6223 // 6224 // However, we currently have no way of hinting to the register allocator that 6225 // MIMG addresses should be placed contiguously when it is possible to do so, 6226 // so force non-NSA for the common 2-address case as a heuristic. 6227 // 6228 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6229 // allocation when possible. 6230 bool UseNSA = 6231 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6232 SDValue VAddr; 6233 if (!UseNSA) 6234 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6235 6236 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6237 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6238 SDValue Unorm; 6239 if (!BaseOpcode->Sampler) { 6240 Unorm = True; 6241 } else { 6242 auto UnormConst = 6243 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6244 6245 Unorm = UnormConst->getZExtValue() ? True : False; 6246 } 6247 6248 SDValue TFE; 6249 SDValue LWE; 6250 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6251 bool IsTexFail = false; 6252 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6253 return Op; 6254 6255 if (IsTexFail) { 6256 if (!DMaskLanes) { 6257 // Expecting to get an error flag since TFC is on - and dmask is 0 6258 // Force dmask to be at least 1 otherwise the instruction will fail 6259 DMask = 0x1; 6260 DMaskLanes = 1; 6261 NumVDataDwords = 1; 6262 } 6263 NumVDataDwords += 1; 6264 AdjustRetType = true; 6265 } 6266 6267 // Has something earlier tagged that the return type needs adjusting 6268 // This happens if the instruction is a load or has set TexFailCtrl flags 6269 if (AdjustRetType) { 6270 // NumVDataDwords reflects the true number of dwords required in the return type 6271 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6272 // This is a no-op load. This can be eliminated 6273 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6274 if (isa<MemSDNode>(Op)) 6275 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6276 return Undef; 6277 } 6278 6279 EVT NewVT = NumVDataDwords > 1 ? 6280 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6281 : MVT::i32; 6282 6283 ResultTypes[0] = NewVT; 6284 if (ResultTypes.size() == 3) { 6285 // Original result was aggregate type used for TexFailCtrl results 6286 // The actual instruction returns as a vector type which has now been 6287 // created. Remove the aggregate result. 6288 ResultTypes.erase(&ResultTypes[1]); 6289 } 6290 } 6291 6292 unsigned CPol = cast<ConstantSDNode>( 6293 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6294 if (BaseOpcode->Atomic) 6295 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6296 if (CPol & ~AMDGPU::CPol::ALL) 6297 return Op; 6298 6299 SmallVector<SDValue, 26> Ops; 6300 if (BaseOpcode->Store || BaseOpcode->Atomic) 6301 Ops.push_back(VData); // vdata 6302 if (UseNSA) 6303 append_range(Ops, VAddrs); 6304 else 6305 Ops.push_back(VAddr); 6306 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6307 if (BaseOpcode->Sampler) 6308 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6309 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6310 if (IsGFX10Plus) 6311 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6312 Ops.push_back(Unorm); 6313 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6314 Ops.push_back(IsA16 && // r128, a16 for gfx9 6315 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6316 if (IsGFX10Plus) 6317 Ops.push_back(IsA16 ? True : False); 6318 if (!Subtarget->hasGFX90AInsts()) { 6319 Ops.push_back(TFE); //tfe 6320 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6321 report_fatal_error("TFE is not supported on this GPU"); 6322 } 6323 Ops.push_back(LWE); // lwe 6324 if (!IsGFX10Plus) 6325 Ops.push_back(DimInfo->DA ? True : False); 6326 if (BaseOpcode->HasD16) 6327 Ops.push_back(IsD16 ? True : False); 6328 if (isa<MemSDNode>(Op)) 6329 Ops.push_back(Op.getOperand(0)); // chain 6330 6331 int NumVAddrDwords = 6332 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6333 int Opcode = -1; 6334 6335 if (IsGFX10Plus) { 6336 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6337 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6338 : AMDGPU::MIMGEncGfx10Default, 6339 NumVDataDwords, NumVAddrDwords); 6340 } else { 6341 if (Subtarget->hasGFX90AInsts()) { 6342 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6343 NumVDataDwords, NumVAddrDwords); 6344 if (Opcode == -1) 6345 report_fatal_error( 6346 "requested image instruction is not supported on this GPU"); 6347 } 6348 if (Opcode == -1 && 6349 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6350 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6351 NumVDataDwords, NumVAddrDwords); 6352 if (Opcode == -1) 6353 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6354 NumVDataDwords, NumVAddrDwords); 6355 } 6356 assert(Opcode != -1); 6357 6358 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6359 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6360 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6361 DAG.setNodeMemRefs(NewNode, {MemRef}); 6362 } 6363 6364 if (BaseOpcode->AtomicX2) { 6365 SmallVector<SDValue, 1> Elt; 6366 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6367 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6368 } 6369 if (BaseOpcode->Store) 6370 return SDValue(NewNode, 0); 6371 return constructRetValue(DAG, NewNode, 6372 OrigResultTypes, IsTexFail, 6373 Subtarget->hasUnpackedD16VMem(), IsD16, 6374 DMaskLanes, NumVDataDwords, DL); 6375 } 6376 6377 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6378 SDValue Offset, SDValue CachePolicy, 6379 SelectionDAG &DAG) const { 6380 MachineFunction &MF = DAG.getMachineFunction(); 6381 6382 const DataLayout &DataLayout = DAG.getDataLayout(); 6383 Align Alignment = 6384 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6385 6386 MachineMemOperand *MMO = MF.getMachineMemOperand( 6387 MachinePointerInfo(), 6388 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6389 MachineMemOperand::MOInvariant, 6390 VT.getStoreSize(), Alignment); 6391 6392 if (!Offset->isDivergent()) { 6393 SDValue Ops[] = { 6394 Rsrc, 6395 Offset, // Offset 6396 CachePolicy 6397 }; 6398 6399 // Widen vec3 load to vec4. 6400 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6401 EVT WidenedVT = 6402 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6403 auto WidenedOp = DAG.getMemIntrinsicNode( 6404 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6405 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6406 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6407 DAG.getVectorIdxConstant(0, DL)); 6408 return Subvector; 6409 } 6410 6411 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6412 DAG.getVTList(VT), Ops, VT, MMO); 6413 } 6414 6415 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6416 // assume that the buffer is unswizzled. 6417 SmallVector<SDValue, 4> Loads; 6418 unsigned NumLoads = 1; 6419 MVT LoadVT = VT.getSimpleVT(); 6420 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6421 assert((LoadVT.getScalarType() == MVT::i32 || 6422 LoadVT.getScalarType() == MVT::f32)); 6423 6424 if (NumElts == 8 || NumElts == 16) { 6425 NumLoads = NumElts / 4; 6426 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6427 } 6428 6429 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6430 SDValue Ops[] = { 6431 DAG.getEntryNode(), // Chain 6432 Rsrc, // rsrc 6433 DAG.getConstant(0, DL, MVT::i32), // vindex 6434 {}, // voffset 6435 {}, // soffset 6436 {}, // offset 6437 CachePolicy, // cachepolicy 6438 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6439 }; 6440 6441 // Use the alignment to ensure that the required offsets will fit into the 6442 // immediate offsets. 6443 setBufferOffsets(Offset, DAG, &Ops[3], 6444 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6445 6446 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6447 for (unsigned i = 0; i < NumLoads; ++i) { 6448 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6449 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6450 LoadVT, MMO, DAG)); 6451 } 6452 6453 if (NumElts == 8 || NumElts == 16) 6454 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6455 6456 return Loads[0]; 6457 } 6458 6459 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6460 SelectionDAG &DAG) const { 6461 MachineFunction &MF = DAG.getMachineFunction(); 6462 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6463 6464 EVT VT = Op.getValueType(); 6465 SDLoc DL(Op); 6466 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6467 6468 // TODO: Should this propagate fast-math-flags? 6469 6470 switch (IntrinsicID) { 6471 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6472 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6473 return emitNonHSAIntrinsicError(DAG, DL, VT); 6474 return getPreloadedValue(DAG, *MFI, VT, 6475 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6476 } 6477 case Intrinsic::amdgcn_dispatch_ptr: 6478 case Intrinsic::amdgcn_queue_ptr: { 6479 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6480 DiagnosticInfoUnsupported BadIntrin( 6481 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6482 DL.getDebugLoc()); 6483 DAG.getContext()->diagnose(BadIntrin); 6484 return DAG.getUNDEF(VT); 6485 } 6486 6487 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6488 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6489 return getPreloadedValue(DAG, *MFI, VT, RegID); 6490 } 6491 case Intrinsic::amdgcn_implicitarg_ptr: { 6492 if (MFI->isEntryFunction()) 6493 return getImplicitArgPtr(DAG, DL); 6494 return getPreloadedValue(DAG, *MFI, VT, 6495 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6496 } 6497 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6498 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6499 // This only makes sense to call in a kernel, so just lower to null. 6500 return DAG.getConstant(0, DL, VT); 6501 } 6502 6503 return getPreloadedValue(DAG, *MFI, VT, 6504 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6505 } 6506 case Intrinsic::amdgcn_dispatch_id: { 6507 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6508 } 6509 case Intrinsic::amdgcn_rcp: 6510 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6511 case Intrinsic::amdgcn_rsq: 6512 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6513 case Intrinsic::amdgcn_rsq_legacy: 6514 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6515 return emitRemovedIntrinsicError(DAG, DL, VT); 6516 return SDValue(); 6517 case Intrinsic::amdgcn_rcp_legacy: 6518 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6519 return emitRemovedIntrinsicError(DAG, DL, VT); 6520 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6521 case Intrinsic::amdgcn_rsq_clamp: { 6522 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6523 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6524 6525 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6526 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6527 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6528 6529 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6530 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6531 DAG.getConstantFP(Max, DL, VT)); 6532 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6533 DAG.getConstantFP(Min, DL, VT)); 6534 } 6535 case Intrinsic::r600_read_ngroups_x: 6536 if (Subtarget->isAmdHsaOS()) 6537 return emitNonHSAIntrinsicError(DAG, DL, VT); 6538 6539 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6540 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6541 false); 6542 case Intrinsic::r600_read_ngroups_y: 6543 if (Subtarget->isAmdHsaOS()) 6544 return emitNonHSAIntrinsicError(DAG, DL, VT); 6545 6546 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6547 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6548 false); 6549 case Intrinsic::r600_read_ngroups_z: 6550 if (Subtarget->isAmdHsaOS()) 6551 return emitNonHSAIntrinsicError(DAG, DL, VT); 6552 6553 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6554 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6555 false); 6556 case Intrinsic::r600_read_global_size_x: 6557 if (Subtarget->isAmdHsaOS()) 6558 return emitNonHSAIntrinsicError(DAG, DL, VT); 6559 6560 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6561 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6562 Align(4), false); 6563 case Intrinsic::r600_read_global_size_y: 6564 if (Subtarget->isAmdHsaOS()) 6565 return emitNonHSAIntrinsicError(DAG, DL, VT); 6566 6567 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6568 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6569 Align(4), false); 6570 case Intrinsic::r600_read_global_size_z: 6571 if (Subtarget->isAmdHsaOS()) 6572 return emitNonHSAIntrinsicError(DAG, DL, VT); 6573 6574 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6575 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6576 Align(4), false); 6577 case Intrinsic::r600_read_local_size_x: 6578 if (Subtarget->isAmdHsaOS()) 6579 return emitNonHSAIntrinsicError(DAG, DL, VT); 6580 6581 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6582 SI::KernelInputOffsets::LOCAL_SIZE_X); 6583 case Intrinsic::r600_read_local_size_y: 6584 if (Subtarget->isAmdHsaOS()) 6585 return emitNonHSAIntrinsicError(DAG, DL, VT); 6586 6587 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6588 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6589 case Intrinsic::r600_read_local_size_z: 6590 if (Subtarget->isAmdHsaOS()) 6591 return emitNonHSAIntrinsicError(DAG, DL, VT); 6592 6593 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6594 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6595 case Intrinsic::amdgcn_workgroup_id_x: 6596 return getPreloadedValue(DAG, *MFI, VT, 6597 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6598 case Intrinsic::amdgcn_workgroup_id_y: 6599 return getPreloadedValue(DAG, *MFI, VT, 6600 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6601 case Intrinsic::amdgcn_workgroup_id_z: 6602 return getPreloadedValue(DAG, *MFI, VT, 6603 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6604 case Intrinsic::amdgcn_workitem_id_x: 6605 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6606 SDLoc(DAG.getEntryNode()), 6607 MFI->getArgInfo().WorkItemIDX); 6608 case Intrinsic::amdgcn_workitem_id_y: 6609 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6610 SDLoc(DAG.getEntryNode()), 6611 MFI->getArgInfo().WorkItemIDY); 6612 case Intrinsic::amdgcn_workitem_id_z: 6613 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6614 SDLoc(DAG.getEntryNode()), 6615 MFI->getArgInfo().WorkItemIDZ); 6616 case Intrinsic::amdgcn_wavefrontsize: 6617 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6618 SDLoc(Op), MVT::i32); 6619 case Intrinsic::amdgcn_s_buffer_load: { 6620 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6621 if (CPol & ~AMDGPU::CPol::ALL) 6622 return Op; 6623 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6624 DAG); 6625 } 6626 case Intrinsic::amdgcn_fdiv_fast: 6627 return lowerFDIV_FAST(Op, DAG); 6628 case Intrinsic::amdgcn_sin: 6629 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6630 6631 case Intrinsic::amdgcn_cos: 6632 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6633 6634 case Intrinsic::amdgcn_mul_u24: 6635 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6636 case Intrinsic::amdgcn_mul_i24: 6637 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6638 6639 case Intrinsic::amdgcn_log_clamp: { 6640 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6641 return SDValue(); 6642 6643 return emitRemovedIntrinsicError(DAG, DL, VT); 6644 } 6645 case Intrinsic::amdgcn_ldexp: 6646 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6647 Op.getOperand(1), Op.getOperand(2)); 6648 6649 case Intrinsic::amdgcn_fract: 6650 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6651 6652 case Intrinsic::amdgcn_class: 6653 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6654 Op.getOperand(1), Op.getOperand(2)); 6655 case Intrinsic::amdgcn_div_fmas: 6656 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6657 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6658 Op.getOperand(4)); 6659 6660 case Intrinsic::amdgcn_div_fixup: 6661 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6662 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6663 6664 case Intrinsic::amdgcn_div_scale: { 6665 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6666 6667 // Translate to the operands expected by the machine instruction. The 6668 // first parameter must be the same as the first instruction. 6669 SDValue Numerator = Op.getOperand(1); 6670 SDValue Denominator = Op.getOperand(2); 6671 6672 // Note this order is opposite of the machine instruction's operations, 6673 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6674 // intrinsic has the numerator as the first operand to match a normal 6675 // division operation. 6676 6677 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6678 6679 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6680 Denominator, Numerator); 6681 } 6682 case Intrinsic::amdgcn_icmp: { 6683 // There is a Pat that handles this variant, so return it as-is. 6684 if (Op.getOperand(1).getValueType() == MVT::i1 && 6685 Op.getConstantOperandVal(2) == 0 && 6686 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6687 return Op; 6688 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6689 } 6690 case Intrinsic::amdgcn_fcmp: { 6691 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6692 } 6693 case Intrinsic::amdgcn_ballot: 6694 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6695 case Intrinsic::amdgcn_fmed3: 6696 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6697 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6698 case Intrinsic::amdgcn_fdot2: 6699 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6700 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6701 Op.getOperand(4)); 6702 case Intrinsic::amdgcn_fmul_legacy: 6703 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6704 Op.getOperand(1), Op.getOperand(2)); 6705 case Intrinsic::amdgcn_sffbh: 6706 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6707 case Intrinsic::amdgcn_sbfe: 6708 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6709 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6710 case Intrinsic::amdgcn_ubfe: 6711 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6712 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6713 case Intrinsic::amdgcn_cvt_pkrtz: 6714 case Intrinsic::amdgcn_cvt_pknorm_i16: 6715 case Intrinsic::amdgcn_cvt_pknorm_u16: 6716 case Intrinsic::amdgcn_cvt_pk_i16: 6717 case Intrinsic::amdgcn_cvt_pk_u16: { 6718 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6719 EVT VT = Op.getValueType(); 6720 unsigned Opcode; 6721 6722 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6723 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6724 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6725 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6726 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6727 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6728 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6729 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6730 else 6731 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6732 6733 if (isTypeLegal(VT)) 6734 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6735 6736 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6737 Op.getOperand(1), Op.getOperand(2)); 6738 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6739 } 6740 case Intrinsic::amdgcn_fmad_ftz: 6741 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6742 Op.getOperand(2), Op.getOperand(3)); 6743 6744 case Intrinsic::amdgcn_if_break: 6745 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6746 Op->getOperand(1), Op->getOperand(2)), 0); 6747 6748 case Intrinsic::amdgcn_groupstaticsize: { 6749 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6750 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6751 return Op; 6752 6753 const Module *M = MF.getFunction().getParent(); 6754 const GlobalValue *GV = 6755 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6756 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6757 SIInstrInfo::MO_ABS32_LO); 6758 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6759 } 6760 case Intrinsic::amdgcn_is_shared: 6761 case Intrinsic::amdgcn_is_private: { 6762 SDLoc SL(Op); 6763 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6764 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6765 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6766 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6767 Op.getOperand(1)); 6768 6769 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6770 DAG.getConstant(1, SL, MVT::i32)); 6771 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6772 } 6773 case Intrinsic::amdgcn_alignbit: 6774 return DAG.getNode(ISD::FSHR, DL, VT, 6775 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6776 case Intrinsic::amdgcn_perm: 6777 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6778 Op.getOperand(2), Op.getOperand(3)); 6779 case Intrinsic::amdgcn_reloc_constant: { 6780 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6781 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6782 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6783 auto RelocSymbol = cast<GlobalVariable>( 6784 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6785 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6786 SIInstrInfo::MO_ABS32_LO); 6787 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6788 } 6789 default: 6790 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6791 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6792 return lowerImage(Op, ImageDimIntr, DAG, false); 6793 6794 return Op; 6795 } 6796 } 6797 6798 // This function computes an appropriate offset to pass to 6799 // MachineMemOperand::setOffset() based on the offset inputs to 6800 // an intrinsic. If any of the offsets are non-contstant or 6801 // if VIndex is non-zero then this function returns 0. Otherwise, 6802 // it returns the sum of VOffset, SOffset, and Offset. 6803 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6804 SDValue SOffset, 6805 SDValue Offset, 6806 SDValue VIndex = SDValue()) { 6807 6808 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6809 !isa<ConstantSDNode>(Offset)) 6810 return 0; 6811 6812 if (VIndex) { 6813 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6814 return 0; 6815 } 6816 6817 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6818 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6819 cast<ConstantSDNode>(Offset)->getSExtValue(); 6820 } 6821 6822 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6823 SelectionDAG &DAG, 6824 unsigned NewOpcode) const { 6825 SDLoc DL(Op); 6826 6827 SDValue VData = Op.getOperand(2); 6828 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6829 SDValue Ops[] = { 6830 Op.getOperand(0), // Chain 6831 VData, // vdata 6832 Op.getOperand(3), // rsrc 6833 DAG.getConstant(0, DL, MVT::i32), // vindex 6834 Offsets.first, // voffset 6835 Op.getOperand(5), // soffset 6836 Offsets.second, // offset 6837 Op.getOperand(6), // cachepolicy 6838 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6839 }; 6840 6841 auto *M = cast<MemSDNode>(Op); 6842 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6843 6844 EVT MemVT = VData.getValueType(); 6845 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6846 M->getMemOperand()); 6847 } 6848 6849 SDValue 6850 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6851 unsigned NewOpcode) const { 6852 SDLoc DL(Op); 6853 6854 SDValue VData = Op.getOperand(2); 6855 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6856 SDValue Ops[] = { 6857 Op.getOperand(0), // Chain 6858 VData, // vdata 6859 Op.getOperand(3), // rsrc 6860 Op.getOperand(4), // vindex 6861 Offsets.first, // voffset 6862 Op.getOperand(6), // soffset 6863 Offsets.second, // offset 6864 Op.getOperand(7), // cachepolicy 6865 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6866 }; 6867 6868 auto *M = cast<MemSDNode>(Op); 6869 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6870 Ops[3])); 6871 6872 EVT MemVT = VData.getValueType(); 6873 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6874 M->getMemOperand()); 6875 } 6876 6877 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6878 SelectionDAG &DAG) const { 6879 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6880 SDLoc DL(Op); 6881 6882 switch (IntrID) { 6883 case Intrinsic::amdgcn_ds_ordered_add: 6884 case Intrinsic::amdgcn_ds_ordered_swap: { 6885 MemSDNode *M = cast<MemSDNode>(Op); 6886 SDValue Chain = M->getOperand(0); 6887 SDValue M0 = M->getOperand(2); 6888 SDValue Value = M->getOperand(3); 6889 unsigned IndexOperand = M->getConstantOperandVal(7); 6890 unsigned WaveRelease = M->getConstantOperandVal(8); 6891 unsigned WaveDone = M->getConstantOperandVal(9); 6892 6893 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6894 IndexOperand &= ~0x3f; 6895 unsigned CountDw = 0; 6896 6897 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6898 CountDw = (IndexOperand >> 24) & 0xf; 6899 IndexOperand &= ~(0xf << 24); 6900 6901 if (CountDw < 1 || CountDw > 4) { 6902 report_fatal_error( 6903 "ds_ordered_count: dword count must be between 1 and 4"); 6904 } 6905 } 6906 6907 if (IndexOperand) 6908 report_fatal_error("ds_ordered_count: bad index operand"); 6909 6910 if (WaveDone && !WaveRelease) 6911 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6912 6913 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6914 unsigned ShaderType = 6915 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6916 unsigned Offset0 = OrderedCountIndex << 2; 6917 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6918 (Instruction << 4); 6919 6920 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6921 Offset1 |= (CountDw - 1) << 6; 6922 6923 unsigned Offset = Offset0 | (Offset1 << 8); 6924 6925 SDValue Ops[] = { 6926 Chain, 6927 Value, 6928 DAG.getTargetConstant(Offset, DL, MVT::i16), 6929 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6930 }; 6931 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6932 M->getVTList(), Ops, M->getMemoryVT(), 6933 M->getMemOperand()); 6934 } 6935 case Intrinsic::amdgcn_ds_fadd: { 6936 MemSDNode *M = cast<MemSDNode>(Op); 6937 unsigned Opc; 6938 switch (IntrID) { 6939 case Intrinsic::amdgcn_ds_fadd: 6940 Opc = ISD::ATOMIC_LOAD_FADD; 6941 break; 6942 } 6943 6944 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6945 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6946 M->getMemOperand()); 6947 } 6948 case Intrinsic::amdgcn_atomic_inc: 6949 case Intrinsic::amdgcn_atomic_dec: 6950 case Intrinsic::amdgcn_ds_fmin: 6951 case Intrinsic::amdgcn_ds_fmax: { 6952 MemSDNode *M = cast<MemSDNode>(Op); 6953 unsigned Opc; 6954 switch (IntrID) { 6955 case Intrinsic::amdgcn_atomic_inc: 6956 Opc = AMDGPUISD::ATOMIC_INC; 6957 break; 6958 case Intrinsic::amdgcn_atomic_dec: 6959 Opc = AMDGPUISD::ATOMIC_DEC; 6960 break; 6961 case Intrinsic::amdgcn_ds_fmin: 6962 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6963 break; 6964 case Intrinsic::amdgcn_ds_fmax: 6965 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6966 break; 6967 default: 6968 llvm_unreachable("Unknown intrinsic!"); 6969 } 6970 SDValue Ops[] = { 6971 M->getOperand(0), // Chain 6972 M->getOperand(2), // Ptr 6973 M->getOperand(3) // Value 6974 }; 6975 6976 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6977 M->getMemoryVT(), M->getMemOperand()); 6978 } 6979 case Intrinsic::amdgcn_buffer_load: 6980 case Intrinsic::amdgcn_buffer_load_format: { 6981 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6982 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6983 unsigned IdxEn = 1; 6984 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6985 IdxEn = Idx->getZExtValue() != 0; 6986 SDValue Ops[] = { 6987 Op.getOperand(0), // Chain 6988 Op.getOperand(2), // rsrc 6989 Op.getOperand(3), // vindex 6990 SDValue(), // voffset -- will be set by setBufferOffsets 6991 SDValue(), // soffset -- will be set by setBufferOffsets 6992 SDValue(), // offset -- will be set by setBufferOffsets 6993 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6994 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6995 }; 6996 6997 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6998 // We don't know the offset if vindex is non-zero, so clear it. 6999 if (IdxEn) 7000 Offset = 0; 7001 7002 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7003 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7004 7005 EVT VT = Op.getValueType(); 7006 EVT IntVT = VT.changeTypeToInteger(); 7007 auto *M = cast<MemSDNode>(Op); 7008 M->getMemOperand()->setOffset(Offset); 7009 EVT LoadVT = Op.getValueType(); 7010 7011 if (LoadVT.getScalarType() == MVT::f16) 7012 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7013 M, DAG, Ops); 7014 7015 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7016 if (LoadVT.getScalarType() == MVT::i8 || 7017 LoadVT.getScalarType() == MVT::i16) 7018 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7019 7020 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7021 M->getMemOperand(), DAG); 7022 } 7023 case Intrinsic::amdgcn_raw_buffer_load: 7024 case Intrinsic::amdgcn_raw_buffer_load_format: { 7025 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7026 7027 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7028 SDValue Ops[] = { 7029 Op.getOperand(0), // Chain 7030 Op.getOperand(2), // rsrc 7031 DAG.getConstant(0, DL, MVT::i32), // vindex 7032 Offsets.first, // voffset 7033 Op.getOperand(4), // soffset 7034 Offsets.second, // offset 7035 Op.getOperand(5), // cachepolicy, swizzled buffer 7036 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7037 }; 7038 7039 auto *M = cast<MemSDNode>(Op); 7040 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 7041 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7042 } 7043 case Intrinsic::amdgcn_struct_buffer_load: 7044 case Intrinsic::amdgcn_struct_buffer_load_format: { 7045 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7046 7047 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7048 SDValue Ops[] = { 7049 Op.getOperand(0), // Chain 7050 Op.getOperand(2), // rsrc 7051 Op.getOperand(3), // vindex 7052 Offsets.first, // voffset 7053 Op.getOperand(5), // soffset 7054 Offsets.second, // offset 7055 Op.getOperand(6), // cachepolicy, swizzled buffer 7056 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7057 }; 7058 7059 auto *M = cast<MemSDNode>(Op); 7060 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 7061 Ops[2])); 7062 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7063 } 7064 case Intrinsic::amdgcn_tbuffer_load: { 7065 MemSDNode *M = cast<MemSDNode>(Op); 7066 EVT LoadVT = Op.getValueType(); 7067 7068 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7069 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7070 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7071 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7072 unsigned IdxEn = 1; 7073 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 7074 IdxEn = Idx->getZExtValue() != 0; 7075 SDValue Ops[] = { 7076 Op.getOperand(0), // Chain 7077 Op.getOperand(2), // rsrc 7078 Op.getOperand(3), // vindex 7079 Op.getOperand(4), // voffset 7080 Op.getOperand(5), // soffset 7081 Op.getOperand(6), // offset 7082 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7083 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7084 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7085 }; 7086 7087 if (LoadVT.getScalarType() == MVT::f16) 7088 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7089 M, DAG, Ops); 7090 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7091 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7092 DAG); 7093 } 7094 case Intrinsic::amdgcn_raw_tbuffer_load: { 7095 MemSDNode *M = cast<MemSDNode>(Op); 7096 EVT LoadVT = Op.getValueType(); 7097 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7098 7099 SDValue Ops[] = { 7100 Op.getOperand(0), // Chain 7101 Op.getOperand(2), // rsrc 7102 DAG.getConstant(0, DL, MVT::i32), // vindex 7103 Offsets.first, // voffset 7104 Op.getOperand(4), // soffset 7105 Offsets.second, // offset 7106 Op.getOperand(5), // format 7107 Op.getOperand(6), // cachepolicy, swizzled buffer 7108 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7109 }; 7110 7111 if (LoadVT.getScalarType() == MVT::f16) 7112 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7113 M, DAG, Ops); 7114 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7115 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7116 DAG); 7117 } 7118 case Intrinsic::amdgcn_struct_tbuffer_load: { 7119 MemSDNode *M = cast<MemSDNode>(Op); 7120 EVT LoadVT = Op.getValueType(); 7121 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7122 7123 SDValue Ops[] = { 7124 Op.getOperand(0), // Chain 7125 Op.getOperand(2), // rsrc 7126 Op.getOperand(3), // vindex 7127 Offsets.first, // voffset 7128 Op.getOperand(5), // soffset 7129 Offsets.second, // offset 7130 Op.getOperand(6), // format 7131 Op.getOperand(7), // cachepolicy, swizzled buffer 7132 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7133 }; 7134 7135 if (LoadVT.getScalarType() == MVT::f16) 7136 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7137 M, DAG, Ops); 7138 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7139 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7140 DAG); 7141 } 7142 case Intrinsic::amdgcn_buffer_atomic_swap: 7143 case Intrinsic::amdgcn_buffer_atomic_add: 7144 case Intrinsic::amdgcn_buffer_atomic_sub: 7145 case Intrinsic::amdgcn_buffer_atomic_csub: 7146 case Intrinsic::amdgcn_buffer_atomic_smin: 7147 case Intrinsic::amdgcn_buffer_atomic_umin: 7148 case Intrinsic::amdgcn_buffer_atomic_smax: 7149 case Intrinsic::amdgcn_buffer_atomic_umax: 7150 case Intrinsic::amdgcn_buffer_atomic_and: 7151 case Intrinsic::amdgcn_buffer_atomic_or: 7152 case Intrinsic::amdgcn_buffer_atomic_xor: 7153 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7154 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7155 unsigned IdxEn = 1; 7156 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7157 IdxEn = Idx->getZExtValue() != 0; 7158 SDValue Ops[] = { 7159 Op.getOperand(0), // Chain 7160 Op.getOperand(2), // vdata 7161 Op.getOperand(3), // rsrc 7162 Op.getOperand(4), // vindex 7163 SDValue(), // voffset -- will be set by setBufferOffsets 7164 SDValue(), // soffset -- will be set by setBufferOffsets 7165 SDValue(), // offset -- will be set by setBufferOffsets 7166 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7167 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7168 }; 7169 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7170 // We don't know the offset if vindex is non-zero, so clear it. 7171 if (IdxEn) 7172 Offset = 0; 7173 EVT VT = Op.getValueType(); 7174 7175 auto *M = cast<MemSDNode>(Op); 7176 M->getMemOperand()->setOffset(Offset); 7177 unsigned Opcode = 0; 7178 7179 switch (IntrID) { 7180 case Intrinsic::amdgcn_buffer_atomic_swap: 7181 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7182 break; 7183 case Intrinsic::amdgcn_buffer_atomic_add: 7184 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7185 break; 7186 case Intrinsic::amdgcn_buffer_atomic_sub: 7187 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7188 break; 7189 case Intrinsic::amdgcn_buffer_atomic_csub: 7190 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7191 break; 7192 case Intrinsic::amdgcn_buffer_atomic_smin: 7193 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7194 break; 7195 case Intrinsic::amdgcn_buffer_atomic_umin: 7196 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7197 break; 7198 case Intrinsic::amdgcn_buffer_atomic_smax: 7199 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7200 break; 7201 case Intrinsic::amdgcn_buffer_atomic_umax: 7202 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7203 break; 7204 case Intrinsic::amdgcn_buffer_atomic_and: 7205 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7206 break; 7207 case Intrinsic::amdgcn_buffer_atomic_or: 7208 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7209 break; 7210 case Intrinsic::amdgcn_buffer_atomic_xor: 7211 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7212 break; 7213 case Intrinsic::amdgcn_buffer_atomic_fadd: 7214 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7215 DiagnosticInfoUnsupported 7216 NoFpRet(DAG.getMachineFunction().getFunction(), 7217 "return versions of fp atomics not supported", 7218 DL.getDebugLoc(), DS_Error); 7219 DAG.getContext()->diagnose(NoFpRet); 7220 return SDValue(); 7221 } 7222 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7223 break; 7224 default: 7225 llvm_unreachable("unhandled atomic opcode"); 7226 } 7227 7228 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7229 M->getMemOperand()); 7230 } 7231 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7232 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7233 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7234 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7235 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7236 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7237 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7238 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7239 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7240 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7241 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7242 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7243 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7244 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7245 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7246 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7247 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7248 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7249 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7250 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7251 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7252 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7253 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7254 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7255 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7256 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7257 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7258 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7259 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7260 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7261 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7262 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7263 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7264 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7265 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7266 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7267 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7268 return lowerStructBufferAtomicIntrin(Op, DAG, 7269 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7270 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7271 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7272 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7273 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7274 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7275 return lowerStructBufferAtomicIntrin(Op, DAG, 7276 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7277 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7278 return lowerStructBufferAtomicIntrin(Op, DAG, 7279 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7280 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7281 return lowerStructBufferAtomicIntrin(Op, DAG, 7282 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7283 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7284 return lowerStructBufferAtomicIntrin(Op, DAG, 7285 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7286 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7287 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7288 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7289 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7290 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7291 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7292 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7293 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7294 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7295 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7296 7297 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7298 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7299 unsigned IdxEn = 1; 7300 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7301 IdxEn = Idx->getZExtValue() != 0; 7302 SDValue Ops[] = { 7303 Op.getOperand(0), // Chain 7304 Op.getOperand(2), // src 7305 Op.getOperand(3), // cmp 7306 Op.getOperand(4), // rsrc 7307 Op.getOperand(5), // vindex 7308 SDValue(), // voffset -- will be set by setBufferOffsets 7309 SDValue(), // soffset -- will be set by setBufferOffsets 7310 SDValue(), // offset -- will be set by setBufferOffsets 7311 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7312 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7313 }; 7314 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7315 // We don't know the offset if vindex is non-zero, so clear it. 7316 if (IdxEn) 7317 Offset = 0; 7318 EVT VT = Op.getValueType(); 7319 auto *M = cast<MemSDNode>(Op); 7320 M->getMemOperand()->setOffset(Offset); 7321 7322 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7323 Op->getVTList(), Ops, VT, M->getMemOperand()); 7324 } 7325 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7326 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7327 SDValue Ops[] = { 7328 Op.getOperand(0), // Chain 7329 Op.getOperand(2), // src 7330 Op.getOperand(3), // cmp 7331 Op.getOperand(4), // rsrc 7332 DAG.getConstant(0, DL, MVT::i32), // vindex 7333 Offsets.first, // voffset 7334 Op.getOperand(6), // soffset 7335 Offsets.second, // offset 7336 Op.getOperand(7), // cachepolicy 7337 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7338 }; 7339 EVT VT = Op.getValueType(); 7340 auto *M = cast<MemSDNode>(Op); 7341 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7342 7343 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7344 Op->getVTList(), Ops, VT, M->getMemOperand()); 7345 } 7346 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7347 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7348 SDValue Ops[] = { 7349 Op.getOperand(0), // Chain 7350 Op.getOperand(2), // src 7351 Op.getOperand(3), // cmp 7352 Op.getOperand(4), // rsrc 7353 Op.getOperand(5), // vindex 7354 Offsets.first, // voffset 7355 Op.getOperand(7), // soffset 7356 Offsets.second, // offset 7357 Op.getOperand(8), // cachepolicy 7358 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7359 }; 7360 EVT VT = Op.getValueType(); 7361 auto *M = cast<MemSDNode>(Op); 7362 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7363 Ops[4])); 7364 7365 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7366 Op->getVTList(), Ops, VT, M->getMemOperand()); 7367 } 7368 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7369 SDLoc DL(Op); 7370 MemSDNode *M = cast<MemSDNode>(Op); 7371 SDValue NodePtr = M->getOperand(2); 7372 SDValue RayExtent = M->getOperand(3); 7373 SDValue RayOrigin = M->getOperand(4); 7374 SDValue RayDir = M->getOperand(5); 7375 SDValue RayInvDir = M->getOperand(6); 7376 SDValue TDescr = M->getOperand(7); 7377 7378 assert(NodePtr.getValueType() == MVT::i32 || 7379 NodePtr.getValueType() == MVT::i64); 7380 assert(RayDir.getValueType() == MVT::v4f16 || 7381 RayDir.getValueType() == MVT::v4f32); 7382 7383 if (!Subtarget->hasGFX10_AEncoding()) { 7384 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7385 return SDValue(); 7386 } 7387 7388 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7389 bool Is64 = NodePtr.getValueType() == MVT::i64; 7390 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7391 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7392 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7393 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7394 7395 SmallVector<SDValue, 16> Ops; 7396 7397 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7398 SmallVector<SDValue, 3> Lanes; 7399 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7400 if (Lanes[0].getValueSizeInBits() == 32) { 7401 for (unsigned I = 0; I < 3; ++I) 7402 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7403 } else { 7404 if (IsAligned) { 7405 Ops.push_back( 7406 DAG.getBitcast(MVT::i32, 7407 DAG.getBuildVector(MVT::v2f16, DL, 7408 { Lanes[0], Lanes[1] }))); 7409 Ops.push_back(Lanes[2]); 7410 } else { 7411 SDValue Elt0 = Ops.pop_back_val(); 7412 Ops.push_back( 7413 DAG.getBitcast(MVT::i32, 7414 DAG.getBuildVector(MVT::v2f16, DL, 7415 { Elt0, Lanes[0] }))); 7416 Ops.push_back( 7417 DAG.getBitcast(MVT::i32, 7418 DAG.getBuildVector(MVT::v2f16, DL, 7419 { Lanes[1], Lanes[2] }))); 7420 } 7421 } 7422 }; 7423 7424 if (Is64) 7425 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7426 else 7427 Ops.push_back(NodePtr); 7428 7429 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7430 packLanes(RayOrigin, true); 7431 packLanes(RayDir, true); 7432 packLanes(RayInvDir, false); 7433 Ops.push_back(TDescr); 7434 if (IsA16) 7435 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7436 Ops.push_back(M->getChain()); 7437 7438 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7439 MachineMemOperand *MemRef = M->getMemOperand(); 7440 DAG.setNodeMemRefs(NewNode, {MemRef}); 7441 return SDValue(NewNode, 0); 7442 } 7443 case Intrinsic::amdgcn_global_atomic_fadd: 7444 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7445 DiagnosticInfoUnsupported 7446 NoFpRet(DAG.getMachineFunction().getFunction(), 7447 "return versions of fp atomics not supported", 7448 DL.getDebugLoc(), DS_Error); 7449 DAG.getContext()->diagnose(NoFpRet); 7450 return SDValue(); 7451 } 7452 LLVM_FALLTHROUGH; 7453 case Intrinsic::amdgcn_global_atomic_fmin: 7454 case Intrinsic::amdgcn_global_atomic_fmax: 7455 case Intrinsic::amdgcn_flat_atomic_fadd: 7456 case Intrinsic::amdgcn_flat_atomic_fmin: 7457 case Intrinsic::amdgcn_flat_atomic_fmax: { 7458 MemSDNode *M = cast<MemSDNode>(Op); 7459 SDValue Ops[] = { 7460 M->getOperand(0), // Chain 7461 M->getOperand(2), // Ptr 7462 M->getOperand(3) // Value 7463 }; 7464 unsigned Opcode = 0; 7465 switch (IntrID) { 7466 case Intrinsic::amdgcn_global_atomic_fadd: 7467 case Intrinsic::amdgcn_flat_atomic_fadd: { 7468 EVT VT = Op.getOperand(3).getValueType(); 7469 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7470 DAG.getVTList(VT, MVT::Other), Ops, 7471 M->getMemOperand()); 7472 } 7473 case Intrinsic::amdgcn_global_atomic_fmin: 7474 case Intrinsic::amdgcn_flat_atomic_fmin: { 7475 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7476 break; 7477 } 7478 case Intrinsic::amdgcn_global_atomic_fmax: 7479 case Intrinsic::amdgcn_flat_atomic_fmax: { 7480 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7481 break; 7482 } 7483 default: 7484 llvm_unreachable("unhandled atomic opcode"); 7485 } 7486 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7487 M->getVTList(), Ops, M->getMemoryVT(), 7488 M->getMemOperand()); 7489 } 7490 default: 7491 7492 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7493 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7494 return lowerImage(Op, ImageDimIntr, DAG, true); 7495 7496 return SDValue(); 7497 } 7498 } 7499 7500 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7501 // dwordx4 if on SI. 7502 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7503 SDVTList VTList, 7504 ArrayRef<SDValue> Ops, EVT MemVT, 7505 MachineMemOperand *MMO, 7506 SelectionDAG &DAG) const { 7507 EVT VT = VTList.VTs[0]; 7508 EVT WidenedVT = VT; 7509 EVT WidenedMemVT = MemVT; 7510 if (!Subtarget->hasDwordx3LoadStores() && 7511 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7512 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7513 WidenedVT.getVectorElementType(), 4); 7514 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7515 WidenedMemVT.getVectorElementType(), 4); 7516 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7517 } 7518 7519 assert(VTList.NumVTs == 2); 7520 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7521 7522 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7523 WidenedMemVT, MMO); 7524 if (WidenedVT != VT) { 7525 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7526 DAG.getVectorIdxConstant(0, DL)); 7527 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7528 } 7529 return NewOp; 7530 } 7531 7532 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7533 bool ImageStore) const { 7534 EVT StoreVT = VData.getValueType(); 7535 7536 // No change for f16 and legal vector D16 types. 7537 if (!StoreVT.isVector()) 7538 return VData; 7539 7540 SDLoc DL(VData); 7541 unsigned NumElements = StoreVT.getVectorNumElements(); 7542 7543 if (Subtarget->hasUnpackedD16VMem()) { 7544 // We need to unpack the packed data to store. 7545 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7546 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7547 7548 EVT EquivStoreVT = 7549 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7550 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7551 return DAG.UnrollVectorOp(ZExt.getNode()); 7552 } 7553 7554 // The sq block of gfx8.1 does not estimate register use correctly for d16 7555 // image store instructions. The data operand is computed as if it were not a 7556 // d16 image instruction. 7557 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7558 // Bitcast to i16 7559 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7560 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7561 7562 // Decompose into scalars 7563 SmallVector<SDValue, 4> Elts; 7564 DAG.ExtractVectorElements(IntVData, Elts); 7565 7566 // Group pairs of i16 into v2i16 and bitcast to i32 7567 SmallVector<SDValue, 4> PackedElts; 7568 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7569 SDValue Pair = 7570 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7571 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7572 PackedElts.push_back(IntPair); 7573 } 7574 if ((NumElements % 2) == 1) { 7575 // Handle v3i16 7576 unsigned I = Elts.size() / 2; 7577 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7578 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7579 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7580 PackedElts.push_back(IntPair); 7581 } 7582 7583 // Pad using UNDEF 7584 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7585 7586 // Build final vector 7587 EVT VecVT = 7588 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7589 return DAG.getBuildVector(VecVT, DL, PackedElts); 7590 } 7591 7592 if (NumElements == 3) { 7593 EVT IntStoreVT = 7594 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7595 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7596 7597 EVT WidenedStoreVT = EVT::getVectorVT( 7598 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7599 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7600 WidenedStoreVT.getStoreSizeInBits()); 7601 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7602 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7603 } 7604 7605 assert(isTypeLegal(StoreVT)); 7606 return VData; 7607 } 7608 7609 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7610 SelectionDAG &DAG) const { 7611 SDLoc DL(Op); 7612 SDValue Chain = Op.getOperand(0); 7613 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7614 MachineFunction &MF = DAG.getMachineFunction(); 7615 7616 switch (IntrinsicID) { 7617 case Intrinsic::amdgcn_exp_compr: { 7618 SDValue Src0 = Op.getOperand(4); 7619 SDValue Src1 = Op.getOperand(5); 7620 // Hack around illegal type on SI by directly selecting it. 7621 if (isTypeLegal(Src0.getValueType())) 7622 return SDValue(); 7623 7624 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7625 SDValue Undef = DAG.getUNDEF(MVT::f32); 7626 const SDValue Ops[] = { 7627 Op.getOperand(2), // tgt 7628 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7629 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7630 Undef, // src2 7631 Undef, // src3 7632 Op.getOperand(7), // vm 7633 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7634 Op.getOperand(3), // en 7635 Op.getOperand(0) // Chain 7636 }; 7637 7638 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7639 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7640 } 7641 case Intrinsic::amdgcn_s_barrier: { 7642 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7643 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7644 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7645 if (WGSize <= ST.getWavefrontSize()) 7646 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7647 Op.getOperand(0)), 0); 7648 } 7649 return SDValue(); 7650 }; 7651 case Intrinsic::amdgcn_tbuffer_store: { 7652 SDValue VData = Op.getOperand(2); 7653 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7654 if (IsD16) 7655 VData = handleD16VData(VData, DAG); 7656 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7657 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7658 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7659 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7660 unsigned IdxEn = 1; 7661 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7662 IdxEn = Idx->getZExtValue() != 0; 7663 SDValue Ops[] = { 7664 Chain, 7665 VData, // vdata 7666 Op.getOperand(3), // rsrc 7667 Op.getOperand(4), // vindex 7668 Op.getOperand(5), // voffset 7669 Op.getOperand(6), // soffset 7670 Op.getOperand(7), // offset 7671 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7672 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7673 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7674 }; 7675 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7676 AMDGPUISD::TBUFFER_STORE_FORMAT; 7677 MemSDNode *M = cast<MemSDNode>(Op); 7678 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7679 M->getMemoryVT(), M->getMemOperand()); 7680 } 7681 7682 case Intrinsic::amdgcn_struct_tbuffer_store: { 7683 SDValue VData = Op.getOperand(2); 7684 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7685 if (IsD16) 7686 VData = handleD16VData(VData, DAG); 7687 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7688 SDValue Ops[] = { 7689 Chain, 7690 VData, // vdata 7691 Op.getOperand(3), // rsrc 7692 Op.getOperand(4), // vindex 7693 Offsets.first, // voffset 7694 Op.getOperand(6), // soffset 7695 Offsets.second, // offset 7696 Op.getOperand(7), // format 7697 Op.getOperand(8), // cachepolicy, swizzled buffer 7698 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7699 }; 7700 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7701 AMDGPUISD::TBUFFER_STORE_FORMAT; 7702 MemSDNode *M = cast<MemSDNode>(Op); 7703 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7704 M->getMemoryVT(), M->getMemOperand()); 7705 } 7706 7707 case Intrinsic::amdgcn_raw_tbuffer_store: { 7708 SDValue VData = Op.getOperand(2); 7709 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7710 if (IsD16) 7711 VData = handleD16VData(VData, DAG); 7712 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7713 SDValue Ops[] = { 7714 Chain, 7715 VData, // vdata 7716 Op.getOperand(3), // rsrc 7717 DAG.getConstant(0, DL, MVT::i32), // vindex 7718 Offsets.first, // voffset 7719 Op.getOperand(5), // soffset 7720 Offsets.second, // offset 7721 Op.getOperand(6), // format 7722 Op.getOperand(7), // cachepolicy, swizzled buffer 7723 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7724 }; 7725 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7726 AMDGPUISD::TBUFFER_STORE_FORMAT; 7727 MemSDNode *M = cast<MemSDNode>(Op); 7728 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7729 M->getMemoryVT(), M->getMemOperand()); 7730 } 7731 7732 case Intrinsic::amdgcn_buffer_store: 7733 case Intrinsic::amdgcn_buffer_store_format: { 7734 SDValue VData = Op.getOperand(2); 7735 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7736 if (IsD16) 7737 VData = handleD16VData(VData, DAG); 7738 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7739 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7740 unsigned IdxEn = 1; 7741 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7742 IdxEn = Idx->getZExtValue() != 0; 7743 SDValue Ops[] = { 7744 Chain, 7745 VData, 7746 Op.getOperand(3), // rsrc 7747 Op.getOperand(4), // vindex 7748 SDValue(), // voffset -- will be set by setBufferOffsets 7749 SDValue(), // soffset -- will be set by setBufferOffsets 7750 SDValue(), // offset -- will be set by setBufferOffsets 7751 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7752 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7753 }; 7754 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7755 // We don't know the offset if vindex is non-zero, so clear it. 7756 if (IdxEn) 7757 Offset = 0; 7758 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7759 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7760 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7761 MemSDNode *M = cast<MemSDNode>(Op); 7762 M->getMemOperand()->setOffset(Offset); 7763 7764 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7765 EVT VDataType = VData.getValueType().getScalarType(); 7766 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7767 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7768 7769 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7770 M->getMemoryVT(), M->getMemOperand()); 7771 } 7772 7773 case Intrinsic::amdgcn_raw_buffer_store: 7774 case Intrinsic::amdgcn_raw_buffer_store_format: { 7775 const bool IsFormat = 7776 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7777 7778 SDValue VData = Op.getOperand(2); 7779 EVT VDataVT = VData.getValueType(); 7780 EVT EltType = VDataVT.getScalarType(); 7781 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7782 if (IsD16) { 7783 VData = handleD16VData(VData, DAG); 7784 VDataVT = VData.getValueType(); 7785 } 7786 7787 if (!isTypeLegal(VDataVT)) { 7788 VData = 7789 DAG.getNode(ISD::BITCAST, DL, 7790 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7791 } 7792 7793 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7794 SDValue Ops[] = { 7795 Chain, 7796 VData, 7797 Op.getOperand(3), // rsrc 7798 DAG.getConstant(0, DL, MVT::i32), // vindex 7799 Offsets.first, // voffset 7800 Op.getOperand(5), // soffset 7801 Offsets.second, // offset 7802 Op.getOperand(6), // cachepolicy, swizzled buffer 7803 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7804 }; 7805 unsigned Opc = 7806 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7807 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7808 MemSDNode *M = cast<MemSDNode>(Op); 7809 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7810 7811 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7812 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7813 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7814 7815 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7816 M->getMemoryVT(), M->getMemOperand()); 7817 } 7818 7819 case Intrinsic::amdgcn_struct_buffer_store: 7820 case Intrinsic::amdgcn_struct_buffer_store_format: { 7821 const bool IsFormat = 7822 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7823 7824 SDValue VData = Op.getOperand(2); 7825 EVT VDataVT = VData.getValueType(); 7826 EVT EltType = VDataVT.getScalarType(); 7827 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7828 7829 if (IsD16) { 7830 VData = handleD16VData(VData, DAG); 7831 VDataVT = VData.getValueType(); 7832 } 7833 7834 if (!isTypeLegal(VDataVT)) { 7835 VData = 7836 DAG.getNode(ISD::BITCAST, DL, 7837 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7838 } 7839 7840 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7841 SDValue Ops[] = { 7842 Chain, 7843 VData, 7844 Op.getOperand(3), // rsrc 7845 Op.getOperand(4), // vindex 7846 Offsets.first, // voffset 7847 Op.getOperand(6), // soffset 7848 Offsets.second, // offset 7849 Op.getOperand(7), // cachepolicy, swizzled buffer 7850 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7851 }; 7852 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7853 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7854 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7855 MemSDNode *M = cast<MemSDNode>(Op); 7856 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7857 Ops[3])); 7858 7859 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7860 EVT VDataType = VData.getValueType().getScalarType(); 7861 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7862 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7863 7864 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7865 M->getMemoryVT(), M->getMemOperand()); 7866 } 7867 case Intrinsic::amdgcn_end_cf: 7868 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7869 Op->getOperand(2), Chain), 0); 7870 7871 default: { 7872 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7873 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7874 return lowerImage(Op, ImageDimIntr, DAG, true); 7875 7876 return Op; 7877 } 7878 } 7879 } 7880 7881 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7882 // offset (the offset that is included in bounds checking and swizzling, to be 7883 // split between the instruction's voffset and immoffset fields) and soffset 7884 // (the offset that is excluded from bounds checking and swizzling, to go in 7885 // the instruction's soffset field). This function takes the first kind of 7886 // offset and figures out how to split it between voffset and immoffset. 7887 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7888 SDValue Offset, SelectionDAG &DAG) const { 7889 SDLoc DL(Offset); 7890 const unsigned MaxImm = 4095; 7891 SDValue N0 = Offset; 7892 ConstantSDNode *C1 = nullptr; 7893 7894 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7895 N0 = SDValue(); 7896 else if (DAG.isBaseWithConstantOffset(N0)) { 7897 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7898 N0 = N0.getOperand(0); 7899 } 7900 7901 if (C1) { 7902 unsigned ImmOffset = C1->getZExtValue(); 7903 // If the immediate value is too big for the immoffset field, put the value 7904 // and -4096 into the immoffset field so that the value that is copied/added 7905 // for the voffset field is a multiple of 4096, and it stands more chance 7906 // of being CSEd with the copy/add for another similar load/store. 7907 // However, do not do that rounding down to a multiple of 4096 if that is a 7908 // negative number, as it appears to be illegal to have a negative offset 7909 // in the vgpr, even if adding the immediate offset makes it positive. 7910 unsigned Overflow = ImmOffset & ~MaxImm; 7911 ImmOffset -= Overflow; 7912 if ((int32_t)Overflow < 0) { 7913 Overflow += ImmOffset; 7914 ImmOffset = 0; 7915 } 7916 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7917 if (Overflow) { 7918 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7919 if (!N0) 7920 N0 = OverflowVal; 7921 else { 7922 SDValue Ops[] = { N0, OverflowVal }; 7923 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7924 } 7925 } 7926 } 7927 if (!N0) 7928 N0 = DAG.getConstant(0, DL, MVT::i32); 7929 if (!C1) 7930 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7931 return {N0, SDValue(C1, 0)}; 7932 } 7933 7934 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7935 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7936 // pointed to by Offsets. 7937 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7938 SelectionDAG &DAG, SDValue *Offsets, 7939 Align Alignment) const { 7940 SDLoc DL(CombinedOffset); 7941 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7942 uint32_t Imm = C->getZExtValue(); 7943 uint32_t SOffset, ImmOffset; 7944 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7945 Alignment)) { 7946 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7947 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7948 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7949 return SOffset + ImmOffset; 7950 } 7951 } 7952 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7953 SDValue N0 = CombinedOffset.getOperand(0); 7954 SDValue N1 = CombinedOffset.getOperand(1); 7955 uint32_t SOffset, ImmOffset; 7956 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7957 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7958 Subtarget, Alignment)) { 7959 Offsets[0] = N0; 7960 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7961 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7962 return 0; 7963 } 7964 } 7965 Offsets[0] = CombinedOffset; 7966 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7967 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7968 return 0; 7969 } 7970 7971 // Handle 8 bit and 16 bit buffer loads 7972 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7973 EVT LoadVT, SDLoc DL, 7974 ArrayRef<SDValue> Ops, 7975 MemSDNode *M) const { 7976 EVT IntVT = LoadVT.changeTypeToInteger(); 7977 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7978 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7979 7980 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7981 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7982 Ops, IntVT, 7983 M->getMemOperand()); 7984 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7985 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7986 7987 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7988 } 7989 7990 // Handle 8 bit and 16 bit buffer stores 7991 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7992 EVT VDataType, SDLoc DL, 7993 SDValue Ops[], 7994 MemSDNode *M) const { 7995 if (VDataType == MVT::f16) 7996 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7997 7998 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7999 Ops[1] = BufferStoreExt; 8000 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8001 AMDGPUISD::BUFFER_STORE_SHORT; 8002 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8003 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8004 M->getMemOperand()); 8005 } 8006 8007 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8008 ISD::LoadExtType ExtType, SDValue Op, 8009 const SDLoc &SL, EVT VT) { 8010 if (VT.bitsLT(Op.getValueType())) 8011 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8012 8013 switch (ExtType) { 8014 case ISD::SEXTLOAD: 8015 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8016 case ISD::ZEXTLOAD: 8017 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8018 case ISD::EXTLOAD: 8019 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8020 case ISD::NON_EXTLOAD: 8021 return Op; 8022 } 8023 8024 llvm_unreachable("invalid ext type"); 8025 } 8026 8027 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8028 SelectionDAG &DAG = DCI.DAG; 8029 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8030 return SDValue(); 8031 8032 // FIXME: Constant loads should all be marked invariant. 8033 unsigned AS = Ld->getAddressSpace(); 8034 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8035 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8036 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8037 return SDValue(); 8038 8039 // Don't do this early, since it may interfere with adjacent load merging for 8040 // illegal types. We can avoid losing alignment information for exotic types 8041 // pre-legalize. 8042 EVT MemVT = Ld->getMemoryVT(); 8043 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8044 MemVT.getSizeInBits() >= 32) 8045 return SDValue(); 8046 8047 SDLoc SL(Ld); 8048 8049 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8050 "unexpected vector extload"); 8051 8052 // TODO: Drop only high part of range. 8053 SDValue Ptr = Ld->getBasePtr(); 8054 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8055 MVT::i32, SL, Ld->getChain(), Ptr, 8056 Ld->getOffset(), 8057 Ld->getPointerInfo(), MVT::i32, 8058 Ld->getAlignment(), 8059 Ld->getMemOperand()->getFlags(), 8060 Ld->getAAInfo(), 8061 nullptr); // Drop ranges 8062 8063 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8064 if (MemVT.isFloatingPoint()) { 8065 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8066 "unexpected fp extload"); 8067 TruncVT = MemVT.changeTypeToInteger(); 8068 } 8069 8070 SDValue Cvt = NewLoad; 8071 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8072 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8073 DAG.getValueType(TruncVT)); 8074 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8075 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8076 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8077 } else { 8078 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8079 } 8080 8081 EVT VT = Ld->getValueType(0); 8082 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8083 8084 DCI.AddToWorklist(Cvt.getNode()); 8085 8086 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8087 // the appropriate extension from the 32-bit load. 8088 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8089 DCI.AddToWorklist(Cvt.getNode()); 8090 8091 // Handle conversion back to floating point if necessary. 8092 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8093 8094 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8095 } 8096 8097 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8098 SDLoc DL(Op); 8099 LoadSDNode *Load = cast<LoadSDNode>(Op); 8100 ISD::LoadExtType ExtType = Load->getExtensionType(); 8101 EVT MemVT = Load->getMemoryVT(); 8102 8103 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8104 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8105 return SDValue(); 8106 8107 // FIXME: Copied from PPC 8108 // First, load into 32 bits, then truncate to 1 bit. 8109 8110 SDValue Chain = Load->getChain(); 8111 SDValue BasePtr = Load->getBasePtr(); 8112 MachineMemOperand *MMO = Load->getMemOperand(); 8113 8114 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8115 8116 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8117 BasePtr, RealMemVT, MMO); 8118 8119 if (!MemVT.isVector()) { 8120 SDValue Ops[] = { 8121 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8122 NewLD.getValue(1) 8123 }; 8124 8125 return DAG.getMergeValues(Ops, DL); 8126 } 8127 8128 SmallVector<SDValue, 3> Elts; 8129 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8130 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8131 DAG.getConstant(I, DL, MVT::i32)); 8132 8133 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8134 } 8135 8136 SDValue Ops[] = { 8137 DAG.getBuildVector(MemVT, DL, Elts), 8138 NewLD.getValue(1) 8139 }; 8140 8141 return DAG.getMergeValues(Ops, DL); 8142 } 8143 8144 if (!MemVT.isVector()) 8145 return SDValue(); 8146 8147 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8148 "Custom lowering for non-i32 vectors hasn't been implemented."); 8149 8150 unsigned Alignment = Load->getAlignment(); 8151 unsigned AS = Load->getAddressSpace(); 8152 if (Subtarget->hasLDSMisalignedBug() && 8153 AS == AMDGPUAS::FLAT_ADDRESS && 8154 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8155 return SplitVectorLoad(Op, DAG); 8156 } 8157 8158 MachineFunction &MF = DAG.getMachineFunction(); 8159 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8160 // If there is a possibilty that flat instruction access scratch memory 8161 // then we need to use the same legalization rules we use for private. 8162 if (AS == AMDGPUAS::FLAT_ADDRESS && 8163 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8164 AS = MFI->hasFlatScratchInit() ? 8165 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8166 8167 unsigned NumElements = MemVT.getVectorNumElements(); 8168 8169 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8170 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8171 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8172 if (MemVT.isPow2VectorType()) 8173 return SDValue(); 8174 return WidenOrSplitVectorLoad(Op, DAG); 8175 } 8176 // Non-uniform loads will be selected to MUBUF instructions, so they 8177 // have the same legalization requirements as global and private 8178 // loads. 8179 // 8180 } 8181 8182 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8183 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8184 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8185 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8186 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8187 Alignment >= 4 && NumElements < 32) { 8188 if (MemVT.isPow2VectorType()) 8189 return SDValue(); 8190 return WidenOrSplitVectorLoad(Op, DAG); 8191 } 8192 // Non-uniform loads will be selected to MUBUF instructions, so they 8193 // have the same legalization requirements as global and private 8194 // loads. 8195 // 8196 } 8197 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8198 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8199 AS == AMDGPUAS::GLOBAL_ADDRESS || 8200 AS == AMDGPUAS::FLAT_ADDRESS) { 8201 if (NumElements > 4) 8202 return SplitVectorLoad(Op, DAG); 8203 // v3 loads not supported on SI. 8204 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8205 return WidenOrSplitVectorLoad(Op, DAG); 8206 8207 // v3 and v4 loads are supported for private and global memory. 8208 return SDValue(); 8209 } 8210 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8211 // Depending on the setting of the private_element_size field in the 8212 // resource descriptor, we can only make private accesses up to a certain 8213 // size. 8214 switch (Subtarget->getMaxPrivateElementSize()) { 8215 case 4: { 8216 SDValue Ops[2]; 8217 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8218 return DAG.getMergeValues(Ops, DL); 8219 } 8220 case 8: 8221 if (NumElements > 2) 8222 return SplitVectorLoad(Op, DAG); 8223 return SDValue(); 8224 case 16: 8225 // Same as global/flat 8226 if (NumElements > 4) 8227 return SplitVectorLoad(Op, DAG); 8228 // v3 loads not supported on SI. 8229 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8230 return WidenOrSplitVectorLoad(Op, DAG); 8231 8232 return SDValue(); 8233 default: 8234 llvm_unreachable("unsupported private_element_size"); 8235 } 8236 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8237 // Use ds_read_b128 or ds_read_b96 when possible. 8238 if (Subtarget->hasDS96AndDS128() && 8239 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8240 MemVT.getStoreSize() == 12) && 8241 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8242 Load->getAlign())) 8243 return SDValue(); 8244 8245 if (NumElements > 2) 8246 return SplitVectorLoad(Op, DAG); 8247 8248 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8249 // address is negative, then the instruction is incorrectly treated as 8250 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8251 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8252 // load later in the SILoadStoreOptimizer. 8253 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8254 NumElements == 2 && MemVT.getStoreSize() == 8 && 8255 Load->getAlignment() < 8) { 8256 return SplitVectorLoad(Op, DAG); 8257 } 8258 } 8259 8260 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8261 MemVT, *Load->getMemOperand())) { 8262 SDValue Ops[2]; 8263 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8264 return DAG.getMergeValues(Ops, DL); 8265 } 8266 8267 return SDValue(); 8268 } 8269 8270 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8271 EVT VT = Op.getValueType(); 8272 assert(VT.getSizeInBits() == 64); 8273 8274 SDLoc DL(Op); 8275 SDValue Cond = Op.getOperand(0); 8276 8277 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8278 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8279 8280 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8281 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8282 8283 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8284 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8285 8286 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8287 8288 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8289 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8290 8291 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8292 8293 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8294 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8295 } 8296 8297 // Catch division cases where we can use shortcuts with rcp and rsq 8298 // instructions. 8299 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8300 SelectionDAG &DAG) const { 8301 SDLoc SL(Op); 8302 SDValue LHS = Op.getOperand(0); 8303 SDValue RHS = Op.getOperand(1); 8304 EVT VT = Op.getValueType(); 8305 const SDNodeFlags Flags = Op->getFlags(); 8306 8307 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8308 8309 // Without !fpmath accuracy information, we can't do more because we don't 8310 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8311 if (!AllowInaccurateRcp) 8312 return SDValue(); 8313 8314 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8315 if (CLHS->isExactlyValue(1.0)) { 8316 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8317 // the CI documentation has a worst case error of 1 ulp. 8318 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8319 // use it as long as we aren't trying to use denormals. 8320 // 8321 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8322 8323 // 1.0 / sqrt(x) -> rsq(x) 8324 8325 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8326 // error seems really high at 2^29 ULP. 8327 if (RHS.getOpcode() == ISD::FSQRT) 8328 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8329 8330 // 1.0 / x -> rcp(x) 8331 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8332 } 8333 8334 // Same as for 1.0, but expand the sign out of the constant. 8335 if (CLHS->isExactlyValue(-1.0)) { 8336 // -1.0 / x -> rcp (fneg x) 8337 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8338 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8339 } 8340 } 8341 8342 // Turn into multiply by the reciprocal. 8343 // x / y -> x * (1.0 / y) 8344 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8345 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8346 } 8347 8348 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8349 SelectionDAG &DAG) const { 8350 SDLoc SL(Op); 8351 SDValue X = Op.getOperand(0); 8352 SDValue Y = Op.getOperand(1); 8353 EVT VT = Op.getValueType(); 8354 const SDNodeFlags Flags = Op->getFlags(); 8355 8356 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8357 DAG.getTarget().Options.UnsafeFPMath; 8358 if (!AllowInaccurateDiv) 8359 return SDValue(); 8360 8361 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8362 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8363 8364 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8365 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8366 8367 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8368 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8369 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8370 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8371 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8372 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8373 } 8374 8375 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8376 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8377 SDNodeFlags Flags) { 8378 if (GlueChain->getNumValues() <= 1) { 8379 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8380 } 8381 8382 assert(GlueChain->getNumValues() == 3); 8383 8384 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8385 switch (Opcode) { 8386 default: llvm_unreachable("no chain equivalent for opcode"); 8387 case ISD::FMUL: 8388 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8389 break; 8390 } 8391 8392 return DAG.getNode(Opcode, SL, VTList, 8393 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8394 Flags); 8395 } 8396 8397 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8398 EVT VT, SDValue A, SDValue B, SDValue C, 8399 SDValue GlueChain, SDNodeFlags Flags) { 8400 if (GlueChain->getNumValues() <= 1) { 8401 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8402 } 8403 8404 assert(GlueChain->getNumValues() == 3); 8405 8406 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8407 switch (Opcode) { 8408 default: llvm_unreachable("no chain equivalent for opcode"); 8409 case ISD::FMA: 8410 Opcode = AMDGPUISD::FMA_W_CHAIN; 8411 break; 8412 } 8413 8414 return DAG.getNode(Opcode, SL, VTList, 8415 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8416 Flags); 8417 } 8418 8419 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8420 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8421 return FastLowered; 8422 8423 SDLoc SL(Op); 8424 SDValue Src0 = Op.getOperand(0); 8425 SDValue Src1 = Op.getOperand(1); 8426 8427 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8428 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8429 8430 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8431 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8432 8433 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8434 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8435 8436 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8437 } 8438 8439 // Faster 2.5 ULP division that does not support denormals. 8440 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8441 SDLoc SL(Op); 8442 SDValue LHS = Op.getOperand(1); 8443 SDValue RHS = Op.getOperand(2); 8444 8445 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8446 8447 const APFloat K0Val(BitsToFloat(0x6f800000)); 8448 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8449 8450 const APFloat K1Val(BitsToFloat(0x2f800000)); 8451 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8452 8453 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8454 8455 EVT SetCCVT = 8456 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8457 8458 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8459 8460 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8461 8462 // TODO: Should this propagate fast-math-flags? 8463 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8464 8465 // rcp does not support denormals. 8466 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8467 8468 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8469 8470 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8471 } 8472 8473 // Returns immediate value for setting the F32 denorm mode when using the 8474 // S_DENORM_MODE instruction. 8475 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8476 const SDLoc &SL, const GCNSubtarget *ST) { 8477 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8478 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8479 ? FP_DENORM_FLUSH_NONE 8480 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8481 8482 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8483 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8484 } 8485 8486 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8487 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8488 return FastLowered; 8489 8490 // The selection matcher assumes anything with a chain selecting to a 8491 // mayRaiseFPException machine instruction. Since we're introducing a chain 8492 // here, we need to explicitly report nofpexcept for the regular fdiv 8493 // lowering. 8494 SDNodeFlags Flags = Op->getFlags(); 8495 Flags.setNoFPExcept(true); 8496 8497 SDLoc SL(Op); 8498 SDValue LHS = Op.getOperand(0); 8499 SDValue RHS = Op.getOperand(1); 8500 8501 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8502 8503 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8504 8505 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8506 {RHS, RHS, LHS}, Flags); 8507 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8508 {LHS, RHS, LHS}, Flags); 8509 8510 // Denominator is scaled to not be denormal, so using rcp is ok. 8511 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8512 DenominatorScaled, Flags); 8513 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8514 DenominatorScaled, Flags); 8515 8516 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8517 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8518 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8519 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8520 8521 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8522 8523 if (!HasFP32Denormals) { 8524 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8525 // lowering. The chain dependence is insufficient, and we need glue. We do 8526 // not need the glue variants in a strictfp function. 8527 8528 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8529 8530 SDNode *EnableDenorm; 8531 if (Subtarget->hasDenormModeInst()) { 8532 const SDValue EnableDenormValue = 8533 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8534 8535 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8536 DAG.getEntryNode(), EnableDenormValue).getNode(); 8537 } else { 8538 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8539 SL, MVT::i32); 8540 EnableDenorm = 8541 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8542 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8543 } 8544 8545 SDValue Ops[3] = { 8546 NegDivScale0, 8547 SDValue(EnableDenorm, 0), 8548 SDValue(EnableDenorm, 1) 8549 }; 8550 8551 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8552 } 8553 8554 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8555 ApproxRcp, One, NegDivScale0, Flags); 8556 8557 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8558 ApproxRcp, Fma0, Flags); 8559 8560 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8561 Fma1, Fma1, Flags); 8562 8563 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8564 NumeratorScaled, Mul, Flags); 8565 8566 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8567 Fma2, Fma1, Mul, Fma2, Flags); 8568 8569 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8570 NumeratorScaled, Fma3, Flags); 8571 8572 if (!HasFP32Denormals) { 8573 SDNode *DisableDenorm; 8574 if (Subtarget->hasDenormModeInst()) { 8575 const SDValue DisableDenormValue = 8576 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8577 8578 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8579 Fma4.getValue(1), DisableDenormValue, 8580 Fma4.getValue(2)).getNode(); 8581 } else { 8582 const SDValue DisableDenormValue = 8583 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8584 8585 DisableDenorm = DAG.getMachineNode( 8586 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8587 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8588 } 8589 8590 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8591 SDValue(DisableDenorm, 0), DAG.getRoot()); 8592 DAG.setRoot(OutputChain); 8593 } 8594 8595 SDValue Scale = NumeratorScaled.getValue(1); 8596 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8597 {Fma4, Fma1, Fma3, Scale}, Flags); 8598 8599 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8600 } 8601 8602 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8603 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8604 return FastLowered; 8605 8606 SDLoc SL(Op); 8607 SDValue X = Op.getOperand(0); 8608 SDValue Y = Op.getOperand(1); 8609 8610 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8611 8612 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8613 8614 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8615 8616 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8617 8618 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8619 8620 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8621 8622 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8623 8624 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8625 8626 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8627 8628 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8629 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8630 8631 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8632 NegDivScale0, Mul, DivScale1); 8633 8634 SDValue Scale; 8635 8636 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8637 // Workaround a hardware bug on SI where the condition output from div_scale 8638 // is not usable. 8639 8640 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8641 8642 // Figure out if the scale to use for div_fmas. 8643 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8644 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8645 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8646 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8647 8648 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8649 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8650 8651 SDValue Scale0Hi 8652 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8653 SDValue Scale1Hi 8654 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8655 8656 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8657 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8658 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8659 } else { 8660 Scale = DivScale1.getValue(1); 8661 } 8662 8663 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8664 Fma4, Fma3, Mul, Scale); 8665 8666 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8667 } 8668 8669 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8670 EVT VT = Op.getValueType(); 8671 8672 if (VT == MVT::f32) 8673 return LowerFDIV32(Op, DAG); 8674 8675 if (VT == MVT::f64) 8676 return LowerFDIV64(Op, DAG); 8677 8678 if (VT == MVT::f16) 8679 return LowerFDIV16(Op, DAG); 8680 8681 llvm_unreachable("Unexpected type for fdiv"); 8682 } 8683 8684 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8685 SDLoc DL(Op); 8686 StoreSDNode *Store = cast<StoreSDNode>(Op); 8687 EVT VT = Store->getMemoryVT(); 8688 8689 if (VT == MVT::i1) { 8690 return DAG.getTruncStore(Store->getChain(), DL, 8691 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8692 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8693 } 8694 8695 assert(VT.isVector() && 8696 Store->getValue().getValueType().getScalarType() == MVT::i32); 8697 8698 unsigned AS = Store->getAddressSpace(); 8699 if (Subtarget->hasLDSMisalignedBug() && 8700 AS == AMDGPUAS::FLAT_ADDRESS && 8701 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8702 return SplitVectorStore(Op, DAG); 8703 } 8704 8705 MachineFunction &MF = DAG.getMachineFunction(); 8706 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8707 // If there is a possibilty that flat instruction access scratch memory 8708 // then we need to use the same legalization rules we use for private. 8709 if (AS == AMDGPUAS::FLAT_ADDRESS && 8710 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8711 AS = MFI->hasFlatScratchInit() ? 8712 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8713 8714 unsigned NumElements = VT.getVectorNumElements(); 8715 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8716 AS == AMDGPUAS::FLAT_ADDRESS) { 8717 if (NumElements > 4) 8718 return SplitVectorStore(Op, DAG); 8719 // v3 stores not supported on SI. 8720 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8721 return SplitVectorStore(Op, DAG); 8722 8723 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8724 VT, *Store->getMemOperand())) 8725 return expandUnalignedStore(Store, DAG); 8726 8727 return SDValue(); 8728 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8729 switch (Subtarget->getMaxPrivateElementSize()) { 8730 case 4: 8731 return scalarizeVectorStore(Store, DAG); 8732 case 8: 8733 if (NumElements > 2) 8734 return SplitVectorStore(Op, DAG); 8735 return SDValue(); 8736 case 16: 8737 if (NumElements > 4 || 8738 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8739 return SplitVectorStore(Op, DAG); 8740 return SDValue(); 8741 default: 8742 llvm_unreachable("unsupported private_element_size"); 8743 } 8744 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8745 // Use ds_write_b128 or ds_write_b96 when possible. 8746 if (Subtarget->hasDS96AndDS128() && 8747 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8748 (VT.getStoreSize() == 12)) && 8749 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8750 Store->getAlign())) 8751 return SDValue(); 8752 8753 if (NumElements > 2) 8754 return SplitVectorStore(Op, DAG); 8755 8756 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8757 // address is negative, then the instruction is incorrectly treated as 8758 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8759 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8760 // store later in the SILoadStoreOptimizer. 8761 if (!Subtarget->hasUsableDSOffset() && 8762 NumElements == 2 && VT.getStoreSize() == 8 && 8763 Store->getAlignment() < 8) { 8764 return SplitVectorStore(Op, DAG); 8765 } 8766 8767 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8768 VT, *Store->getMemOperand())) { 8769 if (VT.isVector()) 8770 return SplitVectorStore(Op, DAG); 8771 return expandUnalignedStore(Store, DAG); 8772 } 8773 8774 return SDValue(); 8775 } else { 8776 llvm_unreachable("unhandled address space"); 8777 } 8778 } 8779 8780 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8781 SDLoc DL(Op); 8782 EVT VT = Op.getValueType(); 8783 SDValue Arg = Op.getOperand(0); 8784 SDValue TrigVal; 8785 8786 // Propagate fast-math flags so that the multiply we introduce can be folded 8787 // if Arg is already the result of a multiply by constant. 8788 auto Flags = Op->getFlags(); 8789 8790 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8791 8792 if (Subtarget->hasTrigReducedRange()) { 8793 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8794 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8795 } else { 8796 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8797 } 8798 8799 switch (Op.getOpcode()) { 8800 case ISD::FCOS: 8801 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8802 case ISD::FSIN: 8803 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8804 default: 8805 llvm_unreachable("Wrong trig opcode"); 8806 } 8807 } 8808 8809 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8810 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8811 assert(AtomicNode->isCompareAndSwap()); 8812 unsigned AS = AtomicNode->getAddressSpace(); 8813 8814 // No custom lowering required for local address space 8815 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8816 return Op; 8817 8818 // Non-local address space requires custom lowering for atomic compare 8819 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8820 SDLoc DL(Op); 8821 SDValue ChainIn = Op.getOperand(0); 8822 SDValue Addr = Op.getOperand(1); 8823 SDValue Old = Op.getOperand(2); 8824 SDValue New = Op.getOperand(3); 8825 EVT VT = Op.getValueType(); 8826 MVT SimpleVT = VT.getSimpleVT(); 8827 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8828 8829 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8830 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8831 8832 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8833 Ops, VT, AtomicNode->getMemOperand()); 8834 } 8835 8836 //===----------------------------------------------------------------------===// 8837 // Custom DAG optimizations 8838 //===----------------------------------------------------------------------===// 8839 8840 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8841 DAGCombinerInfo &DCI) const { 8842 EVT VT = N->getValueType(0); 8843 EVT ScalarVT = VT.getScalarType(); 8844 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8845 return SDValue(); 8846 8847 SelectionDAG &DAG = DCI.DAG; 8848 SDLoc DL(N); 8849 8850 SDValue Src = N->getOperand(0); 8851 EVT SrcVT = Src.getValueType(); 8852 8853 // TODO: We could try to match extracting the higher bytes, which would be 8854 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8855 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8856 // about in practice. 8857 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8858 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8859 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8860 DCI.AddToWorklist(Cvt.getNode()); 8861 8862 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8863 if (ScalarVT != MVT::f32) { 8864 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8865 DAG.getTargetConstant(0, DL, MVT::i32)); 8866 } 8867 return Cvt; 8868 } 8869 } 8870 8871 return SDValue(); 8872 } 8873 8874 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8875 8876 // This is a variant of 8877 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8878 // 8879 // The normal DAG combiner will do this, but only if the add has one use since 8880 // that would increase the number of instructions. 8881 // 8882 // This prevents us from seeing a constant offset that can be folded into a 8883 // memory instruction's addressing mode. If we know the resulting add offset of 8884 // a pointer can be folded into an addressing offset, we can replace the pointer 8885 // operand with the add of new constant offset. This eliminates one of the uses, 8886 // and may allow the remaining use to also be simplified. 8887 // 8888 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8889 unsigned AddrSpace, 8890 EVT MemVT, 8891 DAGCombinerInfo &DCI) const { 8892 SDValue N0 = N->getOperand(0); 8893 SDValue N1 = N->getOperand(1); 8894 8895 // We only do this to handle cases where it's profitable when there are 8896 // multiple uses of the add, so defer to the standard combine. 8897 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8898 N0->hasOneUse()) 8899 return SDValue(); 8900 8901 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8902 if (!CN1) 8903 return SDValue(); 8904 8905 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8906 if (!CAdd) 8907 return SDValue(); 8908 8909 // If the resulting offset is too large, we can't fold it into the addressing 8910 // mode offset. 8911 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8912 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8913 8914 AddrMode AM; 8915 AM.HasBaseReg = true; 8916 AM.BaseOffs = Offset.getSExtValue(); 8917 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8918 return SDValue(); 8919 8920 SelectionDAG &DAG = DCI.DAG; 8921 SDLoc SL(N); 8922 EVT VT = N->getValueType(0); 8923 8924 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8925 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8926 8927 SDNodeFlags Flags; 8928 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8929 (N0.getOpcode() == ISD::OR || 8930 N0->getFlags().hasNoUnsignedWrap())); 8931 8932 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8933 } 8934 8935 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8936 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8937 /// specific intrinsic, but they all place the pointer operand first. 8938 static unsigned getBasePtrIndex(const MemSDNode *N) { 8939 switch (N->getOpcode()) { 8940 case ISD::STORE: 8941 case ISD::INTRINSIC_W_CHAIN: 8942 case ISD::INTRINSIC_VOID: 8943 return 2; 8944 default: 8945 return 1; 8946 } 8947 } 8948 8949 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8950 DAGCombinerInfo &DCI) const { 8951 SelectionDAG &DAG = DCI.DAG; 8952 SDLoc SL(N); 8953 8954 unsigned PtrIdx = getBasePtrIndex(N); 8955 SDValue Ptr = N->getOperand(PtrIdx); 8956 8957 // TODO: We could also do this for multiplies. 8958 if (Ptr.getOpcode() == ISD::SHL) { 8959 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8960 N->getMemoryVT(), DCI); 8961 if (NewPtr) { 8962 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8963 8964 NewOps[PtrIdx] = NewPtr; 8965 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8966 } 8967 } 8968 8969 return SDValue(); 8970 } 8971 8972 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8973 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8974 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8975 (Opc == ISD::XOR && Val == 0); 8976 } 8977 8978 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8979 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8980 // integer combine opportunities since most 64-bit operations are decomposed 8981 // this way. TODO: We won't want this for SALU especially if it is an inline 8982 // immediate. 8983 SDValue SITargetLowering::splitBinaryBitConstantOp( 8984 DAGCombinerInfo &DCI, 8985 const SDLoc &SL, 8986 unsigned Opc, SDValue LHS, 8987 const ConstantSDNode *CRHS) const { 8988 uint64_t Val = CRHS->getZExtValue(); 8989 uint32_t ValLo = Lo_32(Val); 8990 uint32_t ValHi = Hi_32(Val); 8991 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8992 8993 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8994 bitOpWithConstantIsReducible(Opc, ValHi)) || 8995 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8996 // If we need to materialize a 64-bit immediate, it will be split up later 8997 // anyway. Avoid creating the harder to understand 64-bit immediate 8998 // materialization. 8999 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9000 } 9001 9002 return SDValue(); 9003 } 9004 9005 // Returns true if argument is a boolean value which is not serialized into 9006 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9007 static bool isBoolSGPR(SDValue V) { 9008 if (V.getValueType() != MVT::i1) 9009 return false; 9010 switch (V.getOpcode()) { 9011 default: 9012 break; 9013 case ISD::SETCC: 9014 case AMDGPUISD::FP_CLASS: 9015 return true; 9016 case ISD::AND: 9017 case ISD::OR: 9018 case ISD::XOR: 9019 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9020 } 9021 return false; 9022 } 9023 9024 // If a constant has all zeroes or all ones within each byte return it. 9025 // Otherwise return 0. 9026 static uint32_t getConstantPermuteMask(uint32_t C) { 9027 // 0xff for any zero byte in the mask 9028 uint32_t ZeroByteMask = 0; 9029 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9030 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9031 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9032 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9033 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9034 if ((NonZeroByteMask & C) != NonZeroByteMask) 9035 return 0; // Partial bytes selected. 9036 return C; 9037 } 9038 9039 // Check if a node selects whole bytes from its operand 0 starting at a byte 9040 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9041 // or -1 if not succeeded. 9042 // Note byte select encoding: 9043 // value 0-3 selects corresponding source byte; 9044 // value 0xc selects zero; 9045 // value 0xff selects 0xff. 9046 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9047 assert(V.getValueSizeInBits() == 32); 9048 9049 if (V.getNumOperands() != 2) 9050 return ~0; 9051 9052 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9053 if (!N1) 9054 return ~0; 9055 9056 uint32_t C = N1->getZExtValue(); 9057 9058 switch (V.getOpcode()) { 9059 default: 9060 break; 9061 case ISD::AND: 9062 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9063 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9064 } 9065 break; 9066 9067 case ISD::OR: 9068 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9069 return (0x03020100 & ~ConstMask) | ConstMask; 9070 } 9071 break; 9072 9073 case ISD::SHL: 9074 if (C % 8) 9075 return ~0; 9076 9077 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9078 9079 case ISD::SRL: 9080 if (C % 8) 9081 return ~0; 9082 9083 return uint32_t(0x0c0c0c0c03020100ull >> C); 9084 } 9085 9086 return ~0; 9087 } 9088 9089 SDValue SITargetLowering::performAndCombine(SDNode *N, 9090 DAGCombinerInfo &DCI) const { 9091 if (DCI.isBeforeLegalize()) 9092 return SDValue(); 9093 9094 SelectionDAG &DAG = DCI.DAG; 9095 EVT VT = N->getValueType(0); 9096 SDValue LHS = N->getOperand(0); 9097 SDValue RHS = N->getOperand(1); 9098 9099 9100 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9101 if (VT == MVT::i64 && CRHS) { 9102 if (SDValue Split 9103 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9104 return Split; 9105 } 9106 9107 if (CRHS && VT == MVT::i32) { 9108 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9109 // nb = number of trailing zeroes in mask 9110 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9111 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9112 uint64_t Mask = CRHS->getZExtValue(); 9113 unsigned Bits = countPopulation(Mask); 9114 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9115 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9116 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9117 unsigned Shift = CShift->getZExtValue(); 9118 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9119 unsigned Offset = NB + Shift; 9120 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9121 SDLoc SL(N); 9122 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9123 LHS->getOperand(0), 9124 DAG.getConstant(Offset, SL, MVT::i32), 9125 DAG.getConstant(Bits, SL, MVT::i32)); 9126 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9127 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9128 DAG.getValueType(NarrowVT)); 9129 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9130 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9131 return Shl; 9132 } 9133 } 9134 } 9135 9136 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9137 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9138 isa<ConstantSDNode>(LHS.getOperand(2))) { 9139 uint32_t Sel = getConstantPermuteMask(Mask); 9140 if (!Sel) 9141 return SDValue(); 9142 9143 // Select 0xc for all zero bytes 9144 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9145 SDLoc DL(N); 9146 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9147 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9148 } 9149 } 9150 9151 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9152 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9153 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9154 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9155 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9156 9157 SDValue X = LHS.getOperand(0); 9158 SDValue Y = RHS.getOperand(0); 9159 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9160 return SDValue(); 9161 9162 if (LCC == ISD::SETO) { 9163 if (X != LHS.getOperand(1)) 9164 return SDValue(); 9165 9166 if (RCC == ISD::SETUNE) { 9167 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9168 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9169 return SDValue(); 9170 9171 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9172 SIInstrFlags::N_SUBNORMAL | 9173 SIInstrFlags::N_ZERO | 9174 SIInstrFlags::P_ZERO | 9175 SIInstrFlags::P_SUBNORMAL | 9176 SIInstrFlags::P_NORMAL; 9177 9178 static_assert(((~(SIInstrFlags::S_NAN | 9179 SIInstrFlags::Q_NAN | 9180 SIInstrFlags::N_INFINITY | 9181 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9182 "mask not equal"); 9183 9184 SDLoc DL(N); 9185 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9186 X, DAG.getConstant(Mask, DL, MVT::i32)); 9187 } 9188 } 9189 } 9190 9191 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9192 std::swap(LHS, RHS); 9193 9194 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9195 RHS.hasOneUse()) { 9196 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9197 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9198 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9199 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9200 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9201 (RHS.getOperand(0) == LHS.getOperand(0) && 9202 LHS.getOperand(0) == LHS.getOperand(1))) { 9203 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9204 unsigned NewMask = LCC == ISD::SETO ? 9205 Mask->getZExtValue() & ~OrdMask : 9206 Mask->getZExtValue() & OrdMask; 9207 9208 SDLoc DL(N); 9209 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9210 DAG.getConstant(NewMask, DL, MVT::i32)); 9211 } 9212 } 9213 9214 if (VT == MVT::i32 && 9215 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9216 // and x, (sext cc from i1) => select cc, x, 0 9217 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9218 std::swap(LHS, RHS); 9219 if (isBoolSGPR(RHS.getOperand(0))) 9220 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9221 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9222 } 9223 9224 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9225 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9226 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9227 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9228 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9229 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9230 if (LHSMask != ~0u && RHSMask != ~0u) { 9231 // Canonicalize the expression in an attempt to have fewer unique masks 9232 // and therefore fewer registers used to hold the masks. 9233 if (LHSMask > RHSMask) { 9234 std::swap(LHSMask, RHSMask); 9235 std::swap(LHS, RHS); 9236 } 9237 9238 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9239 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9240 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9241 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9242 9243 // Check of we need to combine values from two sources within a byte. 9244 if (!(LHSUsedLanes & RHSUsedLanes) && 9245 // If we select high and lower word keep it for SDWA. 9246 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9247 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9248 // Each byte in each mask is either selector mask 0-3, or has higher 9249 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9250 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9251 // mask which is not 0xff wins. By anding both masks we have a correct 9252 // result except that 0x0c shall be corrected to give 0x0c only. 9253 uint32_t Mask = LHSMask & RHSMask; 9254 for (unsigned I = 0; I < 32; I += 8) { 9255 uint32_t ByteSel = 0xff << I; 9256 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9257 Mask &= (0x0c << I) & 0xffffffff; 9258 } 9259 9260 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9261 // or 0x0c. 9262 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9263 SDLoc DL(N); 9264 9265 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9266 LHS.getOperand(0), RHS.getOperand(0), 9267 DAG.getConstant(Sel, DL, MVT::i32)); 9268 } 9269 } 9270 } 9271 9272 return SDValue(); 9273 } 9274 9275 SDValue SITargetLowering::performOrCombine(SDNode *N, 9276 DAGCombinerInfo &DCI) const { 9277 SelectionDAG &DAG = DCI.DAG; 9278 SDValue LHS = N->getOperand(0); 9279 SDValue RHS = N->getOperand(1); 9280 9281 EVT VT = N->getValueType(0); 9282 if (VT == MVT::i1) { 9283 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9284 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9285 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9286 SDValue Src = LHS.getOperand(0); 9287 if (Src != RHS.getOperand(0)) 9288 return SDValue(); 9289 9290 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9291 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9292 if (!CLHS || !CRHS) 9293 return SDValue(); 9294 9295 // Only 10 bits are used. 9296 static const uint32_t MaxMask = 0x3ff; 9297 9298 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9299 SDLoc DL(N); 9300 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9301 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9302 } 9303 9304 return SDValue(); 9305 } 9306 9307 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9308 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9309 LHS.getOpcode() == AMDGPUISD::PERM && 9310 isa<ConstantSDNode>(LHS.getOperand(2))) { 9311 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9312 if (!Sel) 9313 return SDValue(); 9314 9315 Sel |= LHS.getConstantOperandVal(2); 9316 SDLoc DL(N); 9317 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9318 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9319 } 9320 9321 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9322 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9323 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9324 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9325 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9326 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9327 if (LHSMask != ~0u && RHSMask != ~0u) { 9328 // Canonicalize the expression in an attempt to have fewer unique masks 9329 // and therefore fewer registers used to hold the masks. 9330 if (LHSMask > RHSMask) { 9331 std::swap(LHSMask, RHSMask); 9332 std::swap(LHS, RHS); 9333 } 9334 9335 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9336 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9337 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9338 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9339 9340 // Check of we need to combine values from two sources within a byte. 9341 if (!(LHSUsedLanes & RHSUsedLanes) && 9342 // If we select high and lower word keep it for SDWA. 9343 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9344 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9345 // Kill zero bytes selected by other mask. Zero value is 0xc. 9346 LHSMask &= ~RHSUsedLanes; 9347 RHSMask &= ~LHSUsedLanes; 9348 // Add 4 to each active LHS lane 9349 LHSMask |= LHSUsedLanes & 0x04040404; 9350 // Combine masks 9351 uint32_t Sel = LHSMask | RHSMask; 9352 SDLoc DL(N); 9353 9354 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9355 LHS.getOperand(0), RHS.getOperand(0), 9356 DAG.getConstant(Sel, DL, MVT::i32)); 9357 } 9358 } 9359 } 9360 9361 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9362 return SDValue(); 9363 9364 // TODO: This could be a generic combine with a predicate for extracting the 9365 // high half of an integer being free. 9366 9367 // (or i64:x, (zero_extend i32:y)) -> 9368 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9369 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9370 RHS.getOpcode() != ISD::ZERO_EXTEND) 9371 std::swap(LHS, RHS); 9372 9373 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9374 SDValue ExtSrc = RHS.getOperand(0); 9375 EVT SrcVT = ExtSrc.getValueType(); 9376 if (SrcVT == MVT::i32) { 9377 SDLoc SL(N); 9378 SDValue LowLHS, HiBits; 9379 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9380 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9381 9382 DCI.AddToWorklist(LowOr.getNode()); 9383 DCI.AddToWorklist(HiBits.getNode()); 9384 9385 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9386 LowOr, HiBits); 9387 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9388 } 9389 } 9390 9391 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9392 if (CRHS) { 9393 if (SDValue Split 9394 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9395 return Split; 9396 } 9397 9398 return SDValue(); 9399 } 9400 9401 SDValue SITargetLowering::performXorCombine(SDNode *N, 9402 DAGCombinerInfo &DCI) const { 9403 EVT VT = N->getValueType(0); 9404 if (VT != MVT::i64) 9405 return SDValue(); 9406 9407 SDValue LHS = N->getOperand(0); 9408 SDValue RHS = N->getOperand(1); 9409 9410 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9411 if (CRHS) { 9412 if (SDValue Split 9413 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9414 return Split; 9415 } 9416 9417 return SDValue(); 9418 } 9419 9420 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9421 DAGCombinerInfo &DCI) const { 9422 if (!Subtarget->has16BitInsts() || 9423 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9424 return SDValue(); 9425 9426 EVT VT = N->getValueType(0); 9427 if (VT != MVT::i32) 9428 return SDValue(); 9429 9430 SDValue Src = N->getOperand(0); 9431 if (Src.getValueType() != MVT::i16) 9432 return SDValue(); 9433 9434 return SDValue(); 9435 } 9436 9437 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9438 DAGCombinerInfo &DCI) 9439 const { 9440 SDValue Src = N->getOperand(0); 9441 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9442 9443 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9444 VTSign->getVT() == MVT::i8) || 9445 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9446 VTSign->getVT() == MVT::i16)) && 9447 Src.hasOneUse()) { 9448 auto *M = cast<MemSDNode>(Src); 9449 SDValue Ops[] = { 9450 Src.getOperand(0), // Chain 9451 Src.getOperand(1), // rsrc 9452 Src.getOperand(2), // vindex 9453 Src.getOperand(3), // voffset 9454 Src.getOperand(4), // soffset 9455 Src.getOperand(5), // offset 9456 Src.getOperand(6), 9457 Src.getOperand(7) 9458 }; 9459 // replace with BUFFER_LOAD_BYTE/SHORT 9460 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9461 Src.getOperand(0).getValueType()); 9462 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9463 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9464 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9465 ResList, 9466 Ops, M->getMemoryVT(), 9467 M->getMemOperand()); 9468 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9469 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9470 } 9471 return SDValue(); 9472 } 9473 9474 SDValue SITargetLowering::performClassCombine(SDNode *N, 9475 DAGCombinerInfo &DCI) const { 9476 SelectionDAG &DAG = DCI.DAG; 9477 SDValue Mask = N->getOperand(1); 9478 9479 // fp_class x, 0 -> false 9480 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9481 if (CMask->isNullValue()) 9482 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9483 } 9484 9485 if (N->getOperand(0).isUndef()) 9486 return DAG.getUNDEF(MVT::i1); 9487 9488 return SDValue(); 9489 } 9490 9491 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9492 DAGCombinerInfo &DCI) const { 9493 EVT VT = N->getValueType(0); 9494 SDValue N0 = N->getOperand(0); 9495 9496 if (N0.isUndef()) 9497 return N0; 9498 9499 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9500 N0.getOpcode() == ISD::SINT_TO_FP)) { 9501 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9502 N->getFlags()); 9503 } 9504 9505 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9506 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9507 N0.getOperand(0), N->getFlags()); 9508 } 9509 9510 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9511 } 9512 9513 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9514 unsigned MaxDepth) const { 9515 unsigned Opcode = Op.getOpcode(); 9516 if (Opcode == ISD::FCANONICALIZE) 9517 return true; 9518 9519 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9520 auto F = CFP->getValueAPF(); 9521 if (F.isNaN() && F.isSignaling()) 9522 return false; 9523 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9524 } 9525 9526 // If source is a result of another standard FP operation it is already in 9527 // canonical form. 9528 if (MaxDepth == 0) 9529 return false; 9530 9531 switch (Opcode) { 9532 // These will flush denorms if required. 9533 case ISD::FADD: 9534 case ISD::FSUB: 9535 case ISD::FMUL: 9536 case ISD::FCEIL: 9537 case ISD::FFLOOR: 9538 case ISD::FMA: 9539 case ISD::FMAD: 9540 case ISD::FSQRT: 9541 case ISD::FDIV: 9542 case ISD::FREM: 9543 case ISD::FP_ROUND: 9544 case ISD::FP_EXTEND: 9545 case AMDGPUISD::FMUL_LEGACY: 9546 case AMDGPUISD::FMAD_FTZ: 9547 case AMDGPUISD::RCP: 9548 case AMDGPUISD::RSQ: 9549 case AMDGPUISD::RSQ_CLAMP: 9550 case AMDGPUISD::RCP_LEGACY: 9551 case AMDGPUISD::RCP_IFLAG: 9552 case AMDGPUISD::DIV_SCALE: 9553 case AMDGPUISD::DIV_FMAS: 9554 case AMDGPUISD::DIV_FIXUP: 9555 case AMDGPUISD::FRACT: 9556 case AMDGPUISD::LDEXP: 9557 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9558 case AMDGPUISD::CVT_F32_UBYTE0: 9559 case AMDGPUISD::CVT_F32_UBYTE1: 9560 case AMDGPUISD::CVT_F32_UBYTE2: 9561 case AMDGPUISD::CVT_F32_UBYTE3: 9562 return true; 9563 9564 // It can/will be lowered or combined as a bit operation. 9565 // Need to check their input recursively to handle. 9566 case ISD::FNEG: 9567 case ISD::FABS: 9568 case ISD::FCOPYSIGN: 9569 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9570 9571 case ISD::FSIN: 9572 case ISD::FCOS: 9573 case ISD::FSINCOS: 9574 return Op.getValueType().getScalarType() != MVT::f16; 9575 9576 case ISD::FMINNUM: 9577 case ISD::FMAXNUM: 9578 case ISD::FMINNUM_IEEE: 9579 case ISD::FMAXNUM_IEEE: 9580 case AMDGPUISD::CLAMP: 9581 case AMDGPUISD::FMED3: 9582 case AMDGPUISD::FMAX3: 9583 case AMDGPUISD::FMIN3: { 9584 // FIXME: Shouldn't treat the generic operations different based these. 9585 // However, we aren't really required to flush the result from 9586 // minnum/maxnum.. 9587 9588 // snans will be quieted, so we only need to worry about denormals. 9589 if (Subtarget->supportsMinMaxDenormModes() || 9590 denormalsEnabledForType(DAG, Op.getValueType())) 9591 return true; 9592 9593 // Flushing may be required. 9594 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9595 // targets need to check their input recursively. 9596 9597 // FIXME: Does this apply with clamp? It's implemented with max. 9598 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9599 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9600 return false; 9601 } 9602 9603 return true; 9604 } 9605 case ISD::SELECT: { 9606 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9607 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9608 } 9609 case ISD::BUILD_VECTOR: { 9610 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9611 SDValue SrcOp = Op.getOperand(i); 9612 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9613 return false; 9614 } 9615 9616 return true; 9617 } 9618 case ISD::EXTRACT_VECTOR_ELT: 9619 case ISD::EXTRACT_SUBVECTOR: { 9620 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9621 } 9622 case ISD::INSERT_VECTOR_ELT: { 9623 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9624 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9625 } 9626 case ISD::UNDEF: 9627 // Could be anything. 9628 return false; 9629 9630 case ISD::BITCAST: 9631 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9632 case ISD::TRUNCATE: { 9633 // Hack round the mess we make when legalizing extract_vector_elt 9634 if (Op.getValueType() == MVT::i16) { 9635 SDValue TruncSrc = Op.getOperand(0); 9636 if (TruncSrc.getValueType() == MVT::i32 && 9637 TruncSrc.getOpcode() == ISD::BITCAST && 9638 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9639 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9640 } 9641 } 9642 return false; 9643 } 9644 case ISD::INTRINSIC_WO_CHAIN: { 9645 unsigned IntrinsicID 9646 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9647 // TODO: Handle more intrinsics 9648 switch (IntrinsicID) { 9649 case Intrinsic::amdgcn_cvt_pkrtz: 9650 case Intrinsic::amdgcn_cubeid: 9651 case Intrinsic::amdgcn_frexp_mant: 9652 case Intrinsic::amdgcn_fdot2: 9653 case Intrinsic::amdgcn_rcp: 9654 case Intrinsic::amdgcn_rsq: 9655 case Intrinsic::amdgcn_rsq_clamp: 9656 case Intrinsic::amdgcn_rcp_legacy: 9657 case Intrinsic::amdgcn_rsq_legacy: 9658 case Intrinsic::amdgcn_trig_preop: 9659 return true; 9660 default: 9661 break; 9662 } 9663 9664 LLVM_FALLTHROUGH; 9665 } 9666 default: 9667 return denormalsEnabledForType(DAG, Op.getValueType()) && 9668 DAG.isKnownNeverSNaN(Op); 9669 } 9670 9671 llvm_unreachable("invalid operation"); 9672 } 9673 9674 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9675 unsigned MaxDepth) const { 9676 MachineRegisterInfo &MRI = MF.getRegInfo(); 9677 MachineInstr *MI = MRI.getVRegDef(Reg); 9678 unsigned Opcode = MI->getOpcode(); 9679 9680 if (Opcode == AMDGPU::G_FCANONICALIZE) 9681 return true; 9682 9683 if (Opcode == AMDGPU::G_FCONSTANT) { 9684 auto F = MI->getOperand(1).getFPImm()->getValueAPF(); 9685 if (F.isNaN() && F.isSignaling()) 9686 return false; 9687 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF); 9688 } 9689 9690 if (MaxDepth == 0) 9691 return false; 9692 9693 switch (Opcode) { 9694 case AMDGPU::G_FMINNUM_IEEE: 9695 case AMDGPU::G_FMAXNUM_IEEE: { 9696 if (Subtarget->supportsMinMaxDenormModes() || 9697 denormalsEnabledForType(MRI.getType(Reg), MF)) 9698 return true; 9699 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) { 9700 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1)) 9701 return false; 9702 } 9703 return true; 9704 } 9705 default: 9706 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9707 isKnownNeverSNaN(Reg, MRI); 9708 } 9709 9710 llvm_unreachable("invalid operation"); 9711 } 9712 9713 // Constant fold canonicalize. 9714 SDValue SITargetLowering::getCanonicalConstantFP( 9715 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9716 // Flush denormals to 0 if not enabled. 9717 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9718 return DAG.getConstantFP(0.0, SL, VT); 9719 9720 if (C.isNaN()) { 9721 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9722 if (C.isSignaling()) { 9723 // Quiet a signaling NaN. 9724 // FIXME: Is this supposed to preserve payload bits? 9725 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9726 } 9727 9728 // Make sure it is the canonical NaN bitpattern. 9729 // 9730 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9731 // immediate? 9732 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9733 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9734 } 9735 9736 // Already canonical. 9737 return DAG.getConstantFP(C, SL, VT); 9738 } 9739 9740 static bool vectorEltWillFoldAway(SDValue Op) { 9741 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9742 } 9743 9744 SDValue SITargetLowering::performFCanonicalizeCombine( 9745 SDNode *N, 9746 DAGCombinerInfo &DCI) const { 9747 SelectionDAG &DAG = DCI.DAG; 9748 SDValue N0 = N->getOperand(0); 9749 EVT VT = N->getValueType(0); 9750 9751 // fcanonicalize undef -> qnan 9752 if (N0.isUndef()) { 9753 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9754 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9755 } 9756 9757 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9758 EVT VT = N->getValueType(0); 9759 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9760 } 9761 9762 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9763 // (fcanonicalize k) 9764 // 9765 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9766 9767 // TODO: This could be better with wider vectors that will be split to v2f16, 9768 // and to consider uses since there aren't that many packed operations. 9769 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9770 isTypeLegal(MVT::v2f16)) { 9771 SDLoc SL(N); 9772 SDValue NewElts[2]; 9773 SDValue Lo = N0.getOperand(0); 9774 SDValue Hi = N0.getOperand(1); 9775 EVT EltVT = Lo.getValueType(); 9776 9777 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9778 for (unsigned I = 0; I != 2; ++I) { 9779 SDValue Op = N0.getOperand(I); 9780 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9781 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9782 CFP->getValueAPF()); 9783 } else if (Op.isUndef()) { 9784 // Handled below based on what the other operand is. 9785 NewElts[I] = Op; 9786 } else { 9787 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9788 } 9789 } 9790 9791 // If one half is undef, and one is constant, perfer a splat vector rather 9792 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9793 // cheaper to use and may be free with a packed operation. 9794 if (NewElts[0].isUndef()) { 9795 if (isa<ConstantFPSDNode>(NewElts[1])) 9796 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9797 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9798 } 9799 9800 if (NewElts[1].isUndef()) { 9801 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9802 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9803 } 9804 9805 return DAG.getBuildVector(VT, SL, NewElts); 9806 } 9807 } 9808 9809 unsigned SrcOpc = N0.getOpcode(); 9810 9811 // If it's free to do so, push canonicalizes further up the source, which may 9812 // find a canonical source. 9813 // 9814 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9815 // sNaNs. 9816 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9817 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9818 if (CRHS && N0.hasOneUse()) { 9819 SDLoc SL(N); 9820 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9821 N0.getOperand(0)); 9822 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9823 DCI.AddToWorklist(Canon0.getNode()); 9824 9825 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9826 } 9827 } 9828 9829 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9830 } 9831 9832 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9833 switch (Opc) { 9834 case ISD::FMAXNUM: 9835 case ISD::FMAXNUM_IEEE: 9836 return AMDGPUISD::FMAX3; 9837 case ISD::SMAX: 9838 return AMDGPUISD::SMAX3; 9839 case ISD::UMAX: 9840 return AMDGPUISD::UMAX3; 9841 case ISD::FMINNUM: 9842 case ISD::FMINNUM_IEEE: 9843 return AMDGPUISD::FMIN3; 9844 case ISD::SMIN: 9845 return AMDGPUISD::SMIN3; 9846 case ISD::UMIN: 9847 return AMDGPUISD::UMIN3; 9848 default: 9849 llvm_unreachable("Not a min/max opcode"); 9850 } 9851 } 9852 9853 SDValue SITargetLowering::performIntMed3ImmCombine( 9854 SelectionDAG &DAG, const SDLoc &SL, 9855 SDValue Op0, SDValue Op1, bool Signed) const { 9856 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9857 if (!K1) 9858 return SDValue(); 9859 9860 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9861 if (!K0) 9862 return SDValue(); 9863 9864 if (Signed) { 9865 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9866 return SDValue(); 9867 } else { 9868 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9869 return SDValue(); 9870 } 9871 9872 EVT VT = K0->getValueType(0); 9873 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9874 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9875 return DAG.getNode(Med3Opc, SL, VT, 9876 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9877 } 9878 9879 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9880 if (VT == MVT::i16) { 9881 MVT NVT = MVT::i32; 9882 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9883 9884 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9885 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9886 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9887 9888 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9889 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9890 } 9891 9892 return SDValue(); 9893 } 9894 9895 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9896 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9897 return C; 9898 9899 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9900 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9901 return C; 9902 } 9903 9904 return nullptr; 9905 } 9906 9907 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9908 const SDLoc &SL, 9909 SDValue Op0, 9910 SDValue Op1) const { 9911 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9912 if (!K1) 9913 return SDValue(); 9914 9915 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9916 if (!K0) 9917 return SDValue(); 9918 9919 // Ordered >= (although NaN inputs should have folded away by now). 9920 if (K0->getValueAPF() > K1->getValueAPF()) 9921 return SDValue(); 9922 9923 const MachineFunction &MF = DAG.getMachineFunction(); 9924 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9925 9926 // TODO: Check IEEE bit enabled? 9927 EVT VT = Op0.getValueType(); 9928 if (Info->getMode().DX10Clamp) { 9929 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9930 // hardware fmed3 behavior converting to a min. 9931 // FIXME: Should this be allowing -0.0? 9932 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9933 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9934 } 9935 9936 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9937 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9938 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9939 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9940 // then give the other result, which is different from med3 with a NaN 9941 // input. 9942 SDValue Var = Op0.getOperand(0); 9943 if (!DAG.isKnownNeverSNaN(Var)) 9944 return SDValue(); 9945 9946 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9947 9948 if ((!K0->hasOneUse() || 9949 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9950 (!K1->hasOneUse() || 9951 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9952 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9953 Var, SDValue(K0, 0), SDValue(K1, 0)); 9954 } 9955 } 9956 9957 return SDValue(); 9958 } 9959 9960 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9961 DAGCombinerInfo &DCI) const { 9962 SelectionDAG &DAG = DCI.DAG; 9963 9964 EVT VT = N->getValueType(0); 9965 unsigned Opc = N->getOpcode(); 9966 SDValue Op0 = N->getOperand(0); 9967 SDValue Op1 = N->getOperand(1); 9968 9969 // Only do this if the inner op has one use since this will just increases 9970 // register pressure for no benefit. 9971 9972 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9973 !VT.isVector() && 9974 (VT == MVT::i32 || VT == MVT::f32 || 9975 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9976 // max(max(a, b), c) -> max3(a, b, c) 9977 // min(min(a, b), c) -> min3(a, b, c) 9978 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9979 SDLoc DL(N); 9980 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9981 DL, 9982 N->getValueType(0), 9983 Op0.getOperand(0), 9984 Op0.getOperand(1), 9985 Op1); 9986 } 9987 9988 // Try commuted. 9989 // max(a, max(b, c)) -> max3(a, b, c) 9990 // min(a, min(b, c)) -> min3(a, b, c) 9991 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9992 SDLoc DL(N); 9993 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9994 DL, 9995 N->getValueType(0), 9996 Op0, 9997 Op1.getOperand(0), 9998 Op1.getOperand(1)); 9999 } 10000 } 10001 10002 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10003 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10004 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10005 return Med3; 10006 } 10007 10008 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10009 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10010 return Med3; 10011 } 10012 10013 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10014 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10015 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10016 (Opc == AMDGPUISD::FMIN_LEGACY && 10017 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10018 (VT == MVT::f32 || VT == MVT::f64 || 10019 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10020 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10021 Op0.hasOneUse()) { 10022 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10023 return Res; 10024 } 10025 10026 return SDValue(); 10027 } 10028 10029 static bool isClampZeroToOne(SDValue A, SDValue B) { 10030 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10031 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10032 // FIXME: Should this be allowing -0.0? 10033 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10034 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10035 } 10036 } 10037 10038 return false; 10039 } 10040 10041 // FIXME: Should only worry about snans for version with chain. 10042 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10043 DAGCombinerInfo &DCI) const { 10044 EVT VT = N->getValueType(0); 10045 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10046 // NaNs. With a NaN input, the order of the operands may change the result. 10047 10048 SelectionDAG &DAG = DCI.DAG; 10049 SDLoc SL(N); 10050 10051 SDValue Src0 = N->getOperand(0); 10052 SDValue Src1 = N->getOperand(1); 10053 SDValue Src2 = N->getOperand(2); 10054 10055 if (isClampZeroToOne(Src0, Src1)) { 10056 // const_a, const_b, x -> clamp is safe in all cases including signaling 10057 // nans. 10058 // FIXME: Should this be allowing -0.0? 10059 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10060 } 10061 10062 const MachineFunction &MF = DAG.getMachineFunction(); 10063 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10064 10065 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10066 // handling no dx10-clamp? 10067 if (Info->getMode().DX10Clamp) { 10068 // If NaNs is clamped to 0, we are free to reorder the inputs. 10069 10070 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10071 std::swap(Src0, Src1); 10072 10073 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10074 std::swap(Src1, Src2); 10075 10076 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10077 std::swap(Src0, Src1); 10078 10079 if (isClampZeroToOne(Src1, Src2)) 10080 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10081 } 10082 10083 return SDValue(); 10084 } 10085 10086 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10087 DAGCombinerInfo &DCI) const { 10088 SDValue Src0 = N->getOperand(0); 10089 SDValue Src1 = N->getOperand(1); 10090 if (Src0.isUndef() && Src1.isUndef()) 10091 return DCI.DAG.getUNDEF(N->getValueType(0)); 10092 return SDValue(); 10093 } 10094 10095 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10096 // expanded into a set of cmp/select instructions. 10097 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10098 unsigned NumElem, 10099 bool IsDivergentIdx) { 10100 if (UseDivergentRegisterIndexing) 10101 return false; 10102 10103 unsigned VecSize = EltSize * NumElem; 10104 10105 // Sub-dword vectors of size 2 dword or less have better implementation. 10106 if (VecSize <= 64 && EltSize < 32) 10107 return false; 10108 10109 // Always expand the rest of sub-dword instructions, otherwise it will be 10110 // lowered via memory. 10111 if (EltSize < 32) 10112 return true; 10113 10114 // Always do this if var-idx is divergent, otherwise it will become a loop. 10115 if (IsDivergentIdx) 10116 return true; 10117 10118 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10119 unsigned NumInsts = NumElem /* Number of compares */ + 10120 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10121 return NumInsts <= 16; 10122 } 10123 10124 static bool shouldExpandVectorDynExt(SDNode *N) { 10125 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10126 if (isa<ConstantSDNode>(Idx)) 10127 return false; 10128 10129 SDValue Vec = N->getOperand(0); 10130 EVT VecVT = Vec.getValueType(); 10131 EVT EltVT = VecVT.getVectorElementType(); 10132 unsigned EltSize = EltVT.getSizeInBits(); 10133 unsigned NumElem = VecVT.getVectorNumElements(); 10134 10135 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10136 Idx->isDivergent()); 10137 } 10138 10139 SDValue SITargetLowering::performExtractVectorEltCombine( 10140 SDNode *N, DAGCombinerInfo &DCI) const { 10141 SDValue Vec = N->getOperand(0); 10142 SelectionDAG &DAG = DCI.DAG; 10143 10144 EVT VecVT = Vec.getValueType(); 10145 EVT EltVT = VecVT.getVectorElementType(); 10146 10147 if ((Vec.getOpcode() == ISD::FNEG || 10148 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10149 SDLoc SL(N); 10150 EVT EltVT = N->getValueType(0); 10151 SDValue Idx = N->getOperand(1); 10152 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10153 Vec.getOperand(0), Idx); 10154 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10155 } 10156 10157 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10158 // => 10159 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10160 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10161 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10162 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10163 SDLoc SL(N); 10164 EVT EltVT = N->getValueType(0); 10165 SDValue Idx = N->getOperand(1); 10166 unsigned Opc = Vec.getOpcode(); 10167 10168 switch(Opc) { 10169 default: 10170 break; 10171 // TODO: Support other binary operations. 10172 case ISD::FADD: 10173 case ISD::FSUB: 10174 case ISD::FMUL: 10175 case ISD::ADD: 10176 case ISD::UMIN: 10177 case ISD::UMAX: 10178 case ISD::SMIN: 10179 case ISD::SMAX: 10180 case ISD::FMAXNUM: 10181 case ISD::FMINNUM: 10182 case ISD::FMAXNUM_IEEE: 10183 case ISD::FMINNUM_IEEE: { 10184 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10185 Vec.getOperand(0), Idx); 10186 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10187 Vec.getOperand(1), Idx); 10188 10189 DCI.AddToWorklist(Elt0.getNode()); 10190 DCI.AddToWorklist(Elt1.getNode()); 10191 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10192 } 10193 } 10194 } 10195 10196 unsigned VecSize = VecVT.getSizeInBits(); 10197 unsigned EltSize = EltVT.getSizeInBits(); 10198 10199 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10200 if (::shouldExpandVectorDynExt(N)) { 10201 SDLoc SL(N); 10202 SDValue Idx = N->getOperand(1); 10203 SDValue V; 10204 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10205 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10206 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10207 if (I == 0) 10208 V = Elt; 10209 else 10210 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10211 } 10212 return V; 10213 } 10214 10215 if (!DCI.isBeforeLegalize()) 10216 return SDValue(); 10217 10218 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10219 // elements. This exposes more load reduction opportunities by replacing 10220 // multiple small extract_vector_elements with a single 32-bit extract. 10221 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10222 if (isa<MemSDNode>(Vec) && 10223 EltSize <= 16 && 10224 EltVT.isByteSized() && 10225 VecSize > 32 && 10226 VecSize % 32 == 0 && 10227 Idx) { 10228 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10229 10230 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10231 unsigned EltIdx = BitIndex / 32; 10232 unsigned LeftoverBitIdx = BitIndex % 32; 10233 SDLoc SL(N); 10234 10235 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10236 DCI.AddToWorklist(Cast.getNode()); 10237 10238 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10239 DAG.getConstant(EltIdx, SL, MVT::i32)); 10240 DCI.AddToWorklist(Elt.getNode()); 10241 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10242 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10243 DCI.AddToWorklist(Srl.getNode()); 10244 10245 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10246 DCI.AddToWorklist(Trunc.getNode()); 10247 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10248 } 10249 10250 return SDValue(); 10251 } 10252 10253 SDValue 10254 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10255 DAGCombinerInfo &DCI) const { 10256 SDValue Vec = N->getOperand(0); 10257 SDValue Idx = N->getOperand(2); 10258 EVT VecVT = Vec.getValueType(); 10259 EVT EltVT = VecVT.getVectorElementType(); 10260 10261 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10262 // => BUILD_VECTOR n x select (e, const-idx) 10263 if (!::shouldExpandVectorDynExt(N)) 10264 return SDValue(); 10265 10266 SelectionDAG &DAG = DCI.DAG; 10267 SDLoc SL(N); 10268 SDValue Ins = N->getOperand(1); 10269 EVT IdxVT = Idx.getValueType(); 10270 10271 SmallVector<SDValue, 16> Ops; 10272 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10273 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10274 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10275 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10276 Ops.push_back(V); 10277 } 10278 10279 return DAG.getBuildVector(VecVT, SL, Ops); 10280 } 10281 10282 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10283 const SDNode *N0, 10284 const SDNode *N1) const { 10285 EVT VT = N0->getValueType(0); 10286 10287 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10288 // support denormals ever. 10289 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10290 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10291 getSubtarget()->hasMadF16())) && 10292 isOperationLegal(ISD::FMAD, VT)) 10293 return ISD::FMAD; 10294 10295 const TargetOptions &Options = DAG.getTarget().Options; 10296 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10297 (N0->getFlags().hasAllowContract() && 10298 N1->getFlags().hasAllowContract())) && 10299 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10300 return ISD::FMA; 10301 } 10302 10303 return 0; 10304 } 10305 10306 // For a reassociatable opcode perform: 10307 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10308 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10309 SelectionDAG &DAG) const { 10310 EVT VT = N->getValueType(0); 10311 if (VT != MVT::i32 && VT != MVT::i64) 10312 return SDValue(); 10313 10314 unsigned Opc = N->getOpcode(); 10315 SDValue Op0 = N->getOperand(0); 10316 SDValue Op1 = N->getOperand(1); 10317 10318 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10319 return SDValue(); 10320 10321 if (Op0->isDivergent()) 10322 std::swap(Op0, Op1); 10323 10324 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10325 return SDValue(); 10326 10327 SDValue Op2 = Op1.getOperand(1); 10328 Op1 = Op1.getOperand(0); 10329 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10330 return SDValue(); 10331 10332 if (Op1->isDivergent()) 10333 std::swap(Op1, Op2); 10334 10335 // If either operand is constant this will conflict with 10336 // DAGCombiner::ReassociateOps(). 10337 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10338 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10339 return SDValue(); 10340 10341 SDLoc SL(N); 10342 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10343 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10344 } 10345 10346 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10347 EVT VT, 10348 SDValue N0, SDValue N1, SDValue N2, 10349 bool Signed) { 10350 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10351 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10352 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10353 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10354 } 10355 10356 SDValue SITargetLowering::performAddCombine(SDNode *N, 10357 DAGCombinerInfo &DCI) const { 10358 SelectionDAG &DAG = DCI.DAG; 10359 EVT VT = N->getValueType(0); 10360 SDLoc SL(N); 10361 SDValue LHS = N->getOperand(0); 10362 SDValue RHS = N->getOperand(1); 10363 10364 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10365 && Subtarget->hasMad64_32() && 10366 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10367 VT.getScalarSizeInBits() <= 64) { 10368 if (LHS.getOpcode() != ISD::MUL) 10369 std::swap(LHS, RHS); 10370 10371 SDValue MulLHS = LHS.getOperand(0); 10372 SDValue MulRHS = LHS.getOperand(1); 10373 SDValue AddRHS = RHS; 10374 10375 // TODO: Maybe restrict if SGPR inputs. 10376 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10377 numBitsUnsigned(MulRHS, DAG) <= 32) { 10378 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10379 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10380 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10381 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10382 } 10383 10384 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10385 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10386 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10387 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10388 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10389 } 10390 10391 return SDValue(); 10392 } 10393 10394 if (SDValue V = reassociateScalarOps(N, DAG)) { 10395 return V; 10396 } 10397 10398 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10399 return SDValue(); 10400 10401 // add x, zext (setcc) => addcarry x, 0, setcc 10402 // add x, sext (setcc) => subcarry x, 0, setcc 10403 unsigned Opc = LHS.getOpcode(); 10404 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10405 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10406 std::swap(RHS, LHS); 10407 10408 Opc = RHS.getOpcode(); 10409 switch (Opc) { 10410 default: break; 10411 case ISD::ZERO_EXTEND: 10412 case ISD::SIGN_EXTEND: 10413 case ISD::ANY_EXTEND: { 10414 auto Cond = RHS.getOperand(0); 10415 // If this won't be a real VOPC output, we would still need to insert an 10416 // extra instruction anyway. 10417 if (!isBoolSGPR(Cond)) 10418 break; 10419 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10420 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10421 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10422 return DAG.getNode(Opc, SL, VTList, Args); 10423 } 10424 case ISD::ADDCARRY: { 10425 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10426 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10427 if (!C || C->getZExtValue() != 0) break; 10428 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10429 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10430 } 10431 } 10432 return SDValue(); 10433 } 10434 10435 SDValue SITargetLowering::performSubCombine(SDNode *N, 10436 DAGCombinerInfo &DCI) const { 10437 SelectionDAG &DAG = DCI.DAG; 10438 EVT VT = N->getValueType(0); 10439 10440 if (VT != MVT::i32) 10441 return SDValue(); 10442 10443 SDLoc SL(N); 10444 SDValue LHS = N->getOperand(0); 10445 SDValue RHS = N->getOperand(1); 10446 10447 // sub x, zext (setcc) => subcarry x, 0, setcc 10448 // sub x, sext (setcc) => addcarry x, 0, setcc 10449 unsigned Opc = RHS.getOpcode(); 10450 switch (Opc) { 10451 default: break; 10452 case ISD::ZERO_EXTEND: 10453 case ISD::SIGN_EXTEND: 10454 case ISD::ANY_EXTEND: { 10455 auto Cond = RHS.getOperand(0); 10456 // If this won't be a real VOPC output, we would still need to insert an 10457 // extra instruction anyway. 10458 if (!isBoolSGPR(Cond)) 10459 break; 10460 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10461 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10462 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10463 return DAG.getNode(Opc, SL, VTList, Args); 10464 } 10465 } 10466 10467 if (LHS.getOpcode() == ISD::SUBCARRY) { 10468 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10469 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10470 if (!C || !C->isNullValue()) 10471 return SDValue(); 10472 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10473 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10474 } 10475 return SDValue(); 10476 } 10477 10478 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10479 DAGCombinerInfo &DCI) const { 10480 10481 if (N->getValueType(0) != MVT::i32) 10482 return SDValue(); 10483 10484 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10485 if (!C || C->getZExtValue() != 0) 10486 return SDValue(); 10487 10488 SelectionDAG &DAG = DCI.DAG; 10489 SDValue LHS = N->getOperand(0); 10490 10491 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10492 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10493 unsigned LHSOpc = LHS.getOpcode(); 10494 unsigned Opc = N->getOpcode(); 10495 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10496 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10497 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10498 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10499 } 10500 return SDValue(); 10501 } 10502 10503 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10504 DAGCombinerInfo &DCI) const { 10505 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10506 return SDValue(); 10507 10508 SelectionDAG &DAG = DCI.DAG; 10509 EVT VT = N->getValueType(0); 10510 10511 SDLoc SL(N); 10512 SDValue LHS = N->getOperand(0); 10513 SDValue RHS = N->getOperand(1); 10514 10515 // These should really be instruction patterns, but writing patterns with 10516 // source modiifiers is a pain. 10517 10518 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10519 if (LHS.getOpcode() == ISD::FADD) { 10520 SDValue A = LHS.getOperand(0); 10521 if (A == LHS.getOperand(1)) { 10522 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10523 if (FusedOp != 0) { 10524 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10525 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10526 } 10527 } 10528 } 10529 10530 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10531 if (RHS.getOpcode() == ISD::FADD) { 10532 SDValue A = RHS.getOperand(0); 10533 if (A == RHS.getOperand(1)) { 10534 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10535 if (FusedOp != 0) { 10536 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10537 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10538 } 10539 } 10540 } 10541 10542 return SDValue(); 10543 } 10544 10545 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10546 DAGCombinerInfo &DCI) const { 10547 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10548 return SDValue(); 10549 10550 SelectionDAG &DAG = DCI.DAG; 10551 SDLoc SL(N); 10552 EVT VT = N->getValueType(0); 10553 assert(!VT.isVector()); 10554 10555 // Try to get the fneg to fold into the source modifier. This undoes generic 10556 // DAG combines and folds them into the mad. 10557 // 10558 // Only do this if we are not trying to support denormals. v_mad_f32 does 10559 // not support denormals ever. 10560 SDValue LHS = N->getOperand(0); 10561 SDValue RHS = N->getOperand(1); 10562 if (LHS.getOpcode() == ISD::FADD) { 10563 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10564 SDValue A = LHS.getOperand(0); 10565 if (A == LHS.getOperand(1)) { 10566 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10567 if (FusedOp != 0){ 10568 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10569 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10570 10571 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10572 } 10573 } 10574 } 10575 10576 if (RHS.getOpcode() == ISD::FADD) { 10577 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10578 10579 SDValue A = RHS.getOperand(0); 10580 if (A == RHS.getOperand(1)) { 10581 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10582 if (FusedOp != 0){ 10583 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10584 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10585 } 10586 } 10587 } 10588 10589 return SDValue(); 10590 } 10591 10592 SDValue SITargetLowering::performFMACombine(SDNode *N, 10593 DAGCombinerInfo &DCI) const { 10594 SelectionDAG &DAG = DCI.DAG; 10595 EVT VT = N->getValueType(0); 10596 SDLoc SL(N); 10597 10598 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10599 return SDValue(); 10600 10601 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10602 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10603 SDValue Op1 = N->getOperand(0); 10604 SDValue Op2 = N->getOperand(1); 10605 SDValue FMA = N->getOperand(2); 10606 10607 if (FMA.getOpcode() != ISD::FMA || 10608 Op1.getOpcode() != ISD::FP_EXTEND || 10609 Op2.getOpcode() != ISD::FP_EXTEND) 10610 return SDValue(); 10611 10612 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10613 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10614 // is sufficient to allow generaing fdot2. 10615 const TargetOptions &Options = DAG.getTarget().Options; 10616 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10617 (N->getFlags().hasAllowContract() && 10618 FMA->getFlags().hasAllowContract())) { 10619 Op1 = Op1.getOperand(0); 10620 Op2 = Op2.getOperand(0); 10621 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10622 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10623 return SDValue(); 10624 10625 SDValue Vec1 = Op1.getOperand(0); 10626 SDValue Idx1 = Op1.getOperand(1); 10627 SDValue Vec2 = Op2.getOperand(0); 10628 10629 SDValue FMAOp1 = FMA.getOperand(0); 10630 SDValue FMAOp2 = FMA.getOperand(1); 10631 SDValue FMAAcc = FMA.getOperand(2); 10632 10633 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10634 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10635 return SDValue(); 10636 10637 FMAOp1 = FMAOp1.getOperand(0); 10638 FMAOp2 = FMAOp2.getOperand(0); 10639 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10640 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10641 return SDValue(); 10642 10643 SDValue Vec3 = FMAOp1.getOperand(0); 10644 SDValue Vec4 = FMAOp2.getOperand(0); 10645 SDValue Idx2 = FMAOp1.getOperand(1); 10646 10647 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10648 // Idx1 and Idx2 cannot be the same. 10649 Idx1 == Idx2) 10650 return SDValue(); 10651 10652 if (Vec1 == Vec2 || Vec3 == Vec4) 10653 return SDValue(); 10654 10655 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10656 return SDValue(); 10657 10658 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10659 (Vec1 == Vec4 && Vec2 == Vec3)) { 10660 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10661 DAG.getTargetConstant(0, SL, MVT::i1)); 10662 } 10663 } 10664 return SDValue(); 10665 } 10666 10667 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10668 DAGCombinerInfo &DCI) const { 10669 SelectionDAG &DAG = DCI.DAG; 10670 SDLoc SL(N); 10671 10672 SDValue LHS = N->getOperand(0); 10673 SDValue RHS = N->getOperand(1); 10674 EVT VT = LHS.getValueType(); 10675 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10676 10677 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10678 if (!CRHS) { 10679 CRHS = dyn_cast<ConstantSDNode>(LHS); 10680 if (CRHS) { 10681 std::swap(LHS, RHS); 10682 CC = getSetCCSwappedOperands(CC); 10683 } 10684 } 10685 10686 if (CRHS) { 10687 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10688 isBoolSGPR(LHS.getOperand(0))) { 10689 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10690 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10691 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10692 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10693 if ((CRHS->isAllOnesValue() && 10694 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10695 (CRHS->isNullValue() && 10696 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10697 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10698 DAG.getConstant(-1, SL, MVT::i1)); 10699 if ((CRHS->isAllOnesValue() && 10700 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10701 (CRHS->isNullValue() && 10702 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10703 return LHS.getOperand(0); 10704 } 10705 10706 uint64_t CRHSVal = CRHS->getZExtValue(); 10707 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10708 LHS.getOpcode() == ISD::SELECT && 10709 isa<ConstantSDNode>(LHS.getOperand(1)) && 10710 isa<ConstantSDNode>(LHS.getOperand(2)) && 10711 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10712 isBoolSGPR(LHS.getOperand(0))) { 10713 // Given CT != FT: 10714 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10715 // setcc (select cc, CT, CF), CF, ne => cc 10716 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10717 // setcc (select cc, CT, CF), CT, eq => cc 10718 uint64_t CT = LHS.getConstantOperandVal(1); 10719 uint64_t CF = LHS.getConstantOperandVal(2); 10720 10721 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10722 (CT == CRHSVal && CC == ISD::SETNE)) 10723 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10724 DAG.getConstant(-1, SL, MVT::i1)); 10725 if ((CF == CRHSVal && CC == ISD::SETNE) || 10726 (CT == CRHSVal && CC == ISD::SETEQ)) 10727 return LHS.getOperand(0); 10728 } 10729 } 10730 10731 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10732 VT != MVT::f16)) 10733 return SDValue(); 10734 10735 // Match isinf/isfinite pattern 10736 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10737 // (fcmp one (fabs x), inf) -> (fp_class x, 10738 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10739 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10740 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10741 if (!CRHS) 10742 return SDValue(); 10743 10744 const APFloat &APF = CRHS->getValueAPF(); 10745 if (APF.isInfinity() && !APF.isNegative()) { 10746 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10747 SIInstrFlags::N_INFINITY; 10748 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10749 SIInstrFlags::P_ZERO | 10750 SIInstrFlags::N_NORMAL | 10751 SIInstrFlags::P_NORMAL | 10752 SIInstrFlags::N_SUBNORMAL | 10753 SIInstrFlags::P_SUBNORMAL; 10754 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10755 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10756 DAG.getConstant(Mask, SL, MVT::i32)); 10757 } 10758 } 10759 10760 return SDValue(); 10761 } 10762 10763 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10764 DAGCombinerInfo &DCI) const { 10765 SelectionDAG &DAG = DCI.DAG; 10766 SDLoc SL(N); 10767 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10768 10769 SDValue Src = N->getOperand(0); 10770 SDValue Shift = N->getOperand(0); 10771 10772 // TODO: Extend type shouldn't matter (assuming legal types). 10773 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10774 Shift = Shift.getOperand(0); 10775 10776 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10777 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10778 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10779 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10780 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10781 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10782 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10783 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10784 SDLoc(Shift.getOperand(0)), MVT::i32); 10785 10786 unsigned ShiftOffset = 8 * Offset; 10787 if (Shift.getOpcode() == ISD::SHL) 10788 ShiftOffset -= C->getZExtValue(); 10789 else 10790 ShiftOffset += C->getZExtValue(); 10791 10792 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10793 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10794 MVT::f32, Shift); 10795 } 10796 } 10797 } 10798 10799 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10800 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10801 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10802 // We simplified Src. If this node is not dead, visit it again so it is 10803 // folded properly. 10804 if (N->getOpcode() != ISD::DELETED_NODE) 10805 DCI.AddToWorklist(N); 10806 return SDValue(N, 0); 10807 } 10808 10809 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10810 if (SDValue DemandedSrc = 10811 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10812 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10813 10814 return SDValue(); 10815 } 10816 10817 SDValue SITargetLowering::performClampCombine(SDNode *N, 10818 DAGCombinerInfo &DCI) const { 10819 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10820 if (!CSrc) 10821 return SDValue(); 10822 10823 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10824 const APFloat &F = CSrc->getValueAPF(); 10825 APFloat Zero = APFloat::getZero(F.getSemantics()); 10826 if (F < Zero || 10827 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10828 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10829 } 10830 10831 APFloat One(F.getSemantics(), "1.0"); 10832 if (F > One) 10833 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10834 10835 return SDValue(CSrc, 0); 10836 } 10837 10838 10839 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10840 DAGCombinerInfo &DCI) const { 10841 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10842 return SDValue(); 10843 switch (N->getOpcode()) { 10844 case ISD::ADD: 10845 return performAddCombine(N, DCI); 10846 case ISD::SUB: 10847 return performSubCombine(N, DCI); 10848 case ISD::ADDCARRY: 10849 case ISD::SUBCARRY: 10850 return performAddCarrySubCarryCombine(N, DCI); 10851 case ISD::FADD: 10852 return performFAddCombine(N, DCI); 10853 case ISD::FSUB: 10854 return performFSubCombine(N, DCI); 10855 case ISD::SETCC: 10856 return performSetCCCombine(N, DCI); 10857 case ISD::FMAXNUM: 10858 case ISD::FMINNUM: 10859 case ISD::FMAXNUM_IEEE: 10860 case ISD::FMINNUM_IEEE: 10861 case ISD::SMAX: 10862 case ISD::SMIN: 10863 case ISD::UMAX: 10864 case ISD::UMIN: 10865 case AMDGPUISD::FMIN_LEGACY: 10866 case AMDGPUISD::FMAX_LEGACY: 10867 return performMinMaxCombine(N, DCI); 10868 case ISD::FMA: 10869 return performFMACombine(N, DCI); 10870 case ISD::AND: 10871 return performAndCombine(N, DCI); 10872 case ISD::OR: 10873 return performOrCombine(N, DCI); 10874 case ISD::XOR: 10875 return performXorCombine(N, DCI); 10876 case ISD::ZERO_EXTEND: 10877 return performZeroExtendCombine(N, DCI); 10878 case ISD::SIGN_EXTEND_INREG: 10879 return performSignExtendInRegCombine(N , DCI); 10880 case AMDGPUISD::FP_CLASS: 10881 return performClassCombine(N, DCI); 10882 case ISD::FCANONICALIZE: 10883 return performFCanonicalizeCombine(N, DCI); 10884 case AMDGPUISD::RCP: 10885 return performRcpCombine(N, DCI); 10886 case AMDGPUISD::FRACT: 10887 case AMDGPUISD::RSQ: 10888 case AMDGPUISD::RCP_LEGACY: 10889 case AMDGPUISD::RCP_IFLAG: 10890 case AMDGPUISD::RSQ_CLAMP: 10891 case AMDGPUISD::LDEXP: { 10892 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10893 SDValue Src = N->getOperand(0); 10894 if (Src.isUndef()) 10895 return Src; 10896 break; 10897 } 10898 case ISD::SINT_TO_FP: 10899 case ISD::UINT_TO_FP: 10900 return performUCharToFloatCombine(N, DCI); 10901 case AMDGPUISD::CVT_F32_UBYTE0: 10902 case AMDGPUISD::CVT_F32_UBYTE1: 10903 case AMDGPUISD::CVT_F32_UBYTE2: 10904 case AMDGPUISD::CVT_F32_UBYTE3: 10905 return performCvtF32UByteNCombine(N, DCI); 10906 case AMDGPUISD::FMED3: 10907 return performFMed3Combine(N, DCI); 10908 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10909 return performCvtPkRTZCombine(N, DCI); 10910 case AMDGPUISD::CLAMP: 10911 return performClampCombine(N, DCI); 10912 case ISD::SCALAR_TO_VECTOR: { 10913 SelectionDAG &DAG = DCI.DAG; 10914 EVT VT = N->getValueType(0); 10915 10916 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10917 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10918 SDLoc SL(N); 10919 SDValue Src = N->getOperand(0); 10920 EVT EltVT = Src.getValueType(); 10921 if (EltVT == MVT::f16) 10922 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10923 10924 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10925 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10926 } 10927 10928 break; 10929 } 10930 case ISD::EXTRACT_VECTOR_ELT: 10931 return performExtractVectorEltCombine(N, DCI); 10932 case ISD::INSERT_VECTOR_ELT: 10933 return performInsertVectorEltCombine(N, DCI); 10934 case ISD::LOAD: { 10935 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10936 return Widended; 10937 LLVM_FALLTHROUGH; 10938 } 10939 default: { 10940 if (!DCI.isBeforeLegalize()) { 10941 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10942 return performMemSDNodeCombine(MemNode, DCI); 10943 } 10944 10945 break; 10946 } 10947 } 10948 10949 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10950 } 10951 10952 /// Helper function for adjustWritemask 10953 static unsigned SubIdx2Lane(unsigned Idx) { 10954 switch (Idx) { 10955 default: return ~0u; 10956 case AMDGPU::sub0: return 0; 10957 case AMDGPU::sub1: return 1; 10958 case AMDGPU::sub2: return 2; 10959 case AMDGPU::sub3: return 3; 10960 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10961 } 10962 } 10963 10964 /// Adjust the writemask of MIMG instructions 10965 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10966 SelectionDAG &DAG) const { 10967 unsigned Opcode = Node->getMachineOpcode(); 10968 10969 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10970 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10971 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10972 return Node; // not implemented for D16 10973 10974 SDNode *Users[5] = { nullptr }; 10975 unsigned Lane = 0; 10976 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10977 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10978 unsigned NewDmask = 0; 10979 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10980 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10981 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10982 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10983 unsigned TFCLane = 0; 10984 bool HasChain = Node->getNumValues() > 1; 10985 10986 if (OldDmask == 0) { 10987 // These are folded out, but on the chance it happens don't assert. 10988 return Node; 10989 } 10990 10991 unsigned OldBitsSet = countPopulation(OldDmask); 10992 // Work out which is the TFE/LWE lane if that is enabled. 10993 if (UsesTFC) { 10994 TFCLane = OldBitsSet; 10995 } 10996 10997 // Try to figure out the used register components 10998 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10999 I != E; ++I) { 11000 11001 // Don't look at users of the chain. 11002 if (I.getUse().getResNo() != 0) 11003 continue; 11004 11005 // Abort if we can't understand the usage 11006 if (!I->isMachineOpcode() || 11007 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11008 return Node; 11009 11010 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11011 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11012 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11013 // set, etc. 11014 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11015 if (Lane == ~0u) 11016 return Node; 11017 11018 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11019 if (UsesTFC && Lane == TFCLane) { 11020 Users[Lane] = *I; 11021 } else { 11022 // Set which texture component corresponds to the lane. 11023 unsigned Comp; 11024 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11025 Comp = countTrailingZeros(Dmask); 11026 Dmask &= ~(1 << Comp); 11027 } 11028 11029 // Abort if we have more than one user per component. 11030 if (Users[Lane]) 11031 return Node; 11032 11033 Users[Lane] = *I; 11034 NewDmask |= 1 << Comp; 11035 } 11036 } 11037 11038 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11039 bool NoChannels = !NewDmask; 11040 if (NoChannels) { 11041 if (!UsesTFC) { 11042 // No uses of the result and not using TFC. Then do nothing. 11043 return Node; 11044 } 11045 // If the original dmask has one channel - then nothing to do 11046 if (OldBitsSet == 1) 11047 return Node; 11048 // Use an arbitrary dmask - required for the instruction to work 11049 NewDmask = 1; 11050 } 11051 // Abort if there's no change 11052 if (NewDmask == OldDmask) 11053 return Node; 11054 11055 unsigned BitsSet = countPopulation(NewDmask); 11056 11057 // Check for TFE or LWE - increase the number of channels by one to account 11058 // for the extra return value 11059 // This will need adjustment for D16 if this is also included in 11060 // adjustWriteMask (this function) but at present D16 are excluded. 11061 unsigned NewChannels = BitsSet + UsesTFC; 11062 11063 int NewOpcode = 11064 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11065 assert(NewOpcode != -1 && 11066 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11067 "failed to find equivalent MIMG op"); 11068 11069 // Adjust the writemask in the node 11070 SmallVector<SDValue, 12> Ops; 11071 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11072 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11073 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11074 11075 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11076 11077 MVT ResultVT = NewChannels == 1 ? 11078 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11079 NewChannels == 5 ? 8 : NewChannels); 11080 SDVTList NewVTList = HasChain ? 11081 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11082 11083 11084 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11085 NewVTList, Ops); 11086 11087 if (HasChain) { 11088 // Update chain. 11089 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11090 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11091 } 11092 11093 if (NewChannels == 1) { 11094 assert(Node->hasNUsesOfValue(1, 0)); 11095 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11096 SDLoc(Node), Users[Lane]->getValueType(0), 11097 SDValue(NewNode, 0)); 11098 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11099 return nullptr; 11100 } 11101 11102 // Update the users of the node with the new indices 11103 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11104 SDNode *User = Users[i]; 11105 if (!User) { 11106 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11107 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11108 if (i || !NoChannels) 11109 continue; 11110 } else { 11111 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11112 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11113 } 11114 11115 switch (Idx) { 11116 default: break; 11117 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11118 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11119 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11120 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11121 } 11122 } 11123 11124 DAG.RemoveDeadNode(Node); 11125 return nullptr; 11126 } 11127 11128 static bool isFrameIndexOp(SDValue Op) { 11129 if (Op.getOpcode() == ISD::AssertZext) 11130 Op = Op.getOperand(0); 11131 11132 return isa<FrameIndexSDNode>(Op); 11133 } 11134 11135 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11136 /// with frame index operands. 11137 /// LLVM assumes that inputs are to these instructions are registers. 11138 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11139 SelectionDAG &DAG) const { 11140 if (Node->getOpcode() == ISD::CopyToReg) { 11141 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11142 SDValue SrcVal = Node->getOperand(2); 11143 11144 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11145 // to try understanding copies to physical registers. 11146 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11147 SDLoc SL(Node); 11148 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11149 SDValue VReg = DAG.getRegister( 11150 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11151 11152 SDNode *Glued = Node->getGluedNode(); 11153 SDValue ToVReg 11154 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11155 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11156 SDValue ToResultReg 11157 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11158 VReg, ToVReg.getValue(1)); 11159 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11160 DAG.RemoveDeadNode(Node); 11161 return ToResultReg.getNode(); 11162 } 11163 } 11164 11165 SmallVector<SDValue, 8> Ops; 11166 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11167 if (!isFrameIndexOp(Node->getOperand(i))) { 11168 Ops.push_back(Node->getOperand(i)); 11169 continue; 11170 } 11171 11172 SDLoc DL(Node); 11173 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11174 Node->getOperand(i).getValueType(), 11175 Node->getOperand(i)), 0)); 11176 } 11177 11178 return DAG.UpdateNodeOperands(Node, Ops); 11179 } 11180 11181 /// Fold the instructions after selecting them. 11182 /// Returns null if users were already updated. 11183 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11184 SelectionDAG &DAG) const { 11185 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11186 unsigned Opcode = Node->getMachineOpcode(); 11187 11188 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11189 !TII->isGather4(Opcode) && 11190 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11191 return adjustWritemask(Node, DAG); 11192 } 11193 11194 if (Opcode == AMDGPU::INSERT_SUBREG || 11195 Opcode == AMDGPU::REG_SEQUENCE) { 11196 legalizeTargetIndependentNode(Node, DAG); 11197 return Node; 11198 } 11199 11200 switch (Opcode) { 11201 case AMDGPU::V_DIV_SCALE_F32_e64: 11202 case AMDGPU::V_DIV_SCALE_F64_e64: { 11203 // Satisfy the operand register constraint when one of the inputs is 11204 // undefined. Ordinarily each undef value will have its own implicit_def of 11205 // a vreg, so force these to use a single register. 11206 SDValue Src0 = Node->getOperand(1); 11207 SDValue Src1 = Node->getOperand(3); 11208 SDValue Src2 = Node->getOperand(5); 11209 11210 if ((Src0.isMachineOpcode() && 11211 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11212 (Src0 == Src1 || Src0 == Src2)) 11213 break; 11214 11215 MVT VT = Src0.getValueType().getSimpleVT(); 11216 const TargetRegisterClass *RC = 11217 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11218 11219 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11220 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11221 11222 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11223 UndefReg, Src0, SDValue()); 11224 11225 // src0 must be the same register as src1 or src2, even if the value is 11226 // undefined, so make sure we don't violate this constraint. 11227 if (Src0.isMachineOpcode() && 11228 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11229 if (Src1.isMachineOpcode() && 11230 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11231 Src0 = Src1; 11232 else if (Src2.isMachineOpcode() && 11233 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11234 Src0 = Src2; 11235 else { 11236 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11237 Src0 = UndefReg; 11238 Src1 = UndefReg; 11239 } 11240 } else 11241 break; 11242 11243 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11244 Ops[1] = Src0; 11245 Ops[3] = Src1; 11246 Ops[5] = Src2; 11247 Ops.push_back(ImpDef.getValue(1)); 11248 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11249 } 11250 default: 11251 break; 11252 } 11253 11254 return Node; 11255 } 11256 11257 // Any MIMG instructions that use tfe or lwe require an initialization of the 11258 // result register that will be written in the case of a memory access failure. 11259 // The required code is also added to tie this init code to the result of the 11260 // img instruction. 11261 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11262 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11263 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11264 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11265 MachineBasicBlock &MBB = *MI.getParent(); 11266 11267 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11268 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11269 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11270 11271 if (!TFE && !LWE) // intersect_ray 11272 return; 11273 11274 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11275 unsigned LWEVal = LWE->getImm(); 11276 unsigned D16Val = D16 ? D16->getImm() : 0; 11277 11278 if (!TFEVal && !LWEVal) 11279 return; 11280 11281 // At least one of TFE or LWE are non-zero 11282 // We have to insert a suitable initialization of the result value and 11283 // tie this to the dest of the image instruction. 11284 11285 const DebugLoc &DL = MI.getDebugLoc(); 11286 11287 int DstIdx = 11288 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11289 11290 // Calculate which dword we have to initialize to 0. 11291 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11292 11293 // check that dmask operand is found. 11294 assert(MO_Dmask && "Expected dmask operand in instruction"); 11295 11296 unsigned dmask = MO_Dmask->getImm(); 11297 // Determine the number of active lanes taking into account the 11298 // Gather4 special case 11299 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11300 11301 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11302 11303 unsigned InitIdx = 11304 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11305 11306 // Abandon attempt if the dst size isn't large enough 11307 // - this is in fact an error but this is picked up elsewhere and 11308 // reported correctly. 11309 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11310 if (DstSize < InitIdx) 11311 return; 11312 11313 // Create a register for the intialization value. 11314 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11315 unsigned NewDst = 0; // Final initialized value will be in here 11316 11317 // If PRTStrictNull feature is enabled (the default) then initialize 11318 // all the result registers to 0, otherwise just the error indication 11319 // register (VGPRn+1) 11320 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11321 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11322 11323 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11324 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11325 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11326 // Initialize dword 11327 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11328 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11329 .addImm(0); 11330 // Insert into the super-reg 11331 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11332 .addReg(PrevDst) 11333 .addReg(SubReg) 11334 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11335 11336 PrevDst = NewDst; 11337 } 11338 11339 // Add as an implicit operand 11340 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11341 11342 // Tie the just added implicit operand to the dst 11343 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11344 } 11345 11346 /// Assign the register class depending on the number of 11347 /// bits set in the writemask 11348 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11349 SDNode *Node) const { 11350 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11351 11352 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11353 11354 if (TII->isVOP3(MI.getOpcode())) { 11355 // Make sure constant bus requirements are respected. 11356 TII->legalizeOperandsVOP3(MRI, MI); 11357 11358 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11359 // This saves a chain-copy of registers and better ballance register 11360 // use between vgpr and agpr as agpr tuples tend to be big. 11361 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11362 unsigned Opc = MI.getOpcode(); 11363 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11364 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11365 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11366 if (I == -1) 11367 break; 11368 MachineOperand &Op = MI.getOperand(I); 11369 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11370 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11371 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11372 continue; 11373 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11374 if (!Src || !Src->isCopy() || 11375 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11376 continue; 11377 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11378 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11379 // All uses of agpr64 and agpr32 can also accept vgpr except for 11380 // v_accvgpr_read, but we do not produce agpr reads during selection, 11381 // so no use checks are needed. 11382 MRI.setRegClass(Op.getReg(), NewRC); 11383 } 11384 } 11385 11386 return; 11387 } 11388 11389 // Replace unused atomics with the no return version. 11390 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11391 if (NoRetAtomicOp != -1) { 11392 if (!Node->hasAnyUseOfValue(0)) { 11393 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11394 AMDGPU::OpName::cpol); 11395 if (CPolIdx != -1) { 11396 MachineOperand &CPol = MI.getOperand(CPolIdx); 11397 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11398 } 11399 MI.RemoveOperand(0); 11400 MI.setDesc(TII->get(NoRetAtomicOp)); 11401 return; 11402 } 11403 11404 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11405 // instruction, because the return type of these instructions is a vec2 of 11406 // the memory type, so it can be tied to the input operand. 11407 // This means these instructions always have a use, so we need to add a 11408 // special case to check if the atomic has only one extract_subreg use, 11409 // which itself has no uses. 11410 if ((Node->hasNUsesOfValue(1, 0) && 11411 Node->use_begin()->isMachineOpcode() && 11412 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11413 !Node->use_begin()->hasAnyUseOfValue(0))) { 11414 Register Def = MI.getOperand(0).getReg(); 11415 11416 // Change this into a noret atomic. 11417 MI.setDesc(TII->get(NoRetAtomicOp)); 11418 MI.RemoveOperand(0); 11419 11420 // If we only remove the def operand from the atomic instruction, the 11421 // extract_subreg will be left with a use of a vreg without a def. 11422 // So we need to insert an implicit_def to avoid machine verifier 11423 // errors. 11424 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11425 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11426 } 11427 return; 11428 } 11429 11430 if (TII->isMIMG(MI) && !MI.mayStore()) 11431 AddIMGInit(MI); 11432 } 11433 11434 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11435 uint64_t Val) { 11436 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11437 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11438 } 11439 11440 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11441 const SDLoc &DL, 11442 SDValue Ptr) const { 11443 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11444 11445 // Build the half of the subregister with the constants before building the 11446 // full 128-bit register. If we are building multiple resource descriptors, 11447 // this will allow CSEing of the 2-component register. 11448 const SDValue Ops0[] = { 11449 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11450 buildSMovImm32(DAG, DL, 0), 11451 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11452 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11453 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11454 }; 11455 11456 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11457 MVT::v2i32, Ops0), 0); 11458 11459 // Combine the constants and the pointer. 11460 const SDValue Ops1[] = { 11461 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11462 Ptr, 11463 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11464 SubRegHi, 11465 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11466 }; 11467 11468 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11469 } 11470 11471 /// Return a resource descriptor with the 'Add TID' bit enabled 11472 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11473 /// of the resource descriptor) to create an offset, which is added to 11474 /// the resource pointer. 11475 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11476 SDValue Ptr, uint32_t RsrcDword1, 11477 uint64_t RsrcDword2And3) const { 11478 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11479 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11480 if (RsrcDword1) { 11481 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11482 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11483 0); 11484 } 11485 11486 SDValue DataLo = buildSMovImm32(DAG, DL, 11487 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11488 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11489 11490 const SDValue Ops[] = { 11491 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11492 PtrLo, 11493 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11494 PtrHi, 11495 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11496 DataLo, 11497 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11498 DataHi, 11499 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11500 }; 11501 11502 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11503 } 11504 11505 //===----------------------------------------------------------------------===// 11506 // SI Inline Assembly Support 11507 //===----------------------------------------------------------------------===// 11508 11509 std::pair<unsigned, const TargetRegisterClass *> 11510 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11511 StringRef Constraint, 11512 MVT VT) const { 11513 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11514 11515 const TargetRegisterClass *RC = nullptr; 11516 if (Constraint.size() == 1) { 11517 const unsigned BitWidth = VT.getSizeInBits(); 11518 switch (Constraint[0]) { 11519 default: 11520 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11521 case 's': 11522 case 'r': 11523 switch (BitWidth) { 11524 case 16: 11525 RC = &AMDGPU::SReg_32RegClass; 11526 break; 11527 case 64: 11528 RC = &AMDGPU::SGPR_64RegClass; 11529 break; 11530 default: 11531 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11532 if (!RC) 11533 return std::make_pair(0U, nullptr); 11534 break; 11535 } 11536 break; 11537 case 'v': 11538 switch (BitWidth) { 11539 case 16: 11540 RC = &AMDGPU::VGPR_32RegClass; 11541 break; 11542 default: 11543 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11544 if (!RC) 11545 return std::make_pair(0U, nullptr); 11546 break; 11547 } 11548 break; 11549 case 'a': 11550 if (!Subtarget->hasMAIInsts()) 11551 break; 11552 switch (BitWidth) { 11553 case 16: 11554 RC = &AMDGPU::AGPR_32RegClass; 11555 break; 11556 default: 11557 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11558 if (!RC) 11559 return std::make_pair(0U, nullptr); 11560 break; 11561 } 11562 break; 11563 } 11564 // We actually support i128, i16 and f16 as inline parameters 11565 // even if they are not reported as legal 11566 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11567 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11568 return std::make_pair(0U, RC); 11569 } 11570 11571 if (Constraint.size() > 1) { 11572 if (Constraint[1] == 'v') { 11573 RC = &AMDGPU::VGPR_32RegClass; 11574 } else if (Constraint[1] == 's') { 11575 RC = &AMDGPU::SGPR_32RegClass; 11576 } else if (Constraint[1] == 'a') { 11577 RC = &AMDGPU::AGPR_32RegClass; 11578 } 11579 11580 if (RC) { 11581 uint32_t Idx; 11582 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11583 if (!Failed && Idx < RC->getNumRegs()) 11584 return std::make_pair(RC->getRegister(Idx), RC); 11585 } 11586 } 11587 11588 // FIXME: Returns VS_32 for physical SGPR constraints 11589 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11590 } 11591 11592 static bool isImmConstraint(StringRef Constraint) { 11593 if (Constraint.size() == 1) { 11594 switch (Constraint[0]) { 11595 default: break; 11596 case 'I': 11597 case 'J': 11598 case 'A': 11599 case 'B': 11600 case 'C': 11601 return true; 11602 } 11603 } else if (Constraint == "DA" || 11604 Constraint == "DB") { 11605 return true; 11606 } 11607 return false; 11608 } 11609 11610 SITargetLowering::ConstraintType 11611 SITargetLowering::getConstraintType(StringRef Constraint) const { 11612 if (Constraint.size() == 1) { 11613 switch (Constraint[0]) { 11614 default: break; 11615 case 's': 11616 case 'v': 11617 case 'a': 11618 return C_RegisterClass; 11619 } 11620 } 11621 if (isImmConstraint(Constraint)) { 11622 return C_Other; 11623 } 11624 return TargetLowering::getConstraintType(Constraint); 11625 } 11626 11627 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11628 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11629 Val = Val & maskTrailingOnes<uint64_t>(Size); 11630 } 11631 return Val; 11632 } 11633 11634 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11635 std::string &Constraint, 11636 std::vector<SDValue> &Ops, 11637 SelectionDAG &DAG) const { 11638 if (isImmConstraint(Constraint)) { 11639 uint64_t Val; 11640 if (getAsmOperandConstVal(Op, Val) && 11641 checkAsmConstraintVal(Op, Constraint, Val)) { 11642 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11643 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11644 } 11645 } else { 11646 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11647 } 11648 } 11649 11650 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11651 unsigned Size = Op.getScalarValueSizeInBits(); 11652 if (Size > 64) 11653 return false; 11654 11655 if (Size == 16 && !Subtarget->has16BitInsts()) 11656 return false; 11657 11658 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11659 Val = C->getSExtValue(); 11660 return true; 11661 } 11662 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11663 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11664 return true; 11665 } 11666 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11667 if (Size != 16 || Op.getNumOperands() != 2) 11668 return false; 11669 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11670 return false; 11671 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11672 Val = C->getSExtValue(); 11673 return true; 11674 } 11675 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11676 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11677 return true; 11678 } 11679 } 11680 11681 return false; 11682 } 11683 11684 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11685 const std::string &Constraint, 11686 uint64_t Val) const { 11687 if (Constraint.size() == 1) { 11688 switch (Constraint[0]) { 11689 case 'I': 11690 return AMDGPU::isInlinableIntLiteral(Val); 11691 case 'J': 11692 return isInt<16>(Val); 11693 case 'A': 11694 return checkAsmConstraintValA(Op, Val); 11695 case 'B': 11696 return isInt<32>(Val); 11697 case 'C': 11698 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11699 AMDGPU::isInlinableIntLiteral(Val); 11700 default: 11701 break; 11702 } 11703 } else if (Constraint.size() == 2) { 11704 if (Constraint == "DA") { 11705 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11706 int64_t LoBits = static_cast<int32_t>(Val); 11707 return checkAsmConstraintValA(Op, HiBits, 32) && 11708 checkAsmConstraintValA(Op, LoBits, 32); 11709 } 11710 if (Constraint == "DB") { 11711 return true; 11712 } 11713 } 11714 llvm_unreachable("Invalid asm constraint"); 11715 } 11716 11717 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11718 uint64_t Val, 11719 unsigned MaxSize) const { 11720 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11721 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11722 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11723 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11724 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11725 return true; 11726 } 11727 return false; 11728 } 11729 11730 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11731 switch (UnalignedClassID) { 11732 case AMDGPU::VReg_64RegClassID: 11733 return AMDGPU::VReg_64_Align2RegClassID; 11734 case AMDGPU::VReg_96RegClassID: 11735 return AMDGPU::VReg_96_Align2RegClassID; 11736 case AMDGPU::VReg_128RegClassID: 11737 return AMDGPU::VReg_128_Align2RegClassID; 11738 case AMDGPU::VReg_160RegClassID: 11739 return AMDGPU::VReg_160_Align2RegClassID; 11740 case AMDGPU::VReg_192RegClassID: 11741 return AMDGPU::VReg_192_Align2RegClassID; 11742 case AMDGPU::VReg_224RegClassID: 11743 return AMDGPU::VReg_224_Align2RegClassID; 11744 case AMDGPU::VReg_256RegClassID: 11745 return AMDGPU::VReg_256_Align2RegClassID; 11746 case AMDGPU::VReg_512RegClassID: 11747 return AMDGPU::VReg_512_Align2RegClassID; 11748 case AMDGPU::VReg_1024RegClassID: 11749 return AMDGPU::VReg_1024_Align2RegClassID; 11750 case AMDGPU::AReg_64RegClassID: 11751 return AMDGPU::AReg_64_Align2RegClassID; 11752 case AMDGPU::AReg_96RegClassID: 11753 return AMDGPU::AReg_96_Align2RegClassID; 11754 case AMDGPU::AReg_128RegClassID: 11755 return AMDGPU::AReg_128_Align2RegClassID; 11756 case AMDGPU::AReg_160RegClassID: 11757 return AMDGPU::AReg_160_Align2RegClassID; 11758 case AMDGPU::AReg_192RegClassID: 11759 return AMDGPU::AReg_192_Align2RegClassID; 11760 case AMDGPU::AReg_256RegClassID: 11761 return AMDGPU::AReg_256_Align2RegClassID; 11762 case AMDGPU::AReg_512RegClassID: 11763 return AMDGPU::AReg_512_Align2RegClassID; 11764 case AMDGPU::AReg_1024RegClassID: 11765 return AMDGPU::AReg_1024_Align2RegClassID; 11766 default: 11767 return -1; 11768 } 11769 } 11770 11771 // Figure out which registers should be reserved for stack access. Only after 11772 // the function is legalized do we know all of the non-spill stack objects or if 11773 // calls are present. 11774 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11775 MachineRegisterInfo &MRI = MF.getRegInfo(); 11776 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11777 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11778 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11779 const SIInstrInfo *TII = ST.getInstrInfo(); 11780 11781 if (Info->isEntryFunction()) { 11782 // Callable functions have fixed registers used for stack access. 11783 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11784 } 11785 11786 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11787 Info->getStackPtrOffsetReg())); 11788 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11789 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11790 11791 // We need to worry about replacing the default register with itself in case 11792 // of MIR testcases missing the MFI. 11793 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11794 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11795 11796 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11797 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11798 11799 Info->limitOccupancy(MF); 11800 11801 if (ST.isWave32() && !MF.empty()) { 11802 for (auto &MBB : MF) { 11803 for (auto &MI : MBB) { 11804 TII->fixImplicitOperands(MI); 11805 } 11806 } 11807 } 11808 11809 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11810 // classes if required. Ideally the register class constraints would differ 11811 // per-subtarget, but there's no easy way to achieve that right now. This is 11812 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11813 // from using them as the register class for legal types. 11814 if (ST.needsAlignedVGPRs()) { 11815 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11816 const Register Reg = Register::index2VirtReg(I); 11817 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11818 if (!RC) 11819 continue; 11820 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11821 if (NewClassID != -1) 11822 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11823 } 11824 } 11825 11826 TargetLoweringBase::finalizeLowering(MF); 11827 11828 // Allocate a VGPR for future SGPR Spill if 11829 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11830 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11831 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11832 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11833 Info->reserveVGPRforSGPRSpills(MF); 11834 } 11835 11836 void SITargetLowering::computeKnownBitsForFrameIndex( 11837 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11838 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11839 11840 // Set the high bits to zero based on the maximum allowed scratch size per 11841 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11842 // calculation won't overflow, so assume the sign bit is never set. 11843 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11844 } 11845 11846 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11847 KnownBits &Known, unsigned Dim) { 11848 unsigned MaxValue = 11849 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11850 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11851 } 11852 11853 void SITargetLowering::computeKnownBitsForTargetInstr( 11854 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11855 const MachineRegisterInfo &MRI, unsigned Depth) const { 11856 const MachineInstr *MI = MRI.getVRegDef(R); 11857 switch (MI->getOpcode()) { 11858 case AMDGPU::G_INTRINSIC: { 11859 switch (MI->getIntrinsicID()) { 11860 case Intrinsic::amdgcn_workitem_id_x: 11861 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11862 break; 11863 case Intrinsic::amdgcn_workitem_id_y: 11864 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11865 break; 11866 case Intrinsic::amdgcn_workitem_id_z: 11867 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11868 break; 11869 case Intrinsic::amdgcn_mbcnt_lo: 11870 case Intrinsic::amdgcn_mbcnt_hi: { 11871 // These return at most the wavefront size - 1. 11872 unsigned Size = MRI.getType(R).getSizeInBits(); 11873 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11874 break; 11875 } 11876 case Intrinsic::amdgcn_groupstaticsize: { 11877 // We can report everything over the maximum size as 0. We can't report 11878 // based on the actual size because we don't know if it's accurate or not 11879 // at any given point. 11880 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11881 break; 11882 } 11883 } 11884 break; 11885 } 11886 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11887 Known.Zero.setHighBits(24); 11888 break; 11889 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11890 Known.Zero.setHighBits(16); 11891 break; 11892 } 11893 } 11894 11895 Align SITargetLowering::computeKnownAlignForTargetInstr( 11896 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11897 unsigned Depth) const { 11898 const MachineInstr *MI = MRI.getVRegDef(R); 11899 switch (MI->getOpcode()) { 11900 case AMDGPU::G_INTRINSIC: 11901 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11902 // FIXME: Can this move to generic code? What about the case where the call 11903 // site specifies a lower alignment? 11904 Intrinsic::ID IID = MI->getIntrinsicID(); 11905 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11906 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11907 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11908 return *RetAlign; 11909 return Align(1); 11910 } 11911 default: 11912 return Align(1); 11913 } 11914 } 11915 11916 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11917 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11918 const Align CacheLineAlign = Align(64); 11919 11920 // Pre-GFX10 target did not benefit from loop alignment 11921 if (!ML || DisableLoopAlignment || 11922 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11923 getSubtarget()->hasInstFwdPrefetchBug()) 11924 return PrefAlign; 11925 11926 // On GFX10 I$ is 4 x 64 bytes cache lines. 11927 // By default prefetcher keeps one cache line behind and reads two ahead. 11928 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11929 // behind and one ahead. 11930 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11931 // If loop fits 64 bytes it always spans no more than two cache lines and 11932 // does not need an alignment. 11933 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11934 // Else if loop is less or equal 192 bytes we need two lines behind. 11935 11936 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11937 const MachineBasicBlock *Header = ML->getHeader(); 11938 if (Header->getAlignment() != PrefAlign) 11939 return Header->getAlignment(); // Already processed. 11940 11941 unsigned LoopSize = 0; 11942 for (const MachineBasicBlock *MBB : ML->blocks()) { 11943 // If inner loop block is aligned assume in average half of the alignment 11944 // size to be added as nops. 11945 if (MBB != Header) 11946 LoopSize += MBB->getAlignment().value() / 2; 11947 11948 for (const MachineInstr &MI : *MBB) { 11949 LoopSize += TII->getInstSizeInBytes(MI); 11950 if (LoopSize > 192) 11951 return PrefAlign; 11952 } 11953 } 11954 11955 if (LoopSize <= 64) 11956 return PrefAlign; 11957 11958 if (LoopSize <= 128) 11959 return CacheLineAlign; 11960 11961 // If any of parent loops is surrounded by prefetch instructions do not 11962 // insert new for inner loop, which would reset parent's settings. 11963 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11964 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11965 auto I = Exit->getFirstNonDebugInstr(); 11966 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11967 return CacheLineAlign; 11968 } 11969 } 11970 11971 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11972 MachineBasicBlock *Exit = ML->getExitBlock(); 11973 11974 if (Pre && Exit) { 11975 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11976 TII->get(AMDGPU::S_INST_PREFETCH)) 11977 .addImm(1); // prefetch 2 lines behind PC 11978 11979 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11980 TII->get(AMDGPU::S_INST_PREFETCH)) 11981 .addImm(2); // prefetch 1 line behind PC 11982 } 11983 11984 return CacheLineAlign; 11985 } 11986 11987 LLVM_ATTRIBUTE_UNUSED 11988 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11989 assert(N->getOpcode() == ISD::CopyFromReg); 11990 do { 11991 // Follow the chain until we find an INLINEASM node. 11992 N = N->getOperand(0).getNode(); 11993 if (N->getOpcode() == ISD::INLINEASM || 11994 N->getOpcode() == ISD::INLINEASM_BR) 11995 return true; 11996 } while (N->getOpcode() == ISD::CopyFromReg); 11997 return false; 11998 } 11999 12000 bool SITargetLowering::isSDNodeSourceOfDivergence( 12001 const SDNode *N, FunctionLoweringInfo *FLI, 12002 LegacyDivergenceAnalysis *KDA) const { 12003 switch (N->getOpcode()) { 12004 case ISD::CopyFromReg: { 12005 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12006 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12007 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12008 Register Reg = R->getReg(); 12009 12010 // FIXME: Why does this need to consider isLiveIn? 12011 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12012 return !TRI->isSGPRReg(MRI, Reg); 12013 12014 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12015 return KDA->isDivergent(V); 12016 12017 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12018 return !TRI->isSGPRReg(MRI, Reg); 12019 } 12020 case ISD::LOAD: { 12021 const LoadSDNode *L = cast<LoadSDNode>(N); 12022 unsigned AS = L->getAddressSpace(); 12023 // A flat load may access private memory. 12024 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12025 } 12026 case ISD::CALLSEQ_END: 12027 return true; 12028 case ISD::INTRINSIC_WO_CHAIN: 12029 return AMDGPU::isIntrinsicSourceOfDivergence( 12030 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12031 case ISD::INTRINSIC_W_CHAIN: 12032 return AMDGPU::isIntrinsicSourceOfDivergence( 12033 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12034 case AMDGPUISD::ATOMIC_CMP_SWAP: 12035 case AMDGPUISD::ATOMIC_INC: 12036 case AMDGPUISD::ATOMIC_DEC: 12037 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12038 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12039 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12040 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12041 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12042 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12043 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12044 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12045 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12046 case AMDGPUISD::BUFFER_ATOMIC_AND: 12047 case AMDGPUISD::BUFFER_ATOMIC_OR: 12048 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12049 case AMDGPUISD::BUFFER_ATOMIC_INC: 12050 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12051 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12052 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12053 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12054 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12055 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12056 // Target-specific read-modify-write atomics are sources of divergence. 12057 return true; 12058 default: 12059 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12060 // Generic read-modify-write atomics are sources of divergence. 12061 return A->readMem() && A->writeMem(); 12062 } 12063 return false; 12064 } 12065 } 12066 12067 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12068 EVT VT) const { 12069 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12070 case MVT::f32: 12071 return hasFP32Denormals(DAG.getMachineFunction()); 12072 case MVT::f64: 12073 case MVT::f16: 12074 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12075 default: 12076 return false; 12077 } 12078 } 12079 12080 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12081 MachineFunction &MF) const { 12082 switch (Ty.getScalarSizeInBits()) { 12083 case 32: 12084 return hasFP32Denormals(MF); 12085 case 64: 12086 case 16: 12087 return hasFP64FP16Denormals(MF); 12088 default: 12089 return false; 12090 } 12091 } 12092 12093 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12094 const SelectionDAG &DAG, 12095 bool SNaN, 12096 unsigned Depth) const { 12097 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12098 const MachineFunction &MF = DAG.getMachineFunction(); 12099 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12100 12101 if (Info->getMode().DX10Clamp) 12102 return true; // Clamped to 0. 12103 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12104 } 12105 12106 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12107 SNaN, Depth); 12108 } 12109 12110 // Global FP atomic instructions have a hardcoded FP mode and do not support 12111 // FP32 denormals, and only support v2f16 denormals. 12112 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12113 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12114 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12115 if (&Flt == &APFloat::IEEEsingle()) 12116 return DenormMode == DenormalMode::getPreserveSign(); 12117 return DenormMode == DenormalMode::getIEEE(); 12118 } 12119 12120 TargetLowering::AtomicExpansionKind 12121 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12122 switch (RMW->getOperation()) { 12123 case AtomicRMWInst::FAdd: { 12124 Type *Ty = RMW->getType(); 12125 12126 // We don't have a way to support 16-bit atomics now, so just leave them 12127 // as-is. 12128 if (Ty->isHalfTy()) 12129 return AtomicExpansionKind::None; 12130 12131 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12132 return AtomicExpansionKind::CmpXChg; 12133 12134 unsigned AS = RMW->getPointerAddressSpace(); 12135 12136 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12137 Subtarget->hasAtomicFaddInsts()) { 12138 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12139 // floating point atomic instructions. May generate more efficient code, 12140 // but may not respect rounding and denormal modes, and may give incorrect 12141 // results for certain memory destinations. 12142 if (RMW->getFunction() 12143 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12144 .getValueAsString() != "true") 12145 return AtomicExpansionKind::CmpXChg; 12146 12147 if (Subtarget->hasGFX90AInsts()) { 12148 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12149 return AtomicExpansionKind::CmpXChg; 12150 12151 auto SSID = RMW->getSyncScopeID(); 12152 if (SSID == SyncScope::System || 12153 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12154 return AtomicExpansionKind::CmpXChg; 12155 12156 return AtomicExpansionKind::None; 12157 } 12158 12159 if (AS == AMDGPUAS::FLAT_ADDRESS) 12160 return AtomicExpansionKind::CmpXChg; 12161 12162 return RMW->use_empty() ? AtomicExpansionKind::None 12163 : AtomicExpansionKind::CmpXChg; 12164 } 12165 12166 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12167 // to round-to-nearest-even. 12168 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12169 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 12170 if (!Ty->isDoubleTy()) 12171 return AtomicExpansionKind::None; 12172 12173 return (fpModeMatchesGlobalFPAtomicMode(RMW) || 12174 RMW->getFunction() 12175 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12176 .getValueAsString() == "true") 12177 ? AtomicExpansionKind::None 12178 : AtomicExpansionKind::CmpXChg; 12179 } 12180 12181 return AtomicExpansionKind::CmpXChg; 12182 } 12183 default: 12184 break; 12185 } 12186 12187 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12188 } 12189 12190 const TargetRegisterClass * 12191 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12192 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12193 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12194 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12195 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12196 : &AMDGPU::SReg_32RegClass; 12197 if (!TRI->isSGPRClass(RC) && !isDivergent) 12198 return TRI->getEquivalentSGPRClass(RC); 12199 else if (TRI->isSGPRClass(RC) && isDivergent) 12200 return TRI->getEquivalentVGPRClass(RC); 12201 12202 return RC; 12203 } 12204 12205 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12206 // uniform values (as produced by the mask results of control flow intrinsics) 12207 // used outside of divergent blocks. The phi users need to also be treated as 12208 // always uniform. 12209 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12210 unsigned WaveSize) { 12211 // FIXME: We asssume we never cast the mask results of a control flow 12212 // intrinsic. 12213 // Early exit if the type won't be consistent as a compile time hack. 12214 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12215 if (!IT || IT->getBitWidth() != WaveSize) 12216 return false; 12217 12218 if (!isa<Instruction>(V)) 12219 return false; 12220 if (!Visited.insert(V).second) 12221 return false; 12222 bool Result = false; 12223 for (auto U : V->users()) { 12224 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12225 if (V == U->getOperand(1)) { 12226 switch (Intrinsic->getIntrinsicID()) { 12227 default: 12228 Result = false; 12229 break; 12230 case Intrinsic::amdgcn_if_break: 12231 case Intrinsic::amdgcn_if: 12232 case Intrinsic::amdgcn_else: 12233 Result = true; 12234 break; 12235 } 12236 } 12237 if (V == U->getOperand(0)) { 12238 switch (Intrinsic->getIntrinsicID()) { 12239 default: 12240 Result = false; 12241 break; 12242 case Intrinsic::amdgcn_end_cf: 12243 case Intrinsic::amdgcn_loop: 12244 Result = true; 12245 break; 12246 } 12247 } 12248 } else { 12249 Result = hasCFUser(U, Visited, WaveSize); 12250 } 12251 if (Result) 12252 break; 12253 } 12254 return Result; 12255 } 12256 12257 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12258 const Value *V) const { 12259 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12260 if (CI->isInlineAsm()) { 12261 // FIXME: This cannot give a correct answer. This should only trigger in 12262 // the case where inline asm returns mixed SGPR and VGPR results, used 12263 // outside the defining block. We don't have a specific result to 12264 // consider, so this assumes if any value is SGPR, the overall register 12265 // also needs to be SGPR. 12266 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12267 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12268 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12269 for (auto &TC : TargetConstraints) { 12270 if (TC.Type == InlineAsm::isOutput) { 12271 ComputeConstraintToUse(TC, SDValue()); 12272 unsigned AssignedReg; 12273 const TargetRegisterClass *RC; 12274 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12275 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12276 if (RC) { 12277 MachineRegisterInfo &MRI = MF.getRegInfo(); 12278 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12279 return true; 12280 else if (SIRI->isSGPRClass(RC)) 12281 return true; 12282 } 12283 } 12284 } 12285 } 12286 } 12287 SmallPtrSet<const Value *, 16> Visited; 12288 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12289 } 12290 12291 std::pair<InstructionCost, MVT> 12292 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12293 Type *Ty) const { 12294 std::pair<InstructionCost, MVT> Cost = 12295 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12296 auto Size = DL.getTypeSizeInBits(Ty); 12297 // Maximum load or store can handle 8 dwords for scalar and 4 for 12298 // vector ALU. Let's assume anything above 8 dwords is expensive 12299 // even if legal. 12300 if (Size <= 256) 12301 return Cost; 12302 12303 Cost.first = (Size + 255) / 256; 12304 return Cost; 12305 } 12306