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/MachineFunction.h" 27 #include "llvm/CodeGen/MachineLoopInfo.h" 28 #include "llvm/IR/DiagnosticInfo.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/IntrinsicsAMDGPU.h" 31 #include "llvm/IR/IntrinsicsR600.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/KnownBits.h" 34 35 using namespace llvm; 36 37 #define DEBUG_TYPE "si-lower" 38 39 STATISTIC(NumTailCalls, "Number of tail calls"); 40 41 static cl::opt<bool> DisableLoopAlignment( 42 "amdgpu-disable-loop-alignment", 43 cl::desc("Do not align and prefetch loops"), 44 cl::init(false)); 45 46 static cl::opt<bool> VGPRReserveforSGPRSpill( 47 "amdgpu-reserve-vgpr-for-sgpr-spill", 48 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 49 50 static cl::opt<bool> UseDivergentRegisterIndexing( 51 "amdgpu-use-divergent-register-indexing", 52 cl::Hidden, 53 cl::desc("Use indirect register addressing for divergent indexes"), 54 cl::init(false)); 55 56 static bool hasFP32Denormals(const MachineFunction &MF) { 57 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 58 return Info->getMode().allFP32Denormals(); 59 } 60 61 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 62 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 63 return Info->getMode().allFP64FP16Denormals(); 64 } 65 66 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 67 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 68 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 69 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 70 return AMDGPU::SGPR0 + Reg; 71 } 72 } 73 llvm_unreachable("Cannot allocate sgpr"); 74 } 75 76 SITargetLowering::SITargetLowering(const TargetMachine &TM, 77 const GCNSubtarget &STI) 78 : AMDGPUTargetLowering(TM, STI), 79 Subtarget(&STI) { 80 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 81 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 82 83 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 84 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 85 86 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 87 88 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 89 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 90 91 addRegisterClass(MVT::f64, V64RegClass); 92 addRegisterClass(MVT::v2f32, V64RegClass); 93 94 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 95 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 96 97 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 98 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 99 100 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 101 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 102 103 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 104 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 105 106 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 107 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 108 109 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 110 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 111 112 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 113 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 114 115 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 116 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 117 118 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 119 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 120 121 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 122 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 123 124 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 125 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 126 127 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 128 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 129 130 if (Subtarget->has16BitInsts()) { 131 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 132 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 133 134 // Unless there are also VOP3P operations, not operations are really legal. 135 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 137 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 138 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 139 } 140 141 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 142 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 143 144 computeRegisterProperties(Subtarget->getRegisterInfo()); 145 146 // The boolean content concept here is too inflexible. Compares only ever 147 // really produce a 1-bit result. Any copy/extend from these will turn into a 148 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 149 // it's what most targets use. 150 setBooleanContents(ZeroOrOneBooleanContent); 151 setBooleanVectorContents(ZeroOrOneBooleanContent); 152 153 // We need to custom lower vector stores from local memory 154 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 155 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::i1, Custom); 163 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 164 165 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 166 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 173 setOperationAction(ISD::STORE, MVT::i1, Custom); 174 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 175 176 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 177 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 178 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 179 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 180 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 181 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 182 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 183 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 184 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 185 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 186 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 187 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 188 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 189 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 190 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 191 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 192 193 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 194 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 195 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 196 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 197 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 199 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 200 201 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 202 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 203 204 setOperationAction(ISD::SELECT, MVT::i1, Promote); 205 setOperationAction(ISD::SELECT, MVT::i64, Custom); 206 setOperationAction(ISD::SELECT, MVT::f64, Promote); 207 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 208 209 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 210 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 214 215 setOperationAction(ISD::SETCC, MVT::i1, Promote); 216 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 217 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 218 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 219 220 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 221 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 222 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 223 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 224 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 225 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 226 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 227 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 228 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 229 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 230 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 232 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 233 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 234 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 235 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 236 237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 245 246 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 247 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 248 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 249 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 250 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 251 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 252 253 setOperationAction(ISD::UADDO, MVT::i32, Legal); 254 setOperationAction(ISD::USUBO, MVT::i32, Legal); 255 256 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 257 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 258 259 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 260 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 261 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 262 263 #if 0 264 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 265 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 266 #endif 267 268 // We only support LOAD/STORE and vector manipulation ops for vectors 269 // with > 4 elements. 270 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 271 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 272 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 273 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 274 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 275 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 276 switch (Op) { 277 case ISD::LOAD: 278 case ISD::STORE: 279 case ISD::BUILD_VECTOR: 280 case ISD::BITCAST: 281 case ISD::EXTRACT_VECTOR_ELT: 282 case ISD::INSERT_VECTOR_ELT: 283 case ISD::EXTRACT_SUBVECTOR: 284 case ISD::SCALAR_TO_VECTOR: 285 break; 286 case ISD::INSERT_SUBVECTOR: 287 case ISD::CONCAT_VECTORS: 288 setOperationAction(Op, VT, Custom); 289 break; 290 default: 291 setOperationAction(Op, VT, Expand); 292 break; 293 } 294 } 295 } 296 297 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 298 299 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 300 // is expanded to avoid having two separate loops in case the index is a VGPR. 301 302 // Most operations are naturally 32-bit vector operations. We only support 303 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 304 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 305 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 306 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 307 308 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 309 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 310 311 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 312 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 313 314 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 315 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 316 } 317 318 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 319 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 320 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 321 322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 323 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 324 325 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 326 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 327 328 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 329 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 330 } 331 332 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 333 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 334 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 335 336 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 337 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 338 339 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 340 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 341 342 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 343 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 344 } 345 346 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 347 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 348 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 349 350 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 351 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 352 353 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 354 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 355 356 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 357 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 358 } 359 360 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 361 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 362 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 363 364 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 365 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 366 367 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 368 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 369 370 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 371 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 372 } 373 374 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 378 379 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 380 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 381 382 // Avoid stack access for these. 383 // TODO: Generalize to more vector types. 384 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 385 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 386 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 387 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 388 389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 395 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 398 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 400 401 // Deal with vec3 vector operations when widened to vec4. 402 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 406 407 // Deal with vec5/6/7 vector operations when widened to vec8. 408 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 416 417 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 418 // and output demarshalling 419 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 420 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 421 422 // We can't return success/failure, only the old value, 423 // let LLVM add the comparison 424 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 425 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 426 427 if (Subtarget->hasFlatAddressSpace()) { 428 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 429 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 430 } 431 432 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 433 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 434 435 // FIXME: This should be narrowed to i32, but that only happens if i64 is 436 // illegal. 437 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 438 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 439 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 440 441 // On SI this is s_memtime and s_memrealtime on VI. 442 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 443 setOperationAction(ISD::TRAP, MVT::Other, Custom); 444 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 445 446 if (Subtarget->has16BitInsts()) { 447 setOperationAction(ISD::FPOW, MVT::f16, Promote); 448 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 449 setOperationAction(ISD::FLOG, MVT::f16, Custom); 450 setOperationAction(ISD::FEXP, MVT::f16, Custom); 451 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 452 } 453 454 if (Subtarget->hasMadMacF32Insts()) 455 setOperationAction(ISD::FMAD, MVT::f32, Legal); 456 457 if (!Subtarget->hasBFI()) { 458 // fcopysign can be done in a single instruction with BFI. 459 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 460 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 461 } 462 463 if (!Subtarget->hasBCNT(32)) 464 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 465 466 if (!Subtarget->hasBCNT(64)) 467 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 468 469 if (Subtarget->hasFFBH()) { 470 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 471 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 472 } 473 474 if (Subtarget->hasFFBL()) { 475 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 476 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 477 } 478 479 // We only really have 32-bit BFE instructions (and 16-bit on VI). 480 // 481 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 482 // effort to match them now. We want this to be false for i64 cases when the 483 // extraction isn't restricted to the upper or lower half. Ideally we would 484 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 485 // span the midpoint are probably relatively rare, so don't worry about them 486 // for now. 487 if (Subtarget->hasBFE()) 488 setHasExtractBitsInsn(true); 489 490 // Clamp modifier on add/sub 491 if (Subtarget->hasIntClamp()) { 492 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 493 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 494 } 495 496 if (Subtarget->hasAddNoCarry()) { 497 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 498 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 500 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 501 } 502 503 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 504 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 506 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 507 508 509 // These are really only legal for ieee_mode functions. We should be avoiding 510 // them for functions that don't have ieee_mode enabled, so just say they are 511 // legal. 512 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 513 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 515 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 516 517 518 if (Subtarget->haveRoundOpsF64()) { 519 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 520 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 521 setOperationAction(ISD::FRINT, MVT::f64, Legal); 522 } else { 523 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 524 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 525 setOperationAction(ISD::FRINT, MVT::f64, Custom); 526 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 527 } 528 529 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 530 531 setOperationAction(ISD::FSIN, MVT::f32, Custom); 532 setOperationAction(ISD::FCOS, MVT::f32, Custom); 533 setOperationAction(ISD::FDIV, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f64, Custom); 535 536 if (Subtarget->has16BitInsts()) { 537 setOperationAction(ISD::Constant, MVT::i16, Legal); 538 539 setOperationAction(ISD::SMIN, MVT::i16, Legal); 540 setOperationAction(ISD::SMAX, MVT::i16, Legal); 541 542 setOperationAction(ISD::UMIN, MVT::i16, Legal); 543 setOperationAction(ISD::UMAX, MVT::i16, Legal); 544 545 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 546 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 547 548 setOperationAction(ISD::ROTR, MVT::i16, Expand); 549 setOperationAction(ISD::ROTL, MVT::i16, Expand); 550 551 setOperationAction(ISD::SDIV, MVT::i16, Promote); 552 setOperationAction(ISD::UDIV, MVT::i16, Promote); 553 setOperationAction(ISD::SREM, MVT::i16, Promote); 554 setOperationAction(ISD::UREM, MVT::i16, Promote); 555 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 556 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 557 558 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 559 560 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 561 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 562 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 564 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 565 566 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 567 568 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 569 570 setOperationAction(ISD::LOAD, MVT::i16, Custom); 571 572 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 573 574 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 575 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 576 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 577 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 578 579 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 580 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 581 582 // F16 - Constant Actions. 583 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 584 585 // F16 - Load/Store Actions. 586 setOperationAction(ISD::LOAD, MVT::f16, Promote); 587 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 588 setOperationAction(ISD::STORE, MVT::f16, Promote); 589 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 590 591 // F16 - VOP1 Actions. 592 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 593 setOperationAction(ISD::FCOS, MVT::f16, Custom); 594 setOperationAction(ISD::FSIN, MVT::f16, Custom); 595 596 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 597 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 598 599 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 600 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 601 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 602 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::FROUND, MVT::f16, Custom); 604 605 // F16 - VOP2 Actions. 606 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 607 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 608 609 setOperationAction(ISD::FDIV, MVT::f16, Custom); 610 611 // F16 - VOP3 Actions. 612 setOperationAction(ISD::FMA, MVT::f16, Legal); 613 if (STI.hasMadF16()) 614 setOperationAction(ISD::FMAD, MVT::f16, Legal); 615 616 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 617 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 618 switch (Op) { 619 case ISD::LOAD: 620 case ISD::STORE: 621 case ISD::BUILD_VECTOR: 622 case ISD::BITCAST: 623 case ISD::EXTRACT_VECTOR_ELT: 624 case ISD::INSERT_VECTOR_ELT: 625 case ISD::INSERT_SUBVECTOR: 626 case ISD::EXTRACT_SUBVECTOR: 627 case ISD::SCALAR_TO_VECTOR: 628 break; 629 case ISD::CONCAT_VECTORS: 630 setOperationAction(Op, VT, Custom); 631 break; 632 default: 633 setOperationAction(Op, VT, Expand); 634 break; 635 } 636 } 637 } 638 639 // v_perm_b32 can handle either of these. 640 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 641 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 643 644 // XXX - Do these do anything? Vector constants turn into build_vector. 645 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 646 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 647 648 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 649 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 650 651 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 652 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 653 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 654 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 655 656 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 659 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 660 661 setOperationAction(ISD::AND, MVT::v2i16, Promote); 662 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 663 setOperationAction(ISD::OR, MVT::v2i16, Promote); 664 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 665 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 666 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 667 668 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 669 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 670 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 671 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 672 673 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 674 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 675 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 676 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 677 678 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 679 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 682 683 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 684 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 686 687 if (!Subtarget->hasVOP3PInsts()) { 688 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 690 } 691 692 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 693 // This isn't really legal, but this avoids the legalizer unrolling it (and 694 // allows matching fneg (fabs x) patterns) 695 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 696 697 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 698 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 700 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 701 702 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 703 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 704 705 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 706 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 707 } 708 709 if (Subtarget->hasVOP3PInsts()) { 710 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 711 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 712 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 713 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 716 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 717 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 719 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 720 721 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 722 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 725 726 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 727 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 729 730 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 731 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 732 733 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 734 735 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 737 738 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 740 741 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 742 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 744 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 745 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 746 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 747 748 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 749 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 750 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 752 753 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 754 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 757 758 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 759 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 761 762 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 763 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 764 765 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 766 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 768 769 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 770 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 772 773 if (Subtarget->hasPackedFP32Ops()) { 774 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 775 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 776 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 777 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 778 779 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 780 setOperationAction(ISD::FADD, VT, Custom); 781 setOperationAction(ISD::FMUL, VT, Custom); 782 setOperationAction(ISD::FMA, VT, Custom); 783 } 784 } 785 } 786 787 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 788 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 789 790 if (Subtarget->has16BitInsts()) { 791 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 792 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 793 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 794 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 795 } else { 796 // Legalization hack. 797 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 798 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 799 800 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 801 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 802 } 803 804 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 805 setOperationAction(ISD::SELECT, VT, Custom); 806 } 807 808 setOperationAction(ISD::SMULO, MVT::i64, Custom); 809 setOperationAction(ISD::UMULO, MVT::i64, Custom); 810 811 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 812 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 813 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 814 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 815 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 816 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 817 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 818 819 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 820 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 821 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 822 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 823 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 824 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 825 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 826 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 827 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 828 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 829 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 830 831 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 832 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 833 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 834 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 835 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 836 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 837 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 838 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 839 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 840 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 841 842 setTargetDAGCombine(ISD::ADD); 843 setTargetDAGCombine(ISD::ADDCARRY); 844 setTargetDAGCombine(ISD::SUB); 845 setTargetDAGCombine(ISD::SUBCARRY); 846 setTargetDAGCombine(ISD::FADD); 847 setTargetDAGCombine(ISD::FSUB); 848 setTargetDAGCombine(ISD::FMINNUM); 849 setTargetDAGCombine(ISD::FMAXNUM); 850 setTargetDAGCombine(ISD::FMINNUM_IEEE); 851 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 852 setTargetDAGCombine(ISD::FMA); 853 setTargetDAGCombine(ISD::SMIN); 854 setTargetDAGCombine(ISD::SMAX); 855 setTargetDAGCombine(ISD::UMIN); 856 setTargetDAGCombine(ISD::UMAX); 857 setTargetDAGCombine(ISD::SETCC); 858 setTargetDAGCombine(ISD::AND); 859 setTargetDAGCombine(ISD::OR); 860 setTargetDAGCombine(ISD::XOR); 861 setTargetDAGCombine(ISD::SINT_TO_FP); 862 setTargetDAGCombine(ISD::UINT_TO_FP); 863 setTargetDAGCombine(ISD::FCANONICALIZE); 864 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 865 setTargetDAGCombine(ISD::ZERO_EXTEND); 866 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 867 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 868 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 869 870 // All memory operations. Some folding on the pointer operand is done to help 871 // matching the constant offsets in the addressing modes. 872 setTargetDAGCombine(ISD::LOAD); 873 setTargetDAGCombine(ISD::STORE); 874 setTargetDAGCombine(ISD::ATOMIC_LOAD); 875 setTargetDAGCombine(ISD::ATOMIC_STORE); 876 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 877 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 878 setTargetDAGCombine(ISD::ATOMIC_SWAP); 879 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 880 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 881 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 882 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 883 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 884 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 885 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 886 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 887 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 888 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 889 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 890 setTargetDAGCombine(ISD::INTRINSIC_VOID); 891 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 892 893 // FIXME: In other contexts we pretend this is a per-function property. 894 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 895 896 setSchedulingPreference(Sched::RegPressure); 897 } 898 899 const GCNSubtarget *SITargetLowering::getSubtarget() const { 900 return Subtarget; 901 } 902 903 //===----------------------------------------------------------------------===// 904 // TargetLowering queries 905 //===----------------------------------------------------------------------===// 906 907 // v_mad_mix* support a conversion from f16 to f32. 908 // 909 // There is only one special case when denormals are enabled we don't currently, 910 // where this is OK to use. 911 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 912 EVT DestVT, EVT SrcVT) const { 913 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 914 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 915 DestVT.getScalarType() == MVT::f32 && 916 SrcVT.getScalarType() == MVT::f16 && 917 // TODO: This probably only requires no input flushing? 918 !hasFP32Denormals(DAG.getMachineFunction()); 919 } 920 921 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 922 // SI has some legal vector types, but no legal vector operations. Say no 923 // shuffles are legal in order to prefer scalarizing some vector operations. 924 return false; 925 } 926 927 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 928 CallingConv::ID CC, 929 EVT VT) const { 930 if (CC == CallingConv::AMDGPU_KERNEL) 931 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 932 933 if (VT.isVector()) { 934 EVT ScalarVT = VT.getScalarType(); 935 unsigned Size = ScalarVT.getSizeInBits(); 936 if (Size == 16) { 937 if (Subtarget->has16BitInsts()) 938 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 939 return VT.isInteger() ? MVT::i32 : MVT::f32; 940 } 941 942 if (Size < 16) 943 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 944 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 945 } 946 947 if (VT.getSizeInBits() > 32) 948 return MVT::i32; 949 950 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 951 } 952 953 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 954 CallingConv::ID CC, 955 EVT VT) const { 956 if (CC == CallingConv::AMDGPU_KERNEL) 957 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 958 959 if (VT.isVector()) { 960 unsigned NumElts = VT.getVectorNumElements(); 961 EVT ScalarVT = VT.getScalarType(); 962 unsigned Size = ScalarVT.getSizeInBits(); 963 964 // FIXME: Should probably promote 8-bit vectors to i16. 965 if (Size == 16 && Subtarget->has16BitInsts()) 966 return (NumElts + 1) / 2; 967 968 if (Size <= 32) 969 return NumElts; 970 971 if (Size > 32) 972 return NumElts * ((Size + 31) / 32); 973 } else if (VT.getSizeInBits() > 32) 974 return (VT.getSizeInBits() + 31) / 32; 975 976 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 977 } 978 979 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 980 LLVMContext &Context, CallingConv::ID CC, 981 EVT VT, EVT &IntermediateVT, 982 unsigned &NumIntermediates, MVT &RegisterVT) const { 983 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 984 unsigned NumElts = VT.getVectorNumElements(); 985 EVT ScalarVT = VT.getScalarType(); 986 unsigned Size = ScalarVT.getSizeInBits(); 987 // FIXME: We should fix the ABI to be the same on targets without 16-bit 988 // support, but unless we can properly handle 3-vectors, it will be still be 989 // inconsistent. 990 if (Size == 16 && Subtarget->has16BitInsts()) { 991 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 992 IntermediateVT = RegisterVT; 993 NumIntermediates = (NumElts + 1) / 2; 994 return NumIntermediates; 995 } 996 997 if (Size == 32) { 998 RegisterVT = ScalarVT.getSimpleVT(); 999 IntermediateVT = RegisterVT; 1000 NumIntermediates = NumElts; 1001 return NumIntermediates; 1002 } 1003 1004 if (Size < 16 && Subtarget->has16BitInsts()) { 1005 // FIXME: Should probably form v2i16 pieces 1006 RegisterVT = MVT::i16; 1007 IntermediateVT = ScalarVT; 1008 NumIntermediates = NumElts; 1009 return NumIntermediates; 1010 } 1011 1012 1013 if (Size != 16 && Size <= 32) { 1014 RegisterVT = MVT::i32; 1015 IntermediateVT = ScalarVT; 1016 NumIntermediates = NumElts; 1017 return NumIntermediates; 1018 } 1019 1020 if (Size > 32) { 1021 RegisterVT = MVT::i32; 1022 IntermediateVT = RegisterVT; 1023 NumIntermediates = NumElts * ((Size + 31) / 32); 1024 return NumIntermediates; 1025 } 1026 } 1027 1028 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1029 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1030 } 1031 1032 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1033 assert(DMaskLanes != 0); 1034 1035 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1036 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1037 return EVT::getVectorVT(Ty->getContext(), 1038 EVT::getEVT(VT->getElementType()), 1039 NumElts); 1040 } 1041 1042 return EVT::getEVT(Ty); 1043 } 1044 1045 // Peek through TFE struct returns to only use the data size. 1046 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1047 auto *ST = dyn_cast<StructType>(Ty); 1048 if (!ST) 1049 return memVTFromImageData(Ty, DMaskLanes); 1050 1051 // Some intrinsics return an aggregate type - special case to work out the 1052 // correct memVT. 1053 // 1054 // Only limited forms of aggregate type currently expected. 1055 if (ST->getNumContainedTypes() != 2 || 1056 !ST->getContainedType(1)->isIntegerTy(32)) 1057 return EVT(); 1058 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1059 } 1060 1061 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1062 const CallInst &CI, 1063 MachineFunction &MF, 1064 unsigned IntrID) const { 1065 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1066 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1067 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1068 (Intrinsic::ID)IntrID); 1069 if (Attr.hasFnAttr(Attribute::ReadNone)) 1070 return false; 1071 1072 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1073 1074 if (RsrcIntr->IsImage) { 1075 Info.ptrVal = 1076 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1077 Info.align.reset(); 1078 } else { 1079 Info.ptrVal = 1080 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1081 } 1082 1083 Info.flags = MachineMemOperand::MODereferenceable; 1084 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1085 unsigned DMaskLanes = 4; 1086 1087 if (RsrcIntr->IsImage) { 1088 const AMDGPU::ImageDimIntrinsicInfo *Intr 1089 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1090 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1091 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1092 1093 if (!BaseOpcode->Gather4) { 1094 // If this isn't a gather, we may have excess loaded elements in the 1095 // IR type. Check the dmask for the real number of elements loaded. 1096 unsigned DMask 1097 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1098 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1099 } 1100 1101 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1102 } else 1103 Info.memVT = EVT::getEVT(CI.getType()); 1104 1105 // FIXME: What does alignment mean for an image? 1106 Info.opc = ISD::INTRINSIC_W_CHAIN; 1107 Info.flags |= MachineMemOperand::MOLoad; 1108 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1109 Info.opc = ISD::INTRINSIC_VOID; 1110 1111 Type *DataTy = CI.getArgOperand(0)->getType(); 1112 if (RsrcIntr->IsImage) { 1113 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1114 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1115 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1116 } else 1117 Info.memVT = EVT::getEVT(DataTy); 1118 1119 Info.flags |= MachineMemOperand::MOStore; 1120 } else { 1121 // Atomic 1122 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1123 ISD::INTRINSIC_W_CHAIN; 1124 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1125 Info.flags = MachineMemOperand::MOLoad | 1126 MachineMemOperand::MOStore | 1127 MachineMemOperand::MODereferenceable; 1128 1129 // XXX - Should this be volatile without known ordering? 1130 Info.flags |= MachineMemOperand::MOVolatile; 1131 } 1132 return true; 1133 } 1134 1135 switch (IntrID) { 1136 case Intrinsic::amdgcn_atomic_inc: 1137 case Intrinsic::amdgcn_atomic_dec: 1138 case Intrinsic::amdgcn_ds_ordered_add: 1139 case Intrinsic::amdgcn_ds_ordered_swap: 1140 case Intrinsic::amdgcn_ds_fadd: 1141 case Intrinsic::amdgcn_ds_fmin: 1142 case Intrinsic::amdgcn_ds_fmax: { 1143 Info.opc = ISD::INTRINSIC_W_CHAIN; 1144 Info.memVT = MVT::getVT(CI.getType()); 1145 Info.ptrVal = CI.getOperand(0); 1146 Info.align.reset(); 1147 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1148 1149 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1150 if (!Vol->isZero()) 1151 Info.flags |= MachineMemOperand::MOVolatile; 1152 1153 return true; 1154 } 1155 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1156 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1157 1158 Info.opc = ISD::INTRINSIC_W_CHAIN; 1159 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1160 Info.ptrVal = 1161 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1162 Info.align.reset(); 1163 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1164 1165 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1166 if (!Vol || !Vol->isZero()) 1167 Info.flags |= MachineMemOperand::MOVolatile; 1168 1169 return true; 1170 } 1171 case Intrinsic::amdgcn_ds_append: 1172 case Intrinsic::amdgcn_ds_consume: { 1173 Info.opc = ISD::INTRINSIC_W_CHAIN; 1174 Info.memVT = MVT::getVT(CI.getType()); 1175 Info.ptrVal = CI.getOperand(0); 1176 Info.align.reset(); 1177 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1178 1179 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1180 if (!Vol->isZero()) 1181 Info.flags |= MachineMemOperand::MOVolatile; 1182 1183 return true; 1184 } 1185 case Intrinsic::amdgcn_global_atomic_csub: { 1186 Info.opc = ISD::INTRINSIC_W_CHAIN; 1187 Info.memVT = MVT::getVT(CI.getType()); 1188 Info.ptrVal = CI.getOperand(0); 1189 Info.align.reset(); 1190 Info.flags = MachineMemOperand::MOLoad | 1191 MachineMemOperand::MOStore | 1192 MachineMemOperand::MOVolatile; 1193 return true; 1194 } 1195 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1196 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1197 Info.opc = ISD::INTRINSIC_W_CHAIN; 1198 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1199 Info.ptrVal = 1200 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1201 Info.align.reset(); 1202 Info.flags = MachineMemOperand::MOLoad | 1203 MachineMemOperand::MODereferenceable; 1204 return true; 1205 } 1206 case Intrinsic::amdgcn_global_atomic_fadd: 1207 case Intrinsic::amdgcn_global_atomic_fmin: 1208 case Intrinsic::amdgcn_global_atomic_fmax: 1209 case Intrinsic::amdgcn_flat_atomic_fadd: 1210 case Intrinsic::amdgcn_flat_atomic_fmin: 1211 case Intrinsic::amdgcn_flat_atomic_fmax: { 1212 Info.opc = ISD::INTRINSIC_W_CHAIN; 1213 Info.memVT = MVT::getVT(CI.getType()); 1214 Info.ptrVal = CI.getOperand(0); 1215 Info.align.reset(); 1216 Info.flags = MachineMemOperand::MOLoad | 1217 MachineMemOperand::MOStore | 1218 MachineMemOperand::MODereferenceable | 1219 MachineMemOperand::MOVolatile; 1220 return true; 1221 } 1222 case Intrinsic::amdgcn_ds_gws_init: 1223 case Intrinsic::amdgcn_ds_gws_barrier: 1224 case Intrinsic::amdgcn_ds_gws_sema_v: 1225 case Intrinsic::amdgcn_ds_gws_sema_br: 1226 case Intrinsic::amdgcn_ds_gws_sema_p: 1227 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1228 Info.opc = ISD::INTRINSIC_VOID; 1229 1230 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1231 Info.ptrVal = 1232 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1233 1234 // This is an abstract access, but we need to specify a type and size. 1235 Info.memVT = MVT::i32; 1236 Info.size = 4; 1237 Info.align = Align(4); 1238 1239 Info.flags = MachineMemOperand::MOStore; 1240 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1241 Info.flags = MachineMemOperand::MOLoad; 1242 return true; 1243 } 1244 default: 1245 return false; 1246 } 1247 } 1248 1249 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1250 SmallVectorImpl<Value*> &Ops, 1251 Type *&AccessTy) const { 1252 switch (II->getIntrinsicID()) { 1253 case Intrinsic::amdgcn_atomic_inc: 1254 case Intrinsic::amdgcn_atomic_dec: 1255 case Intrinsic::amdgcn_ds_ordered_add: 1256 case Intrinsic::amdgcn_ds_ordered_swap: 1257 case Intrinsic::amdgcn_ds_append: 1258 case Intrinsic::amdgcn_ds_consume: 1259 case Intrinsic::amdgcn_ds_fadd: 1260 case Intrinsic::amdgcn_ds_fmin: 1261 case Intrinsic::amdgcn_ds_fmax: 1262 case Intrinsic::amdgcn_global_atomic_fadd: 1263 case Intrinsic::amdgcn_flat_atomic_fadd: 1264 case Intrinsic::amdgcn_flat_atomic_fmin: 1265 case Intrinsic::amdgcn_flat_atomic_fmax: 1266 case Intrinsic::amdgcn_global_atomic_csub: { 1267 Value *Ptr = II->getArgOperand(0); 1268 AccessTy = II->getType(); 1269 Ops.push_back(Ptr); 1270 return true; 1271 } 1272 default: 1273 return false; 1274 } 1275 } 1276 1277 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1278 if (!Subtarget->hasFlatInstOffsets()) { 1279 // Flat instructions do not have offsets, and only have the register 1280 // address. 1281 return AM.BaseOffs == 0 && AM.Scale == 0; 1282 } 1283 1284 return AM.Scale == 0 && 1285 (AM.BaseOffs == 0 || 1286 Subtarget->getInstrInfo()->isLegalFLATOffset( 1287 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1288 } 1289 1290 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1291 if (Subtarget->hasFlatGlobalInsts()) 1292 return AM.Scale == 0 && 1293 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1294 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1295 SIInstrFlags::FlatGlobal)); 1296 1297 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1298 // Assume the we will use FLAT for all global memory accesses 1299 // on VI. 1300 // FIXME: This assumption is currently wrong. On VI we still use 1301 // MUBUF instructions for the r + i addressing mode. As currently 1302 // implemented, the MUBUF instructions only work on buffer < 4GB. 1303 // It may be possible to support > 4GB buffers with MUBUF instructions, 1304 // by setting the stride value in the resource descriptor which would 1305 // increase the size limit to (stride * 4GB). However, this is risky, 1306 // because it has never been validated. 1307 return isLegalFlatAddressingMode(AM); 1308 } 1309 1310 return isLegalMUBUFAddressingMode(AM); 1311 } 1312 1313 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1314 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1315 // additionally can do r + r + i with addr64. 32-bit has more addressing 1316 // mode options. Depending on the resource constant, it can also do 1317 // (i64 r0) + (i32 r1) * (i14 i). 1318 // 1319 // Private arrays end up using a scratch buffer most of the time, so also 1320 // assume those use MUBUF instructions. Scratch loads / stores are currently 1321 // implemented as mubuf instructions with offen bit set, so slightly 1322 // different than the normal addr64. 1323 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1324 return false; 1325 1326 // FIXME: Since we can split immediate into soffset and immediate offset, 1327 // would it make sense to allow any immediate? 1328 1329 switch (AM.Scale) { 1330 case 0: // r + i or just i, depending on HasBaseReg. 1331 return true; 1332 case 1: 1333 return true; // We have r + r or r + i. 1334 case 2: 1335 if (AM.HasBaseReg) { 1336 // Reject 2 * r + r. 1337 return false; 1338 } 1339 1340 // Allow 2 * r as r + r 1341 // Or 2 * r + i is allowed as r + r + i. 1342 return true; 1343 default: // Don't allow n * r 1344 return false; 1345 } 1346 } 1347 1348 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1349 const AddrMode &AM, Type *Ty, 1350 unsigned AS, Instruction *I) const { 1351 // No global is ever allowed as a base. 1352 if (AM.BaseGV) 1353 return false; 1354 1355 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1356 return isLegalGlobalAddressingMode(AM); 1357 1358 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1359 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1360 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1361 // If the offset isn't a multiple of 4, it probably isn't going to be 1362 // correctly aligned. 1363 // FIXME: Can we get the real alignment here? 1364 if (AM.BaseOffs % 4 != 0) 1365 return isLegalMUBUFAddressingMode(AM); 1366 1367 // There are no SMRD extloads, so if we have to do a small type access we 1368 // will use a MUBUF load. 1369 // FIXME?: We also need to do this if unaligned, but we don't know the 1370 // alignment here. 1371 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1372 return isLegalGlobalAddressingMode(AM); 1373 1374 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1375 // SMRD instructions have an 8-bit, dword offset on SI. 1376 if (!isUInt<8>(AM.BaseOffs / 4)) 1377 return false; 1378 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1379 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1380 // in 8-bits, it can use a smaller encoding. 1381 if (!isUInt<32>(AM.BaseOffs / 4)) 1382 return false; 1383 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1384 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1385 if (!isUInt<20>(AM.BaseOffs)) 1386 return false; 1387 } else 1388 llvm_unreachable("unhandled generation"); 1389 1390 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1391 return true; 1392 1393 if (AM.Scale == 1 && AM.HasBaseReg) 1394 return true; 1395 1396 return false; 1397 1398 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1399 return isLegalMUBUFAddressingMode(AM); 1400 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1401 AS == AMDGPUAS::REGION_ADDRESS) { 1402 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1403 // field. 1404 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1405 // an 8-bit dword offset but we don't know the alignment here. 1406 if (!isUInt<16>(AM.BaseOffs)) 1407 return false; 1408 1409 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1410 return true; 1411 1412 if (AM.Scale == 1 && AM.HasBaseReg) 1413 return true; 1414 1415 return false; 1416 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1417 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1418 // For an unknown address space, this usually means that this is for some 1419 // reason being used for pure arithmetic, and not based on some addressing 1420 // computation. We don't have instructions that compute pointers with any 1421 // addressing modes, so treat them as having no offset like flat 1422 // instructions. 1423 return isLegalFlatAddressingMode(AM); 1424 } 1425 1426 // Assume a user alias of global for unknown address spaces. 1427 return isLegalGlobalAddressingMode(AM); 1428 } 1429 1430 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1431 const MachineFunction &MF) const { 1432 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1433 return (MemVT.getSizeInBits() <= 4 * 32); 1434 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1435 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1436 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1437 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1438 return (MemVT.getSizeInBits() <= 2 * 32); 1439 } 1440 return true; 1441 } 1442 1443 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1444 unsigned Size, unsigned AddrSpace, Align Alignment, 1445 MachineMemOperand::Flags Flags, bool *IsFast) const { 1446 if (IsFast) 1447 *IsFast = false; 1448 1449 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1450 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1451 // Check if alignment requirements for ds_read/write instructions are 1452 // disabled. 1453 if (Subtarget->hasUnalignedDSAccessEnabled() && 1454 !Subtarget->hasLDSMisalignedBug()) { 1455 if (IsFast) 1456 *IsFast = Alignment != Align(2); 1457 return true; 1458 } 1459 1460 // Either, the alignment requirements are "enabled", or there is an 1461 // unaligned LDS access related hardware bug though alignment requirements 1462 // are "disabled". In either case, we need to check for proper alignment 1463 // requirements. 1464 // 1465 if (Size == 64) { 1466 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1467 // can do a 4 byte aligned, 8 byte access in a single operation using 1468 // ds_read2/write2_b32 with adjacent offsets. 1469 bool AlignedBy4 = Alignment >= Align(4); 1470 if (IsFast) 1471 *IsFast = AlignedBy4; 1472 1473 return AlignedBy4; 1474 } 1475 if (Size == 96) { 1476 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1477 // gfx8 and older. 1478 bool AlignedBy16 = Alignment >= Align(16); 1479 if (IsFast) 1480 *IsFast = AlignedBy16; 1481 1482 return AlignedBy16; 1483 } 1484 if (Size == 128) { 1485 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1486 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1487 // single operation using ds_read2/write2_b64. 1488 bool AlignedBy8 = Alignment >= Align(8); 1489 if (IsFast) 1490 *IsFast = AlignedBy8; 1491 1492 return AlignedBy8; 1493 } 1494 } 1495 1496 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1497 bool AlignedBy4 = Alignment >= Align(4); 1498 if (IsFast) 1499 *IsFast = AlignedBy4; 1500 1501 return AlignedBy4 || 1502 Subtarget->enableFlatScratch() || 1503 Subtarget->hasUnalignedScratchAccess(); 1504 } 1505 1506 // FIXME: We have to be conservative here and assume that flat operations 1507 // will access scratch. If we had access to the IR function, then we 1508 // could determine if any private memory was used in the function. 1509 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1510 !Subtarget->hasUnalignedScratchAccess()) { 1511 bool AlignedBy4 = Alignment >= Align(4); 1512 if (IsFast) 1513 *IsFast = AlignedBy4; 1514 1515 return AlignedBy4; 1516 } 1517 1518 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1519 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1520 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1521 // If we have an uniform constant load, it still requires using a slow 1522 // buffer instruction if unaligned. 1523 if (IsFast) { 1524 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1525 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1526 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1527 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1528 Alignment >= Align(4) : Alignment != Align(2); 1529 } 1530 1531 return true; 1532 } 1533 1534 // Smaller than dword value must be aligned. 1535 if (Size < 32) 1536 return false; 1537 1538 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1539 // byte-address are ignored, thus forcing Dword alignment. 1540 // This applies to private, global, and constant memory. 1541 if (IsFast) 1542 *IsFast = true; 1543 1544 return Size >= 32 && Alignment >= Align(4); 1545 } 1546 1547 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1548 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1549 bool *IsFast) const { 1550 if (IsFast) 1551 *IsFast = false; 1552 1553 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1554 // which isn't a simple VT. 1555 // Until MVT is extended to handle this, simply check for the size and 1556 // rely on the condition below: allow accesses if the size is a multiple of 4. 1557 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1558 VT.getStoreSize() > 16)) { 1559 return false; 1560 } 1561 1562 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1563 Alignment, Flags, IsFast); 1564 } 1565 1566 EVT SITargetLowering::getOptimalMemOpType( 1567 const MemOp &Op, const AttributeList &FuncAttributes) const { 1568 // FIXME: Should account for address space here. 1569 1570 // The default fallback uses the private pointer size as a guess for a type to 1571 // use. Make sure we switch these to 64-bit accesses. 1572 1573 if (Op.size() >= 16 && 1574 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1575 return MVT::v4i32; 1576 1577 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1578 return MVT::v2i32; 1579 1580 // Use the default. 1581 return MVT::Other; 1582 } 1583 1584 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1585 const MemSDNode *MemNode = cast<MemSDNode>(N); 1586 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1587 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1588 return I && I->getMetadata("amdgpu.noclobber"); 1589 } 1590 1591 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1592 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1593 AS == AMDGPUAS::PRIVATE_ADDRESS; 1594 } 1595 1596 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1597 unsigned DestAS) const { 1598 // Flat -> private/local is a simple truncate. 1599 // Flat -> global is no-op 1600 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1601 return true; 1602 1603 const GCNTargetMachine &TM = 1604 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1605 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1606 } 1607 1608 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1609 const MemSDNode *MemNode = cast<MemSDNode>(N); 1610 1611 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1612 } 1613 1614 TargetLoweringBase::LegalizeTypeAction 1615 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1616 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1617 VT.getScalarType().bitsLE(MVT::i16)) 1618 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1619 return TargetLoweringBase::getPreferredVectorAction(VT); 1620 } 1621 1622 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1623 Type *Ty) const { 1624 // FIXME: Could be smarter if called for vector constants. 1625 return true; 1626 } 1627 1628 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1629 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1630 switch (Op) { 1631 case ISD::LOAD: 1632 case ISD::STORE: 1633 1634 // These operations are done with 32-bit instructions anyway. 1635 case ISD::AND: 1636 case ISD::OR: 1637 case ISD::XOR: 1638 case ISD::SELECT: 1639 // TODO: Extensions? 1640 return true; 1641 default: 1642 return false; 1643 } 1644 } 1645 1646 // SimplifySetCC uses this function to determine whether or not it should 1647 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1648 if (VT == MVT::i1 && Op == ISD::SETCC) 1649 return false; 1650 1651 return TargetLowering::isTypeDesirableForOp(Op, VT); 1652 } 1653 1654 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1655 const SDLoc &SL, 1656 SDValue Chain, 1657 uint64_t Offset) const { 1658 const DataLayout &DL = DAG.getDataLayout(); 1659 MachineFunction &MF = DAG.getMachineFunction(); 1660 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1661 1662 const ArgDescriptor *InputPtrReg; 1663 const TargetRegisterClass *RC; 1664 LLT ArgTy; 1665 1666 std::tie(InputPtrReg, RC, ArgTy) = 1667 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1668 1669 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1670 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1671 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1672 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1673 1674 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1675 } 1676 1677 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1678 const SDLoc &SL) const { 1679 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1680 FIRST_IMPLICIT); 1681 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1682 } 1683 1684 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1685 const SDLoc &SL, SDValue Val, 1686 bool Signed, 1687 const ISD::InputArg *Arg) const { 1688 // First, if it is a widened vector, narrow it. 1689 if (VT.isVector() && 1690 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1691 EVT NarrowedVT = 1692 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1693 VT.getVectorNumElements()); 1694 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1695 DAG.getConstant(0, SL, MVT::i32)); 1696 } 1697 1698 // Then convert the vector elements or scalar value. 1699 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1700 VT.bitsLT(MemVT)) { 1701 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1702 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1703 } 1704 1705 if (MemVT.isFloatingPoint()) 1706 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1707 else if (Signed) 1708 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1709 else 1710 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1711 1712 return Val; 1713 } 1714 1715 SDValue SITargetLowering::lowerKernargMemParameter( 1716 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1717 uint64_t Offset, Align Alignment, bool Signed, 1718 const ISD::InputArg *Arg) const { 1719 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1720 1721 // Try to avoid using an extload by loading earlier than the argument address, 1722 // and extracting the relevant bits. The load should hopefully be merged with 1723 // the previous argument. 1724 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1725 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1726 int64_t AlignDownOffset = alignDown(Offset, 4); 1727 int64_t OffsetDiff = Offset - AlignDownOffset; 1728 1729 EVT IntVT = MemVT.changeTypeToInteger(); 1730 1731 // TODO: If we passed in the base kernel offset we could have a better 1732 // alignment than 4, but we don't really need it. 1733 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1734 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1735 MachineMemOperand::MODereferenceable | 1736 MachineMemOperand::MOInvariant); 1737 1738 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1739 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1740 1741 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1742 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1743 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1744 1745 1746 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1747 } 1748 1749 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1750 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1751 MachineMemOperand::MODereferenceable | 1752 MachineMemOperand::MOInvariant); 1753 1754 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1755 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1756 } 1757 1758 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1759 const SDLoc &SL, SDValue Chain, 1760 const ISD::InputArg &Arg) const { 1761 MachineFunction &MF = DAG.getMachineFunction(); 1762 MachineFrameInfo &MFI = MF.getFrameInfo(); 1763 1764 if (Arg.Flags.isByVal()) { 1765 unsigned Size = Arg.Flags.getByValSize(); 1766 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1767 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1768 } 1769 1770 unsigned ArgOffset = VA.getLocMemOffset(); 1771 unsigned ArgSize = VA.getValVT().getStoreSize(); 1772 1773 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1774 1775 // Create load nodes to retrieve arguments from the stack. 1776 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1777 SDValue ArgValue; 1778 1779 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1780 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1781 MVT MemVT = VA.getValVT(); 1782 1783 switch (VA.getLocInfo()) { 1784 default: 1785 break; 1786 case CCValAssign::BCvt: 1787 MemVT = VA.getLocVT(); 1788 break; 1789 case CCValAssign::SExt: 1790 ExtType = ISD::SEXTLOAD; 1791 break; 1792 case CCValAssign::ZExt: 1793 ExtType = ISD::ZEXTLOAD; 1794 break; 1795 case CCValAssign::AExt: 1796 ExtType = ISD::EXTLOAD; 1797 break; 1798 } 1799 1800 ArgValue = DAG.getExtLoad( 1801 ExtType, SL, VA.getLocVT(), Chain, FIN, 1802 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1803 MemVT); 1804 return ArgValue; 1805 } 1806 1807 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1808 const SIMachineFunctionInfo &MFI, 1809 EVT VT, 1810 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1811 const ArgDescriptor *Reg; 1812 const TargetRegisterClass *RC; 1813 LLT Ty; 1814 1815 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1816 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1817 } 1818 1819 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1820 CallingConv::ID CallConv, 1821 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1822 FunctionType *FType, 1823 SIMachineFunctionInfo *Info) { 1824 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1825 const ISD::InputArg *Arg = &Ins[I]; 1826 1827 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1828 "vector type argument should have been split"); 1829 1830 // First check if it's a PS input addr. 1831 if (CallConv == CallingConv::AMDGPU_PS && 1832 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1833 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1834 1835 // Inconveniently only the first part of the split is marked as isSplit, 1836 // so skip to the end. We only want to increment PSInputNum once for the 1837 // entire split argument. 1838 if (Arg->Flags.isSplit()) { 1839 while (!Arg->Flags.isSplitEnd()) { 1840 assert((!Arg->VT.isVector() || 1841 Arg->VT.getScalarSizeInBits() == 16) && 1842 "unexpected vector split in ps argument type"); 1843 if (!SkipArg) 1844 Splits.push_back(*Arg); 1845 Arg = &Ins[++I]; 1846 } 1847 } 1848 1849 if (SkipArg) { 1850 // We can safely skip PS inputs. 1851 Skipped.set(Arg->getOrigArgIndex()); 1852 ++PSInputNum; 1853 continue; 1854 } 1855 1856 Info->markPSInputAllocated(PSInputNum); 1857 if (Arg->Used) 1858 Info->markPSInputEnabled(PSInputNum); 1859 1860 ++PSInputNum; 1861 } 1862 1863 Splits.push_back(*Arg); 1864 } 1865 } 1866 1867 // Allocate special inputs passed in VGPRs. 1868 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1869 MachineFunction &MF, 1870 const SIRegisterInfo &TRI, 1871 SIMachineFunctionInfo &Info) const { 1872 const LLT S32 = LLT::scalar(32); 1873 MachineRegisterInfo &MRI = MF.getRegInfo(); 1874 1875 if (Info.hasWorkItemIDX()) { 1876 Register Reg = AMDGPU::VGPR0; 1877 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1878 1879 CCInfo.AllocateReg(Reg); 1880 unsigned Mask = (Subtarget->hasPackedTID() && 1881 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1882 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1883 } 1884 1885 if (Info.hasWorkItemIDY()) { 1886 assert(Info.hasWorkItemIDX()); 1887 if (Subtarget->hasPackedTID()) { 1888 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1889 0x3ff << 10)); 1890 } else { 1891 unsigned Reg = AMDGPU::VGPR1; 1892 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1893 1894 CCInfo.AllocateReg(Reg); 1895 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1896 } 1897 } 1898 1899 if (Info.hasWorkItemIDZ()) { 1900 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1901 if (Subtarget->hasPackedTID()) { 1902 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1903 0x3ff << 20)); 1904 } else { 1905 unsigned Reg = AMDGPU::VGPR2; 1906 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1907 1908 CCInfo.AllocateReg(Reg); 1909 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1910 } 1911 } 1912 } 1913 1914 // Try to allocate a VGPR at the end of the argument list, or if no argument 1915 // VGPRs are left allocating a stack slot. 1916 // If \p Mask is is given it indicates bitfield position in the register. 1917 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1918 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1919 ArgDescriptor Arg = ArgDescriptor()) { 1920 if (Arg.isSet()) 1921 return ArgDescriptor::createArg(Arg, Mask); 1922 1923 ArrayRef<MCPhysReg> ArgVGPRs 1924 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1925 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1926 if (RegIdx == ArgVGPRs.size()) { 1927 // Spill to stack required. 1928 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1929 1930 return ArgDescriptor::createStack(Offset, Mask); 1931 } 1932 1933 unsigned Reg = ArgVGPRs[RegIdx]; 1934 Reg = CCInfo.AllocateReg(Reg); 1935 assert(Reg != AMDGPU::NoRegister); 1936 1937 MachineFunction &MF = CCInfo.getMachineFunction(); 1938 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1939 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1940 return ArgDescriptor::createRegister(Reg, Mask); 1941 } 1942 1943 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1944 const TargetRegisterClass *RC, 1945 unsigned NumArgRegs) { 1946 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1947 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1948 if (RegIdx == ArgSGPRs.size()) 1949 report_fatal_error("ran out of SGPRs for arguments"); 1950 1951 unsigned Reg = ArgSGPRs[RegIdx]; 1952 Reg = CCInfo.AllocateReg(Reg); 1953 assert(Reg != AMDGPU::NoRegister); 1954 1955 MachineFunction &MF = CCInfo.getMachineFunction(); 1956 MF.addLiveIn(Reg, RC); 1957 return ArgDescriptor::createRegister(Reg); 1958 } 1959 1960 // If this has a fixed position, we still should allocate the register in the 1961 // CCInfo state. Technically we could get away with this for values passed 1962 // outside of the normal argument range. 1963 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1964 const TargetRegisterClass *RC, 1965 MCRegister Reg) { 1966 Reg = CCInfo.AllocateReg(Reg); 1967 assert(Reg != AMDGPU::NoRegister); 1968 MachineFunction &MF = CCInfo.getMachineFunction(); 1969 MF.addLiveIn(Reg, RC); 1970 } 1971 1972 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1973 if (Arg) { 1974 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1975 Arg.getRegister()); 1976 } else 1977 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1978 } 1979 1980 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1981 if (Arg) { 1982 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1983 Arg.getRegister()); 1984 } else 1985 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1986 } 1987 1988 /// Allocate implicit function VGPR arguments at the end of allocated user 1989 /// arguments. 1990 void SITargetLowering::allocateSpecialInputVGPRs( 1991 CCState &CCInfo, MachineFunction &MF, 1992 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1993 const unsigned Mask = 0x3ff; 1994 ArgDescriptor Arg; 1995 1996 if (Info.hasWorkItemIDX()) { 1997 Arg = allocateVGPR32Input(CCInfo, Mask); 1998 Info.setWorkItemIDX(Arg); 1999 } 2000 2001 if (Info.hasWorkItemIDY()) { 2002 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2003 Info.setWorkItemIDY(Arg); 2004 } 2005 2006 if (Info.hasWorkItemIDZ()) 2007 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2008 } 2009 2010 /// Allocate implicit function VGPR arguments in fixed registers. 2011 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2012 CCState &CCInfo, MachineFunction &MF, 2013 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2014 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2015 if (!Reg) 2016 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2017 2018 const unsigned Mask = 0x3ff; 2019 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2020 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2021 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2022 } 2023 2024 void SITargetLowering::allocateSpecialInputSGPRs( 2025 CCState &CCInfo, 2026 MachineFunction &MF, 2027 const SIRegisterInfo &TRI, 2028 SIMachineFunctionInfo &Info) const { 2029 auto &ArgInfo = Info.getArgInfo(); 2030 2031 // TODO: Unify handling with private memory pointers. 2032 2033 if (Info.hasDispatchPtr()) 2034 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2035 2036 if (Info.hasQueuePtr()) 2037 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2038 2039 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2040 // constant offset from the kernarg segment. 2041 if (Info.hasImplicitArgPtr()) 2042 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2043 2044 if (Info.hasDispatchID()) 2045 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2046 2047 // flat_scratch_init is not applicable for non-kernel functions. 2048 2049 if (Info.hasWorkGroupIDX()) 2050 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2051 2052 if (Info.hasWorkGroupIDY()) 2053 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2054 2055 if (Info.hasWorkGroupIDZ()) 2056 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2057 } 2058 2059 // Allocate special inputs passed in user SGPRs. 2060 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2061 MachineFunction &MF, 2062 const SIRegisterInfo &TRI, 2063 SIMachineFunctionInfo &Info) const { 2064 if (Info.hasImplicitBufferPtr()) { 2065 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2066 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2067 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2068 } 2069 2070 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2071 if (Info.hasPrivateSegmentBuffer()) { 2072 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2073 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2074 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2075 } 2076 2077 if (Info.hasDispatchPtr()) { 2078 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2079 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2080 CCInfo.AllocateReg(DispatchPtrReg); 2081 } 2082 2083 if (Info.hasQueuePtr()) { 2084 Register QueuePtrReg = Info.addQueuePtr(TRI); 2085 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2086 CCInfo.AllocateReg(QueuePtrReg); 2087 } 2088 2089 if (Info.hasKernargSegmentPtr()) { 2090 MachineRegisterInfo &MRI = MF.getRegInfo(); 2091 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2092 CCInfo.AllocateReg(InputPtrReg); 2093 2094 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2095 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2096 } 2097 2098 if (Info.hasDispatchID()) { 2099 Register DispatchIDReg = Info.addDispatchID(TRI); 2100 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2101 CCInfo.AllocateReg(DispatchIDReg); 2102 } 2103 2104 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2105 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2106 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2107 CCInfo.AllocateReg(FlatScratchInitReg); 2108 } 2109 2110 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2111 // these from the dispatch pointer. 2112 } 2113 2114 // Allocate special input registers that are initialized per-wave. 2115 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2116 MachineFunction &MF, 2117 SIMachineFunctionInfo &Info, 2118 CallingConv::ID CallConv, 2119 bool IsShader) const { 2120 if (Info.hasWorkGroupIDX()) { 2121 Register Reg = Info.addWorkGroupIDX(); 2122 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2123 CCInfo.AllocateReg(Reg); 2124 } 2125 2126 if (Info.hasWorkGroupIDY()) { 2127 Register Reg = Info.addWorkGroupIDY(); 2128 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2129 CCInfo.AllocateReg(Reg); 2130 } 2131 2132 if (Info.hasWorkGroupIDZ()) { 2133 Register Reg = Info.addWorkGroupIDZ(); 2134 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2135 CCInfo.AllocateReg(Reg); 2136 } 2137 2138 if (Info.hasWorkGroupInfo()) { 2139 Register Reg = Info.addWorkGroupInfo(); 2140 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2141 CCInfo.AllocateReg(Reg); 2142 } 2143 2144 if (Info.hasPrivateSegmentWaveByteOffset()) { 2145 // Scratch wave offset passed in system SGPR. 2146 unsigned PrivateSegmentWaveByteOffsetReg; 2147 2148 if (IsShader) { 2149 PrivateSegmentWaveByteOffsetReg = 2150 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2151 2152 // This is true if the scratch wave byte offset doesn't have a fixed 2153 // location. 2154 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2155 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2156 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2157 } 2158 } else 2159 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2160 2161 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2162 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2163 } 2164 } 2165 2166 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2167 MachineFunction &MF, 2168 const SIRegisterInfo &TRI, 2169 SIMachineFunctionInfo &Info) { 2170 // Now that we've figured out where the scratch register inputs are, see if 2171 // should reserve the arguments and use them directly. 2172 MachineFrameInfo &MFI = MF.getFrameInfo(); 2173 bool HasStackObjects = MFI.hasStackObjects(); 2174 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2175 2176 // Record that we know we have non-spill stack objects so we don't need to 2177 // check all stack objects later. 2178 if (HasStackObjects) 2179 Info.setHasNonSpillStackObjects(true); 2180 2181 // Everything live out of a block is spilled with fast regalloc, so it's 2182 // almost certain that spilling will be required. 2183 if (TM.getOptLevel() == CodeGenOpt::None) 2184 HasStackObjects = true; 2185 2186 // For now assume stack access is needed in any callee functions, so we need 2187 // the scratch registers to pass in. 2188 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2189 2190 if (!ST.enableFlatScratch()) { 2191 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2192 // If we have stack objects, we unquestionably need the private buffer 2193 // resource. For the Code Object V2 ABI, this will be the first 4 user 2194 // SGPR inputs. We can reserve those and use them directly. 2195 2196 Register PrivateSegmentBufferReg = 2197 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2198 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2199 } else { 2200 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2201 // We tentatively reserve the last registers (skipping the last registers 2202 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2203 // we'll replace these with the ones immediately after those which were 2204 // really allocated. In the prologue copies will be inserted from the 2205 // argument to these reserved registers. 2206 2207 // Without HSA, relocations are used for the scratch pointer and the 2208 // buffer resource setup is always inserted in the prologue. Scratch wave 2209 // offset is still in an input SGPR. 2210 Info.setScratchRSrcReg(ReservedBufferReg); 2211 } 2212 } 2213 2214 MachineRegisterInfo &MRI = MF.getRegInfo(); 2215 2216 // For entry functions we have to set up the stack pointer if we use it, 2217 // whereas non-entry functions get this "for free". This means there is no 2218 // intrinsic advantage to using S32 over S34 in cases where we do not have 2219 // calls but do need a frame pointer (i.e. if we are requested to have one 2220 // because frame pointer elimination is disabled). To keep things simple we 2221 // only ever use S32 as the call ABI stack pointer, and so using it does not 2222 // imply we need a separate frame pointer. 2223 // 2224 // Try to use s32 as the SP, but move it if it would interfere with input 2225 // arguments. This won't work with calls though. 2226 // 2227 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2228 // registers. 2229 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2230 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2231 } else { 2232 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2233 2234 if (MFI.hasCalls()) 2235 report_fatal_error("call in graphics shader with too many input SGPRs"); 2236 2237 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2238 if (!MRI.isLiveIn(Reg)) { 2239 Info.setStackPtrOffsetReg(Reg); 2240 break; 2241 } 2242 } 2243 2244 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2245 report_fatal_error("failed to find register for SP"); 2246 } 2247 2248 // hasFP should be accurate for entry functions even before the frame is 2249 // finalized, because it does not rely on the known stack size, only 2250 // properties like whether variable sized objects are present. 2251 if (ST.getFrameLowering()->hasFP(MF)) { 2252 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2253 } 2254 } 2255 2256 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2257 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2258 return !Info->isEntryFunction(); 2259 } 2260 2261 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2262 2263 } 2264 2265 void SITargetLowering::insertCopiesSplitCSR( 2266 MachineBasicBlock *Entry, 2267 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2268 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2269 2270 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2271 if (!IStart) 2272 return; 2273 2274 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2275 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2276 MachineBasicBlock::iterator MBBI = Entry->begin(); 2277 for (const MCPhysReg *I = IStart; *I; ++I) { 2278 const TargetRegisterClass *RC = nullptr; 2279 if (AMDGPU::SReg_64RegClass.contains(*I)) 2280 RC = &AMDGPU::SGPR_64RegClass; 2281 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2282 RC = &AMDGPU::SGPR_32RegClass; 2283 else 2284 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2285 2286 Register NewVR = MRI->createVirtualRegister(RC); 2287 // Create copy from CSR to a virtual register. 2288 Entry->addLiveIn(*I); 2289 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2290 .addReg(*I); 2291 2292 // Insert the copy-back instructions right before the terminator. 2293 for (auto *Exit : Exits) 2294 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2295 TII->get(TargetOpcode::COPY), *I) 2296 .addReg(NewVR); 2297 } 2298 } 2299 2300 SDValue SITargetLowering::LowerFormalArguments( 2301 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2302 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2303 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2304 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2305 2306 MachineFunction &MF = DAG.getMachineFunction(); 2307 const Function &Fn = MF.getFunction(); 2308 FunctionType *FType = MF.getFunction().getFunctionType(); 2309 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2310 2311 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2312 DiagnosticInfoUnsupported NoGraphicsHSA( 2313 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2314 DAG.getContext()->diagnose(NoGraphicsHSA); 2315 return DAG.getEntryNode(); 2316 } 2317 2318 Info->allocateModuleLDSGlobal(Fn.getParent()); 2319 2320 SmallVector<ISD::InputArg, 16> Splits; 2321 SmallVector<CCValAssign, 16> ArgLocs; 2322 BitVector Skipped(Ins.size()); 2323 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2324 *DAG.getContext()); 2325 2326 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2327 bool IsKernel = AMDGPU::isKernel(CallConv); 2328 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2329 2330 if (IsGraphics) { 2331 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2332 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2333 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2334 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2335 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2336 !Info->hasWorkItemIDZ()); 2337 } 2338 2339 if (CallConv == CallingConv::AMDGPU_PS) { 2340 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2341 2342 // At least one interpolation mode must be enabled or else the GPU will 2343 // hang. 2344 // 2345 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2346 // set PSInputAddr, the user wants to enable some bits after the compilation 2347 // based on run-time states. Since we can't know what the final PSInputEna 2348 // will look like, so we shouldn't do anything here and the user should take 2349 // responsibility for the correct programming. 2350 // 2351 // Otherwise, the following restrictions apply: 2352 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2353 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2354 // enabled too. 2355 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2356 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2357 CCInfo.AllocateReg(AMDGPU::VGPR0); 2358 CCInfo.AllocateReg(AMDGPU::VGPR1); 2359 Info->markPSInputAllocated(0); 2360 Info->markPSInputEnabled(0); 2361 } 2362 if (Subtarget->isAmdPalOS()) { 2363 // For isAmdPalOS, the user does not enable some bits after compilation 2364 // based on run-time states; the register values being generated here are 2365 // the final ones set in hardware. Therefore we need to apply the 2366 // workaround to PSInputAddr and PSInputEnable together. (The case where 2367 // a bit is set in PSInputAddr but not PSInputEnable is where the 2368 // frontend set up an input arg for a particular interpolation mode, but 2369 // nothing uses that input arg. Really we should have an earlier pass 2370 // that removes such an arg.) 2371 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2372 if ((PsInputBits & 0x7F) == 0 || 2373 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2374 Info->markPSInputEnabled( 2375 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2376 } 2377 } else if (IsKernel) { 2378 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2379 } else { 2380 Splits.append(Ins.begin(), Ins.end()); 2381 } 2382 2383 if (IsEntryFunc) { 2384 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2385 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2386 } else { 2387 // For the fixed ABI, pass workitem IDs in the last argument register. 2388 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2389 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2390 } 2391 2392 if (IsKernel) { 2393 analyzeFormalArgumentsCompute(CCInfo, Ins); 2394 } else { 2395 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2396 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2397 } 2398 2399 SmallVector<SDValue, 16> Chains; 2400 2401 // FIXME: This is the minimum kernel argument alignment. We should improve 2402 // this to the maximum alignment of the arguments. 2403 // 2404 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2405 // kern arg offset. 2406 const Align KernelArgBaseAlign = Align(16); 2407 2408 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2409 const ISD::InputArg &Arg = Ins[i]; 2410 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2411 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2412 continue; 2413 } 2414 2415 CCValAssign &VA = ArgLocs[ArgIdx++]; 2416 MVT VT = VA.getLocVT(); 2417 2418 if (IsEntryFunc && VA.isMemLoc()) { 2419 VT = Ins[i].VT; 2420 EVT MemVT = VA.getLocVT(); 2421 2422 const uint64_t Offset = VA.getLocMemOffset(); 2423 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2424 2425 if (Arg.Flags.isByRef()) { 2426 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2427 2428 const GCNTargetMachine &TM = 2429 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2430 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2431 Arg.Flags.getPointerAddrSpace())) { 2432 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2433 Arg.Flags.getPointerAddrSpace()); 2434 } 2435 2436 InVals.push_back(Ptr); 2437 continue; 2438 } 2439 2440 SDValue Arg = lowerKernargMemParameter( 2441 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2442 Chains.push_back(Arg.getValue(1)); 2443 2444 auto *ParamTy = 2445 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2446 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2447 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2448 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2449 // On SI local pointers are just offsets into LDS, so they are always 2450 // less than 16-bits. On CI and newer they could potentially be 2451 // real pointers, so we can't guarantee their size. 2452 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2453 DAG.getValueType(MVT::i16)); 2454 } 2455 2456 InVals.push_back(Arg); 2457 continue; 2458 } else if (!IsEntryFunc && VA.isMemLoc()) { 2459 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2460 InVals.push_back(Val); 2461 if (!Arg.Flags.isByVal()) 2462 Chains.push_back(Val.getValue(1)); 2463 continue; 2464 } 2465 2466 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2467 2468 Register Reg = VA.getLocReg(); 2469 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2470 EVT ValVT = VA.getValVT(); 2471 2472 Reg = MF.addLiveIn(Reg, RC); 2473 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2474 2475 if (Arg.Flags.isSRet()) { 2476 // The return object should be reasonably addressable. 2477 2478 // FIXME: This helps when the return is a real sret. If it is a 2479 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2480 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2481 unsigned NumBits 2482 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2483 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2484 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2485 } 2486 2487 // If this is an 8 or 16-bit value, it is really passed promoted 2488 // to 32 bits. Insert an assert[sz]ext to capture this, then 2489 // truncate to the right size. 2490 switch (VA.getLocInfo()) { 2491 case CCValAssign::Full: 2492 break; 2493 case CCValAssign::BCvt: 2494 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2495 break; 2496 case CCValAssign::SExt: 2497 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2498 DAG.getValueType(ValVT)); 2499 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2500 break; 2501 case CCValAssign::ZExt: 2502 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2503 DAG.getValueType(ValVT)); 2504 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2505 break; 2506 case CCValAssign::AExt: 2507 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2508 break; 2509 default: 2510 llvm_unreachable("Unknown loc info!"); 2511 } 2512 2513 InVals.push_back(Val); 2514 } 2515 2516 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2517 // Special inputs come after user arguments. 2518 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2519 } 2520 2521 // Start adding system SGPRs. 2522 if (IsEntryFunc) { 2523 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2524 } else { 2525 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2526 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2527 } 2528 2529 auto &ArgUsageInfo = 2530 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2531 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2532 2533 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2534 Info->setBytesInStackArgArea(StackArgSize); 2535 2536 return Chains.empty() ? Chain : 2537 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2538 } 2539 2540 // TODO: If return values can't fit in registers, we should return as many as 2541 // possible in registers before passing on stack. 2542 bool SITargetLowering::CanLowerReturn( 2543 CallingConv::ID CallConv, 2544 MachineFunction &MF, bool IsVarArg, 2545 const SmallVectorImpl<ISD::OutputArg> &Outs, 2546 LLVMContext &Context) const { 2547 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2548 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2549 // for shaders. Vector types should be explicitly handled by CC. 2550 if (AMDGPU::isEntryFunctionCC(CallConv)) 2551 return true; 2552 2553 SmallVector<CCValAssign, 16> RVLocs; 2554 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2555 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2556 } 2557 2558 SDValue 2559 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2560 bool isVarArg, 2561 const SmallVectorImpl<ISD::OutputArg> &Outs, 2562 const SmallVectorImpl<SDValue> &OutVals, 2563 const SDLoc &DL, SelectionDAG &DAG) const { 2564 MachineFunction &MF = DAG.getMachineFunction(); 2565 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2566 2567 if (AMDGPU::isKernel(CallConv)) { 2568 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2569 OutVals, DL, DAG); 2570 } 2571 2572 bool IsShader = AMDGPU::isShader(CallConv); 2573 2574 Info->setIfReturnsVoid(Outs.empty()); 2575 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2576 2577 // CCValAssign - represent the assignment of the return value to a location. 2578 SmallVector<CCValAssign, 48> RVLocs; 2579 SmallVector<ISD::OutputArg, 48> Splits; 2580 2581 // CCState - Info about the registers and stack slots. 2582 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2583 *DAG.getContext()); 2584 2585 // Analyze outgoing return values. 2586 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2587 2588 SDValue Flag; 2589 SmallVector<SDValue, 48> RetOps; 2590 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2591 2592 // Add return address for callable functions. 2593 if (!Info->isEntryFunction()) { 2594 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2595 SDValue ReturnAddrReg = CreateLiveInRegister( 2596 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2597 2598 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2599 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2600 MVT::i64); 2601 Chain = 2602 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2603 Flag = Chain.getValue(1); 2604 RetOps.push_back(ReturnAddrVirtualReg); 2605 } 2606 2607 // Copy the result values into the output registers. 2608 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2609 ++I, ++RealRVLocIdx) { 2610 CCValAssign &VA = RVLocs[I]; 2611 assert(VA.isRegLoc() && "Can only return in registers!"); 2612 // TODO: Partially return in registers if return values don't fit. 2613 SDValue Arg = OutVals[RealRVLocIdx]; 2614 2615 // Copied from other backends. 2616 switch (VA.getLocInfo()) { 2617 case CCValAssign::Full: 2618 break; 2619 case CCValAssign::BCvt: 2620 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2621 break; 2622 case CCValAssign::SExt: 2623 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2624 break; 2625 case CCValAssign::ZExt: 2626 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2627 break; 2628 case CCValAssign::AExt: 2629 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2630 break; 2631 default: 2632 llvm_unreachable("Unknown loc info!"); 2633 } 2634 2635 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2636 Flag = Chain.getValue(1); 2637 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2638 } 2639 2640 // FIXME: Does sret work properly? 2641 if (!Info->isEntryFunction()) { 2642 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2643 const MCPhysReg *I = 2644 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2645 if (I) { 2646 for (; *I; ++I) { 2647 if (AMDGPU::SReg_64RegClass.contains(*I)) 2648 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2649 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2650 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2651 else 2652 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2653 } 2654 } 2655 } 2656 2657 // Update chain and glue. 2658 RetOps[0] = Chain; 2659 if (Flag.getNode()) 2660 RetOps.push_back(Flag); 2661 2662 unsigned Opc = AMDGPUISD::ENDPGM; 2663 if (!IsWaveEnd) 2664 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2665 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2666 } 2667 2668 SDValue SITargetLowering::LowerCallResult( 2669 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2670 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2671 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2672 SDValue ThisVal) const { 2673 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2674 2675 // Assign locations to each value returned by this call. 2676 SmallVector<CCValAssign, 16> RVLocs; 2677 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2678 *DAG.getContext()); 2679 CCInfo.AnalyzeCallResult(Ins, RetCC); 2680 2681 // Copy all of the result registers out of their specified physreg. 2682 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2683 CCValAssign VA = RVLocs[i]; 2684 SDValue Val; 2685 2686 if (VA.isRegLoc()) { 2687 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2688 Chain = Val.getValue(1); 2689 InFlag = Val.getValue(2); 2690 } else if (VA.isMemLoc()) { 2691 report_fatal_error("TODO: return values in memory"); 2692 } else 2693 llvm_unreachable("unknown argument location type"); 2694 2695 switch (VA.getLocInfo()) { 2696 case CCValAssign::Full: 2697 break; 2698 case CCValAssign::BCvt: 2699 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2700 break; 2701 case CCValAssign::ZExt: 2702 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2703 DAG.getValueType(VA.getValVT())); 2704 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2705 break; 2706 case CCValAssign::SExt: 2707 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2708 DAG.getValueType(VA.getValVT())); 2709 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2710 break; 2711 case CCValAssign::AExt: 2712 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2713 break; 2714 default: 2715 llvm_unreachable("Unknown loc info!"); 2716 } 2717 2718 InVals.push_back(Val); 2719 } 2720 2721 return Chain; 2722 } 2723 2724 // Add code to pass special inputs required depending on used features separate 2725 // from the explicit user arguments present in the IR. 2726 void SITargetLowering::passSpecialInputs( 2727 CallLoweringInfo &CLI, 2728 CCState &CCInfo, 2729 const SIMachineFunctionInfo &Info, 2730 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2731 SmallVectorImpl<SDValue> &MemOpChains, 2732 SDValue Chain) const { 2733 // If we don't have a call site, this was a call inserted by 2734 // legalization. These can never use special inputs. 2735 if (!CLI.CB) 2736 return; 2737 2738 SelectionDAG &DAG = CLI.DAG; 2739 const SDLoc &DL = CLI.DL; 2740 2741 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2742 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2743 2744 const AMDGPUFunctionArgInfo *CalleeArgInfo 2745 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2746 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2747 auto &ArgUsageInfo = 2748 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2749 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2750 } 2751 2752 // TODO: Unify with private memory register handling. This is complicated by 2753 // the fact that at least in kernels, the input argument is not necessarily 2754 // in the same location as the input. 2755 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2756 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2757 AMDGPUFunctionArgInfo::QUEUE_PTR, 2758 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2759 AMDGPUFunctionArgInfo::DISPATCH_ID, 2760 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2761 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2762 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2763 }; 2764 2765 for (auto InputID : InputRegs) { 2766 const ArgDescriptor *OutgoingArg; 2767 const TargetRegisterClass *ArgRC; 2768 LLT ArgTy; 2769 2770 std::tie(OutgoingArg, ArgRC, ArgTy) = 2771 CalleeArgInfo->getPreloadedValue(InputID); 2772 if (!OutgoingArg) 2773 continue; 2774 2775 const ArgDescriptor *IncomingArg; 2776 const TargetRegisterClass *IncomingArgRC; 2777 LLT Ty; 2778 std::tie(IncomingArg, IncomingArgRC, Ty) = 2779 CallerArgInfo.getPreloadedValue(InputID); 2780 assert(IncomingArgRC == ArgRC); 2781 2782 // All special arguments are ints for now. 2783 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2784 SDValue InputReg; 2785 2786 if (IncomingArg) { 2787 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2788 } else { 2789 // The implicit arg ptr is special because it doesn't have a corresponding 2790 // input for kernels, and is computed from the kernarg segment pointer. 2791 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2792 InputReg = getImplicitArgPtr(DAG, DL); 2793 } 2794 2795 if (OutgoingArg->isRegister()) { 2796 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2797 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2798 report_fatal_error("failed to allocate implicit input argument"); 2799 } else { 2800 unsigned SpecialArgOffset = 2801 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2802 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2803 SpecialArgOffset); 2804 MemOpChains.push_back(ArgStore); 2805 } 2806 } 2807 2808 // Pack workitem IDs into a single register or pass it as is if already 2809 // packed. 2810 const ArgDescriptor *OutgoingArg; 2811 const TargetRegisterClass *ArgRC; 2812 LLT Ty; 2813 2814 std::tie(OutgoingArg, ArgRC, Ty) = 2815 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2816 if (!OutgoingArg) 2817 std::tie(OutgoingArg, ArgRC, Ty) = 2818 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2819 if (!OutgoingArg) 2820 std::tie(OutgoingArg, ArgRC, Ty) = 2821 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2822 if (!OutgoingArg) 2823 return; 2824 2825 const ArgDescriptor *IncomingArgX = std::get<0>( 2826 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2827 const ArgDescriptor *IncomingArgY = std::get<0>( 2828 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2829 const ArgDescriptor *IncomingArgZ = std::get<0>( 2830 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2831 2832 SDValue InputReg; 2833 SDLoc SL; 2834 2835 // If incoming ids are not packed we need to pack them. 2836 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2837 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2838 2839 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2840 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2841 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2842 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2843 InputReg = InputReg.getNode() ? 2844 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2845 } 2846 2847 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2848 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2849 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2850 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2851 InputReg = InputReg.getNode() ? 2852 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2853 } 2854 2855 if (!InputReg.getNode()) { 2856 // Workitem ids are already packed, any of present incoming arguments 2857 // will carry all required fields. 2858 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2859 IncomingArgX ? *IncomingArgX : 2860 IncomingArgY ? *IncomingArgY : 2861 *IncomingArgZ, ~0u); 2862 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2863 } 2864 2865 if (OutgoingArg->isRegister()) { 2866 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2867 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2868 } else { 2869 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2870 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2871 SpecialArgOffset); 2872 MemOpChains.push_back(ArgStore); 2873 } 2874 } 2875 2876 static bool canGuaranteeTCO(CallingConv::ID CC) { 2877 return CC == CallingConv::Fast; 2878 } 2879 2880 /// Return true if we might ever do TCO for calls with this calling convention. 2881 static bool mayTailCallThisCC(CallingConv::ID CC) { 2882 switch (CC) { 2883 case CallingConv::C: 2884 case CallingConv::AMDGPU_Gfx: 2885 return true; 2886 default: 2887 return canGuaranteeTCO(CC); 2888 } 2889 } 2890 2891 bool SITargetLowering::isEligibleForTailCallOptimization( 2892 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2893 const SmallVectorImpl<ISD::OutputArg> &Outs, 2894 const SmallVectorImpl<SDValue> &OutVals, 2895 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2896 if (!mayTailCallThisCC(CalleeCC)) 2897 return false; 2898 2899 // For a divergent call target, we need to do a waterfall loop over the 2900 // possible callees which precludes us from using a simple jump. 2901 if (Callee->isDivergent()) 2902 return false; 2903 2904 MachineFunction &MF = DAG.getMachineFunction(); 2905 const Function &CallerF = MF.getFunction(); 2906 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2907 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2908 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2909 2910 // Kernels aren't callable, and don't have a live in return address so it 2911 // doesn't make sense to do a tail call with entry functions. 2912 if (!CallerPreserved) 2913 return false; 2914 2915 bool CCMatch = CallerCC == CalleeCC; 2916 2917 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2918 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2919 return true; 2920 return false; 2921 } 2922 2923 // TODO: Can we handle var args? 2924 if (IsVarArg) 2925 return false; 2926 2927 for (const Argument &Arg : CallerF.args()) { 2928 if (Arg.hasByValAttr()) 2929 return false; 2930 } 2931 2932 LLVMContext &Ctx = *DAG.getContext(); 2933 2934 // Check that the call results are passed in the same way. 2935 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2936 CCAssignFnForCall(CalleeCC, IsVarArg), 2937 CCAssignFnForCall(CallerCC, IsVarArg))) 2938 return false; 2939 2940 // The callee has to preserve all registers the caller needs to preserve. 2941 if (!CCMatch) { 2942 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2943 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2944 return false; 2945 } 2946 2947 // Nothing more to check if the callee is taking no arguments. 2948 if (Outs.empty()) 2949 return true; 2950 2951 SmallVector<CCValAssign, 16> ArgLocs; 2952 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2953 2954 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2955 2956 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2957 // If the stack arguments for this call do not fit into our own save area then 2958 // the call cannot be made tail. 2959 // TODO: Is this really necessary? 2960 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2961 return false; 2962 2963 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2964 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2965 } 2966 2967 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2968 if (!CI->isTailCall()) 2969 return false; 2970 2971 const Function *ParentFn = CI->getParent()->getParent(); 2972 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2973 return false; 2974 return true; 2975 } 2976 2977 // The wave scratch offset register is used as the global base pointer. 2978 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2979 SmallVectorImpl<SDValue> &InVals) const { 2980 SelectionDAG &DAG = CLI.DAG; 2981 const SDLoc &DL = CLI.DL; 2982 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2983 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2984 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2985 SDValue Chain = CLI.Chain; 2986 SDValue Callee = CLI.Callee; 2987 bool &IsTailCall = CLI.IsTailCall; 2988 CallingConv::ID CallConv = CLI.CallConv; 2989 bool IsVarArg = CLI.IsVarArg; 2990 bool IsSibCall = false; 2991 bool IsThisReturn = false; 2992 MachineFunction &MF = DAG.getMachineFunction(); 2993 2994 if (Callee.isUndef() || isNullConstant(Callee)) { 2995 if (!CLI.IsTailCall) { 2996 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2997 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2998 } 2999 3000 return Chain; 3001 } 3002 3003 if (IsVarArg) { 3004 return lowerUnhandledCall(CLI, InVals, 3005 "unsupported call to variadic function "); 3006 } 3007 3008 if (!CLI.CB) 3009 report_fatal_error("unsupported libcall legalization"); 3010 3011 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3012 return lowerUnhandledCall(CLI, InVals, 3013 "unsupported required tail call to function "); 3014 } 3015 3016 if (AMDGPU::isShader(CallConv)) { 3017 // Note the issue is with the CC of the called function, not of the call 3018 // itself. 3019 return lowerUnhandledCall(CLI, InVals, 3020 "unsupported call to a shader function "); 3021 } 3022 3023 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3024 CallConv != CallingConv::AMDGPU_Gfx) { 3025 // Only allow calls with specific calling conventions. 3026 return lowerUnhandledCall(CLI, InVals, 3027 "unsupported calling convention for call from " 3028 "graphics shader of function "); 3029 } 3030 3031 if (IsTailCall) { 3032 IsTailCall = isEligibleForTailCallOptimization( 3033 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3034 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3035 report_fatal_error("failed to perform tail call elimination on a call " 3036 "site marked musttail"); 3037 } 3038 3039 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3040 3041 // A sibling call is one where we're under the usual C ABI and not planning 3042 // to change that but can still do a tail call: 3043 if (!TailCallOpt && IsTailCall) 3044 IsSibCall = true; 3045 3046 if (IsTailCall) 3047 ++NumTailCalls; 3048 } 3049 3050 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3051 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3052 SmallVector<SDValue, 8> MemOpChains; 3053 3054 // Analyze operands of the call, assigning locations to each operand. 3055 SmallVector<CCValAssign, 16> ArgLocs; 3056 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3057 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3058 3059 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3060 CallConv != CallingConv::AMDGPU_Gfx) { 3061 // With a fixed ABI, allocate fixed registers before user arguments. 3062 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3063 } 3064 3065 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3066 3067 // Get a count of how many bytes are to be pushed on the stack. 3068 unsigned NumBytes = CCInfo.getNextStackOffset(); 3069 3070 if (IsSibCall) { 3071 // Since we're not changing the ABI to make this a tail call, the memory 3072 // operands are already available in the caller's incoming argument space. 3073 NumBytes = 0; 3074 } 3075 3076 // FPDiff is the byte offset of the call's argument area from the callee's. 3077 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3078 // by this amount for a tail call. In a sibling call it must be 0 because the 3079 // caller will deallocate the entire stack and the callee still expects its 3080 // arguments to begin at SP+0. Completely unused for non-tail calls. 3081 int32_t FPDiff = 0; 3082 MachineFrameInfo &MFI = MF.getFrameInfo(); 3083 3084 // Adjust the stack pointer for the new arguments... 3085 // These operations are automatically eliminated by the prolog/epilog pass 3086 if (!IsSibCall) { 3087 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3088 3089 if (!Subtarget->enableFlatScratch()) { 3090 SmallVector<SDValue, 4> CopyFromChains; 3091 3092 // In the HSA case, this should be an identity copy. 3093 SDValue ScratchRSrcReg 3094 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3095 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3096 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3097 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3098 } 3099 } 3100 3101 MVT PtrVT = MVT::i32; 3102 3103 // Walk the register/memloc assignments, inserting copies/loads. 3104 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3105 CCValAssign &VA = ArgLocs[i]; 3106 SDValue Arg = OutVals[i]; 3107 3108 // Promote the value if needed. 3109 switch (VA.getLocInfo()) { 3110 case CCValAssign::Full: 3111 break; 3112 case CCValAssign::BCvt: 3113 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3114 break; 3115 case CCValAssign::ZExt: 3116 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3117 break; 3118 case CCValAssign::SExt: 3119 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3120 break; 3121 case CCValAssign::AExt: 3122 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3123 break; 3124 case CCValAssign::FPExt: 3125 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3126 break; 3127 default: 3128 llvm_unreachable("Unknown loc info!"); 3129 } 3130 3131 if (VA.isRegLoc()) { 3132 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3133 } else { 3134 assert(VA.isMemLoc()); 3135 3136 SDValue DstAddr; 3137 MachinePointerInfo DstInfo; 3138 3139 unsigned LocMemOffset = VA.getLocMemOffset(); 3140 int32_t Offset = LocMemOffset; 3141 3142 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3143 MaybeAlign Alignment; 3144 3145 if (IsTailCall) { 3146 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3147 unsigned OpSize = Flags.isByVal() ? 3148 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3149 3150 // FIXME: We can have better than the minimum byval required alignment. 3151 Alignment = 3152 Flags.isByVal() 3153 ? Flags.getNonZeroByValAlign() 3154 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3155 3156 Offset = Offset + FPDiff; 3157 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3158 3159 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3160 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3161 3162 // Make sure any stack arguments overlapping with where we're storing 3163 // are loaded before this eventual operation. Otherwise they'll be 3164 // clobbered. 3165 3166 // FIXME: Why is this really necessary? This seems to just result in a 3167 // lot of code to copy the stack and write them back to the same 3168 // locations, which are supposed to be immutable? 3169 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3170 } else { 3171 // Stores to the argument stack area are relative to the stack pointer. 3172 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3173 MVT::i32); 3174 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3175 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3176 Alignment = 3177 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3178 } 3179 3180 if (Outs[i].Flags.isByVal()) { 3181 SDValue SizeNode = 3182 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3183 SDValue Cpy = 3184 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3185 Outs[i].Flags.getNonZeroByValAlign(), 3186 /*isVol = */ false, /*AlwaysInline = */ true, 3187 /*isTailCall = */ false, DstInfo, 3188 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3189 3190 MemOpChains.push_back(Cpy); 3191 } else { 3192 SDValue Store = 3193 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3194 MemOpChains.push_back(Store); 3195 } 3196 } 3197 } 3198 3199 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3200 CallConv != CallingConv::AMDGPU_Gfx) { 3201 // Copy special input registers after user input arguments. 3202 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3203 } 3204 3205 if (!MemOpChains.empty()) 3206 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3207 3208 // Build a sequence of copy-to-reg nodes chained together with token chain 3209 // and flag operands which copy the outgoing args into the appropriate regs. 3210 SDValue InFlag; 3211 for (auto &RegToPass : RegsToPass) { 3212 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3213 RegToPass.second, InFlag); 3214 InFlag = Chain.getValue(1); 3215 } 3216 3217 3218 SDValue PhysReturnAddrReg; 3219 if (IsTailCall) { 3220 // Since the return is being combined with the call, we need to pass on the 3221 // return address. 3222 3223 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3224 SDValue ReturnAddrReg = CreateLiveInRegister( 3225 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3226 3227 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3228 MVT::i64); 3229 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3230 InFlag = Chain.getValue(1); 3231 } 3232 3233 // We don't usually want to end the call-sequence here because we would tidy 3234 // the frame up *after* the call, however in the ABI-changing tail-call case 3235 // we've carefully laid out the parameters so that when sp is reset they'll be 3236 // in the correct location. 3237 if (IsTailCall && !IsSibCall) { 3238 Chain = DAG.getCALLSEQ_END(Chain, 3239 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3240 DAG.getTargetConstant(0, DL, MVT::i32), 3241 InFlag, DL); 3242 InFlag = Chain.getValue(1); 3243 } 3244 3245 std::vector<SDValue> Ops; 3246 Ops.push_back(Chain); 3247 Ops.push_back(Callee); 3248 // Add a redundant copy of the callee global which will not be legalized, as 3249 // we need direct access to the callee later. 3250 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3251 const GlobalValue *GV = GSD->getGlobal(); 3252 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3253 } else { 3254 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3255 } 3256 3257 if (IsTailCall) { 3258 // Each tail call may have to adjust the stack by a different amount, so 3259 // this information must travel along with the operation for eventual 3260 // consumption by emitEpilogue. 3261 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3262 3263 Ops.push_back(PhysReturnAddrReg); 3264 } 3265 3266 // Add argument registers to the end of the list so that they are known live 3267 // into the call. 3268 for (auto &RegToPass : RegsToPass) { 3269 Ops.push_back(DAG.getRegister(RegToPass.first, 3270 RegToPass.second.getValueType())); 3271 } 3272 3273 // Add a register mask operand representing the call-preserved registers. 3274 3275 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3276 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3277 assert(Mask && "Missing call preserved mask for calling convention"); 3278 Ops.push_back(DAG.getRegisterMask(Mask)); 3279 3280 if (InFlag.getNode()) 3281 Ops.push_back(InFlag); 3282 3283 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3284 3285 // If we're doing a tall call, use a TC_RETURN here rather than an 3286 // actual call instruction. 3287 if (IsTailCall) { 3288 MFI.setHasTailCall(); 3289 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3290 } 3291 3292 // Returns a chain and a flag for retval copy to use. 3293 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3294 Chain = Call.getValue(0); 3295 InFlag = Call.getValue(1); 3296 3297 uint64_t CalleePopBytes = NumBytes; 3298 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3299 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3300 InFlag, DL); 3301 if (!Ins.empty()) 3302 InFlag = Chain.getValue(1); 3303 3304 // Handle result values, copying them out of physregs into vregs that we 3305 // return. 3306 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3307 InVals, IsThisReturn, 3308 IsThisReturn ? OutVals[0] : SDValue()); 3309 } 3310 3311 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3312 // except for applying the wave size scale to the increment amount. 3313 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3314 SDValue Op, SelectionDAG &DAG) const { 3315 const MachineFunction &MF = DAG.getMachineFunction(); 3316 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3317 3318 SDLoc dl(Op); 3319 EVT VT = Op.getValueType(); 3320 SDValue Tmp1 = Op; 3321 SDValue Tmp2 = Op.getValue(1); 3322 SDValue Tmp3 = Op.getOperand(2); 3323 SDValue Chain = Tmp1.getOperand(0); 3324 3325 Register SPReg = Info->getStackPtrOffsetReg(); 3326 3327 // Chain the dynamic stack allocation so that it doesn't modify the stack 3328 // pointer when other instructions are using the stack. 3329 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3330 3331 SDValue Size = Tmp2.getOperand(1); 3332 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3333 Chain = SP.getValue(1); 3334 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3335 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3336 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3337 unsigned Opc = 3338 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3339 ISD::ADD : ISD::SUB; 3340 3341 SDValue ScaledSize = DAG.getNode( 3342 ISD::SHL, dl, VT, Size, 3343 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3344 3345 Align StackAlign = TFL->getStackAlign(); 3346 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3347 if (Alignment && *Alignment > StackAlign) { 3348 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3349 DAG.getConstant(-(uint64_t)Alignment->value() 3350 << ST.getWavefrontSizeLog2(), 3351 dl, VT)); 3352 } 3353 3354 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3355 Tmp2 = DAG.getCALLSEQ_END( 3356 Chain, DAG.getIntPtrConstant(0, dl, true), 3357 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3358 3359 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3360 } 3361 3362 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3363 SelectionDAG &DAG) const { 3364 // We only handle constant sizes here to allow non-entry block, static sized 3365 // allocas. A truly dynamic value is more difficult to support because we 3366 // don't know if the size value is uniform or not. If the size isn't uniform, 3367 // we would need to do a wave reduction to get the maximum size to know how 3368 // much to increment the uniform stack pointer. 3369 SDValue Size = Op.getOperand(1); 3370 if (isa<ConstantSDNode>(Size)) 3371 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3372 3373 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3374 } 3375 3376 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3377 const MachineFunction &MF) const { 3378 Register Reg = StringSwitch<Register>(RegName) 3379 .Case("m0", AMDGPU::M0) 3380 .Case("exec", AMDGPU::EXEC) 3381 .Case("exec_lo", AMDGPU::EXEC_LO) 3382 .Case("exec_hi", AMDGPU::EXEC_HI) 3383 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3384 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3385 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3386 .Default(Register()); 3387 3388 if (Reg == AMDGPU::NoRegister) { 3389 report_fatal_error(Twine("invalid register name \"" 3390 + StringRef(RegName) + "\".")); 3391 3392 } 3393 3394 if (!Subtarget->hasFlatScrRegister() && 3395 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3396 report_fatal_error(Twine("invalid register \"" 3397 + StringRef(RegName) + "\" for subtarget.")); 3398 } 3399 3400 switch (Reg) { 3401 case AMDGPU::M0: 3402 case AMDGPU::EXEC_LO: 3403 case AMDGPU::EXEC_HI: 3404 case AMDGPU::FLAT_SCR_LO: 3405 case AMDGPU::FLAT_SCR_HI: 3406 if (VT.getSizeInBits() == 32) 3407 return Reg; 3408 break; 3409 case AMDGPU::EXEC: 3410 case AMDGPU::FLAT_SCR: 3411 if (VT.getSizeInBits() == 64) 3412 return Reg; 3413 break; 3414 default: 3415 llvm_unreachable("missing register type checking"); 3416 } 3417 3418 report_fatal_error(Twine("invalid type for register \"" 3419 + StringRef(RegName) + "\".")); 3420 } 3421 3422 // If kill is not the last instruction, split the block so kill is always a 3423 // proper terminator. 3424 MachineBasicBlock * 3425 SITargetLowering::splitKillBlock(MachineInstr &MI, 3426 MachineBasicBlock *BB) const { 3427 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3428 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3429 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3430 return SplitBB; 3431 } 3432 3433 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3434 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3435 // be the first instruction in the remainder block. 3436 // 3437 /// \returns { LoopBody, Remainder } 3438 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3439 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3440 MachineFunction *MF = MBB.getParent(); 3441 MachineBasicBlock::iterator I(&MI); 3442 3443 // To insert the loop we need to split the block. Move everything after this 3444 // point to a new block, and insert a new empty block between the two. 3445 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3446 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3447 MachineFunction::iterator MBBI(MBB); 3448 ++MBBI; 3449 3450 MF->insert(MBBI, LoopBB); 3451 MF->insert(MBBI, RemainderBB); 3452 3453 LoopBB->addSuccessor(LoopBB); 3454 LoopBB->addSuccessor(RemainderBB); 3455 3456 // Move the rest of the block into a new block. 3457 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3458 3459 if (InstInLoop) { 3460 auto Next = std::next(I); 3461 3462 // Move instruction to loop body. 3463 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3464 3465 // Move the rest of the block. 3466 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3467 } else { 3468 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3469 } 3470 3471 MBB.addSuccessor(LoopBB); 3472 3473 return std::make_pair(LoopBB, RemainderBB); 3474 } 3475 3476 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3477 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3478 MachineBasicBlock *MBB = MI.getParent(); 3479 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3480 auto I = MI.getIterator(); 3481 auto E = std::next(I); 3482 3483 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3484 .addImm(0); 3485 3486 MIBundleBuilder Bundler(*MBB, I, E); 3487 finalizeBundle(*MBB, Bundler.begin()); 3488 } 3489 3490 MachineBasicBlock * 3491 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3492 MachineBasicBlock *BB) const { 3493 const DebugLoc &DL = MI.getDebugLoc(); 3494 3495 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3496 3497 MachineBasicBlock *LoopBB; 3498 MachineBasicBlock *RemainderBB; 3499 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3500 3501 // Apparently kill flags are only valid if the def is in the same block? 3502 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3503 Src->setIsKill(false); 3504 3505 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3506 3507 MachineBasicBlock::iterator I = LoopBB->end(); 3508 3509 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3510 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3511 3512 // Clear TRAP_STS.MEM_VIOL 3513 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3514 .addImm(0) 3515 .addImm(EncodedReg); 3516 3517 bundleInstWithWaitcnt(MI); 3518 3519 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3520 3521 // Load and check TRAP_STS.MEM_VIOL 3522 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3523 .addImm(EncodedReg); 3524 3525 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3526 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3527 .addReg(Reg, RegState::Kill) 3528 .addImm(0); 3529 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3530 .addMBB(LoopBB); 3531 3532 return RemainderBB; 3533 } 3534 3535 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3536 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3537 // will only do one iteration. In the worst case, this will loop 64 times. 3538 // 3539 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3540 static MachineBasicBlock::iterator 3541 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3542 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3543 const DebugLoc &DL, const MachineOperand &Idx, 3544 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3545 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3546 Register &SGPRIdxReg) { 3547 3548 MachineFunction *MF = OrigBB.getParent(); 3549 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3550 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3551 MachineBasicBlock::iterator I = LoopBB.begin(); 3552 3553 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3554 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3555 Register NewExec = MRI.createVirtualRegister(BoolRC); 3556 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3557 Register CondReg = MRI.createVirtualRegister(BoolRC); 3558 3559 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3560 .addReg(InitReg) 3561 .addMBB(&OrigBB) 3562 .addReg(ResultReg) 3563 .addMBB(&LoopBB); 3564 3565 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3566 .addReg(InitSaveExecReg) 3567 .addMBB(&OrigBB) 3568 .addReg(NewExec) 3569 .addMBB(&LoopBB); 3570 3571 // Read the next variant <- also loop target. 3572 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3573 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3574 3575 // Compare the just read M0 value to all possible Idx values. 3576 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3577 .addReg(CurrentIdxReg) 3578 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3579 3580 // Update EXEC, save the original EXEC value to VCC. 3581 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3582 : AMDGPU::S_AND_SAVEEXEC_B64), 3583 NewExec) 3584 .addReg(CondReg, RegState::Kill); 3585 3586 MRI.setSimpleHint(NewExec, CondReg); 3587 3588 if (UseGPRIdxMode) { 3589 if (Offset == 0) { 3590 SGPRIdxReg = CurrentIdxReg; 3591 } else { 3592 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3593 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3594 .addReg(CurrentIdxReg, RegState::Kill) 3595 .addImm(Offset); 3596 } 3597 } else { 3598 // Move index from VCC into M0 3599 if (Offset == 0) { 3600 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3601 .addReg(CurrentIdxReg, RegState::Kill); 3602 } else { 3603 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3604 .addReg(CurrentIdxReg, RegState::Kill) 3605 .addImm(Offset); 3606 } 3607 } 3608 3609 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3610 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3611 MachineInstr *InsertPt = 3612 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3613 : AMDGPU::S_XOR_B64_term), Exec) 3614 .addReg(Exec) 3615 .addReg(NewExec); 3616 3617 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3618 // s_cbranch_scc0? 3619 3620 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3621 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3622 .addMBB(&LoopBB); 3623 3624 return InsertPt->getIterator(); 3625 } 3626 3627 // This has slightly sub-optimal regalloc when the source vector is killed by 3628 // the read. The register allocator does not understand that the kill is 3629 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3630 // subregister from it, using 1 more VGPR than necessary. This was saved when 3631 // this was expanded after register allocation. 3632 static MachineBasicBlock::iterator 3633 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3634 unsigned InitResultReg, unsigned PhiReg, int Offset, 3635 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3636 MachineFunction *MF = MBB.getParent(); 3637 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3638 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3639 MachineRegisterInfo &MRI = MF->getRegInfo(); 3640 const DebugLoc &DL = MI.getDebugLoc(); 3641 MachineBasicBlock::iterator I(&MI); 3642 3643 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3644 Register DstReg = MI.getOperand(0).getReg(); 3645 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3646 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3647 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3648 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3649 3650 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3651 3652 // Save the EXEC mask 3653 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3654 .addReg(Exec); 3655 3656 MachineBasicBlock *LoopBB; 3657 MachineBasicBlock *RemainderBB; 3658 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3659 3660 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3661 3662 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3663 InitResultReg, DstReg, PhiReg, TmpExec, 3664 Offset, UseGPRIdxMode, SGPRIdxReg); 3665 3666 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3667 MachineFunction::iterator MBBI(LoopBB); 3668 ++MBBI; 3669 MF->insert(MBBI, LandingPad); 3670 LoopBB->removeSuccessor(RemainderBB); 3671 LandingPad->addSuccessor(RemainderBB); 3672 LoopBB->addSuccessor(LandingPad); 3673 MachineBasicBlock::iterator First = LandingPad->begin(); 3674 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3675 .addReg(SaveExec); 3676 3677 return InsPt; 3678 } 3679 3680 // Returns subreg index, offset 3681 static std::pair<unsigned, int> 3682 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3683 const TargetRegisterClass *SuperRC, 3684 unsigned VecReg, 3685 int Offset) { 3686 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3687 3688 // Skip out of bounds offsets, or else we would end up using an undefined 3689 // register. 3690 if (Offset >= NumElts || Offset < 0) 3691 return std::make_pair(AMDGPU::sub0, Offset); 3692 3693 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3694 } 3695 3696 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3697 MachineRegisterInfo &MRI, MachineInstr &MI, 3698 int Offset) { 3699 MachineBasicBlock *MBB = MI.getParent(); 3700 const DebugLoc &DL = MI.getDebugLoc(); 3701 MachineBasicBlock::iterator I(&MI); 3702 3703 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3704 3705 assert(Idx->getReg() != AMDGPU::NoRegister); 3706 3707 if (Offset == 0) { 3708 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3709 } else { 3710 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3711 .add(*Idx) 3712 .addImm(Offset); 3713 } 3714 } 3715 3716 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3717 MachineRegisterInfo &MRI, MachineInstr &MI, 3718 int Offset) { 3719 MachineBasicBlock *MBB = MI.getParent(); 3720 const DebugLoc &DL = MI.getDebugLoc(); 3721 MachineBasicBlock::iterator I(&MI); 3722 3723 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3724 3725 if (Offset == 0) 3726 return Idx->getReg(); 3727 3728 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3729 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3730 .add(*Idx) 3731 .addImm(Offset); 3732 return Tmp; 3733 } 3734 3735 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3736 MachineBasicBlock &MBB, 3737 const GCNSubtarget &ST) { 3738 const SIInstrInfo *TII = ST.getInstrInfo(); 3739 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3740 MachineFunction *MF = MBB.getParent(); 3741 MachineRegisterInfo &MRI = MF->getRegInfo(); 3742 3743 Register Dst = MI.getOperand(0).getReg(); 3744 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3745 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3746 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3747 3748 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3749 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3750 3751 unsigned SubReg; 3752 std::tie(SubReg, Offset) 3753 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3754 3755 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3756 3757 // Check for a SGPR index. 3758 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3759 MachineBasicBlock::iterator I(&MI); 3760 const DebugLoc &DL = MI.getDebugLoc(); 3761 3762 if (UseGPRIdxMode) { 3763 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3764 // to avoid interfering with other uses, so probably requires a new 3765 // optimization pass. 3766 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3767 3768 const MCInstrDesc &GPRIDXDesc = 3769 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3770 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3771 .addReg(SrcReg) 3772 .addReg(Idx) 3773 .addImm(SubReg); 3774 } else { 3775 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3776 3777 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3778 .addReg(SrcReg, 0, SubReg) 3779 .addReg(SrcReg, RegState::Implicit); 3780 } 3781 3782 MI.eraseFromParent(); 3783 3784 return &MBB; 3785 } 3786 3787 // Control flow needs to be inserted if indexing with a VGPR. 3788 const DebugLoc &DL = MI.getDebugLoc(); 3789 MachineBasicBlock::iterator I(&MI); 3790 3791 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3792 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3793 3794 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3795 3796 Register SGPRIdxReg; 3797 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3798 UseGPRIdxMode, SGPRIdxReg); 3799 3800 MachineBasicBlock *LoopBB = InsPt->getParent(); 3801 3802 if (UseGPRIdxMode) { 3803 const MCInstrDesc &GPRIDXDesc = 3804 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3805 3806 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3807 .addReg(SrcReg) 3808 .addReg(SGPRIdxReg) 3809 .addImm(SubReg); 3810 } else { 3811 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3812 .addReg(SrcReg, 0, SubReg) 3813 .addReg(SrcReg, RegState::Implicit); 3814 } 3815 3816 MI.eraseFromParent(); 3817 3818 return LoopBB; 3819 } 3820 3821 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3822 MachineBasicBlock &MBB, 3823 const GCNSubtarget &ST) { 3824 const SIInstrInfo *TII = ST.getInstrInfo(); 3825 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3826 MachineFunction *MF = MBB.getParent(); 3827 MachineRegisterInfo &MRI = MF->getRegInfo(); 3828 3829 Register Dst = MI.getOperand(0).getReg(); 3830 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3831 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3832 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3833 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3834 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3835 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3836 3837 // This can be an immediate, but will be folded later. 3838 assert(Val->getReg()); 3839 3840 unsigned SubReg; 3841 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3842 SrcVec->getReg(), 3843 Offset); 3844 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3845 3846 if (Idx->getReg() == AMDGPU::NoRegister) { 3847 MachineBasicBlock::iterator I(&MI); 3848 const DebugLoc &DL = MI.getDebugLoc(); 3849 3850 assert(Offset == 0); 3851 3852 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3853 .add(*SrcVec) 3854 .add(*Val) 3855 .addImm(SubReg); 3856 3857 MI.eraseFromParent(); 3858 return &MBB; 3859 } 3860 3861 // Check for a SGPR index. 3862 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3863 MachineBasicBlock::iterator I(&MI); 3864 const DebugLoc &DL = MI.getDebugLoc(); 3865 3866 if (UseGPRIdxMode) { 3867 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3868 3869 const MCInstrDesc &GPRIDXDesc = 3870 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3871 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3872 .addReg(SrcVec->getReg()) 3873 .add(*Val) 3874 .addReg(Idx) 3875 .addImm(SubReg); 3876 } else { 3877 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3878 3879 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3880 TRI.getRegSizeInBits(*VecRC), 32, false); 3881 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3882 .addReg(SrcVec->getReg()) 3883 .add(*Val) 3884 .addImm(SubReg); 3885 } 3886 MI.eraseFromParent(); 3887 return &MBB; 3888 } 3889 3890 // Control flow needs to be inserted if indexing with a VGPR. 3891 if (Val->isReg()) 3892 MRI.clearKillFlags(Val->getReg()); 3893 3894 const DebugLoc &DL = MI.getDebugLoc(); 3895 3896 Register PhiReg = MRI.createVirtualRegister(VecRC); 3897 3898 Register SGPRIdxReg; 3899 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3900 UseGPRIdxMode, SGPRIdxReg); 3901 MachineBasicBlock *LoopBB = InsPt->getParent(); 3902 3903 if (UseGPRIdxMode) { 3904 const MCInstrDesc &GPRIDXDesc = 3905 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3906 3907 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3908 .addReg(PhiReg) 3909 .add(*Val) 3910 .addReg(SGPRIdxReg) 3911 .addImm(AMDGPU::sub0); 3912 } else { 3913 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3914 TRI.getRegSizeInBits(*VecRC), 32, false); 3915 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3916 .addReg(PhiReg) 3917 .add(*Val) 3918 .addImm(AMDGPU::sub0); 3919 } 3920 3921 MI.eraseFromParent(); 3922 return LoopBB; 3923 } 3924 3925 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3926 MachineInstr &MI, MachineBasicBlock *BB) const { 3927 3928 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3929 MachineFunction *MF = BB->getParent(); 3930 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3931 3932 switch (MI.getOpcode()) { 3933 case AMDGPU::S_UADDO_PSEUDO: 3934 case AMDGPU::S_USUBO_PSEUDO: { 3935 const DebugLoc &DL = MI.getDebugLoc(); 3936 MachineOperand &Dest0 = MI.getOperand(0); 3937 MachineOperand &Dest1 = MI.getOperand(1); 3938 MachineOperand &Src0 = MI.getOperand(2); 3939 MachineOperand &Src1 = MI.getOperand(3); 3940 3941 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3942 ? AMDGPU::S_ADD_I32 3943 : AMDGPU::S_SUB_I32; 3944 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3945 3946 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3947 .addImm(1) 3948 .addImm(0); 3949 3950 MI.eraseFromParent(); 3951 return BB; 3952 } 3953 case AMDGPU::S_ADD_U64_PSEUDO: 3954 case AMDGPU::S_SUB_U64_PSEUDO: { 3955 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3956 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3957 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3958 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3959 const DebugLoc &DL = MI.getDebugLoc(); 3960 3961 MachineOperand &Dest = MI.getOperand(0); 3962 MachineOperand &Src0 = MI.getOperand(1); 3963 MachineOperand &Src1 = MI.getOperand(2); 3964 3965 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3966 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3967 3968 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3969 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3970 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3971 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3972 3973 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3974 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3975 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3976 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3977 3978 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3979 3980 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3981 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3982 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3983 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3984 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3985 .addReg(DestSub0) 3986 .addImm(AMDGPU::sub0) 3987 .addReg(DestSub1) 3988 .addImm(AMDGPU::sub1); 3989 MI.eraseFromParent(); 3990 return BB; 3991 } 3992 case AMDGPU::V_ADD_U64_PSEUDO: 3993 case AMDGPU::V_SUB_U64_PSEUDO: { 3994 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3995 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3996 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3997 const DebugLoc &DL = MI.getDebugLoc(); 3998 3999 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4000 4001 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4002 4003 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4004 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4005 4006 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4007 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4008 4009 MachineOperand &Dest = MI.getOperand(0); 4010 MachineOperand &Src0 = MI.getOperand(1); 4011 MachineOperand &Src1 = MI.getOperand(2); 4012 4013 const TargetRegisterClass *Src0RC = Src0.isReg() 4014 ? MRI.getRegClass(Src0.getReg()) 4015 : &AMDGPU::VReg_64RegClass; 4016 const TargetRegisterClass *Src1RC = Src1.isReg() 4017 ? MRI.getRegClass(Src1.getReg()) 4018 : &AMDGPU::VReg_64RegClass; 4019 4020 const TargetRegisterClass *Src0SubRC = 4021 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4022 const TargetRegisterClass *Src1SubRC = 4023 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4024 4025 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4026 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4027 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4028 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4029 4030 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4031 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4032 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4033 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4034 4035 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4036 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4037 .addReg(CarryReg, RegState::Define) 4038 .add(SrcReg0Sub0) 4039 .add(SrcReg1Sub0) 4040 .addImm(0); // clamp bit 4041 4042 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4043 MachineInstr *HiHalf = 4044 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4045 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4046 .add(SrcReg0Sub1) 4047 .add(SrcReg1Sub1) 4048 .addReg(CarryReg, RegState::Kill) 4049 .addImm(0); // clamp bit 4050 4051 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4052 .addReg(DestSub0) 4053 .addImm(AMDGPU::sub0) 4054 .addReg(DestSub1) 4055 .addImm(AMDGPU::sub1); 4056 TII->legalizeOperands(*LoHalf); 4057 TII->legalizeOperands(*HiHalf); 4058 MI.eraseFromParent(); 4059 return BB; 4060 } 4061 case AMDGPU::S_ADD_CO_PSEUDO: 4062 case AMDGPU::S_SUB_CO_PSEUDO: { 4063 // This pseudo has a chance to be selected 4064 // only from uniform add/subcarry node. All the VGPR operands 4065 // therefore assumed to be splat vectors. 4066 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4067 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4068 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4069 MachineBasicBlock::iterator MII = MI; 4070 const DebugLoc &DL = MI.getDebugLoc(); 4071 MachineOperand &Dest = MI.getOperand(0); 4072 MachineOperand &CarryDest = MI.getOperand(1); 4073 MachineOperand &Src0 = MI.getOperand(2); 4074 MachineOperand &Src1 = MI.getOperand(3); 4075 MachineOperand &Src2 = MI.getOperand(4); 4076 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4077 ? AMDGPU::S_ADDC_U32 4078 : AMDGPU::S_SUBB_U32; 4079 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4080 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4081 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4082 .addReg(Src0.getReg()); 4083 Src0.setReg(RegOp0); 4084 } 4085 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4086 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4087 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4088 .addReg(Src1.getReg()); 4089 Src1.setReg(RegOp1); 4090 } 4091 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4092 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4093 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4094 .addReg(Src2.getReg()); 4095 Src2.setReg(RegOp2); 4096 } 4097 4098 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4099 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4100 if (ST.hasScalarCompareEq64()) { 4101 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4102 .addReg(Src2.getReg()) 4103 .addImm(0); 4104 } else { 4105 const TargetRegisterClass *SubRC = 4106 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4107 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4108 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4109 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4110 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4111 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4112 4113 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4114 .add(Src2Sub0) 4115 .add(Src2Sub1); 4116 4117 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4118 .addReg(Src2_32, RegState::Kill) 4119 .addImm(0); 4120 } 4121 } else { 4122 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4123 .addReg(Src2.getReg()) 4124 .addImm(0); 4125 } 4126 4127 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4128 4129 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4130 .addReg(AMDGPU::SCC); 4131 MI.eraseFromParent(); 4132 return BB; 4133 } 4134 case AMDGPU::SI_INIT_M0: { 4135 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4136 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4137 .add(MI.getOperand(0)); 4138 MI.eraseFromParent(); 4139 return BB; 4140 } 4141 case AMDGPU::GET_GROUPSTATICSIZE: { 4142 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4143 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4144 DebugLoc DL = MI.getDebugLoc(); 4145 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4146 .add(MI.getOperand(0)) 4147 .addImm(MFI->getLDSSize()); 4148 MI.eraseFromParent(); 4149 return BB; 4150 } 4151 case AMDGPU::SI_INDIRECT_SRC_V1: 4152 case AMDGPU::SI_INDIRECT_SRC_V2: 4153 case AMDGPU::SI_INDIRECT_SRC_V4: 4154 case AMDGPU::SI_INDIRECT_SRC_V8: 4155 case AMDGPU::SI_INDIRECT_SRC_V16: 4156 case AMDGPU::SI_INDIRECT_SRC_V32: 4157 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4158 case AMDGPU::SI_INDIRECT_DST_V1: 4159 case AMDGPU::SI_INDIRECT_DST_V2: 4160 case AMDGPU::SI_INDIRECT_DST_V4: 4161 case AMDGPU::SI_INDIRECT_DST_V8: 4162 case AMDGPU::SI_INDIRECT_DST_V16: 4163 case AMDGPU::SI_INDIRECT_DST_V32: 4164 return emitIndirectDst(MI, *BB, *getSubtarget()); 4165 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4166 case AMDGPU::SI_KILL_I1_PSEUDO: 4167 return splitKillBlock(MI, BB); 4168 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4169 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4170 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4171 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4172 4173 Register Dst = MI.getOperand(0).getReg(); 4174 Register Src0 = MI.getOperand(1).getReg(); 4175 Register Src1 = MI.getOperand(2).getReg(); 4176 const DebugLoc &DL = MI.getDebugLoc(); 4177 Register SrcCond = MI.getOperand(3).getReg(); 4178 4179 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4180 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4181 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4182 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4183 4184 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4185 .addReg(SrcCond); 4186 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4187 .addImm(0) 4188 .addReg(Src0, 0, AMDGPU::sub0) 4189 .addImm(0) 4190 .addReg(Src1, 0, AMDGPU::sub0) 4191 .addReg(SrcCondCopy); 4192 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4193 .addImm(0) 4194 .addReg(Src0, 0, AMDGPU::sub1) 4195 .addImm(0) 4196 .addReg(Src1, 0, AMDGPU::sub1) 4197 .addReg(SrcCondCopy); 4198 4199 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4200 .addReg(DstLo) 4201 .addImm(AMDGPU::sub0) 4202 .addReg(DstHi) 4203 .addImm(AMDGPU::sub1); 4204 MI.eraseFromParent(); 4205 return BB; 4206 } 4207 case AMDGPU::SI_BR_UNDEF: { 4208 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4209 const DebugLoc &DL = MI.getDebugLoc(); 4210 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4211 .add(MI.getOperand(0)); 4212 Br->getOperand(1).setIsUndef(true); // read undef SCC 4213 MI.eraseFromParent(); 4214 return BB; 4215 } 4216 case AMDGPU::ADJCALLSTACKUP: 4217 case AMDGPU::ADJCALLSTACKDOWN: { 4218 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4219 MachineInstrBuilder MIB(*MF, &MI); 4220 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4221 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4222 return BB; 4223 } 4224 case AMDGPU::SI_CALL_ISEL: { 4225 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4226 const DebugLoc &DL = MI.getDebugLoc(); 4227 4228 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4229 4230 MachineInstrBuilder MIB; 4231 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4232 4233 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4234 MIB.add(MI.getOperand(I)); 4235 4236 MIB.cloneMemRefs(MI); 4237 MI.eraseFromParent(); 4238 return BB; 4239 } 4240 case AMDGPU::V_ADD_CO_U32_e32: 4241 case AMDGPU::V_SUB_CO_U32_e32: 4242 case AMDGPU::V_SUBREV_CO_U32_e32: { 4243 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4244 const DebugLoc &DL = MI.getDebugLoc(); 4245 unsigned Opc = MI.getOpcode(); 4246 4247 bool NeedClampOperand = false; 4248 if (TII->pseudoToMCOpcode(Opc) == -1) { 4249 Opc = AMDGPU::getVOPe64(Opc); 4250 NeedClampOperand = true; 4251 } 4252 4253 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4254 if (TII->isVOP3(*I)) { 4255 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4256 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4257 I.addReg(TRI->getVCC(), RegState::Define); 4258 } 4259 I.add(MI.getOperand(1)) 4260 .add(MI.getOperand(2)); 4261 if (NeedClampOperand) 4262 I.addImm(0); // clamp bit for e64 encoding 4263 4264 TII->legalizeOperands(*I); 4265 4266 MI.eraseFromParent(); 4267 return BB; 4268 } 4269 case AMDGPU::V_ADDC_U32_e32: 4270 case AMDGPU::V_SUBB_U32_e32: 4271 case AMDGPU::V_SUBBREV_U32_e32: 4272 // These instructions have an implicit use of vcc which counts towards the 4273 // constant bus limit. 4274 TII->legalizeOperands(MI); 4275 return BB; 4276 case AMDGPU::DS_GWS_INIT: 4277 case AMDGPU::DS_GWS_SEMA_BR: 4278 case AMDGPU::DS_GWS_BARRIER: 4279 if (Subtarget->needsAlignedVGPRs()) { 4280 // Add implicit aligned super-reg to force alignment on the data operand. 4281 const DebugLoc &DL = MI.getDebugLoc(); 4282 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4283 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4284 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4285 Register DataReg = Op->getReg(); 4286 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4287 Register Undef = MRI.createVirtualRegister( 4288 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4289 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4290 Register NewVR = 4291 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4292 : &AMDGPU::VReg_64_Align2RegClass); 4293 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4294 .addReg(DataReg, 0, Op->getSubReg()) 4295 .addImm(AMDGPU::sub0) 4296 .addReg(Undef) 4297 .addImm(AMDGPU::sub1); 4298 Op->setReg(NewVR); 4299 Op->setSubReg(AMDGPU::sub0); 4300 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4301 } 4302 LLVM_FALLTHROUGH; 4303 case AMDGPU::DS_GWS_SEMA_V: 4304 case AMDGPU::DS_GWS_SEMA_P: 4305 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4306 // A s_waitcnt 0 is required to be the instruction immediately following. 4307 if (getSubtarget()->hasGWSAutoReplay()) { 4308 bundleInstWithWaitcnt(MI); 4309 return BB; 4310 } 4311 4312 return emitGWSMemViolTestLoop(MI, BB); 4313 case AMDGPU::S_SETREG_B32: { 4314 // Try to optimize cases that only set the denormal mode or rounding mode. 4315 // 4316 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4317 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4318 // instead. 4319 // 4320 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4321 // allow you to have a no side effect instruction in the output of a 4322 // sideeffecting pattern. 4323 unsigned ID, Offset, Width; 4324 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4325 if (ID != AMDGPU::Hwreg::ID_MODE) 4326 return BB; 4327 4328 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4329 const unsigned SetMask = WidthMask << Offset; 4330 4331 if (getSubtarget()->hasDenormModeInst()) { 4332 unsigned SetDenormOp = 0; 4333 unsigned SetRoundOp = 0; 4334 4335 // The dedicated instructions can only set the whole denorm or round mode 4336 // at once, not a subset of bits in either. 4337 if (SetMask == 4338 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4339 // If this fully sets both the round and denorm mode, emit the two 4340 // dedicated instructions for these. 4341 SetRoundOp = AMDGPU::S_ROUND_MODE; 4342 SetDenormOp = AMDGPU::S_DENORM_MODE; 4343 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4344 SetRoundOp = AMDGPU::S_ROUND_MODE; 4345 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4346 SetDenormOp = AMDGPU::S_DENORM_MODE; 4347 } 4348 4349 if (SetRoundOp || SetDenormOp) { 4350 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4351 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4352 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4353 unsigned ImmVal = Def->getOperand(1).getImm(); 4354 if (SetRoundOp) { 4355 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4356 .addImm(ImmVal & 0xf); 4357 4358 // If we also have the denorm mode, get just the denorm mode bits. 4359 ImmVal >>= 4; 4360 } 4361 4362 if (SetDenormOp) { 4363 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4364 .addImm(ImmVal & 0xf); 4365 } 4366 4367 MI.eraseFromParent(); 4368 return BB; 4369 } 4370 } 4371 } 4372 4373 // If only FP bits are touched, used the no side effects pseudo. 4374 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4375 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4376 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4377 4378 return BB; 4379 } 4380 default: 4381 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4382 } 4383 } 4384 4385 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4386 return isTypeLegal(VT.getScalarType()); 4387 } 4388 4389 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4390 // This currently forces unfolding various combinations of fsub into fma with 4391 // free fneg'd operands. As long as we have fast FMA (controlled by 4392 // isFMAFasterThanFMulAndFAdd), we should perform these. 4393 4394 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4395 // most of these combines appear to be cycle neutral but save on instruction 4396 // count / code size. 4397 return true; 4398 } 4399 4400 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4401 EVT VT) const { 4402 if (!VT.isVector()) { 4403 return MVT::i1; 4404 } 4405 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4406 } 4407 4408 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4409 // TODO: Should i16 be used always if legal? For now it would force VALU 4410 // shifts. 4411 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4412 } 4413 4414 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4415 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4416 ? Ty.changeElementSize(16) 4417 : Ty.changeElementSize(32); 4418 } 4419 4420 // Answering this is somewhat tricky and depends on the specific device which 4421 // have different rates for fma or all f64 operations. 4422 // 4423 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4424 // regardless of which device (although the number of cycles differs between 4425 // devices), so it is always profitable for f64. 4426 // 4427 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4428 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4429 // which we can always do even without fused FP ops since it returns the same 4430 // result as the separate operations and since it is always full 4431 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4432 // however does not support denormals, so we do report fma as faster if we have 4433 // a fast fma device and require denormals. 4434 // 4435 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4436 EVT VT) const { 4437 VT = VT.getScalarType(); 4438 4439 switch (VT.getSimpleVT().SimpleTy) { 4440 case MVT::f32: { 4441 // If mad is not available this depends only on if f32 fma is full rate. 4442 if (!Subtarget->hasMadMacF32Insts()) 4443 return Subtarget->hasFastFMAF32(); 4444 4445 // Otherwise f32 mad is always full rate and returns the same result as 4446 // the separate operations so should be preferred over fma. 4447 // However does not support denomals. 4448 if (hasFP32Denormals(MF)) 4449 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4450 4451 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4452 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4453 } 4454 case MVT::f64: 4455 return true; 4456 case MVT::f16: 4457 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4458 default: 4459 break; 4460 } 4461 4462 return false; 4463 } 4464 4465 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4466 const SDNode *N) const { 4467 // TODO: Check future ftz flag 4468 // v_mad_f32/v_mac_f32 do not support denormals. 4469 EVT VT = N->getValueType(0); 4470 if (VT == MVT::f32) 4471 return Subtarget->hasMadMacF32Insts() && 4472 !hasFP32Denormals(DAG.getMachineFunction()); 4473 if (VT == MVT::f16) { 4474 return Subtarget->hasMadF16() && 4475 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4476 } 4477 4478 return false; 4479 } 4480 4481 //===----------------------------------------------------------------------===// 4482 // Custom DAG Lowering Operations 4483 //===----------------------------------------------------------------------===// 4484 4485 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4486 // wider vector type is legal. 4487 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4488 SelectionDAG &DAG) const { 4489 unsigned Opc = Op.getOpcode(); 4490 EVT VT = Op.getValueType(); 4491 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4492 4493 SDValue Lo, Hi; 4494 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4495 4496 SDLoc SL(Op); 4497 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4498 Op->getFlags()); 4499 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4500 Op->getFlags()); 4501 4502 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4503 } 4504 4505 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4506 // wider vector type is legal. 4507 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4508 SelectionDAG &DAG) const { 4509 unsigned Opc = Op.getOpcode(); 4510 EVT VT = Op.getValueType(); 4511 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4512 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4513 4514 SDValue Lo0, Hi0; 4515 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4516 SDValue Lo1, Hi1; 4517 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4518 4519 SDLoc SL(Op); 4520 4521 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4522 Op->getFlags()); 4523 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4524 Op->getFlags()); 4525 4526 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4527 } 4528 4529 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4530 SelectionDAG &DAG) const { 4531 unsigned Opc = Op.getOpcode(); 4532 EVT VT = Op.getValueType(); 4533 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4534 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4535 4536 SDValue Lo0, Hi0; 4537 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4538 SDValue Lo1, Hi1; 4539 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4540 SDValue Lo2, Hi2; 4541 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4542 4543 SDLoc SL(Op); 4544 4545 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4546 Op->getFlags()); 4547 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4548 Op->getFlags()); 4549 4550 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4551 } 4552 4553 4554 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4555 switch (Op.getOpcode()) { 4556 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4557 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4558 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4559 case ISD::LOAD: { 4560 SDValue Result = LowerLOAD(Op, DAG); 4561 assert((!Result.getNode() || 4562 Result.getNode()->getNumValues() == 2) && 4563 "Load should return a value and a chain"); 4564 return Result; 4565 } 4566 4567 case ISD::FSIN: 4568 case ISD::FCOS: 4569 return LowerTrig(Op, DAG); 4570 case ISD::SELECT: return LowerSELECT(Op, DAG); 4571 case ISD::FDIV: return LowerFDIV(Op, DAG); 4572 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4573 case ISD::STORE: return LowerSTORE(Op, DAG); 4574 case ISD::GlobalAddress: { 4575 MachineFunction &MF = DAG.getMachineFunction(); 4576 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4577 return LowerGlobalAddress(MFI, Op, DAG); 4578 } 4579 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4580 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4581 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4582 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4583 case ISD::INSERT_SUBVECTOR: 4584 return lowerINSERT_SUBVECTOR(Op, DAG); 4585 case ISD::INSERT_VECTOR_ELT: 4586 return lowerINSERT_VECTOR_ELT(Op, DAG); 4587 case ISD::EXTRACT_VECTOR_ELT: 4588 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4589 case ISD::VECTOR_SHUFFLE: 4590 return lowerVECTOR_SHUFFLE(Op, DAG); 4591 case ISD::BUILD_VECTOR: 4592 return lowerBUILD_VECTOR(Op, DAG); 4593 case ISD::FP_ROUND: 4594 return lowerFP_ROUND(Op, DAG); 4595 case ISD::TRAP: 4596 return lowerTRAP(Op, DAG); 4597 case ISD::DEBUGTRAP: 4598 return lowerDEBUGTRAP(Op, DAG); 4599 case ISD::FABS: 4600 case ISD::FNEG: 4601 case ISD::FCANONICALIZE: 4602 case ISD::BSWAP: 4603 return splitUnaryVectorOp(Op, DAG); 4604 case ISD::FMINNUM: 4605 case ISD::FMAXNUM: 4606 return lowerFMINNUM_FMAXNUM(Op, DAG); 4607 case ISD::FMA: 4608 return splitTernaryVectorOp(Op, DAG); 4609 case ISD::FP_TO_SINT: 4610 case ISD::FP_TO_UINT: 4611 return LowerFP_TO_INT(Op, DAG); 4612 case ISD::SHL: 4613 case ISD::SRA: 4614 case ISD::SRL: 4615 case ISD::ADD: 4616 case ISD::SUB: 4617 case ISD::MUL: 4618 case ISD::SMIN: 4619 case ISD::SMAX: 4620 case ISD::UMIN: 4621 case ISD::UMAX: 4622 case ISD::FADD: 4623 case ISD::FMUL: 4624 case ISD::FMINNUM_IEEE: 4625 case ISD::FMAXNUM_IEEE: 4626 case ISD::UADDSAT: 4627 case ISD::USUBSAT: 4628 case ISD::SADDSAT: 4629 case ISD::SSUBSAT: 4630 return splitBinaryVectorOp(Op, DAG); 4631 case ISD::SMULO: 4632 case ISD::UMULO: 4633 return lowerXMULO(Op, DAG); 4634 case ISD::DYNAMIC_STACKALLOC: 4635 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4636 } 4637 return SDValue(); 4638 } 4639 4640 // Used for D16: Casts the result of an instruction into the right vector, 4641 // packs values if loads return unpacked values. 4642 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4643 const SDLoc &DL, 4644 SelectionDAG &DAG, bool Unpacked) { 4645 if (!LoadVT.isVector()) 4646 return Result; 4647 4648 // Cast back to the original packed type or to a larger type that is a 4649 // multiple of 32 bit for D16. Widening the return type is a required for 4650 // legalization. 4651 EVT FittingLoadVT = LoadVT; 4652 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4653 FittingLoadVT = 4654 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4655 LoadVT.getVectorNumElements() + 1); 4656 } 4657 4658 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4659 // Truncate to v2i16/v4i16. 4660 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4661 4662 // Workaround legalizer not scalarizing truncate after vector op 4663 // legalization but not creating intermediate vector trunc. 4664 SmallVector<SDValue, 4> Elts; 4665 DAG.ExtractVectorElements(Result, Elts); 4666 for (SDValue &Elt : Elts) 4667 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4668 4669 // Pad illegal v1i16/v3fi6 to v4i16 4670 if ((LoadVT.getVectorNumElements() % 2) == 1) 4671 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4672 4673 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4674 4675 // Bitcast to original type (v2f16/v4f16). 4676 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4677 } 4678 4679 // Cast back to the original packed type. 4680 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4681 } 4682 4683 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4684 MemSDNode *M, 4685 SelectionDAG &DAG, 4686 ArrayRef<SDValue> Ops, 4687 bool IsIntrinsic) const { 4688 SDLoc DL(M); 4689 4690 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4691 EVT LoadVT = M->getValueType(0); 4692 4693 EVT EquivLoadVT = LoadVT; 4694 if (LoadVT.isVector()) { 4695 if (Unpacked) { 4696 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4697 LoadVT.getVectorNumElements()); 4698 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4699 // Widen v3f16 to legal type 4700 EquivLoadVT = 4701 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4702 LoadVT.getVectorNumElements() + 1); 4703 } 4704 } 4705 4706 // Change from v4f16/v2f16 to EquivLoadVT. 4707 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4708 4709 SDValue Load 4710 = DAG.getMemIntrinsicNode( 4711 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4712 VTList, Ops, M->getMemoryVT(), 4713 M->getMemOperand()); 4714 4715 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4716 4717 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4718 } 4719 4720 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4721 SelectionDAG &DAG, 4722 ArrayRef<SDValue> Ops) const { 4723 SDLoc DL(M); 4724 EVT LoadVT = M->getValueType(0); 4725 EVT EltType = LoadVT.getScalarType(); 4726 EVT IntVT = LoadVT.changeTypeToInteger(); 4727 4728 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4729 4730 unsigned Opc = 4731 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4732 4733 if (IsD16) { 4734 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4735 } 4736 4737 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4738 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4739 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4740 4741 if (isTypeLegal(LoadVT)) { 4742 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4743 M->getMemOperand(), DAG); 4744 } 4745 4746 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4747 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4748 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4749 M->getMemOperand(), DAG); 4750 return DAG.getMergeValues( 4751 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4752 DL); 4753 } 4754 4755 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4756 SDNode *N, SelectionDAG &DAG) { 4757 EVT VT = N->getValueType(0); 4758 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4759 unsigned CondCode = CD->getZExtValue(); 4760 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4761 return DAG.getUNDEF(VT); 4762 4763 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4764 4765 SDValue LHS = N->getOperand(1); 4766 SDValue RHS = N->getOperand(2); 4767 4768 SDLoc DL(N); 4769 4770 EVT CmpVT = LHS.getValueType(); 4771 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4772 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4773 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4774 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4775 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4776 } 4777 4778 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4779 4780 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4781 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4782 4783 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4784 DAG.getCondCode(CCOpcode)); 4785 if (VT.bitsEq(CCVT)) 4786 return SetCC; 4787 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4788 } 4789 4790 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4791 SDNode *N, SelectionDAG &DAG) { 4792 EVT VT = N->getValueType(0); 4793 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4794 4795 unsigned CondCode = CD->getZExtValue(); 4796 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4797 return DAG.getUNDEF(VT); 4798 4799 SDValue Src0 = N->getOperand(1); 4800 SDValue Src1 = N->getOperand(2); 4801 EVT CmpVT = Src0.getValueType(); 4802 SDLoc SL(N); 4803 4804 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4805 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4806 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4807 } 4808 4809 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4810 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4811 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4812 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4813 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4814 Src1, DAG.getCondCode(CCOpcode)); 4815 if (VT.bitsEq(CCVT)) 4816 return SetCC; 4817 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4818 } 4819 4820 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4821 SelectionDAG &DAG) { 4822 EVT VT = N->getValueType(0); 4823 SDValue Src = N->getOperand(1); 4824 SDLoc SL(N); 4825 4826 if (Src.getOpcode() == ISD::SETCC) { 4827 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4828 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4829 Src.getOperand(1), Src.getOperand(2)); 4830 } 4831 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4832 // (ballot 0) -> 0 4833 if (Arg->isNullValue()) 4834 return DAG.getConstant(0, SL, VT); 4835 4836 // (ballot 1) -> EXEC/EXEC_LO 4837 if (Arg->isOne()) { 4838 Register Exec; 4839 if (VT.getScalarSizeInBits() == 32) 4840 Exec = AMDGPU::EXEC_LO; 4841 else if (VT.getScalarSizeInBits() == 64) 4842 Exec = AMDGPU::EXEC; 4843 else 4844 return SDValue(); 4845 4846 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4847 } 4848 } 4849 4850 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4851 // ISD::SETNE) 4852 return DAG.getNode( 4853 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4854 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4855 } 4856 4857 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4858 SmallVectorImpl<SDValue> &Results, 4859 SelectionDAG &DAG) const { 4860 switch (N->getOpcode()) { 4861 case ISD::INSERT_VECTOR_ELT: { 4862 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4863 Results.push_back(Res); 4864 return; 4865 } 4866 case ISD::EXTRACT_VECTOR_ELT: { 4867 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4868 Results.push_back(Res); 4869 return; 4870 } 4871 case ISD::INTRINSIC_WO_CHAIN: { 4872 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4873 switch (IID) { 4874 case Intrinsic::amdgcn_cvt_pkrtz: { 4875 SDValue Src0 = N->getOperand(1); 4876 SDValue Src1 = N->getOperand(2); 4877 SDLoc SL(N); 4878 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4879 Src0, Src1); 4880 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4881 return; 4882 } 4883 case Intrinsic::amdgcn_cvt_pknorm_i16: 4884 case Intrinsic::amdgcn_cvt_pknorm_u16: 4885 case Intrinsic::amdgcn_cvt_pk_i16: 4886 case Intrinsic::amdgcn_cvt_pk_u16: { 4887 SDValue Src0 = N->getOperand(1); 4888 SDValue Src1 = N->getOperand(2); 4889 SDLoc SL(N); 4890 unsigned Opcode; 4891 4892 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4893 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4894 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4895 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4896 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4897 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4898 else 4899 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4900 4901 EVT VT = N->getValueType(0); 4902 if (isTypeLegal(VT)) 4903 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4904 else { 4905 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4906 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4907 } 4908 return; 4909 } 4910 } 4911 break; 4912 } 4913 case ISD::INTRINSIC_W_CHAIN: { 4914 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4915 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4916 // FIXME: Hacky 4917 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4918 Results.push_back(Res.getOperand(I)); 4919 } 4920 } else { 4921 Results.push_back(Res); 4922 Results.push_back(Res.getValue(1)); 4923 } 4924 return; 4925 } 4926 4927 break; 4928 } 4929 case ISD::SELECT: { 4930 SDLoc SL(N); 4931 EVT VT = N->getValueType(0); 4932 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4933 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4934 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4935 4936 EVT SelectVT = NewVT; 4937 if (NewVT.bitsLT(MVT::i32)) { 4938 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4939 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4940 SelectVT = MVT::i32; 4941 } 4942 4943 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4944 N->getOperand(0), LHS, RHS); 4945 4946 if (NewVT != SelectVT) 4947 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4948 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4949 return; 4950 } 4951 case ISD::FNEG: { 4952 if (N->getValueType(0) != MVT::v2f16) 4953 break; 4954 4955 SDLoc SL(N); 4956 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4957 4958 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4959 BC, 4960 DAG.getConstant(0x80008000, SL, MVT::i32)); 4961 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4962 return; 4963 } 4964 case ISD::FABS: { 4965 if (N->getValueType(0) != MVT::v2f16) 4966 break; 4967 4968 SDLoc SL(N); 4969 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4970 4971 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4972 BC, 4973 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4974 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4975 return; 4976 } 4977 default: 4978 break; 4979 } 4980 } 4981 4982 /// Helper function for LowerBRCOND 4983 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4984 4985 SDNode *Parent = Value.getNode(); 4986 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4987 I != E; ++I) { 4988 4989 if (I.getUse().get() != Value) 4990 continue; 4991 4992 if (I->getOpcode() == Opcode) 4993 return *I; 4994 } 4995 return nullptr; 4996 } 4997 4998 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4999 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5000 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5001 case Intrinsic::amdgcn_if: 5002 return AMDGPUISD::IF; 5003 case Intrinsic::amdgcn_else: 5004 return AMDGPUISD::ELSE; 5005 case Intrinsic::amdgcn_loop: 5006 return AMDGPUISD::LOOP; 5007 case Intrinsic::amdgcn_end_cf: 5008 llvm_unreachable("should not occur"); 5009 default: 5010 return 0; 5011 } 5012 } 5013 5014 // break, if_break, else_break are all only used as inputs to loop, not 5015 // directly as branch conditions. 5016 return 0; 5017 } 5018 5019 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5020 const Triple &TT = getTargetMachine().getTargetTriple(); 5021 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5022 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5023 AMDGPU::shouldEmitConstantsToTextSection(TT); 5024 } 5025 5026 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5027 // FIXME: Either avoid relying on address space here or change the default 5028 // address space for functions to avoid the explicit check. 5029 return (GV->getValueType()->isFunctionTy() || 5030 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5031 !shouldEmitFixup(GV) && 5032 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5033 } 5034 5035 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5036 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5037 } 5038 5039 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5040 if (!GV->hasExternalLinkage()) 5041 return true; 5042 5043 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5044 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5045 } 5046 5047 /// This transforms the control flow intrinsics to get the branch destination as 5048 /// last parameter, also switches branch target with BR if the need arise 5049 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5050 SelectionDAG &DAG) const { 5051 SDLoc DL(BRCOND); 5052 5053 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5054 SDValue Target = BRCOND.getOperand(2); 5055 SDNode *BR = nullptr; 5056 SDNode *SetCC = nullptr; 5057 5058 if (Intr->getOpcode() == ISD::SETCC) { 5059 // As long as we negate the condition everything is fine 5060 SetCC = Intr; 5061 Intr = SetCC->getOperand(0).getNode(); 5062 5063 } else { 5064 // Get the target from BR if we don't negate the condition 5065 BR = findUser(BRCOND, ISD::BR); 5066 assert(BR && "brcond missing unconditional branch user"); 5067 Target = BR->getOperand(1); 5068 } 5069 5070 unsigned CFNode = isCFIntrinsic(Intr); 5071 if (CFNode == 0) { 5072 // This is a uniform branch so we don't need to legalize. 5073 return BRCOND; 5074 } 5075 5076 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5077 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5078 5079 assert(!SetCC || 5080 (SetCC->getConstantOperandVal(1) == 1 && 5081 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5082 ISD::SETNE)); 5083 5084 // operands of the new intrinsic call 5085 SmallVector<SDValue, 4> Ops; 5086 if (HaveChain) 5087 Ops.push_back(BRCOND.getOperand(0)); 5088 5089 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5090 Ops.push_back(Target); 5091 5092 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5093 5094 // build the new intrinsic call 5095 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5096 5097 if (!HaveChain) { 5098 SDValue Ops[] = { 5099 SDValue(Result, 0), 5100 BRCOND.getOperand(0) 5101 }; 5102 5103 Result = DAG.getMergeValues(Ops, DL).getNode(); 5104 } 5105 5106 if (BR) { 5107 // Give the branch instruction our target 5108 SDValue Ops[] = { 5109 BR->getOperand(0), 5110 BRCOND.getOperand(2) 5111 }; 5112 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5113 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5114 } 5115 5116 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5117 5118 // Copy the intrinsic results to registers 5119 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5120 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5121 if (!CopyToReg) 5122 continue; 5123 5124 Chain = DAG.getCopyToReg( 5125 Chain, DL, 5126 CopyToReg->getOperand(1), 5127 SDValue(Result, i - 1), 5128 SDValue()); 5129 5130 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5131 } 5132 5133 // Remove the old intrinsic from the chain 5134 DAG.ReplaceAllUsesOfValueWith( 5135 SDValue(Intr, Intr->getNumValues() - 1), 5136 Intr->getOperand(0)); 5137 5138 return Chain; 5139 } 5140 5141 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5142 SelectionDAG &DAG) const { 5143 MVT VT = Op.getSimpleValueType(); 5144 SDLoc DL(Op); 5145 // Checking the depth 5146 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5147 return DAG.getConstant(0, DL, VT); 5148 5149 MachineFunction &MF = DAG.getMachineFunction(); 5150 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5151 // Check for kernel and shader functions 5152 if (Info->isEntryFunction()) 5153 return DAG.getConstant(0, DL, VT); 5154 5155 MachineFrameInfo &MFI = MF.getFrameInfo(); 5156 // There is a call to @llvm.returnaddress in this function 5157 MFI.setReturnAddressIsTaken(true); 5158 5159 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5160 // Get the return address reg and mark it as an implicit live-in 5161 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5162 5163 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5164 } 5165 5166 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5167 SDValue Op, 5168 const SDLoc &DL, 5169 EVT VT) const { 5170 return Op.getValueType().bitsLE(VT) ? 5171 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5172 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5173 DAG.getTargetConstant(0, DL, MVT::i32)); 5174 } 5175 5176 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5177 assert(Op.getValueType() == MVT::f16 && 5178 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5179 5180 SDValue Src = Op.getOperand(0); 5181 EVT SrcVT = Src.getValueType(); 5182 if (SrcVT != MVT::f64) 5183 return Op; 5184 5185 SDLoc DL(Op); 5186 5187 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5188 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5189 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5190 } 5191 5192 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5193 SelectionDAG &DAG) const { 5194 EVT VT = Op.getValueType(); 5195 const MachineFunction &MF = DAG.getMachineFunction(); 5196 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5197 bool IsIEEEMode = Info->getMode().IEEE; 5198 5199 // FIXME: Assert during selection that this is only selected for 5200 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5201 // mode functions, but this happens to be OK since it's only done in cases 5202 // where there is known no sNaN. 5203 if (IsIEEEMode) 5204 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5205 5206 if (VT == MVT::v4f16) 5207 return splitBinaryVectorOp(Op, DAG); 5208 return Op; 5209 } 5210 5211 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5212 EVT VT = Op.getValueType(); 5213 SDLoc SL(Op); 5214 SDValue LHS = Op.getOperand(0); 5215 SDValue RHS = Op.getOperand(1); 5216 bool isSigned = Op.getOpcode() == ISD::SMULO; 5217 5218 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5219 const APInt &C = RHSC->getAPIntValue(); 5220 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5221 if (C.isPowerOf2()) { 5222 // smulo(x, signed_min) is same as umulo(x, signed_min). 5223 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5224 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5225 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5226 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5227 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5228 SL, VT, Result, ShiftAmt), 5229 LHS, ISD::SETNE); 5230 return DAG.getMergeValues({ Result, Overflow }, SL); 5231 } 5232 } 5233 5234 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5235 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5236 SL, VT, LHS, RHS); 5237 5238 SDValue Sign = isSigned 5239 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5240 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5241 : DAG.getConstant(0, SL, VT); 5242 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5243 5244 return DAG.getMergeValues({ Result, Overflow }, SL); 5245 } 5246 5247 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5248 if (!Subtarget->isTrapHandlerEnabled() || 5249 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5250 return lowerTrapEndpgm(Op, DAG); 5251 5252 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5253 switch (*HsaAbiVer) { 5254 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5255 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5256 return lowerTrapHsaQueuePtr(Op, DAG); 5257 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5258 return Subtarget->supportsGetDoorbellID() ? 5259 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5260 } 5261 } 5262 5263 llvm_unreachable("Unknown trap handler"); 5264 } 5265 5266 SDValue SITargetLowering::lowerTrapEndpgm( 5267 SDValue Op, SelectionDAG &DAG) const { 5268 SDLoc SL(Op); 5269 SDValue Chain = Op.getOperand(0); 5270 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5271 } 5272 5273 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5274 SDValue Op, SelectionDAG &DAG) const { 5275 SDLoc SL(Op); 5276 SDValue Chain = Op.getOperand(0); 5277 5278 MachineFunction &MF = DAG.getMachineFunction(); 5279 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5280 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5281 assert(UserSGPR != AMDGPU::NoRegister); 5282 SDValue QueuePtr = CreateLiveInRegister( 5283 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5284 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5285 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5286 QueuePtr, SDValue()); 5287 5288 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5289 SDValue Ops[] = { 5290 ToReg, 5291 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5292 SGPR01, 5293 ToReg.getValue(1) 5294 }; 5295 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5296 } 5297 5298 SDValue SITargetLowering::lowerTrapHsa( 5299 SDValue Op, SelectionDAG &DAG) const { 5300 SDLoc SL(Op); 5301 SDValue Chain = Op.getOperand(0); 5302 5303 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5304 SDValue Ops[] = { 5305 Chain, 5306 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5307 }; 5308 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5309 } 5310 5311 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5312 SDLoc SL(Op); 5313 SDValue Chain = Op.getOperand(0); 5314 MachineFunction &MF = DAG.getMachineFunction(); 5315 5316 if (!Subtarget->isTrapHandlerEnabled() || 5317 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5318 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5319 "debugtrap handler not supported", 5320 Op.getDebugLoc(), 5321 DS_Warning); 5322 LLVMContext &Ctx = MF.getFunction().getContext(); 5323 Ctx.diagnose(NoTrap); 5324 return Chain; 5325 } 5326 5327 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5328 SDValue Ops[] = { 5329 Chain, 5330 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5331 }; 5332 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5333 } 5334 5335 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5336 SelectionDAG &DAG) const { 5337 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5338 if (Subtarget->hasApertureRegs()) { 5339 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5340 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5341 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5342 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5343 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5344 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5345 unsigned Encoding = 5346 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5347 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5348 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5349 5350 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5351 SDValue ApertureReg = SDValue( 5352 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5353 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5354 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5355 } 5356 5357 MachineFunction &MF = DAG.getMachineFunction(); 5358 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5359 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5360 assert(UserSGPR != AMDGPU::NoRegister); 5361 5362 SDValue QueuePtr = CreateLiveInRegister( 5363 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5364 5365 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5366 // private_segment_aperture_base_hi. 5367 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5368 5369 SDValue Ptr = 5370 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5371 5372 // TODO: Use custom target PseudoSourceValue. 5373 // TODO: We should use the value from the IR intrinsic call, but it might not 5374 // be available and how do we get it? 5375 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5376 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5377 commonAlignment(Align(64), StructOffset), 5378 MachineMemOperand::MODereferenceable | 5379 MachineMemOperand::MOInvariant); 5380 } 5381 5382 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5383 SelectionDAG &DAG) const { 5384 SDLoc SL(Op); 5385 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5386 5387 SDValue Src = ASC->getOperand(0); 5388 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5389 5390 const AMDGPUTargetMachine &TM = 5391 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5392 5393 // flat -> local/private 5394 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5395 unsigned DestAS = ASC->getDestAddressSpace(); 5396 5397 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5398 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5399 unsigned NullVal = TM.getNullPointerValue(DestAS); 5400 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5401 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5402 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5403 5404 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5405 NonNull, Ptr, SegmentNullPtr); 5406 } 5407 } 5408 5409 // local/private -> flat 5410 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5411 unsigned SrcAS = ASC->getSrcAddressSpace(); 5412 5413 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5414 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5415 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5416 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5417 5418 SDValue NonNull 5419 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5420 5421 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5422 SDValue CvtPtr 5423 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5424 5425 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5426 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5427 FlatNullPtr); 5428 } 5429 } 5430 5431 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5432 Src.getValueType() == MVT::i64) 5433 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5434 5435 // global <-> flat are no-ops and never emitted. 5436 5437 const MachineFunction &MF = DAG.getMachineFunction(); 5438 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5439 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5440 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5441 5442 return DAG.getUNDEF(ASC->getValueType(0)); 5443 } 5444 5445 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5446 // the small vector and inserting them into the big vector. That is better than 5447 // the default expansion of doing it via a stack slot. Even though the use of 5448 // the stack slot would be optimized away afterwards, the stack slot itself 5449 // remains. 5450 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5451 SelectionDAG &DAG) const { 5452 SDValue Vec = Op.getOperand(0); 5453 SDValue Ins = Op.getOperand(1); 5454 SDValue Idx = Op.getOperand(2); 5455 EVT VecVT = Vec.getValueType(); 5456 EVT InsVT = Ins.getValueType(); 5457 EVT EltVT = VecVT.getVectorElementType(); 5458 unsigned InsNumElts = InsVT.getVectorNumElements(); 5459 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5460 SDLoc SL(Op); 5461 5462 for (unsigned I = 0; I != InsNumElts; ++I) { 5463 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5464 DAG.getConstant(I, SL, MVT::i32)); 5465 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5466 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5467 } 5468 return Vec; 5469 } 5470 5471 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5472 SelectionDAG &DAG) const { 5473 SDValue Vec = Op.getOperand(0); 5474 SDValue InsVal = Op.getOperand(1); 5475 SDValue Idx = Op.getOperand(2); 5476 EVT VecVT = Vec.getValueType(); 5477 EVT EltVT = VecVT.getVectorElementType(); 5478 unsigned VecSize = VecVT.getSizeInBits(); 5479 unsigned EltSize = EltVT.getSizeInBits(); 5480 5481 5482 assert(VecSize <= 64); 5483 5484 unsigned NumElts = VecVT.getVectorNumElements(); 5485 SDLoc SL(Op); 5486 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5487 5488 if (NumElts == 4 && EltSize == 16 && KIdx) { 5489 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5490 5491 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5492 DAG.getConstant(0, SL, MVT::i32)); 5493 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5494 DAG.getConstant(1, SL, MVT::i32)); 5495 5496 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5497 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5498 5499 unsigned Idx = KIdx->getZExtValue(); 5500 bool InsertLo = Idx < 2; 5501 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5502 InsertLo ? LoVec : HiVec, 5503 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5504 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5505 5506 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5507 5508 SDValue Concat = InsertLo ? 5509 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5510 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5511 5512 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5513 } 5514 5515 if (isa<ConstantSDNode>(Idx)) 5516 return SDValue(); 5517 5518 MVT IntVT = MVT::getIntegerVT(VecSize); 5519 5520 // Avoid stack access for dynamic indexing. 5521 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5522 5523 // Create a congruent vector with the target value in each element so that 5524 // the required element can be masked and ORed into the target vector. 5525 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5526 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5527 5528 assert(isPowerOf2_32(EltSize)); 5529 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5530 5531 // Convert vector index to bit-index. 5532 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5533 5534 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5535 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5536 DAG.getConstant(0xffff, SL, IntVT), 5537 ScaledIdx); 5538 5539 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5540 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5541 DAG.getNOT(SL, BFM, IntVT), BCVec); 5542 5543 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5544 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5545 } 5546 5547 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5548 SelectionDAG &DAG) const { 5549 SDLoc SL(Op); 5550 5551 EVT ResultVT = Op.getValueType(); 5552 SDValue Vec = Op.getOperand(0); 5553 SDValue Idx = Op.getOperand(1); 5554 EVT VecVT = Vec.getValueType(); 5555 unsigned VecSize = VecVT.getSizeInBits(); 5556 EVT EltVT = VecVT.getVectorElementType(); 5557 assert(VecSize <= 64); 5558 5559 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5560 5561 // Make sure we do any optimizations that will make it easier to fold 5562 // source modifiers before obscuring it with bit operations. 5563 5564 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5565 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5566 return Combined; 5567 5568 unsigned EltSize = EltVT.getSizeInBits(); 5569 assert(isPowerOf2_32(EltSize)); 5570 5571 MVT IntVT = MVT::getIntegerVT(VecSize); 5572 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5573 5574 // Convert vector index to bit-index (* EltSize) 5575 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5576 5577 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5578 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5579 5580 if (ResultVT == MVT::f16) { 5581 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5582 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5583 } 5584 5585 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5586 } 5587 5588 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5589 assert(Elt % 2 == 0); 5590 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5591 } 5592 5593 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5594 SelectionDAG &DAG) const { 5595 SDLoc SL(Op); 5596 EVT ResultVT = Op.getValueType(); 5597 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5598 5599 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5600 EVT EltVT = PackVT.getVectorElementType(); 5601 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5602 5603 // vector_shuffle <0,1,6,7> lhs, rhs 5604 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5605 // 5606 // vector_shuffle <6,7,2,3> lhs, rhs 5607 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5608 // 5609 // vector_shuffle <6,7,0,1> lhs, rhs 5610 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5611 5612 // Avoid scalarizing when both halves are reading from consecutive elements. 5613 SmallVector<SDValue, 4> Pieces; 5614 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5615 if (elementPairIsContiguous(SVN->getMask(), I)) { 5616 const int Idx = SVN->getMaskElt(I); 5617 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5618 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5619 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5620 PackVT, SVN->getOperand(VecIdx), 5621 DAG.getConstant(EltIdx, SL, MVT::i32)); 5622 Pieces.push_back(SubVec); 5623 } else { 5624 const int Idx0 = SVN->getMaskElt(I); 5625 const int Idx1 = SVN->getMaskElt(I + 1); 5626 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5627 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5628 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5629 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5630 5631 SDValue Vec0 = SVN->getOperand(VecIdx0); 5632 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5633 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5634 5635 SDValue Vec1 = SVN->getOperand(VecIdx1); 5636 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5637 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5638 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5639 } 5640 } 5641 5642 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5643 } 5644 5645 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5646 SelectionDAG &DAG) const { 5647 SDLoc SL(Op); 5648 EVT VT = Op.getValueType(); 5649 5650 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5651 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5652 5653 // Turn into pair of packed build_vectors. 5654 // TODO: Special case for constants that can be materialized with s_mov_b64. 5655 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5656 { Op.getOperand(0), Op.getOperand(1) }); 5657 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5658 { Op.getOperand(2), Op.getOperand(3) }); 5659 5660 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5661 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5662 5663 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5664 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5665 } 5666 5667 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5668 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5669 5670 SDValue Lo = Op.getOperand(0); 5671 SDValue Hi = Op.getOperand(1); 5672 5673 // Avoid adding defined bits with the zero_extend. 5674 if (Hi.isUndef()) { 5675 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5676 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5677 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5678 } 5679 5680 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5681 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5682 5683 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5684 DAG.getConstant(16, SL, MVT::i32)); 5685 if (Lo.isUndef()) 5686 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5687 5688 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5689 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5690 5691 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5692 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5693 } 5694 5695 bool 5696 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5697 // We can fold offsets for anything that doesn't require a GOT relocation. 5698 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5699 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5700 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5701 !shouldEmitGOTReloc(GA->getGlobal()); 5702 } 5703 5704 static SDValue 5705 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5706 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5707 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5708 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5709 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5710 // lowered to the following code sequence: 5711 // 5712 // For constant address space: 5713 // s_getpc_b64 s[0:1] 5714 // s_add_u32 s0, s0, $symbol 5715 // s_addc_u32 s1, s1, 0 5716 // 5717 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5718 // a fixup or relocation is emitted to replace $symbol with a literal 5719 // constant, which is a pc-relative offset from the encoding of the $symbol 5720 // operand to the global variable. 5721 // 5722 // For global address space: 5723 // s_getpc_b64 s[0:1] 5724 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5725 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5726 // 5727 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5728 // fixups or relocations are emitted to replace $symbol@*@lo and 5729 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5730 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5731 // operand to the global variable. 5732 // 5733 // What we want here is an offset from the value returned by s_getpc 5734 // (which is the address of the s_add_u32 instruction) to the global 5735 // variable, but since the encoding of $symbol starts 4 bytes after the start 5736 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5737 // small. This requires us to add 4 to the global variable offset in order to 5738 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5739 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5740 // instruction. 5741 SDValue PtrLo = 5742 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5743 SDValue PtrHi; 5744 if (GAFlags == SIInstrInfo::MO_NONE) { 5745 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5746 } else { 5747 PtrHi = 5748 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5749 } 5750 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5751 } 5752 5753 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5754 SDValue Op, 5755 SelectionDAG &DAG) const { 5756 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5757 SDLoc DL(GSD); 5758 EVT PtrVT = Op.getValueType(); 5759 5760 const GlobalValue *GV = GSD->getGlobal(); 5761 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5762 shouldUseLDSConstAddress(GV)) || 5763 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5764 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5765 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5766 GV->hasExternalLinkage()) { 5767 Type *Ty = GV->getValueType(); 5768 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5769 // zero-sized type in other languages to declare the dynamic shared 5770 // memory which size is not known at the compile time. They will be 5771 // allocated by the runtime and placed directly after the static 5772 // allocated ones. They all share the same offset. 5773 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5774 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5775 // Adjust alignment for that dynamic shared memory array. 5776 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5777 return SDValue( 5778 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5779 } 5780 } 5781 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5782 } 5783 5784 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5785 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5786 SIInstrInfo::MO_ABS32_LO); 5787 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5788 } 5789 5790 if (shouldEmitFixup(GV)) 5791 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5792 else if (shouldEmitPCReloc(GV)) 5793 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5794 SIInstrInfo::MO_REL32); 5795 5796 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5797 SIInstrInfo::MO_GOTPCREL32); 5798 5799 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5800 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5801 const DataLayout &DataLayout = DAG.getDataLayout(); 5802 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5803 MachinePointerInfo PtrInfo 5804 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5805 5806 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5807 MachineMemOperand::MODereferenceable | 5808 MachineMemOperand::MOInvariant); 5809 } 5810 5811 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5812 const SDLoc &DL, SDValue V) const { 5813 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5814 // the destination register. 5815 // 5816 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5817 // so we will end up with redundant moves to m0. 5818 // 5819 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5820 5821 // A Null SDValue creates a glue result. 5822 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5823 V, Chain); 5824 return SDValue(M0, 0); 5825 } 5826 5827 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5828 SDValue Op, 5829 MVT VT, 5830 unsigned Offset) const { 5831 SDLoc SL(Op); 5832 SDValue Param = lowerKernargMemParameter( 5833 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5834 // The local size values will have the hi 16-bits as zero. 5835 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5836 DAG.getValueType(VT)); 5837 } 5838 5839 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5840 EVT VT) { 5841 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5842 "non-hsa intrinsic with hsa target", 5843 DL.getDebugLoc()); 5844 DAG.getContext()->diagnose(BadIntrin); 5845 return DAG.getUNDEF(VT); 5846 } 5847 5848 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5849 EVT VT) { 5850 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5851 "intrinsic not supported on subtarget", 5852 DL.getDebugLoc()); 5853 DAG.getContext()->diagnose(BadIntrin); 5854 return DAG.getUNDEF(VT); 5855 } 5856 5857 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5858 ArrayRef<SDValue> Elts) { 5859 assert(!Elts.empty()); 5860 MVT Type; 5861 unsigned NumElts = Elts.size(); 5862 5863 if (NumElts <= 8) { 5864 Type = MVT::getVectorVT(MVT::f32, NumElts); 5865 } else { 5866 assert(Elts.size() <= 16); 5867 Type = MVT::v16f32; 5868 NumElts = 16; 5869 } 5870 5871 SmallVector<SDValue, 16> VecElts(NumElts); 5872 for (unsigned i = 0; i < Elts.size(); ++i) { 5873 SDValue Elt = Elts[i]; 5874 if (Elt.getValueType() != MVT::f32) 5875 Elt = DAG.getBitcast(MVT::f32, Elt); 5876 VecElts[i] = Elt; 5877 } 5878 for (unsigned i = Elts.size(); i < NumElts; ++i) 5879 VecElts[i] = DAG.getUNDEF(MVT::f32); 5880 5881 if (NumElts == 1) 5882 return VecElts[0]; 5883 return DAG.getBuildVector(Type, DL, VecElts); 5884 } 5885 5886 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5887 SDValue Src, int ExtraElts) { 5888 EVT SrcVT = Src.getValueType(); 5889 5890 SmallVector<SDValue, 8> Elts; 5891 5892 if (SrcVT.isVector()) 5893 DAG.ExtractVectorElements(Src, Elts); 5894 else 5895 Elts.push_back(Src); 5896 5897 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5898 while (ExtraElts--) 5899 Elts.push_back(Undef); 5900 5901 return DAG.getBuildVector(CastVT, DL, Elts); 5902 } 5903 5904 // Re-construct the required return value for a image load intrinsic. 5905 // This is more complicated due to the optional use TexFailCtrl which means the required 5906 // return type is an aggregate 5907 static SDValue constructRetValue(SelectionDAG &DAG, 5908 MachineSDNode *Result, 5909 ArrayRef<EVT> ResultTypes, 5910 bool IsTexFail, bool Unpacked, bool IsD16, 5911 int DMaskPop, int NumVDataDwords, 5912 const SDLoc &DL) { 5913 // Determine the required return type. This is the same regardless of IsTexFail flag 5914 EVT ReqRetVT = ResultTypes[0]; 5915 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5916 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5917 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5918 5919 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5920 DMaskPop : (DMaskPop + 1) / 2; 5921 5922 MVT DataDwordVT = NumDataDwords == 1 ? 5923 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5924 5925 MVT MaskPopVT = MaskPopDwords == 1 ? 5926 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5927 5928 SDValue Data(Result, 0); 5929 SDValue TexFail; 5930 5931 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5932 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5933 if (MaskPopVT.isVector()) { 5934 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5935 SDValue(Result, 0), ZeroIdx); 5936 } else { 5937 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5938 SDValue(Result, 0), ZeroIdx); 5939 } 5940 } 5941 5942 if (DataDwordVT.isVector()) 5943 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5944 NumDataDwords - MaskPopDwords); 5945 5946 if (IsD16) 5947 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5948 5949 EVT LegalReqRetVT = ReqRetVT; 5950 if (!ReqRetVT.isVector()) { 5951 if (!Data.getValueType().isInteger()) 5952 Data = DAG.getNode(ISD::BITCAST, DL, 5953 Data.getValueType().changeTypeToInteger(), Data); 5954 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5955 } else { 5956 // We need to widen the return vector to a legal type 5957 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5958 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5959 LegalReqRetVT = 5960 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5961 ReqRetVT.getVectorNumElements() + 1); 5962 } 5963 } 5964 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5965 5966 if (IsTexFail) { 5967 TexFail = 5968 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5969 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5970 5971 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5972 } 5973 5974 if (Result->getNumValues() == 1) 5975 return Data; 5976 5977 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5978 } 5979 5980 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5981 SDValue *LWE, bool &IsTexFail) { 5982 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5983 5984 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5985 if (Value) { 5986 IsTexFail = true; 5987 } 5988 5989 SDLoc DL(TexFailCtrlConst); 5990 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5991 Value &= ~(uint64_t)0x1; 5992 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5993 Value &= ~(uint64_t)0x2; 5994 5995 return Value == 0; 5996 } 5997 5998 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 5999 MVT PackVectorVT, 6000 SmallVectorImpl<SDValue> &PackedAddrs, 6001 unsigned DimIdx, unsigned EndIdx, 6002 unsigned NumGradients) { 6003 SDLoc DL(Op); 6004 for (unsigned I = DimIdx; I < EndIdx; I++) { 6005 SDValue Addr = Op.getOperand(I); 6006 6007 // Gradients are packed with undef for each coordinate. 6008 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6009 // 1D: undef,dx/dh; undef,dx/dv 6010 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6011 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6012 if (((I + 1) >= EndIdx) || 6013 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6014 I == DimIdx + NumGradients - 1))) { 6015 if (Addr.getValueType() != MVT::i16) 6016 Addr = DAG.getBitcast(MVT::i16, Addr); 6017 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6018 } else { 6019 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6020 I++; 6021 } 6022 Addr = DAG.getBitcast(MVT::f32, Addr); 6023 PackedAddrs.push_back(Addr); 6024 } 6025 } 6026 6027 SDValue SITargetLowering::lowerImage(SDValue Op, 6028 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6029 SelectionDAG &DAG, bool WithChain) const { 6030 SDLoc DL(Op); 6031 MachineFunction &MF = DAG.getMachineFunction(); 6032 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6033 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6034 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6035 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6036 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6037 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6038 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6039 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6040 unsigned IntrOpcode = Intr->BaseOpcode; 6041 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6042 6043 SmallVector<EVT, 3> ResultTypes(Op->values()); 6044 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6045 bool IsD16 = false; 6046 bool IsG16 = false; 6047 bool IsA16 = false; 6048 SDValue VData; 6049 int NumVDataDwords; 6050 bool AdjustRetType = false; 6051 6052 // Offset of intrinsic arguments 6053 const unsigned ArgOffset = WithChain ? 2 : 1; 6054 6055 unsigned DMask; 6056 unsigned DMaskLanes = 0; 6057 6058 if (BaseOpcode->Atomic) { 6059 VData = Op.getOperand(2); 6060 6061 bool Is64Bit = VData.getValueType() == MVT::i64; 6062 if (BaseOpcode->AtomicX2) { 6063 SDValue VData2 = Op.getOperand(3); 6064 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6065 {VData, VData2}); 6066 if (Is64Bit) 6067 VData = DAG.getBitcast(MVT::v4i32, VData); 6068 6069 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6070 DMask = Is64Bit ? 0xf : 0x3; 6071 NumVDataDwords = Is64Bit ? 4 : 2; 6072 } else { 6073 DMask = Is64Bit ? 0x3 : 0x1; 6074 NumVDataDwords = Is64Bit ? 2 : 1; 6075 } 6076 } else { 6077 auto *DMaskConst = 6078 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6079 DMask = DMaskConst->getZExtValue(); 6080 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6081 6082 if (BaseOpcode->Store) { 6083 VData = Op.getOperand(2); 6084 6085 MVT StoreVT = VData.getSimpleValueType(); 6086 if (StoreVT.getScalarType() == MVT::f16) { 6087 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6088 return Op; // D16 is unsupported for this instruction 6089 6090 IsD16 = true; 6091 VData = handleD16VData(VData, DAG, true); 6092 } 6093 6094 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6095 } else { 6096 // Work out the num dwords based on the dmask popcount and underlying type 6097 // and whether packing is supported. 6098 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6099 if (LoadVT.getScalarType() == MVT::f16) { 6100 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6101 return Op; // D16 is unsupported for this instruction 6102 6103 IsD16 = true; 6104 } 6105 6106 // Confirm that the return type is large enough for the dmask specified 6107 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6108 (!LoadVT.isVector() && DMaskLanes > 1)) 6109 return Op; 6110 6111 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6112 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6113 // instructions. 6114 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6115 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6116 NumVDataDwords = (DMaskLanes + 1) / 2; 6117 else 6118 NumVDataDwords = DMaskLanes; 6119 6120 AdjustRetType = true; 6121 } 6122 } 6123 6124 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6125 SmallVector<SDValue, 4> VAddrs; 6126 6127 // Optimize _L to _LZ when _L is zero 6128 if (LZMappingInfo) { 6129 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6130 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6131 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6132 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6133 VAddrEnd--; // remove 'lod' 6134 } 6135 } 6136 } 6137 6138 // Optimize _mip away, when 'lod' is zero 6139 if (MIPMappingInfo) { 6140 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6141 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6142 if (ConstantLod->isNullValue()) { 6143 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6144 VAddrEnd--; // remove 'mip' 6145 } 6146 } 6147 } 6148 6149 // Push back extra arguments. 6150 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6151 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6152 6153 // Check for 16 bit addresses or derivatives and pack if true. 6154 MVT VAddrVT = 6155 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6156 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6157 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6158 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6159 6160 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6161 VAddrScalarVT = VAddrVT.getScalarType(); 6162 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6163 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6164 6165 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6166 // 16 bit gradients are supported, but are tied to the A16 control 6167 // so both gradients and addresses must be 16 bit 6168 LLVM_DEBUG( 6169 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6170 "require 16 bit args for both gradients and addresses"); 6171 return Op; 6172 } 6173 6174 if (IsA16) { 6175 if (!ST->hasA16()) { 6176 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6177 "support 16 bit addresses\n"); 6178 return Op; 6179 } 6180 } 6181 6182 // We've dealt with incorrect input so we know that if IsA16, IsG16 6183 // are set then we have to compress/pack operands (either address, 6184 // gradient or both) 6185 // In the case where a16 and gradients are tied (no G16 support) then we 6186 // have already verified that both IsA16 and IsG16 are true 6187 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6188 // Activate g16 6189 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6190 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6191 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6192 } 6193 6194 // Add gradients (packed or unpacked) 6195 if (IsG16) { 6196 // Pack the gradients 6197 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6198 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6199 ArgOffset + Intr->GradientStart, 6200 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6201 } else { 6202 for (unsigned I = ArgOffset + Intr->GradientStart; 6203 I < ArgOffset + Intr->CoordStart; I++) 6204 VAddrs.push_back(Op.getOperand(I)); 6205 } 6206 6207 // Add addresses (packed or unpacked) 6208 if (IsA16) { 6209 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6210 ArgOffset + Intr->CoordStart, VAddrEnd, 6211 0 /* No gradients */); 6212 } else { 6213 // Add uncompressed address 6214 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6215 VAddrs.push_back(Op.getOperand(I)); 6216 } 6217 6218 // If the register allocator cannot place the address registers contiguously 6219 // without introducing moves, then using the non-sequential address encoding 6220 // is always preferable, since it saves VALU instructions and is usually a 6221 // wash in terms of code size or even better. 6222 // 6223 // However, we currently have no way of hinting to the register allocator that 6224 // MIMG addresses should be placed contiguously when it is possible to do so, 6225 // so force non-NSA for the common 2-address case as a heuristic. 6226 // 6227 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6228 // allocation when possible. 6229 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6230 VAddrs.size() >= 3 && 6231 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 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 /// Update \p MMO based on the offset inputs to an intrinsic. 6799 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6800 SDValue SOffset, SDValue Offset, 6801 SDValue VIndex = SDValue()) { 6802 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6803 !isa<ConstantSDNode>(Offset)) { 6804 // The combined offset is not known to be constant, so we cannot represent 6805 // it in the MMO. Give up. 6806 MMO->setValue((Value *)nullptr); 6807 return; 6808 } 6809 6810 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6811 !cast<ConstantSDNode>(VIndex)->isNullValue())) { 6812 // The strided index component of the address is not known to be zero, so we 6813 // cannot represent it in the MMO. Give up. 6814 MMO->setValue((Value *)nullptr); 6815 return; 6816 } 6817 6818 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6819 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6820 cast<ConstantSDNode>(Offset)->getSExtValue()); 6821 } 6822 6823 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6824 SelectionDAG &DAG, 6825 unsigned NewOpcode) const { 6826 SDLoc DL(Op); 6827 6828 SDValue VData = Op.getOperand(2); 6829 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6830 SDValue Ops[] = { 6831 Op.getOperand(0), // Chain 6832 VData, // vdata 6833 Op.getOperand(3), // rsrc 6834 DAG.getConstant(0, DL, MVT::i32), // vindex 6835 Offsets.first, // voffset 6836 Op.getOperand(5), // soffset 6837 Offsets.second, // offset 6838 Op.getOperand(6), // cachepolicy 6839 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6840 }; 6841 6842 auto *M = cast<MemSDNode>(Op); 6843 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 6844 6845 EVT MemVT = VData.getValueType(); 6846 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6847 M->getMemOperand()); 6848 } 6849 6850 // Return a value to use for the idxen operand by examining the vindex operand. 6851 static unsigned getIdxEn(SDValue VIndex) { 6852 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 6853 // No need to set idxen if vindex is known to be zero. 6854 return VIndexC->getZExtValue() != 0; 6855 return 1; 6856 } 6857 6858 SDValue 6859 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6860 unsigned NewOpcode) const { 6861 SDLoc DL(Op); 6862 6863 SDValue VData = Op.getOperand(2); 6864 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6865 SDValue Ops[] = { 6866 Op.getOperand(0), // Chain 6867 VData, // vdata 6868 Op.getOperand(3), // rsrc 6869 Op.getOperand(4), // vindex 6870 Offsets.first, // voffset 6871 Op.getOperand(6), // soffset 6872 Offsets.second, // offset 6873 Op.getOperand(7), // cachepolicy 6874 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6875 }; 6876 6877 auto *M = cast<MemSDNode>(Op); 6878 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 6879 6880 EVT MemVT = VData.getValueType(); 6881 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6882 M->getMemOperand()); 6883 } 6884 6885 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6886 SelectionDAG &DAG) const { 6887 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6888 SDLoc DL(Op); 6889 6890 switch (IntrID) { 6891 case Intrinsic::amdgcn_ds_ordered_add: 6892 case Intrinsic::amdgcn_ds_ordered_swap: { 6893 MemSDNode *M = cast<MemSDNode>(Op); 6894 SDValue Chain = M->getOperand(0); 6895 SDValue M0 = M->getOperand(2); 6896 SDValue Value = M->getOperand(3); 6897 unsigned IndexOperand = M->getConstantOperandVal(7); 6898 unsigned WaveRelease = M->getConstantOperandVal(8); 6899 unsigned WaveDone = M->getConstantOperandVal(9); 6900 6901 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6902 IndexOperand &= ~0x3f; 6903 unsigned CountDw = 0; 6904 6905 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6906 CountDw = (IndexOperand >> 24) & 0xf; 6907 IndexOperand &= ~(0xf << 24); 6908 6909 if (CountDw < 1 || CountDw > 4) { 6910 report_fatal_error( 6911 "ds_ordered_count: dword count must be between 1 and 4"); 6912 } 6913 } 6914 6915 if (IndexOperand) 6916 report_fatal_error("ds_ordered_count: bad index operand"); 6917 6918 if (WaveDone && !WaveRelease) 6919 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6920 6921 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6922 unsigned ShaderType = 6923 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6924 unsigned Offset0 = OrderedCountIndex << 2; 6925 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6926 (Instruction << 4); 6927 6928 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6929 Offset1 |= (CountDw - 1) << 6; 6930 6931 unsigned Offset = Offset0 | (Offset1 << 8); 6932 6933 SDValue Ops[] = { 6934 Chain, 6935 Value, 6936 DAG.getTargetConstant(Offset, DL, MVT::i16), 6937 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6938 }; 6939 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6940 M->getVTList(), Ops, M->getMemoryVT(), 6941 M->getMemOperand()); 6942 } 6943 case Intrinsic::amdgcn_ds_fadd: { 6944 MemSDNode *M = cast<MemSDNode>(Op); 6945 unsigned Opc; 6946 switch (IntrID) { 6947 case Intrinsic::amdgcn_ds_fadd: 6948 Opc = ISD::ATOMIC_LOAD_FADD; 6949 break; 6950 } 6951 6952 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6953 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6954 M->getMemOperand()); 6955 } 6956 case Intrinsic::amdgcn_atomic_inc: 6957 case Intrinsic::amdgcn_atomic_dec: 6958 case Intrinsic::amdgcn_ds_fmin: 6959 case Intrinsic::amdgcn_ds_fmax: { 6960 MemSDNode *M = cast<MemSDNode>(Op); 6961 unsigned Opc; 6962 switch (IntrID) { 6963 case Intrinsic::amdgcn_atomic_inc: 6964 Opc = AMDGPUISD::ATOMIC_INC; 6965 break; 6966 case Intrinsic::amdgcn_atomic_dec: 6967 Opc = AMDGPUISD::ATOMIC_DEC; 6968 break; 6969 case Intrinsic::amdgcn_ds_fmin: 6970 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6971 break; 6972 case Intrinsic::amdgcn_ds_fmax: 6973 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6974 break; 6975 default: 6976 llvm_unreachable("Unknown intrinsic!"); 6977 } 6978 SDValue Ops[] = { 6979 M->getOperand(0), // Chain 6980 M->getOperand(2), // Ptr 6981 M->getOperand(3) // Value 6982 }; 6983 6984 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6985 M->getMemoryVT(), M->getMemOperand()); 6986 } 6987 case Intrinsic::amdgcn_buffer_load: 6988 case Intrinsic::amdgcn_buffer_load_format: { 6989 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6990 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6991 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 6992 SDValue Ops[] = { 6993 Op.getOperand(0), // Chain 6994 Op.getOperand(2), // rsrc 6995 Op.getOperand(3), // vindex 6996 SDValue(), // voffset -- will be set by setBufferOffsets 6997 SDValue(), // soffset -- will be set by setBufferOffsets 6998 SDValue(), // offset -- will be set by setBufferOffsets 6999 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7000 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7001 }; 7002 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7003 7004 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7005 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7006 7007 EVT VT = Op.getValueType(); 7008 EVT IntVT = VT.changeTypeToInteger(); 7009 auto *M = cast<MemSDNode>(Op); 7010 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7011 EVT LoadVT = Op.getValueType(); 7012 7013 if (LoadVT.getScalarType() == MVT::f16) 7014 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7015 M, DAG, Ops); 7016 7017 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7018 if (LoadVT.getScalarType() == MVT::i8 || 7019 LoadVT.getScalarType() == MVT::i16) 7020 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7021 7022 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7023 M->getMemOperand(), DAG); 7024 } 7025 case Intrinsic::amdgcn_raw_buffer_load: 7026 case Intrinsic::amdgcn_raw_buffer_load_format: { 7027 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7028 7029 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7030 SDValue Ops[] = { 7031 Op.getOperand(0), // Chain 7032 Op.getOperand(2), // rsrc 7033 DAG.getConstant(0, DL, MVT::i32), // vindex 7034 Offsets.first, // voffset 7035 Op.getOperand(4), // soffset 7036 Offsets.second, // offset 7037 Op.getOperand(5), // cachepolicy, swizzled buffer 7038 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7039 }; 7040 7041 auto *M = cast<MemSDNode>(Op); 7042 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7043 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7044 } 7045 case Intrinsic::amdgcn_struct_buffer_load: 7046 case Intrinsic::amdgcn_struct_buffer_load_format: { 7047 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7048 7049 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7050 SDValue Ops[] = { 7051 Op.getOperand(0), // Chain 7052 Op.getOperand(2), // rsrc 7053 Op.getOperand(3), // vindex 7054 Offsets.first, // voffset 7055 Op.getOperand(5), // soffset 7056 Offsets.second, // offset 7057 Op.getOperand(6), // cachepolicy, swizzled buffer 7058 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7059 }; 7060 7061 auto *M = cast<MemSDNode>(Op); 7062 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7063 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7064 } 7065 case Intrinsic::amdgcn_tbuffer_load: { 7066 MemSDNode *M = cast<MemSDNode>(Op); 7067 EVT LoadVT = Op.getValueType(); 7068 7069 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7070 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7071 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7072 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7073 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7074 SDValue Ops[] = { 7075 Op.getOperand(0), // Chain 7076 Op.getOperand(2), // rsrc 7077 Op.getOperand(3), // vindex 7078 Op.getOperand(4), // voffset 7079 Op.getOperand(5), // soffset 7080 Op.getOperand(6), // offset 7081 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7082 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7083 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7084 }; 7085 7086 if (LoadVT.getScalarType() == MVT::f16) 7087 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7088 M, DAG, Ops); 7089 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7090 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7091 DAG); 7092 } 7093 case Intrinsic::amdgcn_raw_tbuffer_load: { 7094 MemSDNode *M = cast<MemSDNode>(Op); 7095 EVT LoadVT = Op.getValueType(); 7096 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7097 7098 SDValue Ops[] = { 7099 Op.getOperand(0), // Chain 7100 Op.getOperand(2), // rsrc 7101 DAG.getConstant(0, DL, MVT::i32), // vindex 7102 Offsets.first, // voffset 7103 Op.getOperand(4), // soffset 7104 Offsets.second, // offset 7105 Op.getOperand(5), // format 7106 Op.getOperand(6), // cachepolicy, swizzled buffer 7107 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7108 }; 7109 7110 if (LoadVT.getScalarType() == MVT::f16) 7111 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7112 M, DAG, Ops); 7113 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7114 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7115 DAG); 7116 } 7117 case Intrinsic::amdgcn_struct_tbuffer_load: { 7118 MemSDNode *M = cast<MemSDNode>(Op); 7119 EVT LoadVT = Op.getValueType(); 7120 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7121 7122 SDValue Ops[] = { 7123 Op.getOperand(0), // Chain 7124 Op.getOperand(2), // rsrc 7125 Op.getOperand(3), // vindex 7126 Offsets.first, // voffset 7127 Op.getOperand(5), // soffset 7128 Offsets.second, // offset 7129 Op.getOperand(6), // format 7130 Op.getOperand(7), // cachepolicy, swizzled buffer 7131 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7132 }; 7133 7134 if (LoadVT.getScalarType() == MVT::f16) 7135 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7136 M, DAG, Ops); 7137 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7138 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7139 DAG); 7140 } 7141 case Intrinsic::amdgcn_buffer_atomic_swap: 7142 case Intrinsic::amdgcn_buffer_atomic_add: 7143 case Intrinsic::amdgcn_buffer_atomic_sub: 7144 case Intrinsic::amdgcn_buffer_atomic_csub: 7145 case Intrinsic::amdgcn_buffer_atomic_smin: 7146 case Intrinsic::amdgcn_buffer_atomic_umin: 7147 case Intrinsic::amdgcn_buffer_atomic_smax: 7148 case Intrinsic::amdgcn_buffer_atomic_umax: 7149 case Intrinsic::amdgcn_buffer_atomic_and: 7150 case Intrinsic::amdgcn_buffer_atomic_or: 7151 case Intrinsic::amdgcn_buffer_atomic_xor: 7152 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7153 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7154 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7155 SDValue Ops[] = { 7156 Op.getOperand(0), // Chain 7157 Op.getOperand(2), // vdata 7158 Op.getOperand(3), // rsrc 7159 Op.getOperand(4), // vindex 7160 SDValue(), // voffset -- will be set by setBufferOffsets 7161 SDValue(), // soffset -- will be set by setBufferOffsets 7162 SDValue(), // offset -- will be set by setBufferOffsets 7163 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7164 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7165 }; 7166 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7167 7168 EVT VT = Op.getValueType(); 7169 7170 auto *M = cast<MemSDNode>(Op); 7171 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7172 unsigned Opcode = 0; 7173 7174 switch (IntrID) { 7175 case Intrinsic::amdgcn_buffer_atomic_swap: 7176 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7177 break; 7178 case Intrinsic::amdgcn_buffer_atomic_add: 7179 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7180 break; 7181 case Intrinsic::amdgcn_buffer_atomic_sub: 7182 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7183 break; 7184 case Intrinsic::amdgcn_buffer_atomic_csub: 7185 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7186 break; 7187 case Intrinsic::amdgcn_buffer_atomic_smin: 7188 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7189 break; 7190 case Intrinsic::amdgcn_buffer_atomic_umin: 7191 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7192 break; 7193 case Intrinsic::amdgcn_buffer_atomic_smax: 7194 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7195 break; 7196 case Intrinsic::amdgcn_buffer_atomic_umax: 7197 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7198 break; 7199 case Intrinsic::amdgcn_buffer_atomic_and: 7200 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7201 break; 7202 case Intrinsic::amdgcn_buffer_atomic_or: 7203 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7204 break; 7205 case Intrinsic::amdgcn_buffer_atomic_xor: 7206 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7207 break; 7208 case Intrinsic::amdgcn_buffer_atomic_fadd: 7209 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7210 DiagnosticInfoUnsupported 7211 NoFpRet(DAG.getMachineFunction().getFunction(), 7212 "return versions of fp atomics not supported", 7213 DL.getDebugLoc(), DS_Error); 7214 DAG.getContext()->diagnose(NoFpRet); 7215 return SDValue(); 7216 } 7217 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7218 break; 7219 default: 7220 llvm_unreachable("unhandled atomic opcode"); 7221 } 7222 7223 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7224 M->getMemOperand()); 7225 } 7226 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7227 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7228 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7229 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7230 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7231 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7232 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7233 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7234 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7235 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7236 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7237 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7238 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7239 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7240 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7241 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7242 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7243 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7244 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7245 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7246 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7247 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7248 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7249 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7250 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7251 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7252 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7253 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7254 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7255 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7256 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7257 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7258 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7259 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7260 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7261 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7262 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7263 return lowerStructBufferAtomicIntrin(Op, DAG, 7264 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7265 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7266 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7267 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7268 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7269 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7270 return lowerStructBufferAtomicIntrin(Op, DAG, 7271 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7272 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7273 return lowerStructBufferAtomicIntrin(Op, DAG, 7274 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7275 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7276 return lowerStructBufferAtomicIntrin(Op, DAG, 7277 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7278 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7279 return lowerStructBufferAtomicIntrin(Op, DAG, 7280 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7281 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7282 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7283 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7284 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7285 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7286 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7287 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7288 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7289 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7290 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7291 7292 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7293 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7294 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7295 SDValue Ops[] = { 7296 Op.getOperand(0), // Chain 7297 Op.getOperand(2), // src 7298 Op.getOperand(3), // cmp 7299 Op.getOperand(4), // rsrc 7300 Op.getOperand(5), // vindex 7301 SDValue(), // voffset -- will be set by setBufferOffsets 7302 SDValue(), // soffset -- will be set by setBufferOffsets 7303 SDValue(), // offset -- will be set by setBufferOffsets 7304 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7305 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7306 }; 7307 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7308 7309 EVT VT = Op.getValueType(); 7310 auto *M = cast<MemSDNode>(Op); 7311 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7312 7313 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7314 Op->getVTList(), Ops, VT, M->getMemOperand()); 7315 } 7316 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7317 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7318 SDValue Ops[] = { 7319 Op.getOperand(0), // Chain 7320 Op.getOperand(2), // src 7321 Op.getOperand(3), // cmp 7322 Op.getOperand(4), // rsrc 7323 DAG.getConstant(0, DL, MVT::i32), // vindex 7324 Offsets.first, // voffset 7325 Op.getOperand(6), // soffset 7326 Offsets.second, // offset 7327 Op.getOperand(7), // cachepolicy 7328 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7329 }; 7330 EVT VT = Op.getValueType(); 7331 auto *M = cast<MemSDNode>(Op); 7332 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7333 7334 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7335 Op->getVTList(), Ops, VT, M->getMemOperand()); 7336 } 7337 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7338 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7339 SDValue Ops[] = { 7340 Op.getOperand(0), // Chain 7341 Op.getOperand(2), // src 7342 Op.getOperand(3), // cmp 7343 Op.getOperand(4), // rsrc 7344 Op.getOperand(5), // vindex 7345 Offsets.first, // voffset 7346 Op.getOperand(7), // soffset 7347 Offsets.second, // offset 7348 Op.getOperand(8), // cachepolicy 7349 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7350 }; 7351 EVT VT = Op.getValueType(); 7352 auto *M = cast<MemSDNode>(Op); 7353 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7354 7355 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7356 Op->getVTList(), Ops, VT, M->getMemOperand()); 7357 } 7358 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7359 MemSDNode *M = cast<MemSDNode>(Op); 7360 SDValue NodePtr = M->getOperand(2); 7361 SDValue RayExtent = M->getOperand(3); 7362 SDValue RayOrigin = M->getOperand(4); 7363 SDValue RayDir = M->getOperand(5); 7364 SDValue RayInvDir = M->getOperand(6); 7365 SDValue TDescr = M->getOperand(7); 7366 7367 assert(NodePtr.getValueType() == MVT::i32 || 7368 NodePtr.getValueType() == MVT::i64); 7369 assert(RayDir.getValueType() == MVT::v4f16 || 7370 RayDir.getValueType() == MVT::v4f32); 7371 7372 if (!Subtarget->hasGFX10_AEncoding()) { 7373 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7374 return SDValue(); 7375 } 7376 7377 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7378 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7379 const unsigned NumVDataDwords = 4; 7380 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7381 const bool UseNSA = Subtarget->hasNSAEncoding() && 7382 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7383 const unsigned BaseOpcodes[2][2] = { 7384 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7385 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7386 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7387 int Opcode; 7388 if (UseNSA) { 7389 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7390 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7391 NumVAddrDwords); 7392 } else { 7393 Opcode = AMDGPU::getMIMGOpcode( 7394 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7395 PowerOf2Ceil(NumVAddrDwords)); 7396 } 7397 assert(Opcode != -1); 7398 7399 SmallVector<SDValue, 16> Ops; 7400 7401 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7402 SmallVector<SDValue, 3> Lanes; 7403 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7404 if (Lanes[0].getValueSizeInBits() == 32) { 7405 for (unsigned I = 0; I < 3; ++I) 7406 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7407 } else { 7408 if (IsAligned) { 7409 Ops.push_back( 7410 DAG.getBitcast(MVT::i32, 7411 DAG.getBuildVector(MVT::v2f16, DL, 7412 { Lanes[0], Lanes[1] }))); 7413 Ops.push_back(Lanes[2]); 7414 } else { 7415 SDValue Elt0 = Ops.pop_back_val(); 7416 Ops.push_back( 7417 DAG.getBitcast(MVT::i32, 7418 DAG.getBuildVector(MVT::v2f16, DL, 7419 { Elt0, Lanes[0] }))); 7420 Ops.push_back( 7421 DAG.getBitcast(MVT::i32, 7422 DAG.getBuildVector(MVT::v2f16, DL, 7423 { Lanes[1], Lanes[2] }))); 7424 } 7425 } 7426 }; 7427 7428 if (Is64) 7429 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7430 else 7431 Ops.push_back(NodePtr); 7432 7433 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7434 packLanes(RayOrigin, true); 7435 packLanes(RayDir, true); 7436 packLanes(RayInvDir, false); 7437 7438 if (!UseNSA) { 7439 // Build a single vector containing all the operands so far prepared. 7440 if (NumVAddrDwords > 8) { 7441 SDValue Undef = DAG.getUNDEF(MVT::i32); 7442 Ops.append(16 - Ops.size(), Undef); 7443 } 7444 assert(Ops.size() == 8 || Ops.size() == 16); 7445 SDValue MergedOps = DAG.getBuildVector( 7446 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7447 Ops.clear(); 7448 Ops.push_back(MergedOps); 7449 } 7450 7451 Ops.push_back(TDescr); 7452 if (IsA16) 7453 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7454 Ops.push_back(M->getChain()); 7455 7456 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7457 MachineMemOperand *MemRef = M->getMemOperand(); 7458 DAG.setNodeMemRefs(NewNode, {MemRef}); 7459 return SDValue(NewNode, 0); 7460 } 7461 case Intrinsic::amdgcn_global_atomic_fadd: 7462 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7463 DiagnosticInfoUnsupported 7464 NoFpRet(DAG.getMachineFunction().getFunction(), 7465 "return versions of fp atomics not supported", 7466 DL.getDebugLoc(), DS_Error); 7467 DAG.getContext()->diagnose(NoFpRet); 7468 return SDValue(); 7469 } 7470 LLVM_FALLTHROUGH; 7471 case Intrinsic::amdgcn_global_atomic_fmin: 7472 case Intrinsic::amdgcn_global_atomic_fmax: 7473 case Intrinsic::amdgcn_flat_atomic_fadd: 7474 case Intrinsic::amdgcn_flat_atomic_fmin: 7475 case Intrinsic::amdgcn_flat_atomic_fmax: { 7476 MemSDNode *M = cast<MemSDNode>(Op); 7477 SDValue Ops[] = { 7478 M->getOperand(0), // Chain 7479 M->getOperand(2), // Ptr 7480 M->getOperand(3) // Value 7481 }; 7482 unsigned Opcode = 0; 7483 switch (IntrID) { 7484 case Intrinsic::amdgcn_global_atomic_fadd: 7485 case Intrinsic::amdgcn_flat_atomic_fadd: { 7486 EVT VT = Op.getOperand(3).getValueType(); 7487 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7488 DAG.getVTList(VT, MVT::Other), Ops, 7489 M->getMemOperand()); 7490 } 7491 case Intrinsic::amdgcn_global_atomic_fmin: 7492 case Intrinsic::amdgcn_flat_atomic_fmin: { 7493 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7494 break; 7495 } 7496 case Intrinsic::amdgcn_global_atomic_fmax: 7497 case Intrinsic::amdgcn_flat_atomic_fmax: { 7498 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7499 break; 7500 } 7501 default: 7502 llvm_unreachable("unhandled atomic opcode"); 7503 } 7504 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7505 M->getVTList(), Ops, M->getMemoryVT(), 7506 M->getMemOperand()); 7507 } 7508 default: 7509 7510 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7511 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7512 return lowerImage(Op, ImageDimIntr, DAG, true); 7513 7514 return SDValue(); 7515 } 7516 } 7517 7518 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7519 // dwordx4 if on SI. 7520 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7521 SDVTList VTList, 7522 ArrayRef<SDValue> Ops, EVT MemVT, 7523 MachineMemOperand *MMO, 7524 SelectionDAG &DAG) const { 7525 EVT VT = VTList.VTs[0]; 7526 EVT WidenedVT = VT; 7527 EVT WidenedMemVT = MemVT; 7528 if (!Subtarget->hasDwordx3LoadStores() && 7529 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7530 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7531 WidenedVT.getVectorElementType(), 4); 7532 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7533 WidenedMemVT.getVectorElementType(), 4); 7534 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7535 } 7536 7537 assert(VTList.NumVTs == 2); 7538 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7539 7540 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7541 WidenedMemVT, MMO); 7542 if (WidenedVT != VT) { 7543 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7544 DAG.getVectorIdxConstant(0, DL)); 7545 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7546 } 7547 return NewOp; 7548 } 7549 7550 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7551 bool ImageStore) const { 7552 EVT StoreVT = VData.getValueType(); 7553 7554 // No change for f16 and legal vector D16 types. 7555 if (!StoreVT.isVector()) 7556 return VData; 7557 7558 SDLoc DL(VData); 7559 unsigned NumElements = StoreVT.getVectorNumElements(); 7560 7561 if (Subtarget->hasUnpackedD16VMem()) { 7562 // We need to unpack the packed data to store. 7563 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7564 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7565 7566 EVT EquivStoreVT = 7567 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7568 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7569 return DAG.UnrollVectorOp(ZExt.getNode()); 7570 } 7571 7572 // The sq block of gfx8.1 does not estimate register use correctly for d16 7573 // image store instructions. The data operand is computed as if it were not a 7574 // d16 image instruction. 7575 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7576 // Bitcast to i16 7577 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7578 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7579 7580 // Decompose into scalars 7581 SmallVector<SDValue, 4> Elts; 7582 DAG.ExtractVectorElements(IntVData, Elts); 7583 7584 // Group pairs of i16 into v2i16 and bitcast to i32 7585 SmallVector<SDValue, 4> PackedElts; 7586 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7587 SDValue Pair = 7588 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7589 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7590 PackedElts.push_back(IntPair); 7591 } 7592 if ((NumElements % 2) == 1) { 7593 // Handle v3i16 7594 unsigned I = Elts.size() / 2; 7595 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7596 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7597 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7598 PackedElts.push_back(IntPair); 7599 } 7600 7601 // Pad using UNDEF 7602 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7603 7604 // Build final vector 7605 EVT VecVT = 7606 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7607 return DAG.getBuildVector(VecVT, DL, PackedElts); 7608 } 7609 7610 if (NumElements == 3) { 7611 EVT IntStoreVT = 7612 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7613 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7614 7615 EVT WidenedStoreVT = EVT::getVectorVT( 7616 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7617 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7618 WidenedStoreVT.getStoreSizeInBits()); 7619 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7620 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7621 } 7622 7623 assert(isTypeLegal(StoreVT)); 7624 return VData; 7625 } 7626 7627 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7628 SelectionDAG &DAG) const { 7629 SDLoc DL(Op); 7630 SDValue Chain = Op.getOperand(0); 7631 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7632 MachineFunction &MF = DAG.getMachineFunction(); 7633 7634 switch (IntrinsicID) { 7635 case Intrinsic::amdgcn_exp_compr: { 7636 SDValue Src0 = Op.getOperand(4); 7637 SDValue Src1 = Op.getOperand(5); 7638 // Hack around illegal type on SI by directly selecting it. 7639 if (isTypeLegal(Src0.getValueType())) 7640 return SDValue(); 7641 7642 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7643 SDValue Undef = DAG.getUNDEF(MVT::f32); 7644 const SDValue Ops[] = { 7645 Op.getOperand(2), // tgt 7646 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7647 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7648 Undef, // src2 7649 Undef, // src3 7650 Op.getOperand(7), // vm 7651 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7652 Op.getOperand(3), // en 7653 Op.getOperand(0) // Chain 7654 }; 7655 7656 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7657 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7658 } 7659 case Intrinsic::amdgcn_s_barrier: { 7660 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7661 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7662 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7663 if (WGSize <= ST.getWavefrontSize()) 7664 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7665 Op.getOperand(0)), 0); 7666 } 7667 return SDValue(); 7668 }; 7669 case Intrinsic::amdgcn_tbuffer_store: { 7670 SDValue VData = Op.getOperand(2); 7671 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7672 if (IsD16) 7673 VData = handleD16VData(VData, DAG); 7674 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7675 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7676 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7677 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7678 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7679 SDValue Ops[] = { 7680 Chain, 7681 VData, // vdata 7682 Op.getOperand(3), // rsrc 7683 Op.getOperand(4), // vindex 7684 Op.getOperand(5), // voffset 7685 Op.getOperand(6), // soffset 7686 Op.getOperand(7), // offset 7687 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7688 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7689 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7690 }; 7691 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7692 AMDGPUISD::TBUFFER_STORE_FORMAT; 7693 MemSDNode *M = cast<MemSDNode>(Op); 7694 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7695 M->getMemoryVT(), M->getMemOperand()); 7696 } 7697 7698 case Intrinsic::amdgcn_struct_tbuffer_store: { 7699 SDValue VData = Op.getOperand(2); 7700 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7701 if (IsD16) 7702 VData = handleD16VData(VData, DAG); 7703 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7704 SDValue Ops[] = { 7705 Chain, 7706 VData, // vdata 7707 Op.getOperand(3), // rsrc 7708 Op.getOperand(4), // vindex 7709 Offsets.first, // voffset 7710 Op.getOperand(6), // soffset 7711 Offsets.second, // offset 7712 Op.getOperand(7), // format 7713 Op.getOperand(8), // cachepolicy, swizzled buffer 7714 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7715 }; 7716 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7717 AMDGPUISD::TBUFFER_STORE_FORMAT; 7718 MemSDNode *M = cast<MemSDNode>(Op); 7719 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7720 M->getMemoryVT(), M->getMemOperand()); 7721 } 7722 7723 case Intrinsic::amdgcn_raw_tbuffer_store: { 7724 SDValue VData = Op.getOperand(2); 7725 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7726 if (IsD16) 7727 VData = handleD16VData(VData, DAG); 7728 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7729 SDValue Ops[] = { 7730 Chain, 7731 VData, // vdata 7732 Op.getOperand(3), // rsrc 7733 DAG.getConstant(0, DL, MVT::i32), // vindex 7734 Offsets.first, // voffset 7735 Op.getOperand(5), // soffset 7736 Offsets.second, // offset 7737 Op.getOperand(6), // format 7738 Op.getOperand(7), // cachepolicy, swizzled buffer 7739 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7740 }; 7741 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7742 AMDGPUISD::TBUFFER_STORE_FORMAT; 7743 MemSDNode *M = cast<MemSDNode>(Op); 7744 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7745 M->getMemoryVT(), M->getMemOperand()); 7746 } 7747 7748 case Intrinsic::amdgcn_buffer_store: 7749 case Intrinsic::amdgcn_buffer_store_format: { 7750 SDValue VData = Op.getOperand(2); 7751 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7752 if (IsD16) 7753 VData = handleD16VData(VData, DAG); 7754 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7755 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7756 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7757 SDValue Ops[] = { 7758 Chain, 7759 VData, 7760 Op.getOperand(3), // rsrc 7761 Op.getOperand(4), // vindex 7762 SDValue(), // voffset -- will be set by setBufferOffsets 7763 SDValue(), // soffset -- will be set by setBufferOffsets 7764 SDValue(), // offset -- will be set by setBufferOffsets 7765 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7766 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7767 }; 7768 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7769 7770 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7771 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7772 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7773 MemSDNode *M = cast<MemSDNode>(Op); 7774 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7775 7776 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7777 EVT VDataType = VData.getValueType().getScalarType(); 7778 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7779 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7780 7781 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7782 M->getMemoryVT(), M->getMemOperand()); 7783 } 7784 7785 case Intrinsic::amdgcn_raw_buffer_store: 7786 case Intrinsic::amdgcn_raw_buffer_store_format: { 7787 const bool IsFormat = 7788 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7789 7790 SDValue VData = Op.getOperand(2); 7791 EVT VDataVT = VData.getValueType(); 7792 EVT EltType = VDataVT.getScalarType(); 7793 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7794 if (IsD16) { 7795 VData = handleD16VData(VData, DAG); 7796 VDataVT = VData.getValueType(); 7797 } 7798 7799 if (!isTypeLegal(VDataVT)) { 7800 VData = 7801 DAG.getNode(ISD::BITCAST, DL, 7802 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7803 } 7804 7805 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7806 SDValue Ops[] = { 7807 Chain, 7808 VData, 7809 Op.getOperand(3), // rsrc 7810 DAG.getConstant(0, DL, MVT::i32), // vindex 7811 Offsets.first, // voffset 7812 Op.getOperand(5), // soffset 7813 Offsets.second, // offset 7814 Op.getOperand(6), // cachepolicy, swizzled buffer 7815 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7816 }; 7817 unsigned Opc = 7818 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7819 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7820 MemSDNode *M = cast<MemSDNode>(Op); 7821 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7822 7823 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7824 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7825 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7826 7827 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7828 M->getMemoryVT(), M->getMemOperand()); 7829 } 7830 7831 case Intrinsic::amdgcn_struct_buffer_store: 7832 case Intrinsic::amdgcn_struct_buffer_store_format: { 7833 const bool IsFormat = 7834 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7835 7836 SDValue VData = Op.getOperand(2); 7837 EVT VDataVT = VData.getValueType(); 7838 EVT EltType = VDataVT.getScalarType(); 7839 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7840 7841 if (IsD16) { 7842 VData = handleD16VData(VData, DAG); 7843 VDataVT = VData.getValueType(); 7844 } 7845 7846 if (!isTypeLegal(VDataVT)) { 7847 VData = 7848 DAG.getNode(ISD::BITCAST, DL, 7849 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7850 } 7851 7852 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7853 SDValue Ops[] = { 7854 Chain, 7855 VData, 7856 Op.getOperand(3), // rsrc 7857 Op.getOperand(4), // vindex 7858 Offsets.first, // voffset 7859 Op.getOperand(6), // soffset 7860 Offsets.second, // offset 7861 Op.getOperand(7), // cachepolicy, swizzled buffer 7862 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7863 }; 7864 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7865 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7866 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7867 MemSDNode *M = cast<MemSDNode>(Op); 7868 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7869 7870 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7871 EVT VDataType = VData.getValueType().getScalarType(); 7872 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7873 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7874 7875 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7876 M->getMemoryVT(), M->getMemOperand()); 7877 } 7878 case Intrinsic::amdgcn_end_cf: 7879 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7880 Op->getOperand(2), Chain), 0); 7881 7882 default: { 7883 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7884 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7885 return lowerImage(Op, ImageDimIntr, DAG, true); 7886 7887 return Op; 7888 } 7889 } 7890 } 7891 7892 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7893 // offset (the offset that is included in bounds checking and swizzling, to be 7894 // split between the instruction's voffset and immoffset fields) and soffset 7895 // (the offset that is excluded from bounds checking and swizzling, to go in 7896 // the instruction's soffset field). This function takes the first kind of 7897 // offset and figures out how to split it between voffset and immoffset. 7898 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7899 SDValue Offset, SelectionDAG &DAG) const { 7900 SDLoc DL(Offset); 7901 const unsigned MaxImm = 4095; 7902 SDValue N0 = Offset; 7903 ConstantSDNode *C1 = nullptr; 7904 7905 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7906 N0 = SDValue(); 7907 else if (DAG.isBaseWithConstantOffset(N0)) { 7908 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7909 N0 = N0.getOperand(0); 7910 } 7911 7912 if (C1) { 7913 unsigned ImmOffset = C1->getZExtValue(); 7914 // If the immediate value is too big for the immoffset field, put the value 7915 // and -4096 into the immoffset field so that the value that is copied/added 7916 // for the voffset field is a multiple of 4096, and it stands more chance 7917 // of being CSEd with the copy/add for another similar load/store. 7918 // However, do not do that rounding down to a multiple of 4096 if that is a 7919 // negative number, as it appears to be illegal to have a negative offset 7920 // in the vgpr, even if adding the immediate offset makes it positive. 7921 unsigned Overflow = ImmOffset & ~MaxImm; 7922 ImmOffset -= Overflow; 7923 if ((int32_t)Overflow < 0) { 7924 Overflow += ImmOffset; 7925 ImmOffset = 0; 7926 } 7927 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7928 if (Overflow) { 7929 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7930 if (!N0) 7931 N0 = OverflowVal; 7932 else { 7933 SDValue Ops[] = { N0, OverflowVal }; 7934 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7935 } 7936 } 7937 } 7938 if (!N0) 7939 N0 = DAG.getConstant(0, DL, MVT::i32); 7940 if (!C1) 7941 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7942 return {N0, SDValue(C1, 0)}; 7943 } 7944 7945 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7946 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7947 // pointed to by Offsets. 7948 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7949 SelectionDAG &DAG, SDValue *Offsets, 7950 Align Alignment) const { 7951 SDLoc DL(CombinedOffset); 7952 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7953 uint32_t Imm = C->getZExtValue(); 7954 uint32_t SOffset, ImmOffset; 7955 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7956 Alignment)) { 7957 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7958 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7959 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7960 return; 7961 } 7962 } 7963 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7964 SDValue N0 = CombinedOffset.getOperand(0); 7965 SDValue N1 = CombinedOffset.getOperand(1); 7966 uint32_t SOffset, ImmOffset; 7967 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7968 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7969 Subtarget, Alignment)) { 7970 Offsets[0] = N0; 7971 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7972 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7973 return; 7974 } 7975 } 7976 Offsets[0] = CombinedOffset; 7977 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7978 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7979 } 7980 7981 // Handle 8 bit and 16 bit buffer loads 7982 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7983 EVT LoadVT, SDLoc DL, 7984 ArrayRef<SDValue> Ops, 7985 MemSDNode *M) const { 7986 EVT IntVT = LoadVT.changeTypeToInteger(); 7987 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7988 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7989 7990 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7991 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7992 Ops, IntVT, 7993 M->getMemOperand()); 7994 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7995 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7996 7997 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7998 } 7999 8000 // Handle 8 bit and 16 bit buffer stores 8001 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8002 EVT VDataType, SDLoc DL, 8003 SDValue Ops[], 8004 MemSDNode *M) const { 8005 if (VDataType == MVT::f16) 8006 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8007 8008 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8009 Ops[1] = BufferStoreExt; 8010 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8011 AMDGPUISD::BUFFER_STORE_SHORT; 8012 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8013 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8014 M->getMemOperand()); 8015 } 8016 8017 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8018 ISD::LoadExtType ExtType, SDValue Op, 8019 const SDLoc &SL, EVT VT) { 8020 if (VT.bitsLT(Op.getValueType())) 8021 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8022 8023 switch (ExtType) { 8024 case ISD::SEXTLOAD: 8025 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8026 case ISD::ZEXTLOAD: 8027 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8028 case ISD::EXTLOAD: 8029 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8030 case ISD::NON_EXTLOAD: 8031 return Op; 8032 } 8033 8034 llvm_unreachable("invalid ext type"); 8035 } 8036 8037 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8038 SelectionDAG &DAG = DCI.DAG; 8039 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8040 return SDValue(); 8041 8042 // FIXME: Constant loads should all be marked invariant. 8043 unsigned AS = Ld->getAddressSpace(); 8044 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8045 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8046 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8047 return SDValue(); 8048 8049 // Don't do this early, since it may interfere with adjacent load merging for 8050 // illegal types. We can avoid losing alignment information for exotic types 8051 // pre-legalize. 8052 EVT MemVT = Ld->getMemoryVT(); 8053 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8054 MemVT.getSizeInBits() >= 32) 8055 return SDValue(); 8056 8057 SDLoc SL(Ld); 8058 8059 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8060 "unexpected vector extload"); 8061 8062 // TODO: Drop only high part of range. 8063 SDValue Ptr = Ld->getBasePtr(); 8064 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8065 MVT::i32, SL, Ld->getChain(), Ptr, 8066 Ld->getOffset(), 8067 Ld->getPointerInfo(), MVT::i32, 8068 Ld->getAlignment(), 8069 Ld->getMemOperand()->getFlags(), 8070 Ld->getAAInfo(), 8071 nullptr); // Drop ranges 8072 8073 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8074 if (MemVT.isFloatingPoint()) { 8075 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8076 "unexpected fp extload"); 8077 TruncVT = MemVT.changeTypeToInteger(); 8078 } 8079 8080 SDValue Cvt = NewLoad; 8081 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8082 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8083 DAG.getValueType(TruncVT)); 8084 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8085 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8086 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8087 } else { 8088 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8089 } 8090 8091 EVT VT = Ld->getValueType(0); 8092 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8093 8094 DCI.AddToWorklist(Cvt.getNode()); 8095 8096 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8097 // the appropriate extension from the 32-bit load. 8098 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8099 DCI.AddToWorklist(Cvt.getNode()); 8100 8101 // Handle conversion back to floating point if necessary. 8102 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8103 8104 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8105 } 8106 8107 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8108 SDLoc DL(Op); 8109 LoadSDNode *Load = cast<LoadSDNode>(Op); 8110 ISD::LoadExtType ExtType = Load->getExtensionType(); 8111 EVT MemVT = Load->getMemoryVT(); 8112 8113 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8114 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8115 return SDValue(); 8116 8117 // FIXME: Copied from PPC 8118 // First, load into 32 bits, then truncate to 1 bit. 8119 8120 SDValue Chain = Load->getChain(); 8121 SDValue BasePtr = Load->getBasePtr(); 8122 MachineMemOperand *MMO = Load->getMemOperand(); 8123 8124 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8125 8126 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8127 BasePtr, RealMemVT, MMO); 8128 8129 if (!MemVT.isVector()) { 8130 SDValue Ops[] = { 8131 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8132 NewLD.getValue(1) 8133 }; 8134 8135 return DAG.getMergeValues(Ops, DL); 8136 } 8137 8138 SmallVector<SDValue, 3> Elts; 8139 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8140 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8141 DAG.getConstant(I, DL, MVT::i32)); 8142 8143 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8144 } 8145 8146 SDValue Ops[] = { 8147 DAG.getBuildVector(MemVT, DL, Elts), 8148 NewLD.getValue(1) 8149 }; 8150 8151 return DAG.getMergeValues(Ops, DL); 8152 } 8153 8154 if (!MemVT.isVector()) 8155 return SDValue(); 8156 8157 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8158 "Custom lowering for non-i32 vectors hasn't been implemented."); 8159 8160 unsigned Alignment = Load->getAlignment(); 8161 unsigned AS = Load->getAddressSpace(); 8162 if (Subtarget->hasLDSMisalignedBug() && 8163 AS == AMDGPUAS::FLAT_ADDRESS && 8164 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8165 return SplitVectorLoad(Op, DAG); 8166 } 8167 8168 MachineFunction &MF = DAG.getMachineFunction(); 8169 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8170 // If there is a possibilty that flat instruction access scratch memory 8171 // then we need to use the same legalization rules we use for private. 8172 if (AS == AMDGPUAS::FLAT_ADDRESS && 8173 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8174 AS = MFI->hasFlatScratchInit() ? 8175 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8176 8177 unsigned NumElements = MemVT.getVectorNumElements(); 8178 8179 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8180 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8181 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8182 if (MemVT.isPow2VectorType()) 8183 return SDValue(); 8184 return WidenOrSplitVectorLoad(Op, DAG); 8185 } 8186 // Non-uniform loads will be selected to MUBUF instructions, so they 8187 // have the same legalization requirements as global and private 8188 // loads. 8189 // 8190 } 8191 8192 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8193 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8194 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8195 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8196 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8197 Alignment >= 4 && NumElements < 32) { 8198 if (MemVT.isPow2VectorType()) 8199 return SDValue(); 8200 return WidenOrSplitVectorLoad(Op, DAG); 8201 } 8202 // Non-uniform loads will be selected to MUBUF instructions, so they 8203 // have the same legalization requirements as global and private 8204 // loads. 8205 // 8206 } 8207 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8208 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8209 AS == AMDGPUAS::GLOBAL_ADDRESS || 8210 AS == AMDGPUAS::FLAT_ADDRESS) { 8211 if (NumElements > 4) 8212 return SplitVectorLoad(Op, DAG); 8213 // v3 loads not supported on SI. 8214 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8215 return WidenOrSplitVectorLoad(Op, DAG); 8216 8217 // v3 and v4 loads are supported for private and global memory. 8218 return SDValue(); 8219 } 8220 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8221 // Depending on the setting of the private_element_size field in the 8222 // resource descriptor, we can only make private accesses up to a certain 8223 // size. 8224 switch (Subtarget->getMaxPrivateElementSize()) { 8225 case 4: { 8226 SDValue Ops[2]; 8227 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8228 return DAG.getMergeValues(Ops, DL); 8229 } 8230 case 8: 8231 if (NumElements > 2) 8232 return SplitVectorLoad(Op, DAG); 8233 return SDValue(); 8234 case 16: 8235 // Same as global/flat 8236 if (NumElements > 4) 8237 return SplitVectorLoad(Op, DAG); 8238 // v3 loads not supported on SI. 8239 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8240 return WidenOrSplitVectorLoad(Op, DAG); 8241 8242 return SDValue(); 8243 default: 8244 llvm_unreachable("unsupported private_element_size"); 8245 } 8246 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8247 // Use ds_read_b128 or ds_read_b96 when possible. 8248 if (Subtarget->hasDS96AndDS128() && 8249 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8250 MemVT.getStoreSize() == 12) && 8251 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8252 Load->getAlign())) 8253 return SDValue(); 8254 8255 if (NumElements > 2) 8256 return SplitVectorLoad(Op, DAG); 8257 8258 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8259 // address is negative, then the instruction is incorrectly treated as 8260 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8261 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8262 // load later in the SILoadStoreOptimizer. 8263 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8264 NumElements == 2 && MemVT.getStoreSize() == 8 && 8265 Load->getAlignment() < 8) { 8266 return SplitVectorLoad(Op, DAG); 8267 } 8268 } 8269 8270 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8271 MemVT, *Load->getMemOperand())) { 8272 SDValue Ops[2]; 8273 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8274 return DAG.getMergeValues(Ops, DL); 8275 } 8276 8277 return SDValue(); 8278 } 8279 8280 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8281 EVT VT = Op.getValueType(); 8282 assert(VT.getSizeInBits() == 64); 8283 8284 SDLoc DL(Op); 8285 SDValue Cond = Op.getOperand(0); 8286 8287 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8288 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8289 8290 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8291 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8292 8293 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8294 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8295 8296 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8297 8298 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8299 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8300 8301 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8302 8303 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8304 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8305 } 8306 8307 // Catch division cases where we can use shortcuts with rcp and rsq 8308 // instructions. 8309 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8310 SelectionDAG &DAG) const { 8311 SDLoc SL(Op); 8312 SDValue LHS = Op.getOperand(0); 8313 SDValue RHS = Op.getOperand(1); 8314 EVT VT = Op.getValueType(); 8315 const SDNodeFlags Flags = Op->getFlags(); 8316 8317 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8318 8319 // Without !fpmath accuracy information, we can't do more because we don't 8320 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8321 if (!AllowInaccurateRcp) 8322 return SDValue(); 8323 8324 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8325 if (CLHS->isExactlyValue(1.0)) { 8326 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8327 // the CI documentation has a worst case error of 1 ulp. 8328 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8329 // use it as long as we aren't trying to use denormals. 8330 // 8331 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8332 8333 // 1.0 / sqrt(x) -> rsq(x) 8334 8335 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8336 // error seems really high at 2^29 ULP. 8337 if (RHS.getOpcode() == ISD::FSQRT) 8338 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8339 8340 // 1.0 / x -> rcp(x) 8341 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8342 } 8343 8344 // Same as for 1.0, but expand the sign out of the constant. 8345 if (CLHS->isExactlyValue(-1.0)) { 8346 // -1.0 / x -> rcp (fneg x) 8347 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8348 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8349 } 8350 } 8351 8352 // Turn into multiply by the reciprocal. 8353 // x / y -> x * (1.0 / y) 8354 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8355 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8356 } 8357 8358 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8359 SelectionDAG &DAG) const { 8360 SDLoc SL(Op); 8361 SDValue X = Op.getOperand(0); 8362 SDValue Y = Op.getOperand(1); 8363 EVT VT = Op.getValueType(); 8364 const SDNodeFlags Flags = Op->getFlags(); 8365 8366 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8367 DAG.getTarget().Options.UnsafeFPMath; 8368 if (!AllowInaccurateDiv) 8369 return SDValue(); 8370 8371 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8372 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8373 8374 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8375 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8376 8377 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8378 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8379 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8380 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8381 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8382 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8383 } 8384 8385 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8386 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8387 SDNodeFlags Flags) { 8388 if (GlueChain->getNumValues() <= 1) { 8389 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8390 } 8391 8392 assert(GlueChain->getNumValues() == 3); 8393 8394 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8395 switch (Opcode) { 8396 default: llvm_unreachable("no chain equivalent for opcode"); 8397 case ISD::FMUL: 8398 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8399 break; 8400 } 8401 8402 return DAG.getNode(Opcode, SL, VTList, 8403 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8404 Flags); 8405 } 8406 8407 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8408 EVT VT, SDValue A, SDValue B, SDValue C, 8409 SDValue GlueChain, SDNodeFlags Flags) { 8410 if (GlueChain->getNumValues() <= 1) { 8411 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8412 } 8413 8414 assert(GlueChain->getNumValues() == 3); 8415 8416 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8417 switch (Opcode) { 8418 default: llvm_unreachable("no chain equivalent for opcode"); 8419 case ISD::FMA: 8420 Opcode = AMDGPUISD::FMA_W_CHAIN; 8421 break; 8422 } 8423 8424 return DAG.getNode(Opcode, SL, VTList, 8425 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8426 Flags); 8427 } 8428 8429 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8430 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8431 return FastLowered; 8432 8433 SDLoc SL(Op); 8434 SDValue Src0 = Op.getOperand(0); 8435 SDValue Src1 = Op.getOperand(1); 8436 8437 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8438 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8439 8440 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8441 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8442 8443 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8444 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8445 8446 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8447 } 8448 8449 // Faster 2.5 ULP division that does not support denormals. 8450 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8451 SDLoc SL(Op); 8452 SDValue LHS = Op.getOperand(1); 8453 SDValue RHS = Op.getOperand(2); 8454 8455 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8456 8457 const APFloat K0Val(BitsToFloat(0x6f800000)); 8458 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8459 8460 const APFloat K1Val(BitsToFloat(0x2f800000)); 8461 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8462 8463 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8464 8465 EVT SetCCVT = 8466 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8467 8468 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8469 8470 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8471 8472 // TODO: Should this propagate fast-math-flags? 8473 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8474 8475 // rcp does not support denormals. 8476 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8477 8478 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8479 8480 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8481 } 8482 8483 // Returns immediate value for setting the F32 denorm mode when using the 8484 // S_DENORM_MODE instruction. 8485 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8486 const SDLoc &SL, const GCNSubtarget *ST) { 8487 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8488 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8489 ? FP_DENORM_FLUSH_NONE 8490 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8491 8492 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8493 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8494 } 8495 8496 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8497 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8498 return FastLowered; 8499 8500 // The selection matcher assumes anything with a chain selecting to a 8501 // mayRaiseFPException machine instruction. Since we're introducing a chain 8502 // here, we need to explicitly report nofpexcept for the regular fdiv 8503 // lowering. 8504 SDNodeFlags Flags = Op->getFlags(); 8505 Flags.setNoFPExcept(true); 8506 8507 SDLoc SL(Op); 8508 SDValue LHS = Op.getOperand(0); 8509 SDValue RHS = Op.getOperand(1); 8510 8511 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8512 8513 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8514 8515 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8516 {RHS, RHS, LHS}, Flags); 8517 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8518 {LHS, RHS, LHS}, Flags); 8519 8520 // Denominator is scaled to not be denormal, so using rcp is ok. 8521 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8522 DenominatorScaled, Flags); 8523 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8524 DenominatorScaled, Flags); 8525 8526 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8527 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8528 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8529 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8530 8531 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8532 8533 if (!HasFP32Denormals) { 8534 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8535 // lowering. The chain dependence is insufficient, and we need glue. We do 8536 // not need the glue variants in a strictfp function. 8537 8538 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8539 8540 SDNode *EnableDenorm; 8541 if (Subtarget->hasDenormModeInst()) { 8542 const SDValue EnableDenormValue = 8543 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8544 8545 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8546 DAG.getEntryNode(), EnableDenormValue).getNode(); 8547 } else { 8548 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8549 SL, MVT::i32); 8550 EnableDenorm = 8551 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8552 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8553 } 8554 8555 SDValue Ops[3] = { 8556 NegDivScale0, 8557 SDValue(EnableDenorm, 0), 8558 SDValue(EnableDenorm, 1) 8559 }; 8560 8561 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8562 } 8563 8564 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8565 ApproxRcp, One, NegDivScale0, Flags); 8566 8567 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8568 ApproxRcp, Fma0, Flags); 8569 8570 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8571 Fma1, Fma1, Flags); 8572 8573 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8574 NumeratorScaled, Mul, Flags); 8575 8576 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8577 Fma2, Fma1, Mul, Fma2, Flags); 8578 8579 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8580 NumeratorScaled, Fma3, Flags); 8581 8582 if (!HasFP32Denormals) { 8583 SDNode *DisableDenorm; 8584 if (Subtarget->hasDenormModeInst()) { 8585 const SDValue DisableDenormValue = 8586 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8587 8588 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8589 Fma4.getValue(1), DisableDenormValue, 8590 Fma4.getValue(2)).getNode(); 8591 } else { 8592 const SDValue DisableDenormValue = 8593 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8594 8595 DisableDenorm = DAG.getMachineNode( 8596 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8597 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8598 } 8599 8600 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8601 SDValue(DisableDenorm, 0), DAG.getRoot()); 8602 DAG.setRoot(OutputChain); 8603 } 8604 8605 SDValue Scale = NumeratorScaled.getValue(1); 8606 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8607 {Fma4, Fma1, Fma3, Scale}, Flags); 8608 8609 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8610 } 8611 8612 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8613 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8614 return FastLowered; 8615 8616 SDLoc SL(Op); 8617 SDValue X = Op.getOperand(0); 8618 SDValue Y = Op.getOperand(1); 8619 8620 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8621 8622 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8623 8624 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8625 8626 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8627 8628 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8629 8630 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8631 8632 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8633 8634 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8635 8636 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8637 8638 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8639 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8640 8641 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8642 NegDivScale0, Mul, DivScale1); 8643 8644 SDValue Scale; 8645 8646 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8647 // Workaround a hardware bug on SI where the condition output from div_scale 8648 // is not usable. 8649 8650 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8651 8652 // Figure out if the scale to use for div_fmas. 8653 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8654 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8655 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8656 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8657 8658 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8659 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8660 8661 SDValue Scale0Hi 8662 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8663 SDValue Scale1Hi 8664 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8665 8666 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8667 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8668 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8669 } else { 8670 Scale = DivScale1.getValue(1); 8671 } 8672 8673 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8674 Fma4, Fma3, Mul, Scale); 8675 8676 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8677 } 8678 8679 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8680 EVT VT = Op.getValueType(); 8681 8682 if (VT == MVT::f32) 8683 return LowerFDIV32(Op, DAG); 8684 8685 if (VT == MVT::f64) 8686 return LowerFDIV64(Op, DAG); 8687 8688 if (VT == MVT::f16) 8689 return LowerFDIV16(Op, DAG); 8690 8691 llvm_unreachable("Unexpected type for fdiv"); 8692 } 8693 8694 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8695 SDLoc DL(Op); 8696 StoreSDNode *Store = cast<StoreSDNode>(Op); 8697 EVT VT = Store->getMemoryVT(); 8698 8699 if (VT == MVT::i1) { 8700 return DAG.getTruncStore(Store->getChain(), DL, 8701 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8702 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8703 } 8704 8705 assert(VT.isVector() && 8706 Store->getValue().getValueType().getScalarType() == MVT::i32); 8707 8708 unsigned AS = Store->getAddressSpace(); 8709 if (Subtarget->hasLDSMisalignedBug() && 8710 AS == AMDGPUAS::FLAT_ADDRESS && 8711 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8712 return SplitVectorStore(Op, DAG); 8713 } 8714 8715 MachineFunction &MF = DAG.getMachineFunction(); 8716 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8717 // If there is a possibilty that flat instruction access scratch memory 8718 // then we need to use the same legalization rules we use for private. 8719 if (AS == AMDGPUAS::FLAT_ADDRESS && 8720 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8721 AS = MFI->hasFlatScratchInit() ? 8722 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8723 8724 unsigned NumElements = VT.getVectorNumElements(); 8725 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8726 AS == AMDGPUAS::FLAT_ADDRESS) { 8727 if (NumElements > 4) 8728 return SplitVectorStore(Op, DAG); 8729 // v3 stores not supported on SI. 8730 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8731 return SplitVectorStore(Op, DAG); 8732 8733 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8734 VT, *Store->getMemOperand())) 8735 return expandUnalignedStore(Store, DAG); 8736 8737 return SDValue(); 8738 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8739 switch (Subtarget->getMaxPrivateElementSize()) { 8740 case 4: 8741 return scalarizeVectorStore(Store, DAG); 8742 case 8: 8743 if (NumElements > 2) 8744 return SplitVectorStore(Op, DAG); 8745 return SDValue(); 8746 case 16: 8747 if (NumElements > 4 || 8748 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8749 return SplitVectorStore(Op, DAG); 8750 return SDValue(); 8751 default: 8752 llvm_unreachable("unsupported private_element_size"); 8753 } 8754 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8755 // Use ds_write_b128 or ds_write_b96 when possible. 8756 if (Subtarget->hasDS96AndDS128() && 8757 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8758 (VT.getStoreSize() == 12)) && 8759 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8760 Store->getAlign())) 8761 return SDValue(); 8762 8763 if (NumElements > 2) 8764 return SplitVectorStore(Op, DAG); 8765 8766 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8767 // address is negative, then the instruction is incorrectly treated as 8768 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8769 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8770 // store later in the SILoadStoreOptimizer. 8771 if (!Subtarget->hasUsableDSOffset() && 8772 NumElements == 2 && VT.getStoreSize() == 8 && 8773 Store->getAlignment() < 8) { 8774 return SplitVectorStore(Op, DAG); 8775 } 8776 8777 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8778 VT, *Store->getMemOperand())) { 8779 if (VT.isVector()) 8780 return SplitVectorStore(Op, DAG); 8781 return expandUnalignedStore(Store, DAG); 8782 } 8783 8784 return SDValue(); 8785 } else { 8786 llvm_unreachable("unhandled address space"); 8787 } 8788 } 8789 8790 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8791 SDLoc DL(Op); 8792 EVT VT = Op.getValueType(); 8793 SDValue Arg = Op.getOperand(0); 8794 SDValue TrigVal; 8795 8796 // Propagate fast-math flags so that the multiply we introduce can be folded 8797 // if Arg is already the result of a multiply by constant. 8798 auto Flags = Op->getFlags(); 8799 8800 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8801 8802 if (Subtarget->hasTrigReducedRange()) { 8803 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8804 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8805 } else { 8806 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8807 } 8808 8809 switch (Op.getOpcode()) { 8810 case ISD::FCOS: 8811 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8812 case ISD::FSIN: 8813 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8814 default: 8815 llvm_unreachable("Wrong trig opcode"); 8816 } 8817 } 8818 8819 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8820 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8821 assert(AtomicNode->isCompareAndSwap()); 8822 unsigned AS = AtomicNode->getAddressSpace(); 8823 8824 // No custom lowering required for local address space 8825 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8826 return Op; 8827 8828 // Non-local address space requires custom lowering for atomic compare 8829 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8830 SDLoc DL(Op); 8831 SDValue ChainIn = Op.getOperand(0); 8832 SDValue Addr = Op.getOperand(1); 8833 SDValue Old = Op.getOperand(2); 8834 SDValue New = Op.getOperand(3); 8835 EVT VT = Op.getValueType(); 8836 MVT SimpleVT = VT.getSimpleVT(); 8837 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8838 8839 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8840 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8841 8842 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8843 Ops, VT, AtomicNode->getMemOperand()); 8844 } 8845 8846 //===----------------------------------------------------------------------===// 8847 // Custom DAG optimizations 8848 //===----------------------------------------------------------------------===// 8849 8850 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8851 DAGCombinerInfo &DCI) const { 8852 EVT VT = N->getValueType(0); 8853 EVT ScalarVT = VT.getScalarType(); 8854 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8855 return SDValue(); 8856 8857 SelectionDAG &DAG = DCI.DAG; 8858 SDLoc DL(N); 8859 8860 SDValue Src = N->getOperand(0); 8861 EVT SrcVT = Src.getValueType(); 8862 8863 // TODO: We could try to match extracting the higher bytes, which would be 8864 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8865 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8866 // about in practice. 8867 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8868 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8869 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8870 DCI.AddToWorklist(Cvt.getNode()); 8871 8872 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8873 if (ScalarVT != MVT::f32) { 8874 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8875 DAG.getTargetConstant(0, DL, MVT::i32)); 8876 } 8877 return Cvt; 8878 } 8879 } 8880 8881 return SDValue(); 8882 } 8883 8884 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8885 8886 // This is a variant of 8887 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8888 // 8889 // The normal DAG combiner will do this, but only if the add has one use since 8890 // that would increase the number of instructions. 8891 // 8892 // This prevents us from seeing a constant offset that can be folded into a 8893 // memory instruction's addressing mode. If we know the resulting add offset of 8894 // a pointer can be folded into an addressing offset, we can replace the pointer 8895 // operand with the add of new constant offset. This eliminates one of the uses, 8896 // and may allow the remaining use to also be simplified. 8897 // 8898 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8899 unsigned AddrSpace, 8900 EVT MemVT, 8901 DAGCombinerInfo &DCI) const { 8902 SDValue N0 = N->getOperand(0); 8903 SDValue N1 = N->getOperand(1); 8904 8905 // We only do this to handle cases where it's profitable when there are 8906 // multiple uses of the add, so defer to the standard combine. 8907 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8908 N0->hasOneUse()) 8909 return SDValue(); 8910 8911 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8912 if (!CN1) 8913 return SDValue(); 8914 8915 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8916 if (!CAdd) 8917 return SDValue(); 8918 8919 // If the resulting offset is too large, we can't fold it into the addressing 8920 // mode offset. 8921 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8922 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8923 8924 AddrMode AM; 8925 AM.HasBaseReg = true; 8926 AM.BaseOffs = Offset.getSExtValue(); 8927 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8928 return SDValue(); 8929 8930 SelectionDAG &DAG = DCI.DAG; 8931 SDLoc SL(N); 8932 EVT VT = N->getValueType(0); 8933 8934 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8935 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8936 8937 SDNodeFlags Flags; 8938 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8939 (N0.getOpcode() == ISD::OR || 8940 N0->getFlags().hasNoUnsignedWrap())); 8941 8942 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8943 } 8944 8945 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8946 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8947 /// specific intrinsic, but they all place the pointer operand first. 8948 static unsigned getBasePtrIndex(const MemSDNode *N) { 8949 switch (N->getOpcode()) { 8950 case ISD::STORE: 8951 case ISD::INTRINSIC_W_CHAIN: 8952 case ISD::INTRINSIC_VOID: 8953 return 2; 8954 default: 8955 return 1; 8956 } 8957 } 8958 8959 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8960 DAGCombinerInfo &DCI) const { 8961 SelectionDAG &DAG = DCI.DAG; 8962 SDLoc SL(N); 8963 8964 unsigned PtrIdx = getBasePtrIndex(N); 8965 SDValue Ptr = N->getOperand(PtrIdx); 8966 8967 // TODO: We could also do this for multiplies. 8968 if (Ptr.getOpcode() == ISD::SHL) { 8969 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8970 N->getMemoryVT(), DCI); 8971 if (NewPtr) { 8972 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8973 8974 NewOps[PtrIdx] = NewPtr; 8975 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8976 } 8977 } 8978 8979 return SDValue(); 8980 } 8981 8982 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8983 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8984 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8985 (Opc == ISD::XOR && Val == 0); 8986 } 8987 8988 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8989 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8990 // integer combine opportunities since most 64-bit operations are decomposed 8991 // this way. TODO: We won't want this for SALU especially if it is an inline 8992 // immediate. 8993 SDValue SITargetLowering::splitBinaryBitConstantOp( 8994 DAGCombinerInfo &DCI, 8995 const SDLoc &SL, 8996 unsigned Opc, SDValue LHS, 8997 const ConstantSDNode *CRHS) const { 8998 uint64_t Val = CRHS->getZExtValue(); 8999 uint32_t ValLo = Lo_32(Val); 9000 uint32_t ValHi = Hi_32(Val); 9001 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9002 9003 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9004 bitOpWithConstantIsReducible(Opc, ValHi)) || 9005 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9006 // If we need to materialize a 64-bit immediate, it will be split up later 9007 // anyway. Avoid creating the harder to understand 64-bit immediate 9008 // materialization. 9009 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9010 } 9011 9012 return SDValue(); 9013 } 9014 9015 // Returns true if argument is a boolean value which is not serialized into 9016 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9017 static bool isBoolSGPR(SDValue V) { 9018 if (V.getValueType() != MVT::i1) 9019 return false; 9020 switch (V.getOpcode()) { 9021 default: 9022 break; 9023 case ISD::SETCC: 9024 case AMDGPUISD::FP_CLASS: 9025 return true; 9026 case ISD::AND: 9027 case ISD::OR: 9028 case ISD::XOR: 9029 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9030 } 9031 return false; 9032 } 9033 9034 // If a constant has all zeroes or all ones within each byte return it. 9035 // Otherwise return 0. 9036 static uint32_t getConstantPermuteMask(uint32_t C) { 9037 // 0xff for any zero byte in the mask 9038 uint32_t ZeroByteMask = 0; 9039 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9040 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9041 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9042 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9043 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9044 if ((NonZeroByteMask & C) != NonZeroByteMask) 9045 return 0; // Partial bytes selected. 9046 return C; 9047 } 9048 9049 // Check if a node selects whole bytes from its operand 0 starting at a byte 9050 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9051 // or -1 if not succeeded. 9052 // Note byte select encoding: 9053 // value 0-3 selects corresponding source byte; 9054 // value 0xc selects zero; 9055 // value 0xff selects 0xff. 9056 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9057 assert(V.getValueSizeInBits() == 32); 9058 9059 if (V.getNumOperands() != 2) 9060 return ~0; 9061 9062 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9063 if (!N1) 9064 return ~0; 9065 9066 uint32_t C = N1->getZExtValue(); 9067 9068 switch (V.getOpcode()) { 9069 default: 9070 break; 9071 case ISD::AND: 9072 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9073 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9074 } 9075 break; 9076 9077 case ISD::OR: 9078 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9079 return (0x03020100 & ~ConstMask) | ConstMask; 9080 } 9081 break; 9082 9083 case ISD::SHL: 9084 if (C % 8) 9085 return ~0; 9086 9087 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9088 9089 case ISD::SRL: 9090 if (C % 8) 9091 return ~0; 9092 9093 return uint32_t(0x0c0c0c0c03020100ull >> C); 9094 } 9095 9096 return ~0; 9097 } 9098 9099 SDValue SITargetLowering::performAndCombine(SDNode *N, 9100 DAGCombinerInfo &DCI) const { 9101 if (DCI.isBeforeLegalize()) 9102 return SDValue(); 9103 9104 SelectionDAG &DAG = DCI.DAG; 9105 EVT VT = N->getValueType(0); 9106 SDValue LHS = N->getOperand(0); 9107 SDValue RHS = N->getOperand(1); 9108 9109 9110 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9111 if (VT == MVT::i64 && CRHS) { 9112 if (SDValue Split 9113 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9114 return Split; 9115 } 9116 9117 if (CRHS && VT == MVT::i32) { 9118 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9119 // nb = number of trailing zeroes in mask 9120 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9121 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9122 uint64_t Mask = CRHS->getZExtValue(); 9123 unsigned Bits = countPopulation(Mask); 9124 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9125 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9126 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9127 unsigned Shift = CShift->getZExtValue(); 9128 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9129 unsigned Offset = NB + Shift; 9130 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9131 SDLoc SL(N); 9132 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9133 LHS->getOperand(0), 9134 DAG.getConstant(Offset, SL, MVT::i32), 9135 DAG.getConstant(Bits, SL, MVT::i32)); 9136 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9137 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9138 DAG.getValueType(NarrowVT)); 9139 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9140 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9141 return Shl; 9142 } 9143 } 9144 } 9145 9146 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9147 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9148 isa<ConstantSDNode>(LHS.getOperand(2))) { 9149 uint32_t Sel = getConstantPermuteMask(Mask); 9150 if (!Sel) 9151 return SDValue(); 9152 9153 // Select 0xc for all zero bytes 9154 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9155 SDLoc DL(N); 9156 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9157 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9158 } 9159 } 9160 9161 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9162 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9163 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9164 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9165 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9166 9167 SDValue X = LHS.getOperand(0); 9168 SDValue Y = RHS.getOperand(0); 9169 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9170 return SDValue(); 9171 9172 if (LCC == ISD::SETO) { 9173 if (X != LHS.getOperand(1)) 9174 return SDValue(); 9175 9176 if (RCC == ISD::SETUNE) { 9177 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9178 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9179 return SDValue(); 9180 9181 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9182 SIInstrFlags::N_SUBNORMAL | 9183 SIInstrFlags::N_ZERO | 9184 SIInstrFlags::P_ZERO | 9185 SIInstrFlags::P_SUBNORMAL | 9186 SIInstrFlags::P_NORMAL; 9187 9188 static_assert(((~(SIInstrFlags::S_NAN | 9189 SIInstrFlags::Q_NAN | 9190 SIInstrFlags::N_INFINITY | 9191 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9192 "mask not equal"); 9193 9194 SDLoc DL(N); 9195 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9196 X, DAG.getConstant(Mask, DL, MVT::i32)); 9197 } 9198 } 9199 } 9200 9201 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9202 std::swap(LHS, RHS); 9203 9204 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9205 RHS.hasOneUse()) { 9206 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9207 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9208 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9209 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9210 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9211 (RHS.getOperand(0) == LHS.getOperand(0) && 9212 LHS.getOperand(0) == LHS.getOperand(1))) { 9213 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9214 unsigned NewMask = LCC == ISD::SETO ? 9215 Mask->getZExtValue() & ~OrdMask : 9216 Mask->getZExtValue() & OrdMask; 9217 9218 SDLoc DL(N); 9219 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9220 DAG.getConstant(NewMask, DL, MVT::i32)); 9221 } 9222 } 9223 9224 if (VT == MVT::i32 && 9225 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9226 // and x, (sext cc from i1) => select cc, x, 0 9227 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9228 std::swap(LHS, RHS); 9229 if (isBoolSGPR(RHS.getOperand(0))) 9230 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9231 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9232 } 9233 9234 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9235 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9236 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9237 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9238 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9239 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9240 if (LHSMask != ~0u && RHSMask != ~0u) { 9241 // Canonicalize the expression in an attempt to have fewer unique masks 9242 // and therefore fewer registers used to hold the masks. 9243 if (LHSMask > RHSMask) { 9244 std::swap(LHSMask, RHSMask); 9245 std::swap(LHS, RHS); 9246 } 9247 9248 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9249 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9250 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9251 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9252 9253 // Check of we need to combine values from two sources within a byte. 9254 if (!(LHSUsedLanes & RHSUsedLanes) && 9255 // If we select high and lower word keep it for SDWA. 9256 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9257 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9258 // Each byte in each mask is either selector mask 0-3, or has higher 9259 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9260 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9261 // mask which is not 0xff wins. By anding both masks we have a correct 9262 // result except that 0x0c shall be corrected to give 0x0c only. 9263 uint32_t Mask = LHSMask & RHSMask; 9264 for (unsigned I = 0; I < 32; I += 8) { 9265 uint32_t ByteSel = 0xff << I; 9266 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9267 Mask &= (0x0c << I) & 0xffffffff; 9268 } 9269 9270 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9271 // or 0x0c. 9272 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9273 SDLoc DL(N); 9274 9275 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9276 LHS.getOperand(0), RHS.getOperand(0), 9277 DAG.getConstant(Sel, DL, MVT::i32)); 9278 } 9279 } 9280 } 9281 9282 return SDValue(); 9283 } 9284 9285 SDValue SITargetLowering::performOrCombine(SDNode *N, 9286 DAGCombinerInfo &DCI) const { 9287 SelectionDAG &DAG = DCI.DAG; 9288 SDValue LHS = N->getOperand(0); 9289 SDValue RHS = N->getOperand(1); 9290 9291 EVT VT = N->getValueType(0); 9292 if (VT == MVT::i1) { 9293 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9294 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9295 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9296 SDValue Src = LHS.getOperand(0); 9297 if (Src != RHS.getOperand(0)) 9298 return SDValue(); 9299 9300 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9301 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9302 if (!CLHS || !CRHS) 9303 return SDValue(); 9304 9305 // Only 10 bits are used. 9306 static const uint32_t MaxMask = 0x3ff; 9307 9308 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9309 SDLoc DL(N); 9310 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9311 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9312 } 9313 9314 return SDValue(); 9315 } 9316 9317 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9318 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9319 LHS.getOpcode() == AMDGPUISD::PERM && 9320 isa<ConstantSDNode>(LHS.getOperand(2))) { 9321 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9322 if (!Sel) 9323 return SDValue(); 9324 9325 Sel |= LHS.getConstantOperandVal(2); 9326 SDLoc DL(N); 9327 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9328 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9329 } 9330 9331 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9332 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9333 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9334 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9335 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9336 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9337 if (LHSMask != ~0u && RHSMask != ~0u) { 9338 // Canonicalize the expression in an attempt to have fewer unique masks 9339 // and therefore fewer registers used to hold the masks. 9340 if (LHSMask > RHSMask) { 9341 std::swap(LHSMask, RHSMask); 9342 std::swap(LHS, RHS); 9343 } 9344 9345 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9346 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9347 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9348 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9349 9350 // Check of we need to combine values from two sources within a byte. 9351 if (!(LHSUsedLanes & RHSUsedLanes) && 9352 // If we select high and lower word keep it for SDWA. 9353 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9354 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9355 // Kill zero bytes selected by other mask. Zero value is 0xc. 9356 LHSMask &= ~RHSUsedLanes; 9357 RHSMask &= ~LHSUsedLanes; 9358 // Add 4 to each active LHS lane 9359 LHSMask |= LHSUsedLanes & 0x04040404; 9360 // Combine masks 9361 uint32_t Sel = LHSMask | RHSMask; 9362 SDLoc DL(N); 9363 9364 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9365 LHS.getOperand(0), RHS.getOperand(0), 9366 DAG.getConstant(Sel, DL, MVT::i32)); 9367 } 9368 } 9369 } 9370 9371 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9372 return SDValue(); 9373 9374 // TODO: This could be a generic combine with a predicate for extracting the 9375 // high half of an integer being free. 9376 9377 // (or i64:x, (zero_extend i32:y)) -> 9378 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9379 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9380 RHS.getOpcode() != ISD::ZERO_EXTEND) 9381 std::swap(LHS, RHS); 9382 9383 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9384 SDValue ExtSrc = RHS.getOperand(0); 9385 EVT SrcVT = ExtSrc.getValueType(); 9386 if (SrcVT == MVT::i32) { 9387 SDLoc SL(N); 9388 SDValue LowLHS, HiBits; 9389 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9390 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9391 9392 DCI.AddToWorklist(LowOr.getNode()); 9393 DCI.AddToWorklist(HiBits.getNode()); 9394 9395 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9396 LowOr, HiBits); 9397 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9398 } 9399 } 9400 9401 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9402 if (CRHS) { 9403 if (SDValue Split 9404 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9405 return Split; 9406 } 9407 9408 return SDValue(); 9409 } 9410 9411 SDValue SITargetLowering::performXorCombine(SDNode *N, 9412 DAGCombinerInfo &DCI) const { 9413 EVT VT = N->getValueType(0); 9414 if (VT != MVT::i64) 9415 return SDValue(); 9416 9417 SDValue LHS = N->getOperand(0); 9418 SDValue RHS = N->getOperand(1); 9419 9420 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9421 if (CRHS) { 9422 if (SDValue Split 9423 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9424 return Split; 9425 } 9426 9427 return SDValue(); 9428 } 9429 9430 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9431 DAGCombinerInfo &DCI) const { 9432 if (!Subtarget->has16BitInsts() || 9433 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9434 return SDValue(); 9435 9436 EVT VT = N->getValueType(0); 9437 if (VT != MVT::i32) 9438 return SDValue(); 9439 9440 SDValue Src = N->getOperand(0); 9441 if (Src.getValueType() != MVT::i16) 9442 return SDValue(); 9443 9444 return SDValue(); 9445 } 9446 9447 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9448 DAGCombinerInfo &DCI) 9449 const { 9450 SDValue Src = N->getOperand(0); 9451 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9452 9453 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9454 VTSign->getVT() == MVT::i8) || 9455 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9456 VTSign->getVT() == MVT::i16)) && 9457 Src.hasOneUse()) { 9458 auto *M = cast<MemSDNode>(Src); 9459 SDValue Ops[] = { 9460 Src.getOperand(0), // Chain 9461 Src.getOperand(1), // rsrc 9462 Src.getOperand(2), // vindex 9463 Src.getOperand(3), // voffset 9464 Src.getOperand(4), // soffset 9465 Src.getOperand(5), // offset 9466 Src.getOperand(6), 9467 Src.getOperand(7) 9468 }; 9469 // replace with BUFFER_LOAD_BYTE/SHORT 9470 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9471 Src.getOperand(0).getValueType()); 9472 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9473 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9474 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9475 ResList, 9476 Ops, M->getMemoryVT(), 9477 M->getMemOperand()); 9478 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9479 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9480 } 9481 return SDValue(); 9482 } 9483 9484 SDValue SITargetLowering::performClassCombine(SDNode *N, 9485 DAGCombinerInfo &DCI) const { 9486 SelectionDAG &DAG = DCI.DAG; 9487 SDValue Mask = N->getOperand(1); 9488 9489 // fp_class x, 0 -> false 9490 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9491 if (CMask->isNullValue()) 9492 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9493 } 9494 9495 if (N->getOperand(0).isUndef()) 9496 return DAG.getUNDEF(MVT::i1); 9497 9498 return SDValue(); 9499 } 9500 9501 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9502 DAGCombinerInfo &DCI) const { 9503 EVT VT = N->getValueType(0); 9504 SDValue N0 = N->getOperand(0); 9505 9506 if (N0.isUndef()) 9507 return N0; 9508 9509 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9510 N0.getOpcode() == ISD::SINT_TO_FP)) { 9511 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9512 N->getFlags()); 9513 } 9514 9515 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9516 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9517 N0.getOperand(0), N->getFlags()); 9518 } 9519 9520 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9521 } 9522 9523 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9524 unsigned MaxDepth) const { 9525 unsigned Opcode = Op.getOpcode(); 9526 if (Opcode == ISD::FCANONICALIZE) 9527 return true; 9528 9529 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9530 auto F = CFP->getValueAPF(); 9531 if (F.isNaN() && F.isSignaling()) 9532 return false; 9533 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9534 } 9535 9536 // If source is a result of another standard FP operation it is already in 9537 // canonical form. 9538 if (MaxDepth == 0) 9539 return false; 9540 9541 switch (Opcode) { 9542 // These will flush denorms if required. 9543 case ISD::FADD: 9544 case ISD::FSUB: 9545 case ISD::FMUL: 9546 case ISD::FCEIL: 9547 case ISD::FFLOOR: 9548 case ISD::FMA: 9549 case ISD::FMAD: 9550 case ISD::FSQRT: 9551 case ISD::FDIV: 9552 case ISD::FREM: 9553 case ISD::FP_ROUND: 9554 case ISD::FP_EXTEND: 9555 case AMDGPUISD::FMUL_LEGACY: 9556 case AMDGPUISD::FMAD_FTZ: 9557 case AMDGPUISD::RCP: 9558 case AMDGPUISD::RSQ: 9559 case AMDGPUISD::RSQ_CLAMP: 9560 case AMDGPUISD::RCP_LEGACY: 9561 case AMDGPUISD::RCP_IFLAG: 9562 case AMDGPUISD::DIV_SCALE: 9563 case AMDGPUISD::DIV_FMAS: 9564 case AMDGPUISD::DIV_FIXUP: 9565 case AMDGPUISD::FRACT: 9566 case AMDGPUISD::LDEXP: 9567 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9568 case AMDGPUISD::CVT_F32_UBYTE0: 9569 case AMDGPUISD::CVT_F32_UBYTE1: 9570 case AMDGPUISD::CVT_F32_UBYTE2: 9571 case AMDGPUISD::CVT_F32_UBYTE3: 9572 return true; 9573 9574 // It can/will be lowered or combined as a bit operation. 9575 // Need to check their input recursively to handle. 9576 case ISD::FNEG: 9577 case ISD::FABS: 9578 case ISD::FCOPYSIGN: 9579 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9580 9581 case ISD::FSIN: 9582 case ISD::FCOS: 9583 case ISD::FSINCOS: 9584 return Op.getValueType().getScalarType() != MVT::f16; 9585 9586 case ISD::FMINNUM: 9587 case ISD::FMAXNUM: 9588 case ISD::FMINNUM_IEEE: 9589 case ISD::FMAXNUM_IEEE: 9590 case AMDGPUISD::CLAMP: 9591 case AMDGPUISD::FMED3: 9592 case AMDGPUISD::FMAX3: 9593 case AMDGPUISD::FMIN3: { 9594 // FIXME: Shouldn't treat the generic operations different based these. 9595 // However, we aren't really required to flush the result from 9596 // minnum/maxnum.. 9597 9598 // snans will be quieted, so we only need to worry about denormals. 9599 if (Subtarget->supportsMinMaxDenormModes() || 9600 denormalsEnabledForType(DAG, Op.getValueType())) 9601 return true; 9602 9603 // Flushing may be required. 9604 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9605 // targets need to check their input recursively. 9606 9607 // FIXME: Does this apply with clamp? It's implemented with max. 9608 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9609 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9610 return false; 9611 } 9612 9613 return true; 9614 } 9615 case ISD::SELECT: { 9616 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9617 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9618 } 9619 case ISD::BUILD_VECTOR: { 9620 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9621 SDValue SrcOp = Op.getOperand(i); 9622 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9623 return false; 9624 } 9625 9626 return true; 9627 } 9628 case ISD::EXTRACT_VECTOR_ELT: 9629 case ISD::EXTRACT_SUBVECTOR: { 9630 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9631 } 9632 case ISD::INSERT_VECTOR_ELT: { 9633 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9634 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9635 } 9636 case ISD::UNDEF: 9637 // Could be anything. 9638 return false; 9639 9640 case ISD::BITCAST: 9641 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9642 case ISD::TRUNCATE: { 9643 // Hack round the mess we make when legalizing extract_vector_elt 9644 if (Op.getValueType() == MVT::i16) { 9645 SDValue TruncSrc = Op.getOperand(0); 9646 if (TruncSrc.getValueType() == MVT::i32 && 9647 TruncSrc.getOpcode() == ISD::BITCAST && 9648 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9649 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9650 } 9651 } 9652 return false; 9653 } 9654 case ISD::INTRINSIC_WO_CHAIN: { 9655 unsigned IntrinsicID 9656 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9657 // TODO: Handle more intrinsics 9658 switch (IntrinsicID) { 9659 case Intrinsic::amdgcn_cvt_pkrtz: 9660 case Intrinsic::amdgcn_cubeid: 9661 case Intrinsic::amdgcn_frexp_mant: 9662 case Intrinsic::amdgcn_fdot2: 9663 case Intrinsic::amdgcn_rcp: 9664 case Intrinsic::amdgcn_rsq: 9665 case Intrinsic::amdgcn_rsq_clamp: 9666 case Intrinsic::amdgcn_rcp_legacy: 9667 case Intrinsic::amdgcn_rsq_legacy: 9668 case Intrinsic::amdgcn_trig_preop: 9669 return true; 9670 default: 9671 break; 9672 } 9673 9674 LLVM_FALLTHROUGH; 9675 } 9676 default: 9677 return denormalsEnabledForType(DAG, Op.getValueType()) && 9678 DAG.isKnownNeverSNaN(Op); 9679 } 9680 9681 llvm_unreachable("invalid operation"); 9682 } 9683 9684 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9685 unsigned MaxDepth) const { 9686 MachineRegisterInfo &MRI = MF.getRegInfo(); 9687 MachineInstr *MI = MRI.getVRegDef(Reg); 9688 unsigned Opcode = MI->getOpcode(); 9689 9690 if (Opcode == AMDGPU::G_FCANONICALIZE) 9691 return true; 9692 9693 if (Opcode == AMDGPU::G_FCONSTANT) { 9694 auto F = MI->getOperand(1).getFPImm()->getValueAPF(); 9695 if (F.isNaN() && F.isSignaling()) 9696 return false; 9697 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF); 9698 } 9699 9700 if (MaxDepth == 0) 9701 return false; 9702 9703 switch (Opcode) { 9704 case AMDGPU::G_FMINNUM_IEEE: 9705 case AMDGPU::G_FMAXNUM_IEEE: { 9706 if (Subtarget->supportsMinMaxDenormModes() || 9707 denormalsEnabledForType(MRI.getType(Reg), MF)) 9708 return true; 9709 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) { 9710 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1)) 9711 return false; 9712 } 9713 return true; 9714 } 9715 default: 9716 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9717 isKnownNeverSNaN(Reg, MRI); 9718 } 9719 9720 llvm_unreachable("invalid operation"); 9721 } 9722 9723 // Constant fold canonicalize. 9724 SDValue SITargetLowering::getCanonicalConstantFP( 9725 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9726 // Flush denormals to 0 if not enabled. 9727 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9728 return DAG.getConstantFP(0.0, SL, VT); 9729 9730 if (C.isNaN()) { 9731 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9732 if (C.isSignaling()) { 9733 // Quiet a signaling NaN. 9734 // FIXME: Is this supposed to preserve payload bits? 9735 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9736 } 9737 9738 // Make sure it is the canonical NaN bitpattern. 9739 // 9740 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9741 // immediate? 9742 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9743 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9744 } 9745 9746 // Already canonical. 9747 return DAG.getConstantFP(C, SL, VT); 9748 } 9749 9750 static bool vectorEltWillFoldAway(SDValue Op) { 9751 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9752 } 9753 9754 SDValue SITargetLowering::performFCanonicalizeCombine( 9755 SDNode *N, 9756 DAGCombinerInfo &DCI) const { 9757 SelectionDAG &DAG = DCI.DAG; 9758 SDValue N0 = N->getOperand(0); 9759 EVT VT = N->getValueType(0); 9760 9761 // fcanonicalize undef -> qnan 9762 if (N0.isUndef()) { 9763 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9764 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9765 } 9766 9767 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9768 EVT VT = N->getValueType(0); 9769 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9770 } 9771 9772 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9773 // (fcanonicalize k) 9774 // 9775 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9776 9777 // TODO: This could be better with wider vectors that will be split to v2f16, 9778 // and to consider uses since there aren't that many packed operations. 9779 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9780 isTypeLegal(MVT::v2f16)) { 9781 SDLoc SL(N); 9782 SDValue NewElts[2]; 9783 SDValue Lo = N0.getOperand(0); 9784 SDValue Hi = N0.getOperand(1); 9785 EVT EltVT = Lo.getValueType(); 9786 9787 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9788 for (unsigned I = 0; I != 2; ++I) { 9789 SDValue Op = N0.getOperand(I); 9790 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9791 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9792 CFP->getValueAPF()); 9793 } else if (Op.isUndef()) { 9794 // Handled below based on what the other operand is. 9795 NewElts[I] = Op; 9796 } else { 9797 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9798 } 9799 } 9800 9801 // If one half is undef, and one is constant, perfer a splat vector rather 9802 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9803 // cheaper to use and may be free with a packed operation. 9804 if (NewElts[0].isUndef()) { 9805 if (isa<ConstantFPSDNode>(NewElts[1])) 9806 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9807 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9808 } 9809 9810 if (NewElts[1].isUndef()) { 9811 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9812 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9813 } 9814 9815 return DAG.getBuildVector(VT, SL, NewElts); 9816 } 9817 } 9818 9819 unsigned SrcOpc = N0.getOpcode(); 9820 9821 // If it's free to do so, push canonicalizes further up the source, which may 9822 // find a canonical source. 9823 // 9824 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9825 // sNaNs. 9826 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9827 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9828 if (CRHS && N0.hasOneUse()) { 9829 SDLoc SL(N); 9830 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9831 N0.getOperand(0)); 9832 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9833 DCI.AddToWorklist(Canon0.getNode()); 9834 9835 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9836 } 9837 } 9838 9839 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9840 } 9841 9842 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9843 switch (Opc) { 9844 case ISD::FMAXNUM: 9845 case ISD::FMAXNUM_IEEE: 9846 return AMDGPUISD::FMAX3; 9847 case ISD::SMAX: 9848 return AMDGPUISD::SMAX3; 9849 case ISD::UMAX: 9850 return AMDGPUISD::UMAX3; 9851 case ISD::FMINNUM: 9852 case ISD::FMINNUM_IEEE: 9853 return AMDGPUISD::FMIN3; 9854 case ISD::SMIN: 9855 return AMDGPUISD::SMIN3; 9856 case ISD::UMIN: 9857 return AMDGPUISD::UMIN3; 9858 default: 9859 llvm_unreachable("Not a min/max opcode"); 9860 } 9861 } 9862 9863 SDValue SITargetLowering::performIntMed3ImmCombine( 9864 SelectionDAG &DAG, const SDLoc &SL, 9865 SDValue Op0, SDValue Op1, bool Signed) const { 9866 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9867 if (!K1) 9868 return SDValue(); 9869 9870 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9871 if (!K0) 9872 return SDValue(); 9873 9874 if (Signed) { 9875 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9876 return SDValue(); 9877 } else { 9878 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9879 return SDValue(); 9880 } 9881 9882 EVT VT = K0->getValueType(0); 9883 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9884 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9885 return DAG.getNode(Med3Opc, SL, VT, 9886 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9887 } 9888 9889 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9890 if (VT == MVT::i16) { 9891 MVT NVT = MVT::i32; 9892 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9893 9894 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9895 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9896 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9897 9898 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9899 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9900 } 9901 9902 return SDValue(); 9903 } 9904 9905 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9906 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9907 return C; 9908 9909 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9910 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9911 return C; 9912 } 9913 9914 return nullptr; 9915 } 9916 9917 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9918 const SDLoc &SL, 9919 SDValue Op0, 9920 SDValue Op1) const { 9921 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9922 if (!K1) 9923 return SDValue(); 9924 9925 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9926 if (!K0) 9927 return SDValue(); 9928 9929 // Ordered >= (although NaN inputs should have folded away by now). 9930 if (K0->getValueAPF() > K1->getValueAPF()) 9931 return SDValue(); 9932 9933 const MachineFunction &MF = DAG.getMachineFunction(); 9934 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9935 9936 // TODO: Check IEEE bit enabled? 9937 EVT VT = Op0.getValueType(); 9938 if (Info->getMode().DX10Clamp) { 9939 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9940 // hardware fmed3 behavior converting to a min. 9941 // FIXME: Should this be allowing -0.0? 9942 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9943 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9944 } 9945 9946 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9947 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9948 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9949 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9950 // then give the other result, which is different from med3 with a NaN 9951 // input. 9952 SDValue Var = Op0.getOperand(0); 9953 if (!DAG.isKnownNeverSNaN(Var)) 9954 return SDValue(); 9955 9956 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9957 9958 if ((!K0->hasOneUse() || 9959 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9960 (!K1->hasOneUse() || 9961 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9962 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9963 Var, SDValue(K0, 0), SDValue(K1, 0)); 9964 } 9965 } 9966 9967 return SDValue(); 9968 } 9969 9970 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9971 DAGCombinerInfo &DCI) const { 9972 SelectionDAG &DAG = DCI.DAG; 9973 9974 EVT VT = N->getValueType(0); 9975 unsigned Opc = N->getOpcode(); 9976 SDValue Op0 = N->getOperand(0); 9977 SDValue Op1 = N->getOperand(1); 9978 9979 // Only do this if the inner op has one use since this will just increases 9980 // register pressure for no benefit. 9981 9982 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9983 !VT.isVector() && 9984 (VT == MVT::i32 || VT == MVT::f32 || 9985 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9986 // max(max(a, b), c) -> max3(a, b, c) 9987 // min(min(a, b), c) -> min3(a, b, c) 9988 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9989 SDLoc DL(N); 9990 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9991 DL, 9992 N->getValueType(0), 9993 Op0.getOperand(0), 9994 Op0.getOperand(1), 9995 Op1); 9996 } 9997 9998 // Try commuted. 9999 // max(a, max(b, c)) -> max3(a, b, c) 10000 // min(a, min(b, c)) -> min3(a, b, c) 10001 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10002 SDLoc DL(N); 10003 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10004 DL, 10005 N->getValueType(0), 10006 Op0, 10007 Op1.getOperand(0), 10008 Op1.getOperand(1)); 10009 } 10010 } 10011 10012 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10013 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10014 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10015 return Med3; 10016 } 10017 10018 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10019 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10020 return Med3; 10021 } 10022 10023 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10024 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10025 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10026 (Opc == AMDGPUISD::FMIN_LEGACY && 10027 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10028 (VT == MVT::f32 || VT == MVT::f64 || 10029 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10030 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10031 Op0.hasOneUse()) { 10032 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10033 return Res; 10034 } 10035 10036 return SDValue(); 10037 } 10038 10039 static bool isClampZeroToOne(SDValue A, SDValue B) { 10040 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10041 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10042 // FIXME: Should this be allowing -0.0? 10043 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10044 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10045 } 10046 } 10047 10048 return false; 10049 } 10050 10051 // FIXME: Should only worry about snans for version with chain. 10052 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10053 DAGCombinerInfo &DCI) const { 10054 EVT VT = N->getValueType(0); 10055 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10056 // NaNs. With a NaN input, the order of the operands may change the result. 10057 10058 SelectionDAG &DAG = DCI.DAG; 10059 SDLoc SL(N); 10060 10061 SDValue Src0 = N->getOperand(0); 10062 SDValue Src1 = N->getOperand(1); 10063 SDValue Src2 = N->getOperand(2); 10064 10065 if (isClampZeroToOne(Src0, Src1)) { 10066 // const_a, const_b, x -> clamp is safe in all cases including signaling 10067 // nans. 10068 // FIXME: Should this be allowing -0.0? 10069 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10070 } 10071 10072 const MachineFunction &MF = DAG.getMachineFunction(); 10073 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10074 10075 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10076 // handling no dx10-clamp? 10077 if (Info->getMode().DX10Clamp) { 10078 // If NaNs is clamped to 0, we are free to reorder the inputs. 10079 10080 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10081 std::swap(Src0, Src1); 10082 10083 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10084 std::swap(Src1, Src2); 10085 10086 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10087 std::swap(Src0, Src1); 10088 10089 if (isClampZeroToOne(Src1, Src2)) 10090 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10091 } 10092 10093 return SDValue(); 10094 } 10095 10096 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10097 DAGCombinerInfo &DCI) const { 10098 SDValue Src0 = N->getOperand(0); 10099 SDValue Src1 = N->getOperand(1); 10100 if (Src0.isUndef() && Src1.isUndef()) 10101 return DCI.DAG.getUNDEF(N->getValueType(0)); 10102 return SDValue(); 10103 } 10104 10105 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10106 // expanded into a set of cmp/select instructions. 10107 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10108 unsigned NumElem, 10109 bool IsDivergentIdx) { 10110 if (UseDivergentRegisterIndexing) 10111 return false; 10112 10113 unsigned VecSize = EltSize * NumElem; 10114 10115 // Sub-dword vectors of size 2 dword or less have better implementation. 10116 if (VecSize <= 64 && EltSize < 32) 10117 return false; 10118 10119 // Always expand the rest of sub-dword instructions, otherwise it will be 10120 // lowered via memory. 10121 if (EltSize < 32) 10122 return true; 10123 10124 // Always do this if var-idx is divergent, otherwise it will become a loop. 10125 if (IsDivergentIdx) 10126 return true; 10127 10128 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10129 unsigned NumInsts = NumElem /* Number of compares */ + 10130 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10131 return NumInsts <= 16; 10132 } 10133 10134 static bool shouldExpandVectorDynExt(SDNode *N) { 10135 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10136 if (isa<ConstantSDNode>(Idx)) 10137 return false; 10138 10139 SDValue Vec = N->getOperand(0); 10140 EVT VecVT = Vec.getValueType(); 10141 EVT EltVT = VecVT.getVectorElementType(); 10142 unsigned EltSize = EltVT.getSizeInBits(); 10143 unsigned NumElem = VecVT.getVectorNumElements(); 10144 10145 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10146 Idx->isDivergent()); 10147 } 10148 10149 SDValue SITargetLowering::performExtractVectorEltCombine( 10150 SDNode *N, DAGCombinerInfo &DCI) const { 10151 SDValue Vec = N->getOperand(0); 10152 SelectionDAG &DAG = DCI.DAG; 10153 10154 EVT VecVT = Vec.getValueType(); 10155 EVT EltVT = VecVT.getVectorElementType(); 10156 10157 if ((Vec.getOpcode() == ISD::FNEG || 10158 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10159 SDLoc SL(N); 10160 EVT EltVT = N->getValueType(0); 10161 SDValue Idx = N->getOperand(1); 10162 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10163 Vec.getOperand(0), Idx); 10164 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10165 } 10166 10167 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10168 // => 10169 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10170 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10171 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10172 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10173 SDLoc SL(N); 10174 EVT EltVT = N->getValueType(0); 10175 SDValue Idx = N->getOperand(1); 10176 unsigned Opc = Vec.getOpcode(); 10177 10178 switch(Opc) { 10179 default: 10180 break; 10181 // TODO: Support other binary operations. 10182 case ISD::FADD: 10183 case ISD::FSUB: 10184 case ISD::FMUL: 10185 case ISD::ADD: 10186 case ISD::UMIN: 10187 case ISD::UMAX: 10188 case ISD::SMIN: 10189 case ISD::SMAX: 10190 case ISD::FMAXNUM: 10191 case ISD::FMINNUM: 10192 case ISD::FMAXNUM_IEEE: 10193 case ISD::FMINNUM_IEEE: { 10194 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10195 Vec.getOperand(0), Idx); 10196 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10197 Vec.getOperand(1), Idx); 10198 10199 DCI.AddToWorklist(Elt0.getNode()); 10200 DCI.AddToWorklist(Elt1.getNode()); 10201 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10202 } 10203 } 10204 } 10205 10206 unsigned VecSize = VecVT.getSizeInBits(); 10207 unsigned EltSize = EltVT.getSizeInBits(); 10208 10209 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10210 if (::shouldExpandVectorDynExt(N)) { 10211 SDLoc SL(N); 10212 SDValue Idx = N->getOperand(1); 10213 SDValue V; 10214 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10215 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10216 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10217 if (I == 0) 10218 V = Elt; 10219 else 10220 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10221 } 10222 return V; 10223 } 10224 10225 if (!DCI.isBeforeLegalize()) 10226 return SDValue(); 10227 10228 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10229 // elements. This exposes more load reduction opportunities by replacing 10230 // multiple small extract_vector_elements with a single 32-bit extract. 10231 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10232 if (isa<MemSDNode>(Vec) && 10233 EltSize <= 16 && 10234 EltVT.isByteSized() && 10235 VecSize > 32 && 10236 VecSize % 32 == 0 && 10237 Idx) { 10238 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10239 10240 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10241 unsigned EltIdx = BitIndex / 32; 10242 unsigned LeftoverBitIdx = BitIndex % 32; 10243 SDLoc SL(N); 10244 10245 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10246 DCI.AddToWorklist(Cast.getNode()); 10247 10248 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10249 DAG.getConstant(EltIdx, SL, MVT::i32)); 10250 DCI.AddToWorklist(Elt.getNode()); 10251 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10252 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10253 DCI.AddToWorklist(Srl.getNode()); 10254 10255 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10256 DCI.AddToWorklist(Trunc.getNode()); 10257 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10258 } 10259 10260 return SDValue(); 10261 } 10262 10263 SDValue 10264 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10265 DAGCombinerInfo &DCI) const { 10266 SDValue Vec = N->getOperand(0); 10267 SDValue Idx = N->getOperand(2); 10268 EVT VecVT = Vec.getValueType(); 10269 EVT EltVT = VecVT.getVectorElementType(); 10270 10271 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10272 // => BUILD_VECTOR n x select (e, const-idx) 10273 if (!::shouldExpandVectorDynExt(N)) 10274 return SDValue(); 10275 10276 SelectionDAG &DAG = DCI.DAG; 10277 SDLoc SL(N); 10278 SDValue Ins = N->getOperand(1); 10279 EVT IdxVT = Idx.getValueType(); 10280 10281 SmallVector<SDValue, 16> Ops; 10282 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10283 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10284 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10285 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10286 Ops.push_back(V); 10287 } 10288 10289 return DAG.getBuildVector(VecVT, SL, Ops); 10290 } 10291 10292 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10293 const SDNode *N0, 10294 const SDNode *N1) const { 10295 EVT VT = N0->getValueType(0); 10296 10297 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10298 // support denormals ever. 10299 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10300 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10301 getSubtarget()->hasMadF16())) && 10302 isOperationLegal(ISD::FMAD, VT)) 10303 return ISD::FMAD; 10304 10305 const TargetOptions &Options = DAG.getTarget().Options; 10306 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10307 (N0->getFlags().hasAllowContract() && 10308 N1->getFlags().hasAllowContract())) && 10309 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10310 return ISD::FMA; 10311 } 10312 10313 return 0; 10314 } 10315 10316 // For a reassociatable opcode perform: 10317 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10318 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10319 SelectionDAG &DAG) const { 10320 EVT VT = N->getValueType(0); 10321 if (VT != MVT::i32 && VT != MVT::i64) 10322 return SDValue(); 10323 10324 unsigned Opc = N->getOpcode(); 10325 SDValue Op0 = N->getOperand(0); 10326 SDValue Op1 = N->getOperand(1); 10327 10328 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10329 return SDValue(); 10330 10331 if (Op0->isDivergent()) 10332 std::swap(Op0, Op1); 10333 10334 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10335 return SDValue(); 10336 10337 SDValue Op2 = Op1.getOperand(1); 10338 Op1 = Op1.getOperand(0); 10339 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10340 return SDValue(); 10341 10342 if (Op1->isDivergent()) 10343 std::swap(Op1, Op2); 10344 10345 // If either operand is constant this will conflict with 10346 // DAGCombiner::ReassociateOps(). 10347 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10348 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10349 return SDValue(); 10350 10351 SDLoc SL(N); 10352 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10353 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10354 } 10355 10356 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10357 EVT VT, 10358 SDValue N0, SDValue N1, SDValue N2, 10359 bool Signed) { 10360 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10361 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10362 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10363 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10364 } 10365 10366 SDValue SITargetLowering::performAddCombine(SDNode *N, 10367 DAGCombinerInfo &DCI) const { 10368 SelectionDAG &DAG = DCI.DAG; 10369 EVT VT = N->getValueType(0); 10370 SDLoc SL(N); 10371 SDValue LHS = N->getOperand(0); 10372 SDValue RHS = N->getOperand(1); 10373 10374 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10375 && Subtarget->hasMad64_32() && 10376 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10377 VT.getScalarSizeInBits() <= 64) { 10378 if (LHS.getOpcode() != ISD::MUL) 10379 std::swap(LHS, RHS); 10380 10381 SDValue MulLHS = LHS.getOperand(0); 10382 SDValue MulRHS = LHS.getOperand(1); 10383 SDValue AddRHS = RHS; 10384 10385 // TODO: Maybe restrict if SGPR inputs. 10386 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10387 numBitsUnsigned(MulRHS, DAG) <= 32) { 10388 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10389 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10390 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10391 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10392 } 10393 10394 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10395 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10396 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10397 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10398 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10399 } 10400 10401 return SDValue(); 10402 } 10403 10404 if (SDValue V = reassociateScalarOps(N, DAG)) { 10405 return V; 10406 } 10407 10408 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10409 return SDValue(); 10410 10411 // add x, zext (setcc) => addcarry x, 0, setcc 10412 // add x, sext (setcc) => subcarry x, 0, setcc 10413 unsigned Opc = LHS.getOpcode(); 10414 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10415 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10416 std::swap(RHS, LHS); 10417 10418 Opc = RHS.getOpcode(); 10419 switch (Opc) { 10420 default: break; 10421 case ISD::ZERO_EXTEND: 10422 case ISD::SIGN_EXTEND: 10423 case ISD::ANY_EXTEND: { 10424 auto Cond = RHS.getOperand(0); 10425 // If this won't be a real VOPC output, we would still need to insert an 10426 // extra instruction anyway. 10427 if (!isBoolSGPR(Cond)) 10428 break; 10429 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10430 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10431 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10432 return DAG.getNode(Opc, SL, VTList, Args); 10433 } 10434 case ISD::ADDCARRY: { 10435 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10436 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10437 if (!C || C->getZExtValue() != 0) break; 10438 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10439 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10440 } 10441 } 10442 return SDValue(); 10443 } 10444 10445 SDValue SITargetLowering::performSubCombine(SDNode *N, 10446 DAGCombinerInfo &DCI) const { 10447 SelectionDAG &DAG = DCI.DAG; 10448 EVT VT = N->getValueType(0); 10449 10450 if (VT != MVT::i32) 10451 return SDValue(); 10452 10453 SDLoc SL(N); 10454 SDValue LHS = N->getOperand(0); 10455 SDValue RHS = N->getOperand(1); 10456 10457 // sub x, zext (setcc) => subcarry x, 0, setcc 10458 // sub x, sext (setcc) => addcarry x, 0, setcc 10459 unsigned Opc = RHS.getOpcode(); 10460 switch (Opc) { 10461 default: break; 10462 case ISD::ZERO_EXTEND: 10463 case ISD::SIGN_EXTEND: 10464 case ISD::ANY_EXTEND: { 10465 auto Cond = RHS.getOperand(0); 10466 // If this won't be a real VOPC output, we would still need to insert an 10467 // extra instruction anyway. 10468 if (!isBoolSGPR(Cond)) 10469 break; 10470 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10471 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10472 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10473 return DAG.getNode(Opc, SL, VTList, Args); 10474 } 10475 } 10476 10477 if (LHS.getOpcode() == ISD::SUBCARRY) { 10478 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10479 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10480 if (!C || !C->isNullValue()) 10481 return SDValue(); 10482 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10483 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10484 } 10485 return SDValue(); 10486 } 10487 10488 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10489 DAGCombinerInfo &DCI) const { 10490 10491 if (N->getValueType(0) != MVT::i32) 10492 return SDValue(); 10493 10494 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10495 if (!C || C->getZExtValue() != 0) 10496 return SDValue(); 10497 10498 SelectionDAG &DAG = DCI.DAG; 10499 SDValue LHS = N->getOperand(0); 10500 10501 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10502 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10503 unsigned LHSOpc = LHS.getOpcode(); 10504 unsigned Opc = N->getOpcode(); 10505 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10506 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10507 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10508 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10509 } 10510 return SDValue(); 10511 } 10512 10513 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10514 DAGCombinerInfo &DCI) const { 10515 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10516 return SDValue(); 10517 10518 SelectionDAG &DAG = DCI.DAG; 10519 EVT VT = N->getValueType(0); 10520 10521 SDLoc SL(N); 10522 SDValue LHS = N->getOperand(0); 10523 SDValue RHS = N->getOperand(1); 10524 10525 // These should really be instruction patterns, but writing patterns with 10526 // source modiifiers is a pain. 10527 10528 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10529 if (LHS.getOpcode() == ISD::FADD) { 10530 SDValue A = LHS.getOperand(0); 10531 if (A == LHS.getOperand(1)) { 10532 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10533 if (FusedOp != 0) { 10534 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10535 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10536 } 10537 } 10538 } 10539 10540 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10541 if (RHS.getOpcode() == ISD::FADD) { 10542 SDValue A = RHS.getOperand(0); 10543 if (A == RHS.getOperand(1)) { 10544 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10545 if (FusedOp != 0) { 10546 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10547 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10548 } 10549 } 10550 } 10551 10552 return SDValue(); 10553 } 10554 10555 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10556 DAGCombinerInfo &DCI) const { 10557 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10558 return SDValue(); 10559 10560 SelectionDAG &DAG = DCI.DAG; 10561 SDLoc SL(N); 10562 EVT VT = N->getValueType(0); 10563 assert(!VT.isVector()); 10564 10565 // Try to get the fneg to fold into the source modifier. This undoes generic 10566 // DAG combines and folds them into the mad. 10567 // 10568 // Only do this if we are not trying to support denormals. v_mad_f32 does 10569 // not support denormals ever. 10570 SDValue LHS = N->getOperand(0); 10571 SDValue RHS = N->getOperand(1); 10572 if (LHS.getOpcode() == ISD::FADD) { 10573 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10574 SDValue A = LHS.getOperand(0); 10575 if (A == LHS.getOperand(1)) { 10576 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10577 if (FusedOp != 0){ 10578 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10579 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10580 10581 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10582 } 10583 } 10584 } 10585 10586 if (RHS.getOpcode() == ISD::FADD) { 10587 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10588 10589 SDValue A = RHS.getOperand(0); 10590 if (A == RHS.getOperand(1)) { 10591 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10592 if (FusedOp != 0){ 10593 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10594 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10595 } 10596 } 10597 } 10598 10599 return SDValue(); 10600 } 10601 10602 SDValue SITargetLowering::performFMACombine(SDNode *N, 10603 DAGCombinerInfo &DCI) const { 10604 SelectionDAG &DAG = DCI.DAG; 10605 EVT VT = N->getValueType(0); 10606 SDLoc SL(N); 10607 10608 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10609 return SDValue(); 10610 10611 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10612 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10613 SDValue Op1 = N->getOperand(0); 10614 SDValue Op2 = N->getOperand(1); 10615 SDValue FMA = N->getOperand(2); 10616 10617 if (FMA.getOpcode() != ISD::FMA || 10618 Op1.getOpcode() != ISD::FP_EXTEND || 10619 Op2.getOpcode() != ISD::FP_EXTEND) 10620 return SDValue(); 10621 10622 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10623 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10624 // is sufficient to allow generaing fdot2. 10625 const TargetOptions &Options = DAG.getTarget().Options; 10626 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10627 (N->getFlags().hasAllowContract() && 10628 FMA->getFlags().hasAllowContract())) { 10629 Op1 = Op1.getOperand(0); 10630 Op2 = Op2.getOperand(0); 10631 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10632 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10633 return SDValue(); 10634 10635 SDValue Vec1 = Op1.getOperand(0); 10636 SDValue Idx1 = Op1.getOperand(1); 10637 SDValue Vec2 = Op2.getOperand(0); 10638 10639 SDValue FMAOp1 = FMA.getOperand(0); 10640 SDValue FMAOp2 = FMA.getOperand(1); 10641 SDValue FMAAcc = FMA.getOperand(2); 10642 10643 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10644 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10645 return SDValue(); 10646 10647 FMAOp1 = FMAOp1.getOperand(0); 10648 FMAOp2 = FMAOp2.getOperand(0); 10649 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10650 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10651 return SDValue(); 10652 10653 SDValue Vec3 = FMAOp1.getOperand(0); 10654 SDValue Vec4 = FMAOp2.getOperand(0); 10655 SDValue Idx2 = FMAOp1.getOperand(1); 10656 10657 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10658 // Idx1 and Idx2 cannot be the same. 10659 Idx1 == Idx2) 10660 return SDValue(); 10661 10662 if (Vec1 == Vec2 || Vec3 == Vec4) 10663 return SDValue(); 10664 10665 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10666 return SDValue(); 10667 10668 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10669 (Vec1 == Vec4 && Vec2 == Vec3)) { 10670 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10671 DAG.getTargetConstant(0, SL, MVT::i1)); 10672 } 10673 } 10674 return SDValue(); 10675 } 10676 10677 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10678 DAGCombinerInfo &DCI) const { 10679 SelectionDAG &DAG = DCI.DAG; 10680 SDLoc SL(N); 10681 10682 SDValue LHS = N->getOperand(0); 10683 SDValue RHS = N->getOperand(1); 10684 EVT VT = LHS.getValueType(); 10685 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10686 10687 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10688 if (!CRHS) { 10689 CRHS = dyn_cast<ConstantSDNode>(LHS); 10690 if (CRHS) { 10691 std::swap(LHS, RHS); 10692 CC = getSetCCSwappedOperands(CC); 10693 } 10694 } 10695 10696 if (CRHS) { 10697 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10698 isBoolSGPR(LHS.getOperand(0))) { 10699 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10700 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10701 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10702 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10703 if ((CRHS->isAllOnesValue() && 10704 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10705 (CRHS->isNullValue() && 10706 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10707 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10708 DAG.getConstant(-1, SL, MVT::i1)); 10709 if ((CRHS->isAllOnesValue() && 10710 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10711 (CRHS->isNullValue() && 10712 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10713 return LHS.getOperand(0); 10714 } 10715 10716 uint64_t CRHSVal = CRHS->getZExtValue(); 10717 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10718 LHS.getOpcode() == ISD::SELECT && 10719 isa<ConstantSDNode>(LHS.getOperand(1)) && 10720 isa<ConstantSDNode>(LHS.getOperand(2)) && 10721 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10722 isBoolSGPR(LHS.getOperand(0))) { 10723 // Given CT != FT: 10724 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10725 // setcc (select cc, CT, CF), CF, ne => cc 10726 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10727 // setcc (select cc, CT, CF), CT, eq => cc 10728 uint64_t CT = LHS.getConstantOperandVal(1); 10729 uint64_t CF = LHS.getConstantOperandVal(2); 10730 10731 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10732 (CT == CRHSVal && CC == ISD::SETNE)) 10733 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10734 DAG.getConstant(-1, SL, MVT::i1)); 10735 if ((CF == CRHSVal && CC == ISD::SETNE) || 10736 (CT == CRHSVal && CC == ISD::SETEQ)) 10737 return LHS.getOperand(0); 10738 } 10739 } 10740 10741 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10742 VT != MVT::f16)) 10743 return SDValue(); 10744 10745 // Match isinf/isfinite pattern 10746 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10747 // (fcmp one (fabs x), inf) -> (fp_class x, 10748 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10749 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10750 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10751 if (!CRHS) 10752 return SDValue(); 10753 10754 const APFloat &APF = CRHS->getValueAPF(); 10755 if (APF.isInfinity() && !APF.isNegative()) { 10756 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10757 SIInstrFlags::N_INFINITY; 10758 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10759 SIInstrFlags::P_ZERO | 10760 SIInstrFlags::N_NORMAL | 10761 SIInstrFlags::P_NORMAL | 10762 SIInstrFlags::N_SUBNORMAL | 10763 SIInstrFlags::P_SUBNORMAL; 10764 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10765 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10766 DAG.getConstant(Mask, SL, MVT::i32)); 10767 } 10768 } 10769 10770 return SDValue(); 10771 } 10772 10773 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10774 DAGCombinerInfo &DCI) const { 10775 SelectionDAG &DAG = DCI.DAG; 10776 SDLoc SL(N); 10777 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10778 10779 SDValue Src = N->getOperand(0); 10780 SDValue Shift = N->getOperand(0); 10781 10782 // TODO: Extend type shouldn't matter (assuming legal types). 10783 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10784 Shift = Shift.getOperand(0); 10785 10786 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10787 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10788 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10789 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10790 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10791 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10792 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10793 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10794 SDLoc(Shift.getOperand(0)), MVT::i32); 10795 10796 unsigned ShiftOffset = 8 * Offset; 10797 if (Shift.getOpcode() == ISD::SHL) 10798 ShiftOffset -= C->getZExtValue(); 10799 else 10800 ShiftOffset += C->getZExtValue(); 10801 10802 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10803 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10804 MVT::f32, Shift); 10805 } 10806 } 10807 } 10808 10809 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10810 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10811 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10812 // We simplified Src. If this node is not dead, visit it again so it is 10813 // folded properly. 10814 if (N->getOpcode() != ISD::DELETED_NODE) 10815 DCI.AddToWorklist(N); 10816 return SDValue(N, 0); 10817 } 10818 10819 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10820 if (SDValue DemandedSrc = 10821 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10822 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10823 10824 return SDValue(); 10825 } 10826 10827 SDValue SITargetLowering::performClampCombine(SDNode *N, 10828 DAGCombinerInfo &DCI) const { 10829 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10830 if (!CSrc) 10831 return SDValue(); 10832 10833 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10834 const APFloat &F = CSrc->getValueAPF(); 10835 APFloat Zero = APFloat::getZero(F.getSemantics()); 10836 if (F < Zero || 10837 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10838 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10839 } 10840 10841 APFloat One(F.getSemantics(), "1.0"); 10842 if (F > One) 10843 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10844 10845 return SDValue(CSrc, 0); 10846 } 10847 10848 10849 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10850 DAGCombinerInfo &DCI) const { 10851 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10852 return SDValue(); 10853 switch (N->getOpcode()) { 10854 case ISD::ADD: 10855 return performAddCombine(N, DCI); 10856 case ISD::SUB: 10857 return performSubCombine(N, DCI); 10858 case ISD::ADDCARRY: 10859 case ISD::SUBCARRY: 10860 return performAddCarrySubCarryCombine(N, DCI); 10861 case ISD::FADD: 10862 return performFAddCombine(N, DCI); 10863 case ISD::FSUB: 10864 return performFSubCombine(N, DCI); 10865 case ISD::SETCC: 10866 return performSetCCCombine(N, DCI); 10867 case ISD::FMAXNUM: 10868 case ISD::FMINNUM: 10869 case ISD::FMAXNUM_IEEE: 10870 case ISD::FMINNUM_IEEE: 10871 case ISD::SMAX: 10872 case ISD::SMIN: 10873 case ISD::UMAX: 10874 case ISD::UMIN: 10875 case AMDGPUISD::FMIN_LEGACY: 10876 case AMDGPUISD::FMAX_LEGACY: 10877 return performMinMaxCombine(N, DCI); 10878 case ISD::FMA: 10879 return performFMACombine(N, DCI); 10880 case ISD::AND: 10881 return performAndCombine(N, DCI); 10882 case ISD::OR: 10883 return performOrCombine(N, DCI); 10884 case ISD::XOR: 10885 return performXorCombine(N, DCI); 10886 case ISD::ZERO_EXTEND: 10887 return performZeroExtendCombine(N, DCI); 10888 case ISD::SIGN_EXTEND_INREG: 10889 return performSignExtendInRegCombine(N , DCI); 10890 case AMDGPUISD::FP_CLASS: 10891 return performClassCombine(N, DCI); 10892 case ISD::FCANONICALIZE: 10893 return performFCanonicalizeCombine(N, DCI); 10894 case AMDGPUISD::RCP: 10895 return performRcpCombine(N, DCI); 10896 case AMDGPUISD::FRACT: 10897 case AMDGPUISD::RSQ: 10898 case AMDGPUISD::RCP_LEGACY: 10899 case AMDGPUISD::RCP_IFLAG: 10900 case AMDGPUISD::RSQ_CLAMP: 10901 case AMDGPUISD::LDEXP: { 10902 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10903 SDValue Src = N->getOperand(0); 10904 if (Src.isUndef()) 10905 return Src; 10906 break; 10907 } 10908 case ISD::SINT_TO_FP: 10909 case ISD::UINT_TO_FP: 10910 return performUCharToFloatCombine(N, DCI); 10911 case AMDGPUISD::CVT_F32_UBYTE0: 10912 case AMDGPUISD::CVT_F32_UBYTE1: 10913 case AMDGPUISD::CVT_F32_UBYTE2: 10914 case AMDGPUISD::CVT_F32_UBYTE3: 10915 return performCvtF32UByteNCombine(N, DCI); 10916 case AMDGPUISD::FMED3: 10917 return performFMed3Combine(N, DCI); 10918 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10919 return performCvtPkRTZCombine(N, DCI); 10920 case AMDGPUISD::CLAMP: 10921 return performClampCombine(N, DCI); 10922 case ISD::SCALAR_TO_VECTOR: { 10923 SelectionDAG &DAG = DCI.DAG; 10924 EVT VT = N->getValueType(0); 10925 10926 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10927 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10928 SDLoc SL(N); 10929 SDValue Src = N->getOperand(0); 10930 EVT EltVT = Src.getValueType(); 10931 if (EltVT == MVT::f16) 10932 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10933 10934 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10935 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10936 } 10937 10938 break; 10939 } 10940 case ISD::EXTRACT_VECTOR_ELT: 10941 return performExtractVectorEltCombine(N, DCI); 10942 case ISD::INSERT_VECTOR_ELT: 10943 return performInsertVectorEltCombine(N, DCI); 10944 case ISD::LOAD: { 10945 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10946 return Widended; 10947 LLVM_FALLTHROUGH; 10948 } 10949 default: { 10950 if (!DCI.isBeforeLegalize()) { 10951 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10952 return performMemSDNodeCombine(MemNode, DCI); 10953 } 10954 10955 break; 10956 } 10957 } 10958 10959 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10960 } 10961 10962 /// Helper function for adjustWritemask 10963 static unsigned SubIdx2Lane(unsigned Idx) { 10964 switch (Idx) { 10965 default: return ~0u; 10966 case AMDGPU::sub0: return 0; 10967 case AMDGPU::sub1: return 1; 10968 case AMDGPU::sub2: return 2; 10969 case AMDGPU::sub3: return 3; 10970 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10971 } 10972 } 10973 10974 /// Adjust the writemask of MIMG instructions 10975 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10976 SelectionDAG &DAG) const { 10977 unsigned Opcode = Node->getMachineOpcode(); 10978 10979 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10980 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10981 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10982 return Node; // not implemented for D16 10983 10984 SDNode *Users[5] = { nullptr }; 10985 unsigned Lane = 0; 10986 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10987 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10988 unsigned NewDmask = 0; 10989 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10990 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10991 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10992 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10993 unsigned TFCLane = 0; 10994 bool HasChain = Node->getNumValues() > 1; 10995 10996 if (OldDmask == 0) { 10997 // These are folded out, but on the chance it happens don't assert. 10998 return Node; 10999 } 11000 11001 unsigned OldBitsSet = countPopulation(OldDmask); 11002 // Work out which is the TFE/LWE lane if that is enabled. 11003 if (UsesTFC) { 11004 TFCLane = OldBitsSet; 11005 } 11006 11007 // Try to figure out the used register components 11008 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11009 I != E; ++I) { 11010 11011 // Don't look at users of the chain. 11012 if (I.getUse().getResNo() != 0) 11013 continue; 11014 11015 // Abort if we can't understand the usage 11016 if (!I->isMachineOpcode() || 11017 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11018 return Node; 11019 11020 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11021 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11022 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11023 // set, etc. 11024 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11025 if (Lane == ~0u) 11026 return Node; 11027 11028 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11029 if (UsesTFC && Lane == TFCLane) { 11030 Users[Lane] = *I; 11031 } else { 11032 // Set which texture component corresponds to the lane. 11033 unsigned Comp; 11034 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11035 Comp = countTrailingZeros(Dmask); 11036 Dmask &= ~(1 << Comp); 11037 } 11038 11039 // Abort if we have more than one user per component. 11040 if (Users[Lane]) 11041 return Node; 11042 11043 Users[Lane] = *I; 11044 NewDmask |= 1 << Comp; 11045 } 11046 } 11047 11048 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11049 bool NoChannels = !NewDmask; 11050 if (NoChannels) { 11051 if (!UsesTFC) { 11052 // No uses of the result and not using TFC. Then do nothing. 11053 return Node; 11054 } 11055 // If the original dmask has one channel - then nothing to do 11056 if (OldBitsSet == 1) 11057 return Node; 11058 // Use an arbitrary dmask - required for the instruction to work 11059 NewDmask = 1; 11060 } 11061 // Abort if there's no change 11062 if (NewDmask == OldDmask) 11063 return Node; 11064 11065 unsigned BitsSet = countPopulation(NewDmask); 11066 11067 // Check for TFE or LWE - increase the number of channels by one to account 11068 // for the extra return value 11069 // This will need adjustment for D16 if this is also included in 11070 // adjustWriteMask (this function) but at present D16 are excluded. 11071 unsigned NewChannels = BitsSet + UsesTFC; 11072 11073 int NewOpcode = 11074 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11075 assert(NewOpcode != -1 && 11076 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11077 "failed to find equivalent MIMG op"); 11078 11079 // Adjust the writemask in the node 11080 SmallVector<SDValue, 12> Ops; 11081 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11082 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11083 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11084 11085 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11086 11087 MVT ResultVT = NewChannels == 1 ? 11088 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11089 NewChannels == 5 ? 8 : NewChannels); 11090 SDVTList NewVTList = HasChain ? 11091 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11092 11093 11094 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11095 NewVTList, Ops); 11096 11097 if (HasChain) { 11098 // Update chain. 11099 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11100 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11101 } 11102 11103 if (NewChannels == 1) { 11104 assert(Node->hasNUsesOfValue(1, 0)); 11105 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11106 SDLoc(Node), Users[Lane]->getValueType(0), 11107 SDValue(NewNode, 0)); 11108 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11109 return nullptr; 11110 } 11111 11112 // Update the users of the node with the new indices 11113 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11114 SDNode *User = Users[i]; 11115 if (!User) { 11116 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11117 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11118 if (i || !NoChannels) 11119 continue; 11120 } else { 11121 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11122 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11123 } 11124 11125 switch (Idx) { 11126 default: break; 11127 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11128 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11129 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11130 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11131 } 11132 } 11133 11134 DAG.RemoveDeadNode(Node); 11135 return nullptr; 11136 } 11137 11138 static bool isFrameIndexOp(SDValue Op) { 11139 if (Op.getOpcode() == ISD::AssertZext) 11140 Op = Op.getOperand(0); 11141 11142 return isa<FrameIndexSDNode>(Op); 11143 } 11144 11145 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11146 /// with frame index operands. 11147 /// LLVM assumes that inputs are to these instructions are registers. 11148 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11149 SelectionDAG &DAG) const { 11150 if (Node->getOpcode() == ISD::CopyToReg) { 11151 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11152 SDValue SrcVal = Node->getOperand(2); 11153 11154 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11155 // to try understanding copies to physical registers. 11156 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11157 SDLoc SL(Node); 11158 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11159 SDValue VReg = DAG.getRegister( 11160 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11161 11162 SDNode *Glued = Node->getGluedNode(); 11163 SDValue ToVReg 11164 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11165 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11166 SDValue ToResultReg 11167 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11168 VReg, ToVReg.getValue(1)); 11169 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11170 DAG.RemoveDeadNode(Node); 11171 return ToResultReg.getNode(); 11172 } 11173 } 11174 11175 SmallVector<SDValue, 8> Ops; 11176 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11177 if (!isFrameIndexOp(Node->getOperand(i))) { 11178 Ops.push_back(Node->getOperand(i)); 11179 continue; 11180 } 11181 11182 SDLoc DL(Node); 11183 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11184 Node->getOperand(i).getValueType(), 11185 Node->getOperand(i)), 0)); 11186 } 11187 11188 return DAG.UpdateNodeOperands(Node, Ops); 11189 } 11190 11191 /// Fold the instructions after selecting them. 11192 /// Returns null if users were already updated. 11193 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11194 SelectionDAG &DAG) const { 11195 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11196 unsigned Opcode = Node->getMachineOpcode(); 11197 11198 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11199 !TII->isGather4(Opcode) && 11200 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11201 return adjustWritemask(Node, DAG); 11202 } 11203 11204 if (Opcode == AMDGPU::INSERT_SUBREG || 11205 Opcode == AMDGPU::REG_SEQUENCE) { 11206 legalizeTargetIndependentNode(Node, DAG); 11207 return Node; 11208 } 11209 11210 switch (Opcode) { 11211 case AMDGPU::V_DIV_SCALE_F32_e64: 11212 case AMDGPU::V_DIV_SCALE_F64_e64: { 11213 // Satisfy the operand register constraint when one of the inputs is 11214 // undefined. Ordinarily each undef value will have its own implicit_def of 11215 // a vreg, so force these to use a single register. 11216 SDValue Src0 = Node->getOperand(1); 11217 SDValue Src1 = Node->getOperand(3); 11218 SDValue Src2 = Node->getOperand(5); 11219 11220 if ((Src0.isMachineOpcode() && 11221 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11222 (Src0 == Src1 || Src0 == Src2)) 11223 break; 11224 11225 MVT VT = Src0.getValueType().getSimpleVT(); 11226 const TargetRegisterClass *RC = 11227 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11228 11229 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11230 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11231 11232 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11233 UndefReg, Src0, SDValue()); 11234 11235 // src0 must be the same register as src1 or src2, even if the value is 11236 // undefined, so make sure we don't violate this constraint. 11237 if (Src0.isMachineOpcode() && 11238 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11239 if (Src1.isMachineOpcode() && 11240 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11241 Src0 = Src1; 11242 else if (Src2.isMachineOpcode() && 11243 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11244 Src0 = Src2; 11245 else { 11246 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11247 Src0 = UndefReg; 11248 Src1 = UndefReg; 11249 } 11250 } else 11251 break; 11252 11253 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11254 Ops[1] = Src0; 11255 Ops[3] = Src1; 11256 Ops[5] = Src2; 11257 Ops.push_back(ImpDef.getValue(1)); 11258 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11259 } 11260 default: 11261 break; 11262 } 11263 11264 return Node; 11265 } 11266 11267 // Any MIMG instructions that use tfe or lwe require an initialization of the 11268 // result register that will be written in the case of a memory access failure. 11269 // The required code is also added to tie this init code to the result of the 11270 // img instruction. 11271 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11272 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11273 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11274 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11275 MachineBasicBlock &MBB = *MI.getParent(); 11276 11277 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11278 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11279 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11280 11281 if (!TFE && !LWE) // intersect_ray 11282 return; 11283 11284 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11285 unsigned LWEVal = LWE->getImm(); 11286 unsigned D16Val = D16 ? D16->getImm() : 0; 11287 11288 if (!TFEVal && !LWEVal) 11289 return; 11290 11291 // At least one of TFE or LWE are non-zero 11292 // We have to insert a suitable initialization of the result value and 11293 // tie this to the dest of the image instruction. 11294 11295 const DebugLoc &DL = MI.getDebugLoc(); 11296 11297 int DstIdx = 11298 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11299 11300 // Calculate which dword we have to initialize to 0. 11301 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11302 11303 // check that dmask operand is found. 11304 assert(MO_Dmask && "Expected dmask operand in instruction"); 11305 11306 unsigned dmask = MO_Dmask->getImm(); 11307 // Determine the number of active lanes taking into account the 11308 // Gather4 special case 11309 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11310 11311 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11312 11313 unsigned InitIdx = 11314 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11315 11316 // Abandon attempt if the dst size isn't large enough 11317 // - this is in fact an error but this is picked up elsewhere and 11318 // reported correctly. 11319 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11320 if (DstSize < InitIdx) 11321 return; 11322 11323 // Create a register for the intialization value. 11324 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11325 unsigned NewDst = 0; // Final initialized value will be in here 11326 11327 // If PRTStrictNull feature is enabled (the default) then initialize 11328 // all the result registers to 0, otherwise just the error indication 11329 // register (VGPRn+1) 11330 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11331 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11332 11333 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11334 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11335 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11336 // Initialize dword 11337 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11338 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11339 .addImm(0); 11340 // Insert into the super-reg 11341 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11342 .addReg(PrevDst) 11343 .addReg(SubReg) 11344 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11345 11346 PrevDst = NewDst; 11347 } 11348 11349 // Add as an implicit operand 11350 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11351 11352 // Tie the just added implicit operand to the dst 11353 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11354 } 11355 11356 /// Assign the register class depending on the number of 11357 /// bits set in the writemask 11358 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11359 SDNode *Node) const { 11360 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11361 11362 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11363 11364 if (TII->isVOP3(MI.getOpcode())) { 11365 // Make sure constant bus requirements are respected. 11366 TII->legalizeOperandsVOP3(MRI, MI); 11367 11368 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11369 // This saves a chain-copy of registers and better ballance register 11370 // use between vgpr and agpr as agpr tuples tend to be big. 11371 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11372 unsigned Opc = MI.getOpcode(); 11373 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11374 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11375 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11376 if (I == -1) 11377 break; 11378 MachineOperand &Op = MI.getOperand(I); 11379 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11380 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11381 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11382 continue; 11383 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11384 if (!Src || !Src->isCopy() || 11385 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11386 continue; 11387 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11388 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11389 // All uses of agpr64 and agpr32 can also accept vgpr except for 11390 // v_accvgpr_read, but we do not produce agpr reads during selection, 11391 // so no use checks are needed. 11392 MRI.setRegClass(Op.getReg(), NewRC); 11393 } 11394 } 11395 11396 return; 11397 } 11398 11399 // Replace unused atomics with the no return version. 11400 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11401 if (NoRetAtomicOp != -1) { 11402 if (!Node->hasAnyUseOfValue(0)) { 11403 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11404 AMDGPU::OpName::cpol); 11405 if (CPolIdx != -1) { 11406 MachineOperand &CPol = MI.getOperand(CPolIdx); 11407 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11408 } 11409 MI.RemoveOperand(0); 11410 MI.setDesc(TII->get(NoRetAtomicOp)); 11411 return; 11412 } 11413 11414 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11415 // instruction, because the return type of these instructions is a vec2 of 11416 // the memory type, so it can be tied to the input operand. 11417 // This means these instructions always have a use, so we need to add a 11418 // special case to check if the atomic has only one extract_subreg use, 11419 // which itself has no uses. 11420 if ((Node->hasNUsesOfValue(1, 0) && 11421 Node->use_begin()->isMachineOpcode() && 11422 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11423 !Node->use_begin()->hasAnyUseOfValue(0))) { 11424 Register Def = MI.getOperand(0).getReg(); 11425 11426 // Change this into a noret atomic. 11427 MI.setDesc(TII->get(NoRetAtomicOp)); 11428 MI.RemoveOperand(0); 11429 11430 // If we only remove the def operand from the atomic instruction, the 11431 // extract_subreg will be left with a use of a vreg without a def. 11432 // So we need to insert an implicit_def to avoid machine verifier 11433 // errors. 11434 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11435 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11436 } 11437 return; 11438 } 11439 11440 if (TII->isMIMG(MI) && !MI.mayStore()) 11441 AddIMGInit(MI); 11442 } 11443 11444 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11445 uint64_t Val) { 11446 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11447 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11448 } 11449 11450 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11451 const SDLoc &DL, 11452 SDValue Ptr) const { 11453 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11454 11455 // Build the half of the subregister with the constants before building the 11456 // full 128-bit register. If we are building multiple resource descriptors, 11457 // this will allow CSEing of the 2-component register. 11458 const SDValue Ops0[] = { 11459 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11460 buildSMovImm32(DAG, DL, 0), 11461 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11462 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11463 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11464 }; 11465 11466 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11467 MVT::v2i32, Ops0), 0); 11468 11469 // Combine the constants and the pointer. 11470 const SDValue Ops1[] = { 11471 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11472 Ptr, 11473 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11474 SubRegHi, 11475 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11476 }; 11477 11478 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11479 } 11480 11481 /// Return a resource descriptor with the 'Add TID' bit enabled 11482 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11483 /// of the resource descriptor) to create an offset, which is added to 11484 /// the resource pointer. 11485 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11486 SDValue Ptr, uint32_t RsrcDword1, 11487 uint64_t RsrcDword2And3) const { 11488 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11489 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11490 if (RsrcDword1) { 11491 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11492 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11493 0); 11494 } 11495 11496 SDValue DataLo = buildSMovImm32(DAG, DL, 11497 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11498 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11499 11500 const SDValue Ops[] = { 11501 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11502 PtrLo, 11503 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11504 PtrHi, 11505 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11506 DataLo, 11507 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11508 DataHi, 11509 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11510 }; 11511 11512 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11513 } 11514 11515 //===----------------------------------------------------------------------===// 11516 // SI Inline Assembly Support 11517 //===----------------------------------------------------------------------===// 11518 11519 std::pair<unsigned, const TargetRegisterClass *> 11520 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11521 StringRef Constraint, 11522 MVT VT) const { 11523 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11524 11525 const TargetRegisterClass *RC = nullptr; 11526 if (Constraint.size() == 1) { 11527 const unsigned BitWidth = VT.getSizeInBits(); 11528 switch (Constraint[0]) { 11529 default: 11530 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11531 case 's': 11532 case 'r': 11533 switch (BitWidth) { 11534 case 16: 11535 RC = &AMDGPU::SReg_32RegClass; 11536 break; 11537 case 64: 11538 RC = &AMDGPU::SGPR_64RegClass; 11539 break; 11540 default: 11541 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11542 if (!RC) 11543 return std::make_pair(0U, nullptr); 11544 break; 11545 } 11546 break; 11547 case 'v': 11548 switch (BitWidth) { 11549 case 16: 11550 RC = &AMDGPU::VGPR_32RegClass; 11551 break; 11552 default: 11553 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11554 if (!RC) 11555 return std::make_pair(0U, nullptr); 11556 break; 11557 } 11558 break; 11559 case 'a': 11560 if (!Subtarget->hasMAIInsts()) 11561 break; 11562 switch (BitWidth) { 11563 case 16: 11564 RC = &AMDGPU::AGPR_32RegClass; 11565 break; 11566 default: 11567 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11568 if (!RC) 11569 return std::make_pair(0U, nullptr); 11570 break; 11571 } 11572 break; 11573 } 11574 // We actually support i128, i16 and f16 as inline parameters 11575 // even if they are not reported as legal 11576 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11577 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11578 return std::make_pair(0U, RC); 11579 } 11580 11581 if (Constraint.size() > 1) { 11582 if (Constraint[1] == 'v') { 11583 RC = &AMDGPU::VGPR_32RegClass; 11584 } else if (Constraint[1] == 's') { 11585 RC = &AMDGPU::SGPR_32RegClass; 11586 } else if (Constraint[1] == 'a') { 11587 RC = &AMDGPU::AGPR_32RegClass; 11588 } 11589 11590 if (RC) { 11591 uint32_t Idx; 11592 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11593 if (!Failed && Idx < RC->getNumRegs()) 11594 return std::make_pair(RC->getRegister(Idx), RC); 11595 } 11596 } 11597 11598 // FIXME: Returns VS_32 for physical SGPR constraints 11599 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11600 } 11601 11602 static bool isImmConstraint(StringRef Constraint) { 11603 if (Constraint.size() == 1) { 11604 switch (Constraint[0]) { 11605 default: break; 11606 case 'I': 11607 case 'J': 11608 case 'A': 11609 case 'B': 11610 case 'C': 11611 return true; 11612 } 11613 } else if (Constraint == "DA" || 11614 Constraint == "DB") { 11615 return true; 11616 } 11617 return false; 11618 } 11619 11620 SITargetLowering::ConstraintType 11621 SITargetLowering::getConstraintType(StringRef Constraint) const { 11622 if (Constraint.size() == 1) { 11623 switch (Constraint[0]) { 11624 default: break; 11625 case 's': 11626 case 'v': 11627 case 'a': 11628 return C_RegisterClass; 11629 } 11630 } 11631 if (isImmConstraint(Constraint)) { 11632 return C_Other; 11633 } 11634 return TargetLowering::getConstraintType(Constraint); 11635 } 11636 11637 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11638 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11639 Val = Val & maskTrailingOnes<uint64_t>(Size); 11640 } 11641 return Val; 11642 } 11643 11644 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11645 std::string &Constraint, 11646 std::vector<SDValue> &Ops, 11647 SelectionDAG &DAG) const { 11648 if (isImmConstraint(Constraint)) { 11649 uint64_t Val; 11650 if (getAsmOperandConstVal(Op, Val) && 11651 checkAsmConstraintVal(Op, Constraint, Val)) { 11652 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11653 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11654 } 11655 } else { 11656 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11657 } 11658 } 11659 11660 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11661 unsigned Size = Op.getScalarValueSizeInBits(); 11662 if (Size > 64) 11663 return false; 11664 11665 if (Size == 16 && !Subtarget->has16BitInsts()) 11666 return false; 11667 11668 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11669 Val = C->getSExtValue(); 11670 return true; 11671 } 11672 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11673 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11674 return true; 11675 } 11676 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11677 if (Size != 16 || Op.getNumOperands() != 2) 11678 return false; 11679 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11680 return false; 11681 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11682 Val = C->getSExtValue(); 11683 return true; 11684 } 11685 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11686 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11687 return true; 11688 } 11689 } 11690 11691 return false; 11692 } 11693 11694 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11695 const std::string &Constraint, 11696 uint64_t Val) const { 11697 if (Constraint.size() == 1) { 11698 switch (Constraint[0]) { 11699 case 'I': 11700 return AMDGPU::isInlinableIntLiteral(Val); 11701 case 'J': 11702 return isInt<16>(Val); 11703 case 'A': 11704 return checkAsmConstraintValA(Op, Val); 11705 case 'B': 11706 return isInt<32>(Val); 11707 case 'C': 11708 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11709 AMDGPU::isInlinableIntLiteral(Val); 11710 default: 11711 break; 11712 } 11713 } else if (Constraint.size() == 2) { 11714 if (Constraint == "DA") { 11715 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11716 int64_t LoBits = static_cast<int32_t>(Val); 11717 return checkAsmConstraintValA(Op, HiBits, 32) && 11718 checkAsmConstraintValA(Op, LoBits, 32); 11719 } 11720 if (Constraint == "DB") { 11721 return true; 11722 } 11723 } 11724 llvm_unreachable("Invalid asm constraint"); 11725 } 11726 11727 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11728 uint64_t Val, 11729 unsigned MaxSize) const { 11730 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11731 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11732 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11733 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11734 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11735 return true; 11736 } 11737 return false; 11738 } 11739 11740 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11741 switch (UnalignedClassID) { 11742 case AMDGPU::VReg_64RegClassID: 11743 return AMDGPU::VReg_64_Align2RegClassID; 11744 case AMDGPU::VReg_96RegClassID: 11745 return AMDGPU::VReg_96_Align2RegClassID; 11746 case AMDGPU::VReg_128RegClassID: 11747 return AMDGPU::VReg_128_Align2RegClassID; 11748 case AMDGPU::VReg_160RegClassID: 11749 return AMDGPU::VReg_160_Align2RegClassID; 11750 case AMDGPU::VReg_192RegClassID: 11751 return AMDGPU::VReg_192_Align2RegClassID; 11752 case AMDGPU::VReg_224RegClassID: 11753 return AMDGPU::VReg_224_Align2RegClassID; 11754 case AMDGPU::VReg_256RegClassID: 11755 return AMDGPU::VReg_256_Align2RegClassID; 11756 case AMDGPU::VReg_512RegClassID: 11757 return AMDGPU::VReg_512_Align2RegClassID; 11758 case AMDGPU::VReg_1024RegClassID: 11759 return AMDGPU::VReg_1024_Align2RegClassID; 11760 case AMDGPU::AReg_64RegClassID: 11761 return AMDGPU::AReg_64_Align2RegClassID; 11762 case AMDGPU::AReg_96RegClassID: 11763 return AMDGPU::AReg_96_Align2RegClassID; 11764 case AMDGPU::AReg_128RegClassID: 11765 return AMDGPU::AReg_128_Align2RegClassID; 11766 case AMDGPU::AReg_160RegClassID: 11767 return AMDGPU::AReg_160_Align2RegClassID; 11768 case AMDGPU::AReg_192RegClassID: 11769 return AMDGPU::AReg_192_Align2RegClassID; 11770 case AMDGPU::AReg_256RegClassID: 11771 return AMDGPU::AReg_256_Align2RegClassID; 11772 case AMDGPU::AReg_512RegClassID: 11773 return AMDGPU::AReg_512_Align2RegClassID; 11774 case AMDGPU::AReg_1024RegClassID: 11775 return AMDGPU::AReg_1024_Align2RegClassID; 11776 default: 11777 return -1; 11778 } 11779 } 11780 11781 // Figure out which registers should be reserved for stack access. Only after 11782 // the function is legalized do we know all of the non-spill stack objects or if 11783 // calls are present. 11784 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11785 MachineRegisterInfo &MRI = MF.getRegInfo(); 11786 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11787 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11788 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11789 const SIInstrInfo *TII = ST.getInstrInfo(); 11790 11791 if (Info->isEntryFunction()) { 11792 // Callable functions have fixed registers used for stack access. 11793 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11794 } 11795 11796 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11797 Info->getStackPtrOffsetReg())); 11798 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11799 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11800 11801 // We need to worry about replacing the default register with itself in case 11802 // of MIR testcases missing the MFI. 11803 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11804 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11805 11806 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11807 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11808 11809 Info->limitOccupancy(MF); 11810 11811 if (ST.isWave32() && !MF.empty()) { 11812 for (auto &MBB : MF) { 11813 for (auto &MI : MBB) { 11814 TII->fixImplicitOperands(MI); 11815 } 11816 } 11817 } 11818 11819 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11820 // classes if required. Ideally the register class constraints would differ 11821 // per-subtarget, but there's no easy way to achieve that right now. This is 11822 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11823 // from using them as the register class for legal types. 11824 if (ST.needsAlignedVGPRs()) { 11825 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11826 const Register Reg = Register::index2VirtReg(I); 11827 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11828 if (!RC) 11829 continue; 11830 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11831 if (NewClassID != -1) 11832 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11833 } 11834 } 11835 11836 TargetLoweringBase::finalizeLowering(MF); 11837 11838 // Allocate a VGPR for future SGPR Spill if 11839 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11840 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11841 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11842 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11843 Info->reserveVGPRforSGPRSpills(MF); 11844 } 11845 11846 void SITargetLowering::computeKnownBitsForFrameIndex( 11847 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11848 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11849 11850 // Set the high bits to zero based on the maximum allowed scratch size per 11851 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11852 // calculation won't overflow, so assume the sign bit is never set. 11853 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11854 } 11855 11856 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11857 KnownBits &Known, unsigned Dim) { 11858 unsigned MaxValue = 11859 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11860 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11861 } 11862 11863 void SITargetLowering::computeKnownBitsForTargetInstr( 11864 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11865 const MachineRegisterInfo &MRI, unsigned Depth) const { 11866 const MachineInstr *MI = MRI.getVRegDef(R); 11867 switch (MI->getOpcode()) { 11868 case AMDGPU::G_INTRINSIC: { 11869 switch (MI->getIntrinsicID()) { 11870 case Intrinsic::amdgcn_workitem_id_x: 11871 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11872 break; 11873 case Intrinsic::amdgcn_workitem_id_y: 11874 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11875 break; 11876 case Intrinsic::amdgcn_workitem_id_z: 11877 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11878 break; 11879 case Intrinsic::amdgcn_mbcnt_lo: 11880 case Intrinsic::amdgcn_mbcnt_hi: { 11881 // These return at most the wavefront size - 1. 11882 unsigned Size = MRI.getType(R).getSizeInBits(); 11883 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11884 break; 11885 } 11886 case Intrinsic::amdgcn_groupstaticsize: { 11887 // We can report everything over the maximum size as 0. We can't report 11888 // based on the actual size because we don't know if it's accurate or not 11889 // at any given point. 11890 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11891 break; 11892 } 11893 } 11894 break; 11895 } 11896 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11897 Known.Zero.setHighBits(24); 11898 break; 11899 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11900 Known.Zero.setHighBits(16); 11901 break; 11902 } 11903 } 11904 11905 Align SITargetLowering::computeKnownAlignForTargetInstr( 11906 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11907 unsigned Depth) const { 11908 const MachineInstr *MI = MRI.getVRegDef(R); 11909 switch (MI->getOpcode()) { 11910 case AMDGPU::G_INTRINSIC: 11911 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11912 // FIXME: Can this move to generic code? What about the case where the call 11913 // site specifies a lower alignment? 11914 Intrinsic::ID IID = MI->getIntrinsicID(); 11915 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11916 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11917 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11918 return *RetAlign; 11919 return Align(1); 11920 } 11921 default: 11922 return Align(1); 11923 } 11924 } 11925 11926 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11927 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11928 const Align CacheLineAlign = Align(64); 11929 11930 // Pre-GFX10 target did not benefit from loop alignment 11931 if (!ML || DisableLoopAlignment || 11932 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11933 getSubtarget()->hasInstFwdPrefetchBug()) 11934 return PrefAlign; 11935 11936 // On GFX10 I$ is 4 x 64 bytes cache lines. 11937 // By default prefetcher keeps one cache line behind and reads two ahead. 11938 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11939 // behind and one ahead. 11940 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11941 // If loop fits 64 bytes it always spans no more than two cache lines and 11942 // does not need an alignment. 11943 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11944 // Else if loop is less or equal 192 bytes we need two lines behind. 11945 11946 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11947 const MachineBasicBlock *Header = ML->getHeader(); 11948 if (Header->getAlignment() != PrefAlign) 11949 return Header->getAlignment(); // Already processed. 11950 11951 unsigned LoopSize = 0; 11952 for (const MachineBasicBlock *MBB : ML->blocks()) { 11953 // If inner loop block is aligned assume in average half of the alignment 11954 // size to be added as nops. 11955 if (MBB != Header) 11956 LoopSize += MBB->getAlignment().value() / 2; 11957 11958 for (const MachineInstr &MI : *MBB) { 11959 LoopSize += TII->getInstSizeInBytes(MI); 11960 if (LoopSize > 192) 11961 return PrefAlign; 11962 } 11963 } 11964 11965 if (LoopSize <= 64) 11966 return PrefAlign; 11967 11968 if (LoopSize <= 128) 11969 return CacheLineAlign; 11970 11971 // If any of parent loops is surrounded by prefetch instructions do not 11972 // insert new for inner loop, which would reset parent's settings. 11973 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11974 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11975 auto I = Exit->getFirstNonDebugInstr(); 11976 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11977 return CacheLineAlign; 11978 } 11979 } 11980 11981 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11982 MachineBasicBlock *Exit = ML->getExitBlock(); 11983 11984 if (Pre && Exit) { 11985 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11986 TII->get(AMDGPU::S_INST_PREFETCH)) 11987 .addImm(1); // prefetch 2 lines behind PC 11988 11989 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11990 TII->get(AMDGPU::S_INST_PREFETCH)) 11991 .addImm(2); // prefetch 1 line behind PC 11992 } 11993 11994 return CacheLineAlign; 11995 } 11996 11997 LLVM_ATTRIBUTE_UNUSED 11998 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11999 assert(N->getOpcode() == ISD::CopyFromReg); 12000 do { 12001 // Follow the chain until we find an INLINEASM node. 12002 N = N->getOperand(0).getNode(); 12003 if (N->getOpcode() == ISD::INLINEASM || 12004 N->getOpcode() == ISD::INLINEASM_BR) 12005 return true; 12006 } while (N->getOpcode() == ISD::CopyFromReg); 12007 return false; 12008 } 12009 12010 bool SITargetLowering::isSDNodeSourceOfDivergence( 12011 const SDNode *N, FunctionLoweringInfo *FLI, 12012 LegacyDivergenceAnalysis *KDA) const { 12013 switch (N->getOpcode()) { 12014 case ISD::CopyFromReg: { 12015 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12016 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12017 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12018 Register Reg = R->getReg(); 12019 12020 // FIXME: Why does this need to consider isLiveIn? 12021 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12022 return !TRI->isSGPRReg(MRI, Reg); 12023 12024 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12025 return KDA->isDivergent(V); 12026 12027 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12028 return !TRI->isSGPRReg(MRI, Reg); 12029 } 12030 case ISD::LOAD: { 12031 const LoadSDNode *L = cast<LoadSDNode>(N); 12032 unsigned AS = L->getAddressSpace(); 12033 // A flat load may access private memory. 12034 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12035 } 12036 case ISD::CALLSEQ_END: 12037 return true; 12038 case ISD::INTRINSIC_WO_CHAIN: 12039 return AMDGPU::isIntrinsicSourceOfDivergence( 12040 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12041 case ISD::INTRINSIC_W_CHAIN: 12042 return AMDGPU::isIntrinsicSourceOfDivergence( 12043 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12044 case AMDGPUISD::ATOMIC_CMP_SWAP: 12045 case AMDGPUISD::ATOMIC_INC: 12046 case AMDGPUISD::ATOMIC_DEC: 12047 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12048 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12049 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12050 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12051 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12052 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12053 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12054 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12055 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12056 case AMDGPUISD::BUFFER_ATOMIC_AND: 12057 case AMDGPUISD::BUFFER_ATOMIC_OR: 12058 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12059 case AMDGPUISD::BUFFER_ATOMIC_INC: 12060 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12061 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12062 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12063 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12064 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12065 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12066 // Target-specific read-modify-write atomics are sources of divergence. 12067 return true; 12068 default: 12069 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12070 // Generic read-modify-write atomics are sources of divergence. 12071 return A->readMem() && A->writeMem(); 12072 } 12073 return false; 12074 } 12075 } 12076 12077 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12078 EVT VT) const { 12079 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12080 case MVT::f32: 12081 return hasFP32Denormals(DAG.getMachineFunction()); 12082 case MVT::f64: 12083 case MVT::f16: 12084 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12085 default: 12086 return false; 12087 } 12088 } 12089 12090 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12091 MachineFunction &MF) const { 12092 switch (Ty.getScalarSizeInBits()) { 12093 case 32: 12094 return hasFP32Denormals(MF); 12095 case 64: 12096 case 16: 12097 return hasFP64FP16Denormals(MF); 12098 default: 12099 return false; 12100 } 12101 } 12102 12103 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12104 const SelectionDAG &DAG, 12105 bool SNaN, 12106 unsigned Depth) const { 12107 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12108 const MachineFunction &MF = DAG.getMachineFunction(); 12109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12110 12111 if (Info->getMode().DX10Clamp) 12112 return true; // Clamped to 0. 12113 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12114 } 12115 12116 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12117 SNaN, Depth); 12118 } 12119 12120 // Global FP atomic instructions have a hardcoded FP mode and do not support 12121 // FP32 denormals, and only support v2f16 denormals. 12122 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12123 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12124 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12125 if (&Flt == &APFloat::IEEEsingle()) 12126 return DenormMode == DenormalMode::getPreserveSign(); 12127 return DenormMode == DenormalMode::getIEEE(); 12128 } 12129 12130 TargetLowering::AtomicExpansionKind 12131 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12132 switch (RMW->getOperation()) { 12133 case AtomicRMWInst::FAdd: { 12134 Type *Ty = RMW->getType(); 12135 12136 // We don't have a way to support 16-bit atomics now, so just leave them 12137 // as-is. 12138 if (Ty->isHalfTy()) 12139 return AtomicExpansionKind::None; 12140 12141 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12142 return AtomicExpansionKind::CmpXChg; 12143 12144 unsigned AS = RMW->getPointerAddressSpace(); 12145 12146 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12147 Subtarget->hasAtomicFaddInsts()) { 12148 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12149 // floating point atomic instructions. May generate more efficient code, 12150 // but may not respect rounding and denormal modes, and may give incorrect 12151 // results for certain memory destinations. 12152 if (RMW->getFunction() 12153 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12154 .getValueAsString() != "true") 12155 return AtomicExpansionKind::CmpXChg; 12156 12157 if (Subtarget->hasGFX90AInsts()) { 12158 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12159 return AtomicExpansionKind::CmpXChg; 12160 12161 auto SSID = RMW->getSyncScopeID(); 12162 if (SSID == SyncScope::System || 12163 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12164 return AtomicExpansionKind::CmpXChg; 12165 12166 return AtomicExpansionKind::None; 12167 } 12168 12169 if (AS == AMDGPUAS::FLAT_ADDRESS) 12170 return AtomicExpansionKind::CmpXChg; 12171 12172 return RMW->use_empty() ? AtomicExpansionKind::None 12173 : AtomicExpansionKind::CmpXChg; 12174 } 12175 12176 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12177 // to round-to-nearest-even. 12178 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12179 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 12180 if (!Ty->isDoubleTy()) 12181 return AtomicExpansionKind::None; 12182 12183 return (fpModeMatchesGlobalFPAtomicMode(RMW) || 12184 RMW->getFunction() 12185 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12186 .getValueAsString() == "true") 12187 ? AtomicExpansionKind::None 12188 : AtomicExpansionKind::CmpXChg; 12189 } 12190 12191 return AtomicExpansionKind::CmpXChg; 12192 } 12193 default: 12194 break; 12195 } 12196 12197 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12198 } 12199 12200 const TargetRegisterClass * 12201 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12202 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12203 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12204 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12205 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12206 : &AMDGPU::SReg_32RegClass; 12207 if (!TRI->isSGPRClass(RC) && !isDivergent) 12208 return TRI->getEquivalentSGPRClass(RC); 12209 else if (TRI->isSGPRClass(RC) && isDivergent) 12210 return TRI->getEquivalentVGPRClass(RC); 12211 12212 return RC; 12213 } 12214 12215 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12216 // uniform values (as produced by the mask results of control flow intrinsics) 12217 // used outside of divergent blocks. The phi users need to also be treated as 12218 // always uniform. 12219 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12220 unsigned WaveSize) { 12221 // FIXME: We asssume we never cast the mask results of a control flow 12222 // intrinsic. 12223 // Early exit if the type won't be consistent as a compile time hack. 12224 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12225 if (!IT || IT->getBitWidth() != WaveSize) 12226 return false; 12227 12228 if (!isa<Instruction>(V)) 12229 return false; 12230 if (!Visited.insert(V).second) 12231 return false; 12232 bool Result = false; 12233 for (auto U : V->users()) { 12234 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12235 if (V == U->getOperand(1)) { 12236 switch (Intrinsic->getIntrinsicID()) { 12237 default: 12238 Result = false; 12239 break; 12240 case Intrinsic::amdgcn_if_break: 12241 case Intrinsic::amdgcn_if: 12242 case Intrinsic::amdgcn_else: 12243 Result = true; 12244 break; 12245 } 12246 } 12247 if (V == U->getOperand(0)) { 12248 switch (Intrinsic->getIntrinsicID()) { 12249 default: 12250 Result = false; 12251 break; 12252 case Intrinsic::amdgcn_end_cf: 12253 case Intrinsic::amdgcn_loop: 12254 Result = true; 12255 break; 12256 } 12257 } 12258 } else { 12259 Result = hasCFUser(U, Visited, WaveSize); 12260 } 12261 if (Result) 12262 break; 12263 } 12264 return Result; 12265 } 12266 12267 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12268 const Value *V) const { 12269 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12270 if (CI->isInlineAsm()) { 12271 // FIXME: This cannot give a correct answer. This should only trigger in 12272 // the case where inline asm returns mixed SGPR and VGPR results, used 12273 // outside the defining block. We don't have a specific result to 12274 // consider, so this assumes if any value is SGPR, the overall register 12275 // also needs to be SGPR. 12276 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12277 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12278 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12279 for (auto &TC : TargetConstraints) { 12280 if (TC.Type == InlineAsm::isOutput) { 12281 ComputeConstraintToUse(TC, SDValue()); 12282 unsigned AssignedReg; 12283 const TargetRegisterClass *RC; 12284 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12285 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12286 if (RC) { 12287 MachineRegisterInfo &MRI = MF.getRegInfo(); 12288 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12289 return true; 12290 else if (SIRI->isSGPRClass(RC)) 12291 return true; 12292 } 12293 } 12294 } 12295 } 12296 } 12297 SmallPtrSet<const Value *, 16> Visited; 12298 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12299 } 12300 12301 std::pair<InstructionCost, MVT> 12302 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12303 Type *Ty) const { 12304 std::pair<InstructionCost, MVT> Cost = 12305 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12306 auto Size = DL.getTypeSizeInBits(Ty); 12307 // Maximum load or store can handle 8 dwords for scalar and 4 for 12308 // vector ALU. Let's assume anything above 8 dwords is expensive 12309 // even if legal. 12310 if (Size <= 256) 12311 return Cost; 12312 12313 Cost.first = (Size + 255) / 256; 12314 return Cost; 12315 } 12316