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/FloatingPointMode.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/BinaryFormat/ELF.h" 25 #include "llvm/CodeGen/Analysis.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/IR/DiagnosticInfo.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/IntrinsicsAMDGPU.h" 35 #include "llvm/IR/IntrinsicsR600.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/KnownBits.h" 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "si-lower" 42 43 STATISTIC(NumTailCalls, "Number of tail calls"); 44 45 static cl::opt<bool> DisableLoopAlignment( 46 "amdgpu-disable-loop-alignment", 47 cl::desc("Do not align and prefetch loops"), 48 cl::init(false)); 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 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass); 140 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass); 141 } 142 143 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 144 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 145 146 computeRegisterProperties(Subtarget->getRegisterInfo()); 147 148 // The boolean content concept here is too inflexible. Compares only ever 149 // really produce a 1-bit result. Any copy/extend from these will turn into a 150 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 151 // it's what most targets use. 152 setBooleanContents(ZeroOrOneBooleanContent); 153 setBooleanVectorContents(ZeroOrOneBooleanContent); 154 155 // We need to custom lower vector stores from local memory 156 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 164 setOperationAction(ISD::LOAD, MVT::i1, Custom); 165 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 166 167 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 174 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 175 setOperationAction(ISD::STORE, MVT::i1, Custom); 176 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 177 178 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 179 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 180 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 181 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 182 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 183 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 184 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 185 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 186 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 187 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 188 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 189 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 190 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 191 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 192 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 193 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 194 195 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 197 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 200 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 201 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 202 203 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 204 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 205 206 setOperationAction(ISD::SELECT, MVT::i1, Promote); 207 setOperationAction(ISD::SELECT, MVT::i64, Custom); 208 setOperationAction(ISD::SELECT, MVT::f64, Promote); 209 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 210 211 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 216 217 setOperationAction(ISD::SETCC, MVT::i1, Promote); 218 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 219 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 220 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 221 222 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 223 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 224 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 225 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 226 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 227 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 228 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 229 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 230 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 232 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 233 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 234 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 235 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 236 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 237 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 238 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 246 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 247 248 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 249 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 251 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 253 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 254 255 setOperationAction(ISD::UADDO, MVT::i32, Legal); 256 setOperationAction(ISD::USUBO, MVT::i32, Legal); 257 258 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 259 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 260 261 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 263 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 264 265 #if 0 266 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 267 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 268 #endif 269 270 // We only support LOAD/STORE and vector manipulation ops for vectors 271 // with > 4 elements. 272 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 273 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 274 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 275 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 276 MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64, 277 MVT::v32i32, MVT::v32f32 }) { 278 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 279 switch (Op) { 280 case ISD::LOAD: 281 case ISD::STORE: 282 case ISD::BUILD_VECTOR: 283 case ISD::BITCAST: 284 case ISD::EXTRACT_VECTOR_ELT: 285 case ISD::INSERT_VECTOR_ELT: 286 case ISD::EXTRACT_SUBVECTOR: 287 case ISD::SCALAR_TO_VECTOR: 288 break; 289 case ISD::INSERT_SUBVECTOR: 290 case ISD::CONCAT_VECTORS: 291 setOperationAction(Op, VT, Custom); 292 break; 293 default: 294 setOperationAction(Op, VT, Expand); 295 break; 296 } 297 } 298 } 299 300 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 301 302 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 303 // is expanded to avoid having two separate loops in case the index is a VGPR. 304 305 // Most operations are naturally 32-bit vector operations. We only support 306 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 307 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 308 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 309 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 310 311 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 312 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 313 314 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 315 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 316 317 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 318 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 319 } 320 321 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 322 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 323 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 324 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 326 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 329 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 330 331 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 332 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 333 } 334 335 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 336 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 337 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 338 339 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 340 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 341 342 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 343 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 344 345 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 346 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 347 } 348 349 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 350 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 351 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 352 353 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 354 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 355 356 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 357 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 358 359 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 360 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 361 } 362 363 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 364 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 365 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 366 367 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 368 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 369 370 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 371 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 372 373 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 374 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 375 } 376 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 379 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 381 382 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 383 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 384 385 // Avoid stack access for these. 386 // TODO: Generalize to more vector types. 387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 389 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 391 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 398 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 403 404 // Deal with vec3 vector operations when widened to vec4. 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 408 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 409 410 // Deal with vec5/6/7 vector operations when widened to vec8. 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 419 420 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 421 // and output demarshalling 422 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 423 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 424 425 // We can't return success/failure, only the old value, 426 // let LLVM add the comparison 427 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 428 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 429 430 if (Subtarget->hasFlatAddressSpace()) { 431 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 432 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 433 } 434 435 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 436 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 437 438 // FIXME: This should be narrowed to i32, but that only happens if i64 is 439 // illegal. 440 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 441 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 442 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 443 444 // On SI this is s_memtime and s_memrealtime on VI. 445 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 446 setOperationAction(ISD::TRAP, MVT::Other, Custom); 447 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 448 449 if (Subtarget->has16BitInsts()) { 450 setOperationAction(ISD::FPOW, MVT::f16, Promote); 451 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 452 setOperationAction(ISD::FLOG, MVT::f16, Custom); 453 setOperationAction(ISD::FEXP, MVT::f16, Custom); 454 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 455 } 456 457 if (Subtarget->hasMadMacF32Insts()) 458 setOperationAction(ISD::FMAD, MVT::f32, Legal); 459 460 if (!Subtarget->hasBFI()) { 461 // fcopysign can be done in a single instruction with BFI. 462 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 463 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 464 } 465 466 if (!Subtarget->hasBCNT(32)) 467 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 468 469 if (!Subtarget->hasBCNT(64)) 470 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 471 472 if (Subtarget->hasFFBH()) { 473 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 474 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 475 } 476 477 if (Subtarget->hasFFBL()) { 478 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 479 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 480 } 481 482 // We only really have 32-bit BFE instructions (and 16-bit on VI). 483 // 484 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 485 // effort to match them now. We want this to be false for i64 cases when the 486 // extraction isn't restricted to the upper or lower half. Ideally we would 487 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 488 // span the midpoint are probably relatively rare, so don't worry about them 489 // for now. 490 if (Subtarget->hasBFE()) 491 setHasExtractBitsInsn(true); 492 493 // Clamp modifier on add/sub 494 if (Subtarget->hasIntClamp()) { 495 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 496 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 497 } 498 499 if (Subtarget->hasAddNoCarry()) { 500 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 502 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 503 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 504 } 505 506 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 508 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 509 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 510 511 512 // These are really only legal for ieee_mode functions. We should be avoiding 513 // them for functions that don't have ieee_mode enabled, so just say they are 514 // legal. 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 517 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 518 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 519 520 521 if (Subtarget->haveRoundOpsF64()) { 522 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 523 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 524 setOperationAction(ISD::FRINT, MVT::f64, Legal); 525 } else { 526 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 527 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 528 setOperationAction(ISD::FRINT, MVT::f64, Custom); 529 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 530 } 531 532 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 533 534 setOperationAction(ISD::FSIN, MVT::f32, Custom); 535 setOperationAction(ISD::FCOS, MVT::f32, Custom); 536 setOperationAction(ISD::FDIV, MVT::f32, Custom); 537 setOperationAction(ISD::FDIV, MVT::f64, Custom); 538 539 if (Subtarget->has16BitInsts()) { 540 setOperationAction(ISD::Constant, MVT::i16, Legal); 541 542 setOperationAction(ISD::SMIN, MVT::i16, Legal); 543 setOperationAction(ISD::SMAX, MVT::i16, Legal); 544 545 setOperationAction(ISD::UMIN, MVT::i16, Legal); 546 setOperationAction(ISD::UMAX, MVT::i16, Legal); 547 548 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 549 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 550 551 setOperationAction(ISD::ROTR, MVT::i16, Expand); 552 setOperationAction(ISD::ROTL, MVT::i16, Expand); 553 554 setOperationAction(ISD::SDIV, MVT::i16, Promote); 555 setOperationAction(ISD::UDIV, MVT::i16, Promote); 556 setOperationAction(ISD::SREM, MVT::i16, Promote); 557 setOperationAction(ISD::UREM, MVT::i16, Promote); 558 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 559 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 560 561 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 562 563 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 566 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 567 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 568 569 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 572 573 setOperationAction(ISD::LOAD, MVT::i16, Custom); 574 575 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 576 577 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 579 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 580 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 581 582 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 583 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 584 585 // F16 - Constant Actions. 586 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 587 588 // F16 - Load/Store Actions. 589 setOperationAction(ISD::LOAD, MVT::f16, Promote); 590 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 591 setOperationAction(ISD::STORE, MVT::f16, Promote); 592 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 593 594 // F16 - VOP1 Actions. 595 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 596 setOperationAction(ISD::FCOS, MVT::f16, Custom); 597 setOperationAction(ISD::FSIN, MVT::f16, Custom); 598 599 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 600 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 601 602 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 603 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 604 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 605 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 606 setOperationAction(ISD::FROUND, MVT::f16, Custom); 607 setOperationAction(ISD::FPTRUNC_ROUND, MVT::f16, Custom); 608 609 // F16 - VOP2 Actions. 610 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 611 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 612 613 setOperationAction(ISD::FDIV, MVT::f16, Custom); 614 615 // F16 - VOP3 Actions. 616 setOperationAction(ISD::FMA, MVT::f16, Legal); 617 if (STI.hasMadF16()) 618 setOperationAction(ISD::FMAD, MVT::f16, Legal); 619 620 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16, 621 MVT::v8f16}) { 622 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 623 switch (Op) { 624 case ISD::LOAD: 625 case ISD::STORE: 626 case ISD::BUILD_VECTOR: 627 case ISD::BITCAST: 628 case ISD::EXTRACT_VECTOR_ELT: 629 case ISD::INSERT_VECTOR_ELT: 630 case ISD::INSERT_SUBVECTOR: 631 case ISD::EXTRACT_SUBVECTOR: 632 case ISD::SCALAR_TO_VECTOR: 633 break; 634 case ISD::CONCAT_VECTORS: 635 setOperationAction(Op, VT, Custom); 636 break; 637 default: 638 setOperationAction(Op, VT, Expand); 639 break; 640 } 641 } 642 } 643 644 // v_perm_b32 can handle either of these. 645 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 646 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 647 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 648 649 // XXX - Do these do anything? Vector constants turn into build_vector. 650 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 651 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 652 653 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 654 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 655 656 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 659 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 660 661 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 662 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 663 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 664 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 665 666 setOperationAction(ISD::AND, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 668 setOperationAction(ISD::OR, MVT::v2i16, Promote); 669 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 670 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 671 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 672 673 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 674 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 675 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 676 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 677 678 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 679 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 680 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 681 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 682 683 setOperationAction(ISD::LOAD, MVT::v8i16, Promote); 684 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32); 685 setOperationAction(ISD::LOAD, MVT::v8f16, Promote); 686 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32); 687 688 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 689 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 690 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 691 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 692 693 setOperationAction(ISD::STORE, MVT::v8i16, Promote); 694 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32); 695 setOperationAction(ISD::STORE, MVT::v8f16, Promote); 696 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32); 697 698 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 699 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 700 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 701 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 702 703 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 704 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 705 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 706 707 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand); 708 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand); 709 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand); 710 711 if (!Subtarget->hasVOP3PInsts()) { 712 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 713 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 714 } 715 716 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 717 // This isn't really legal, but this avoids the legalizer unrolling it (and 718 // allows matching fneg (fabs x) patterns) 719 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 720 721 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 722 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 723 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 724 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 725 726 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 727 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 728 setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom); 729 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom); 730 731 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 732 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 733 setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand); 734 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand); 735 736 for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) { 737 setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom); 738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom); 739 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand); 740 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand); 741 } 742 } 743 744 if (Subtarget->hasVOP3PInsts()) { 745 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 746 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 747 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 748 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 749 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 750 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 751 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 752 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 753 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 754 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 755 756 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 757 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 758 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 759 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 760 761 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 762 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 763 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 764 765 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 766 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 767 768 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 769 770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 771 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 772 773 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 774 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 775 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom); 776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom); 777 778 for (MVT VT : { MVT::v4i16, MVT::v8i16 }) { 779 // Split vector operations. 780 setOperationAction(ISD::SHL, VT, Custom); 781 setOperationAction(ISD::SRA, VT, Custom); 782 setOperationAction(ISD::SRL, VT, Custom); 783 setOperationAction(ISD::ADD, VT, Custom); 784 setOperationAction(ISD::SUB, VT, Custom); 785 setOperationAction(ISD::MUL, VT, Custom); 786 787 setOperationAction(ISD::SMIN, VT, Custom); 788 setOperationAction(ISD::SMAX, VT, Custom); 789 setOperationAction(ISD::UMIN, VT, Custom); 790 setOperationAction(ISD::UMAX, VT, Custom); 791 792 setOperationAction(ISD::UADDSAT, VT, Custom); 793 setOperationAction(ISD::SADDSAT, VT, Custom); 794 setOperationAction(ISD::USUBSAT, VT, Custom); 795 setOperationAction(ISD::SSUBSAT, VT, Custom); 796 } 797 798 for (MVT VT : { MVT::v4f16, MVT::v8f16 }) { 799 // Split vector operations. 800 setOperationAction(ISD::FADD, VT, Custom); 801 setOperationAction(ISD::FMUL, VT, Custom); 802 setOperationAction(ISD::FMA, VT, Custom); 803 setOperationAction(ISD::FCANONICALIZE, VT, Custom); 804 } 805 806 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 807 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 808 809 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 810 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 811 812 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 813 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 814 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 815 816 if (Subtarget->hasPackedFP32Ops()) { 817 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 818 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 819 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 820 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 821 822 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 823 setOperationAction(ISD::FADD, VT, Custom); 824 setOperationAction(ISD::FMUL, VT, Custom); 825 setOperationAction(ISD::FMA, VT, Custom); 826 } 827 } 828 } 829 830 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 831 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 832 833 if (Subtarget->has16BitInsts()) { 834 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 835 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 836 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 837 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 838 } else { 839 // Legalization hack. 840 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 841 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 842 843 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 844 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 845 } 846 847 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 848 MVT::v8i16, MVT::v8f16 }) { 849 setOperationAction(ISD::SELECT, VT, Custom); 850 } 851 852 setOperationAction(ISD::SMULO, MVT::i64, Custom); 853 setOperationAction(ISD::UMULO, MVT::i64, Custom); 854 855 if (Subtarget->hasMad64_32()) { 856 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 857 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 858 } 859 860 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 861 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 862 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 863 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 864 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 865 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 866 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 867 868 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 869 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 870 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 871 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 872 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 873 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 874 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 875 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 876 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 877 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 878 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 879 880 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 881 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 882 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 883 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 884 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 885 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 886 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 887 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 888 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 889 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 890 891 setTargetDAGCombine(ISD::ADD); 892 setTargetDAGCombine(ISD::ADDCARRY); 893 setTargetDAGCombine(ISD::SUB); 894 setTargetDAGCombine(ISD::SUBCARRY); 895 setTargetDAGCombine(ISD::FADD); 896 setTargetDAGCombine(ISD::FSUB); 897 setTargetDAGCombine(ISD::FMINNUM); 898 setTargetDAGCombine(ISD::FMAXNUM); 899 setTargetDAGCombine(ISD::FMINNUM_IEEE); 900 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 901 setTargetDAGCombine(ISD::FMA); 902 setTargetDAGCombine(ISD::SMIN); 903 setTargetDAGCombine(ISD::SMAX); 904 setTargetDAGCombine(ISD::UMIN); 905 setTargetDAGCombine(ISD::UMAX); 906 setTargetDAGCombine(ISD::SETCC); 907 setTargetDAGCombine(ISD::AND); 908 setTargetDAGCombine(ISD::OR); 909 setTargetDAGCombine(ISD::XOR); 910 setTargetDAGCombine(ISD::SINT_TO_FP); 911 setTargetDAGCombine(ISD::UINT_TO_FP); 912 setTargetDAGCombine(ISD::FCANONICALIZE); 913 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 914 setTargetDAGCombine(ISD::ZERO_EXTEND); 915 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 916 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 917 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 918 919 // All memory operations. Some folding on the pointer operand is done to help 920 // matching the constant offsets in the addressing modes. 921 setTargetDAGCombine(ISD::LOAD); 922 setTargetDAGCombine(ISD::STORE); 923 setTargetDAGCombine(ISD::ATOMIC_LOAD); 924 setTargetDAGCombine(ISD::ATOMIC_STORE); 925 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 926 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 927 setTargetDAGCombine(ISD::ATOMIC_SWAP); 928 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 929 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 930 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 931 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 932 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 933 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 934 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 935 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 936 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 937 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 938 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 939 setTargetDAGCombine(ISD::INTRINSIC_VOID); 940 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 941 942 // FIXME: In other contexts we pretend this is a per-function property. 943 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 944 945 setSchedulingPreference(Sched::RegPressure); 946 } 947 948 const GCNSubtarget *SITargetLowering::getSubtarget() const { 949 return Subtarget; 950 } 951 952 //===----------------------------------------------------------------------===// 953 // TargetLowering queries 954 //===----------------------------------------------------------------------===// 955 956 // v_mad_mix* support a conversion from f16 to f32. 957 // 958 // There is only one special case when denormals are enabled we don't currently, 959 // where this is OK to use. 960 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 961 EVT DestVT, EVT SrcVT) const { 962 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 963 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 964 DestVT.getScalarType() == MVT::f32 && 965 SrcVT.getScalarType() == MVT::f16 && 966 // TODO: This probably only requires no input flushing? 967 !hasFP32Denormals(DAG.getMachineFunction()); 968 } 969 970 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 971 LLT DestTy, LLT SrcTy) const { 972 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 973 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 974 DestTy.getScalarSizeInBits() == 32 && 975 SrcTy.getScalarSizeInBits() == 16 && 976 // TODO: This probably only requires no input flushing? 977 !hasFP32Denormals(*MI.getMF()); 978 } 979 980 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 981 // SI has some legal vector types, but no legal vector operations. Say no 982 // shuffles are legal in order to prefer scalarizing some vector operations. 983 return false; 984 } 985 986 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 987 CallingConv::ID CC, 988 EVT VT) const { 989 if (CC == CallingConv::AMDGPU_KERNEL) 990 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 991 992 if (VT.isVector()) { 993 EVT ScalarVT = VT.getScalarType(); 994 unsigned Size = ScalarVT.getSizeInBits(); 995 if (Size == 16) { 996 if (Subtarget->has16BitInsts()) 997 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 998 return VT.isInteger() ? MVT::i32 : MVT::f32; 999 } 1000 1001 if (Size < 16) 1002 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 1003 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 1004 } 1005 1006 if (VT.getSizeInBits() > 32) 1007 return MVT::i32; 1008 1009 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1010 } 1011 1012 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1013 CallingConv::ID CC, 1014 EVT VT) const { 1015 if (CC == CallingConv::AMDGPU_KERNEL) 1016 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1017 1018 if (VT.isVector()) { 1019 unsigned NumElts = VT.getVectorNumElements(); 1020 EVT ScalarVT = VT.getScalarType(); 1021 unsigned Size = ScalarVT.getSizeInBits(); 1022 1023 // FIXME: Should probably promote 8-bit vectors to i16. 1024 if (Size == 16 && Subtarget->has16BitInsts()) 1025 return (NumElts + 1) / 2; 1026 1027 if (Size <= 32) 1028 return NumElts; 1029 1030 if (Size > 32) 1031 return NumElts * ((Size + 31) / 32); 1032 } else if (VT.getSizeInBits() > 32) 1033 return (VT.getSizeInBits() + 31) / 32; 1034 1035 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1036 } 1037 1038 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 1039 LLVMContext &Context, CallingConv::ID CC, 1040 EVT VT, EVT &IntermediateVT, 1041 unsigned &NumIntermediates, MVT &RegisterVT) const { 1042 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 1043 unsigned NumElts = VT.getVectorNumElements(); 1044 EVT ScalarVT = VT.getScalarType(); 1045 unsigned Size = ScalarVT.getSizeInBits(); 1046 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1047 // support, but unless we can properly handle 3-vectors, it will be still be 1048 // inconsistent. 1049 if (Size == 16 && Subtarget->has16BitInsts()) { 1050 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1051 IntermediateVT = RegisterVT; 1052 NumIntermediates = (NumElts + 1) / 2; 1053 return NumIntermediates; 1054 } 1055 1056 if (Size == 32) { 1057 RegisterVT = ScalarVT.getSimpleVT(); 1058 IntermediateVT = RegisterVT; 1059 NumIntermediates = NumElts; 1060 return NumIntermediates; 1061 } 1062 1063 if (Size < 16 && Subtarget->has16BitInsts()) { 1064 // FIXME: Should probably form v2i16 pieces 1065 RegisterVT = MVT::i16; 1066 IntermediateVT = ScalarVT; 1067 NumIntermediates = NumElts; 1068 return NumIntermediates; 1069 } 1070 1071 1072 if (Size != 16 && Size <= 32) { 1073 RegisterVT = MVT::i32; 1074 IntermediateVT = ScalarVT; 1075 NumIntermediates = NumElts; 1076 return NumIntermediates; 1077 } 1078 1079 if (Size > 32) { 1080 RegisterVT = MVT::i32; 1081 IntermediateVT = RegisterVT; 1082 NumIntermediates = NumElts * ((Size + 31) / 32); 1083 return NumIntermediates; 1084 } 1085 } 1086 1087 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1088 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1089 } 1090 1091 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1092 assert(DMaskLanes != 0); 1093 1094 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1095 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1096 return EVT::getVectorVT(Ty->getContext(), 1097 EVT::getEVT(VT->getElementType()), 1098 NumElts); 1099 } 1100 1101 return EVT::getEVT(Ty); 1102 } 1103 1104 // Peek through TFE struct returns to only use the data size. 1105 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1106 auto *ST = dyn_cast<StructType>(Ty); 1107 if (!ST) 1108 return memVTFromImageData(Ty, DMaskLanes); 1109 1110 // Some intrinsics return an aggregate type - special case to work out the 1111 // correct memVT. 1112 // 1113 // Only limited forms of aggregate type currently expected. 1114 if (ST->getNumContainedTypes() != 2 || 1115 !ST->getContainedType(1)->isIntegerTy(32)) 1116 return EVT(); 1117 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1118 } 1119 1120 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1121 const CallInst &CI, 1122 MachineFunction &MF, 1123 unsigned IntrID) const { 1124 Info.flags = MachineMemOperand::MONone; 1125 if (CI.hasMetadata(LLVMContext::MD_invariant_load)) 1126 Info.flags |= MachineMemOperand::MOInvariant; 1127 1128 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1129 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1130 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1131 (Intrinsic::ID)IntrID); 1132 if (Attr.hasFnAttr(Attribute::ReadNone)) 1133 return false; 1134 1135 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1136 1137 if (RsrcIntr->IsImage) { 1138 Info.ptrVal = 1139 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1140 Info.align.reset(); 1141 } else { 1142 Info.ptrVal = 1143 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1144 } 1145 1146 Info.flags |= MachineMemOperand::MODereferenceable; 1147 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1148 unsigned DMaskLanes = 4; 1149 1150 if (RsrcIntr->IsImage) { 1151 const AMDGPU::ImageDimIntrinsicInfo *Intr 1152 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1153 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1154 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1155 1156 if (!BaseOpcode->Gather4) { 1157 // If this isn't a gather, we may have excess loaded elements in the 1158 // IR type. Check the dmask for the real number of elements loaded. 1159 unsigned DMask 1160 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1161 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1162 } 1163 1164 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1165 } else 1166 Info.memVT = EVT::getEVT(CI.getType()); 1167 1168 // FIXME: What does alignment mean for an image? 1169 Info.opc = ISD::INTRINSIC_W_CHAIN; 1170 Info.flags |= MachineMemOperand::MOLoad; 1171 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1172 Info.opc = ISD::INTRINSIC_VOID; 1173 1174 Type *DataTy = CI.getArgOperand(0)->getType(); 1175 if (RsrcIntr->IsImage) { 1176 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1177 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1178 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1179 } else 1180 Info.memVT = EVT::getEVT(DataTy); 1181 1182 Info.flags |= MachineMemOperand::MOStore; 1183 } else { 1184 // Atomic 1185 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1186 ISD::INTRINSIC_W_CHAIN; 1187 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1188 Info.flags |= MachineMemOperand::MOLoad | 1189 MachineMemOperand::MOStore | 1190 MachineMemOperand::MODereferenceable; 1191 1192 // XXX - Should this be volatile without known ordering? 1193 Info.flags |= MachineMemOperand::MOVolatile; 1194 } 1195 return true; 1196 } 1197 1198 switch (IntrID) { 1199 case Intrinsic::amdgcn_atomic_inc: 1200 case Intrinsic::amdgcn_atomic_dec: 1201 case Intrinsic::amdgcn_ds_ordered_add: 1202 case Intrinsic::amdgcn_ds_ordered_swap: 1203 case Intrinsic::amdgcn_ds_fadd: 1204 case Intrinsic::amdgcn_ds_fmin: 1205 case Intrinsic::amdgcn_ds_fmax: { 1206 Info.opc = ISD::INTRINSIC_W_CHAIN; 1207 Info.memVT = MVT::getVT(CI.getType()); 1208 Info.ptrVal = CI.getOperand(0); 1209 Info.align.reset(); 1210 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1211 1212 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1213 if (!Vol->isZero()) 1214 Info.flags |= MachineMemOperand::MOVolatile; 1215 1216 return true; 1217 } 1218 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1219 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1220 1221 Info.opc = ISD::INTRINSIC_W_CHAIN; 1222 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1223 Info.ptrVal = 1224 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1225 Info.align.reset(); 1226 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1227 1228 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1229 if (!Vol || !Vol->isZero()) 1230 Info.flags |= MachineMemOperand::MOVolatile; 1231 1232 return true; 1233 } 1234 case Intrinsic::amdgcn_ds_append: 1235 case Intrinsic::amdgcn_ds_consume: { 1236 Info.opc = ISD::INTRINSIC_W_CHAIN; 1237 Info.memVT = MVT::getVT(CI.getType()); 1238 Info.ptrVal = CI.getOperand(0); 1239 Info.align.reset(); 1240 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1241 1242 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1243 if (!Vol->isZero()) 1244 Info.flags |= MachineMemOperand::MOVolatile; 1245 1246 return true; 1247 } 1248 case Intrinsic::amdgcn_global_atomic_csub: { 1249 Info.opc = ISD::INTRINSIC_W_CHAIN; 1250 Info.memVT = MVT::getVT(CI.getType()); 1251 Info.ptrVal = CI.getOperand(0); 1252 Info.align.reset(); 1253 Info.flags |= MachineMemOperand::MOLoad | 1254 MachineMemOperand::MOStore | 1255 MachineMemOperand::MOVolatile; 1256 return true; 1257 } 1258 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1259 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1260 Info.opc = ISD::INTRINSIC_W_CHAIN; 1261 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1262 Info.ptrVal = 1263 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1264 Info.align.reset(); 1265 Info.flags |= MachineMemOperand::MOLoad | 1266 MachineMemOperand::MODereferenceable; 1267 return true; 1268 } 1269 case Intrinsic::amdgcn_global_atomic_fadd: 1270 case Intrinsic::amdgcn_global_atomic_fmin: 1271 case Intrinsic::amdgcn_global_atomic_fmax: 1272 case Intrinsic::amdgcn_flat_atomic_fadd: 1273 case Intrinsic::amdgcn_flat_atomic_fmin: 1274 case Intrinsic::amdgcn_flat_atomic_fmax: 1275 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1276 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: { 1277 Info.opc = ISD::INTRINSIC_W_CHAIN; 1278 Info.memVT = MVT::getVT(CI.getType()); 1279 Info.ptrVal = CI.getOperand(0); 1280 Info.align.reset(); 1281 Info.flags |= MachineMemOperand::MOLoad | 1282 MachineMemOperand::MOStore | 1283 MachineMemOperand::MODereferenceable | 1284 MachineMemOperand::MOVolatile; 1285 return true; 1286 } 1287 case Intrinsic::amdgcn_ds_gws_init: 1288 case Intrinsic::amdgcn_ds_gws_barrier: 1289 case Intrinsic::amdgcn_ds_gws_sema_v: 1290 case Intrinsic::amdgcn_ds_gws_sema_br: 1291 case Intrinsic::amdgcn_ds_gws_sema_p: 1292 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1293 Info.opc = ISD::INTRINSIC_VOID; 1294 1295 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1296 Info.ptrVal = 1297 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1298 1299 // This is an abstract access, but we need to specify a type and size. 1300 Info.memVT = MVT::i32; 1301 Info.size = 4; 1302 Info.align = Align(4); 1303 1304 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1305 Info.flags |= MachineMemOperand::MOLoad; 1306 else 1307 Info.flags |= MachineMemOperand::MOStore; 1308 return true; 1309 } 1310 default: 1311 return false; 1312 } 1313 } 1314 1315 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1316 SmallVectorImpl<Value*> &Ops, 1317 Type *&AccessTy) const { 1318 switch (II->getIntrinsicID()) { 1319 case Intrinsic::amdgcn_atomic_inc: 1320 case Intrinsic::amdgcn_atomic_dec: 1321 case Intrinsic::amdgcn_ds_ordered_add: 1322 case Intrinsic::amdgcn_ds_ordered_swap: 1323 case Intrinsic::amdgcn_ds_append: 1324 case Intrinsic::amdgcn_ds_consume: 1325 case Intrinsic::amdgcn_ds_fadd: 1326 case Intrinsic::amdgcn_ds_fmin: 1327 case Intrinsic::amdgcn_ds_fmax: 1328 case Intrinsic::amdgcn_global_atomic_fadd: 1329 case Intrinsic::amdgcn_flat_atomic_fadd: 1330 case Intrinsic::amdgcn_flat_atomic_fmin: 1331 case Intrinsic::amdgcn_flat_atomic_fmax: 1332 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1333 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: 1334 case Intrinsic::amdgcn_global_atomic_csub: { 1335 Value *Ptr = II->getArgOperand(0); 1336 AccessTy = II->getType(); 1337 Ops.push_back(Ptr); 1338 return true; 1339 } 1340 default: 1341 return false; 1342 } 1343 } 1344 1345 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1346 if (!Subtarget->hasFlatInstOffsets()) { 1347 // Flat instructions do not have offsets, and only have the register 1348 // address. 1349 return AM.BaseOffs == 0 && AM.Scale == 0; 1350 } 1351 1352 return AM.Scale == 0 && 1353 (AM.BaseOffs == 0 || 1354 Subtarget->getInstrInfo()->isLegalFLATOffset( 1355 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1356 } 1357 1358 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1359 if (Subtarget->hasFlatGlobalInsts()) 1360 return AM.Scale == 0 && 1361 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1362 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1363 SIInstrFlags::FlatGlobal)); 1364 1365 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1366 // Assume the we will use FLAT for all global memory accesses 1367 // on VI. 1368 // FIXME: This assumption is currently wrong. On VI we still use 1369 // MUBUF instructions for the r + i addressing mode. As currently 1370 // implemented, the MUBUF instructions only work on buffer < 4GB. 1371 // It may be possible to support > 4GB buffers with MUBUF instructions, 1372 // by setting the stride value in the resource descriptor which would 1373 // increase the size limit to (stride * 4GB). However, this is risky, 1374 // because it has never been validated. 1375 return isLegalFlatAddressingMode(AM); 1376 } 1377 1378 return isLegalMUBUFAddressingMode(AM); 1379 } 1380 1381 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1382 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1383 // additionally can do r + r + i with addr64. 32-bit has more addressing 1384 // mode options. Depending on the resource constant, it can also do 1385 // (i64 r0) + (i32 r1) * (i14 i). 1386 // 1387 // Private arrays end up using a scratch buffer most of the time, so also 1388 // assume those use MUBUF instructions. Scratch loads / stores are currently 1389 // implemented as mubuf instructions with offen bit set, so slightly 1390 // different than the normal addr64. 1391 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1392 return false; 1393 1394 // FIXME: Since we can split immediate into soffset and immediate offset, 1395 // would it make sense to allow any immediate? 1396 1397 switch (AM.Scale) { 1398 case 0: // r + i or just i, depending on HasBaseReg. 1399 return true; 1400 case 1: 1401 return true; // We have r + r or r + i. 1402 case 2: 1403 if (AM.HasBaseReg) { 1404 // Reject 2 * r + r. 1405 return false; 1406 } 1407 1408 // Allow 2 * r as r + r 1409 // Or 2 * r + i is allowed as r + r + i. 1410 return true; 1411 default: // Don't allow n * r 1412 return false; 1413 } 1414 } 1415 1416 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1417 const AddrMode &AM, Type *Ty, 1418 unsigned AS, Instruction *I) const { 1419 // No global is ever allowed as a base. 1420 if (AM.BaseGV) 1421 return false; 1422 1423 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1424 return isLegalGlobalAddressingMode(AM); 1425 1426 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1427 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1428 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1429 // If the offset isn't a multiple of 4, it probably isn't going to be 1430 // correctly aligned. 1431 // FIXME: Can we get the real alignment here? 1432 if (AM.BaseOffs % 4 != 0) 1433 return isLegalMUBUFAddressingMode(AM); 1434 1435 // There are no SMRD extloads, so if we have to do a small type access we 1436 // will use a MUBUF load. 1437 // FIXME?: We also need to do this if unaligned, but we don't know the 1438 // alignment here. 1439 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1440 return isLegalGlobalAddressingMode(AM); 1441 1442 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1443 // SMRD instructions have an 8-bit, dword offset on SI. 1444 if (!isUInt<8>(AM.BaseOffs / 4)) 1445 return false; 1446 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1447 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1448 // in 8-bits, it can use a smaller encoding. 1449 if (!isUInt<32>(AM.BaseOffs / 4)) 1450 return false; 1451 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1452 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1453 if (!isUInt<20>(AM.BaseOffs)) 1454 return false; 1455 } else 1456 llvm_unreachable("unhandled generation"); 1457 1458 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1459 return true; 1460 1461 if (AM.Scale == 1 && AM.HasBaseReg) 1462 return true; 1463 1464 return false; 1465 1466 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1467 return isLegalMUBUFAddressingMode(AM); 1468 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1469 AS == AMDGPUAS::REGION_ADDRESS) { 1470 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1471 // field. 1472 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1473 // an 8-bit dword offset but we don't know the alignment here. 1474 if (!isUInt<16>(AM.BaseOffs)) 1475 return false; 1476 1477 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1478 return true; 1479 1480 if (AM.Scale == 1 && AM.HasBaseReg) 1481 return true; 1482 1483 return false; 1484 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1485 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1486 // For an unknown address space, this usually means that this is for some 1487 // reason being used for pure arithmetic, and not based on some addressing 1488 // computation. We don't have instructions that compute pointers with any 1489 // addressing modes, so treat them as having no offset like flat 1490 // instructions. 1491 return isLegalFlatAddressingMode(AM); 1492 } 1493 1494 // Assume a user alias of global for unknown address spaces. 1495 return isLegalGlobalAddressingMode(AM); 1496 } 1497 1498 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1499 const MachineFunction &MF) const { 1500 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1501 return (MemVT.getSizeInBits() <= 4 * 32); 1502 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1503 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1504 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1505 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1506 return (MemVT.getSizeInBits() <= 2 * 32); 1507 } 1508 return true; 1509 } 1510 1511 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1512 unsigned Size, unsigned AddrSpace, Align Alignment, 1513 MachineMemOperand::Flags Flags, bool *IsFast) const { 1514 if (IsFast) 1515 *IsFast = false; 1516 1517 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1518 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1519 // Check if alignment requirements for ds_read/write instructions are 1520 // disabled. 1521 if (Subtarget->hasUnalignedDSAccessEnabled() && 1522 !Subtarget->hasLDSMisalignedBug()) { 1523 if (IsFast) 1524 *IsFast = Alignment != Align(2); 1525 return true; 1526 } 1527 1528 // Either, the alignment requirements are "enabled", or there is an 1529 // unaligned LDS access related hardware bug though alignment requirements 1530 // are "disabled". In either case, we need to check for proper alignment 1531 // requirements. 1532 // 1533 if (Size == 64) { 1534 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1535 // can do a 4 byte aligned, 8 byte access in a single operation using 1536 // ds_read2/write2_b32 with adjacent offsets. 1537 bool AlignedBy4 = Alignment >= Align(4); 1538 if (IsFast) 1539 *IsFast = AlignedBy4; 1540 1541 return AlignedBy4; 1542 } 1543 if (Size == 96) { 1544 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1545 // gfx8 and older. 1546 bool AlignedBy16 = Alignment >= Align(16); 1547 if (IsFast) 1548 *IsFast = AlignedBy16; 1549 1550 return AlignedBy16; 1551 } 1552 if (Size == 128) { 1553 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1554 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1555 // single operation using ds_read2/write2_b64. 1556 bool AlignedBy8 = Alignment >= Align(8); 1557 if (IsFast) 1558 *IsFast = AlignedBy8; 1559 1560 return AlignedBy8; 1561 } 1562 } 1563 1564 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1565 bool AlignedBy4 = Alignment >= Align(4); 1566 if (IsFast) 1567 *IsFast = AlignedBy4; 1568 1569 return AlignedBy4 || 1570 Subtarget->enableFlatScratch() || 1571 Subtarget->hasUnalignedScratchAccess(); 1572 } 1573 1574 // FIXME: We have to be conservative here and assume that flat operations 1575 // will access scratch. If we had access to the IR function, then we 1576 // could determine if any private memory was used in the function. 1577 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1578 !Subtarget->hasUnalignedScratchAccess()) { 1579 bool AlignedBy4 = Alignment >= Align(4); 1580 if (IsFast) 1581 *IsFast = AlignedBy4; 1582 1583 return AlignedBy4; 1584 } 1585 1586 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1587 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1588 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1589 // If we have a uniform constant load, it still requires using a slow 1590 // buffer instruction if unaligned. 1591 if (IsFast) { 1592 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1593 // 2-byte alignment is worse than 1 unless doing a 2-byte access. 1594 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1595 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1596 Alignment >= Align(4) : Alignment != Align(2); 1597 } 1598 1599 return true; 1600 } 1601 1602 // Smaller than dword value must be aligned. 1603 if (Size < 32) 1604 return false; 1605 1606 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1607 // byte-address are ignored, thus forcing Dword alignment. 1608 // This applies to private, global, and constant memory. 1609 if (IsFast) 1610 *IsFast = true; 1611 1612 return Size >= 32 && Alignment >= Align(4); 1613 } 1614 1615 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1616 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1617 bool *IsFast) const { 1618 if (IsFast) 1619 *IsFast = false; 1620 1621 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1622 // which isn't a simple VT. 1623 // Until MVT is extended to handle this, simply check for the size and 1624 // rely on the condition below: allow accesses if the size is a multiple of 4. 1625 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1626 VT.getStoreSize() > 16)) { 1627 return false; 1628 } 1629 1630 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1631 Alignment, Flags, IsFast); 1632 } 1633 1634 EVT SITargetLowering::getOptimalMemOpType( 1635 const MemOp &Op, const AttributeList &FuncAttributes) const { 1636 // FIXME: Should account for address space here. 1637 1638 // The default fallback uses the private pointer size as a guess for a type to 1639 // use. Make sure we switch these to 64-bit accesses. 1640 1641 if (Op.size() >= 16 && 1642 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1643 return MVT::v4i32; 1644 1645 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1646 return MVT::v2i32; 1647 1648 // Use the default. 1649 return MVT::Other; 1650 } 1651 1652 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1653 const MemSDNode *MemNode = cast<MemSDNode>(N); 1654 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1655 } 1656 1657 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1658 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1659 AS == AMDGPUAS::PRIVATE_ADDRESS; 1660 } 1661 1662 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1663 unsigned DestAS) const { 1664 // Flat -> private/local is a simple truncate. 1665 // Flat -> global is no-op 1666 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1667 return true; 1668 1669 const GCNTargetMachine &TM = 1670 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1671 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1672 } 1673 1674 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1675 const MemSDNode *MemNode = cast<MemSDNode>(N); 1676 1677 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1678 } 1679 1680 TargetLoweringBase::LegalizeTypeAction 1681 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1682 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1683 VT.getScalarType().bitsLE(MVT::i16)) 1684 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1685 return TargetLoweringBase::getPreferredVectorAction(VT); 1686 } 1687 1688 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1689 Type *Ty) const { 1690 // FIXME: Could be smarter if called for vector constants. 1691 return true; 1692 } 1693 1694 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1695 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1696 switch (Op) { 1697 case ISD::LOAD: 1698 case ISD::STORE: 1699 1700 // These operations are done with 32-bit instructions anyway. 1701 case ISD::AND: 1702 case ISD::OR: 1703 case ISD::XOR: 1704 case ISD::SELECT: 1705 // TODO: Extensions? 1706 return true; 1707 default: 1708 return false; 1709 } 1710 } 1711 1712 // SimplifySetCC uses this function to determine whether or not it should 1713 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1714 if (VT == MVT::i1 && Op == ISD::SETCC) 1715 return false; 1716 1717 return TargetLowering::isTypeDesirableForOp(Op, VT); 1718 } 1719 1720 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1721 const SDLoc &SL, 1722 SDValue Chain, 1723 uint64_t Offset) const { 1724 const DataLayout &DL = DAG.getDataLayout(); 1725 MachineFunction &MF = DAG.getMachineFunction(); 1726 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1727 1728 const ArgDescriptor *InputPtrReg; 1729 const TargetRegisterClass *RC; 1730 LLT ArgTy; 1731 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1732 1733 std::tie(InputPtrReg, RC, ArgTy) = 1734 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1735 1736 // We may not have the kernarg segment argument if we have no kernel 1737 // arguments. 1738 if (!InputPtrReg) 1739 return DAG.getConstant(0, SL, PtrVT); 1740 1741 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1742 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1743 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1744 1745 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1746 } 1747 1748 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1749 const SDLoc &SL) const { 1750 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1751 FIRST_IMPLICIT); 1752 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1753 } 1754 1755 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1756 const SDLoc &SL, SDValue Val, 1757 bool Signed, 1758 const ISD::InputArg *Arg) const { 1759 // First, if it is a widened vector, narrow it. 1760 if (VT.isVector() && 1761 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1762 EVT NarrowedVT = 1763 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1764 VT.getVectorNumElements()); 1765 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1766 DAG.getConstant(0, SL, MVT::i32)); 1767 } 1768 1769 // Then convert the vector elements or scalar value. 1770 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1771 VT.bitsLT(MemVT)) { 1772 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1773 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1774 } 1775 1776 if (MemVT.isFloatingPoint()) 1777 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1778 else if (Signed) 1779 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1780 else 1781 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1782 1783 return Val; 1784 } 1785 1786 SDValue SITargetLowering::lowerKernargMemParameter( 1787 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1788 uint64_t Offset, Align Alignment, bool Signed, 1789 const ISD::InputArg *Arg) const { 1790 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1791 1792 // Try to avoid using an extload by loading earlier than the argument address, 1793 // and extracting the relevant bits. The load should hopefully be merged with 1794 // the previous argument. 1795 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1796 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1797 int64_t AlignDownOffset = alignDown(Offset, 4); 1798 int64_t OffsetDiff = Offset - AlignDownOffset; 1799 1800 EVT IntVT = MemVT.changeTypeToInteger(); 1801 1802 // TODO: If we passed in the base kernel offset we could have a better 1803 // alignment than 4, but we don't really need it. 1804 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1805 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1806 MachineMemOperand::MODereferenceable | 1807 MachineMemOperand::MOInvariant); 1808 1809 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1810 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1811 1812 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1813 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1814 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1815 1816 1817 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1818 } 1819 1820 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1821 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1822 MachineMemOperand::MODereferenceable | 1823 MachineMemOperand::MOInvariant); 1824 1825 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1826 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1827 } 1828 1829 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1830 const SDLoc &SL, SDValue Chain, 1831 const ISD::InputArg &Arg) const { 1832 MachineFunction &MF = DAG.getMachineFunction(); 1833 MachineFrameInfo &MFI = MF.getFrameInfo(); 1834 1835 if (Arg.Flags.isByVal()) { 1836 unsigned Size = Arg.Flags.getByValSize(); 1837 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1838 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1839 } 1840 1841 unsigned ArgOffset = VA.getLocMemOffset(); 1842 unsigned ArgSize = VA.getValVT().getStoreSize(); 1843 1844 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1845 1846 // Create load nodes to retrieve arguments from the stack. 1847 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1848 SDValue ArgValue; 1849 1850 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1851 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1852 MVT MemVT = VA.getValVT(); 1853 1854 switch (VA.getLocInfo()) { 1855 default: 1856 break; 1857 case CCValAssign::BCvt: 1858 MemVT = VA.getLocVT(); 1859 break; 1860 case CCValAssign::SExt: 1861 ExtType = ISD::SEXTLOAD; 1862 break; 1863 case CCValAssign::ZExt: 1864 ExtType = ISD::ZEXTLOAD; 1865 break; 1866 case CCValAssign::AExt: 1867 ExtType = ISD::EXTLOAD; 1868 break; 1869 } 1870 1871 ArgValue = DAG.getExtLoad( 1872 ExtType, SL, VA.getLocVT(), Chain, FIN, 1873 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1874 MemVT); 1875 return ArgValue; 1876 } 1877 1878 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1879 const SIMachineFunctionInfo &MFI, 1880 EVT VT, 1881 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1882 const ArgDescriptor *Reg; 1883 const TargetRegisterClass *RC; 1884 LLT Ty; 1885 1886 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1887 if (!Reg) { 1888 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1889 // It's possible for a kernarg intrinsic call to appear in a kernel with 1890 // no allocated segment, in which case we do not add the user sgpr 1891 // argument, so just return null. 1892 return DAG.getConstant(0, SDLoc(), VT); 1893 } 1894 1895 // It's undefined behavior if a function marked with the amdgpu-no-* 1896 // attributes uses the corresponding intrinsic. 1897 return DAG.getUNDEF(VT); 1898 } 1899 1900 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1901 } 1902 1903 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1904 CallingConv::ID CallConv, 1905 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1906 FunctionType *FType, 1907 SIMachineFunctionInfo *Info) { 1908 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1909 const ISD::InputArg *Arg = &Ins[I]; 1910 1911 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1912 "vector type argument should have been split"); 1913 1914 // First check if it's a PS input addr. 1915 if (CallConv == CallingConv::AMDGPU_PS && 1916 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1917 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1918 1919 // Inconveniently only the first part of the split is marked as isSplit, 1920 // so skip to the end. We only want to increment PSInputNum once for the 1921 // entire split argument. 1922 if (Arg->Flags.isSplit()) { 1923 while (!Arg->Flags.isSplitEnd()) { 1924 assert((!Arg->VT.isVector() || 1925 Arg->VT.getScalarSizeInBits() == 16) && 1926 "unexpected vector split in ps argument type"); 1927 if (!SkipArg) 1928 Splits.push_back(*Arg); 1929 Arg = &Ins[++I]; 1930 } 1931 } 1932 1933 if (SkipArg) { 1934 // We can safely skip PS inputs. 1935 Skipped.set(Arg->getOrigArgIndex()); 1936 ++PSInputNum; 1937 continue; 1938 } 1939 1940 Info->markPSInputAllocated(PSInputNum); 1941 if (Arg->Used) 1942 Info->markPSInputEnabled(PSInputNum); 1943 1944 ++PSInputNum; 1945 } 1946 1947 Splits.push_back(*Arg); 1948 } 1949 } 1950 1951 // Allocate special inputs passed in VGPRs. 1952 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1953 MachineFunction &MF, 1954 const SIRegisterInfo &TRI, 1955 SIMachineFunctionInfo &Info) const { 1956 const LLT S32 = LLT::scalar(32); 1957 MachineRegisterInfo &MRI = MF.getRegInfo(); 1958 1959 if (Info.hasWorkItemIDX()) { 1960 Register Reg = AMDGPU::VGPR0; 1961 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1962 1963 CCInfo.AllocateReg(Reg); 1964 unsigned Mask = (Subtarget->hasPackedTID() && 1965 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1966 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1967 } 1968 1969 if (Info.hasWorkItemIDY()) { 1970 assert(Info.hasWorkItemIDX()); 1971 if (Subtarget->hasPackedTID()) { 1972 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1973 0x3ff << 10)); 1974 } else { 1975 unsigned Reg = AMDGPU::VGPR1; 1976 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1977 1978 CCInfo.AllocateReg(Reg); 1979 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1980 } 1981 } 1982 1983 if (Info.hasWorkItemIDZ()) { 1984 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1985 if (Subtarget->hasPackedTID()) { 1986 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1987 0x3ff << 20)); 1988 } else { 1989 unsigned Reg = AMDGPU::VGPR2; 1990 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1991 1992 CCInfo.AllocateReg(Reg); 1993 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1994 } 1995 } 1996 } 1997 1998 // Try to allocate a VGPR at the end of the argument list, or if no argument 1999 // VGPRs are left allocating a stack slot. 2000 // If \p Mask is is given it indicates bitfield position in the register. 2001 // If \p Arg is given use it with new ]p Mask instead of allocating new. 2002 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 2003 ArgDescriptor Arg = ArgDescriptor()) { 2004 if (Arg.isSet()) 2005 return ArgDescriptor::createArg(Arg, Mask); 2006 2007 ArrayRef<MCPhysReg> ArgVGPRs 2008 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 2009 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 2010 if (RegIdx == ArgVGPRs.size()) { 2011 // Spill to stack required. 2012 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 2013 2014 return ArgDescriptor::createStack(Offset, Mask); 2015 } 2016 2017 unsigned Reg = ArgVGPRs[RegIdx]; 2018 Reg = CCInfo.AllocateReg(Reg); 2019 assert(Reg != AMDGPU::NoRegister); 2020 2021 MachineFunction &MF = CCInfo.getMachineFunction(); 2022 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 2023 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 2024 return ArgDescriptor::createRegister(Reg, Mask); 2025 } 2026 2027 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 2028 const TargetRegisterClass *RC, 2029 unsigned NumArgRegs) { 2030 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 2031 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 2032 if (RegIdx == ArgSGPRs.size()) 2033 report_fatal_error("ran out of SGPRs for arguments"); 2034 2035 unsigned Reg = ArgSGPRs[RegIdx]; 2036 Reg = CCInfo.AllocateReg(Reg); 2037 assert(Reg != AMDGPU::NoRegister); 2038 2039 MachineFunction &MF = CCInfo.getMachineFunction(); 2040 MF.addLiveIn(Reg, RC); 2041 return ArgDescriptor::createRegister(Reg); 2042 } 2043 2044 // If this has a fixed position, we still should allocate the register in the 2045 // CCInfo state. Technically we could get away with this for values passed 2046 // outside of the normal argument range. 2047 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 2048 const TargetRegisterClass *RC, 2049 MCRegister Reg) { 2050 Reg = CCInfo.AllocateReg(Reg); 2051 assert(Reg != AMDGPU::NoRegister); 2052 MachineFunction &MF = CCInfo.getMachineFunction(); 2053 MF.addLiveIn(Reg, RC); 2054 } 2055 2056 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2057 if (Arg) { 2058 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2059 Arg.getRegister()); 2060 } else 2061 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2062 } 2063 2064 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2065 if (Arg) { 2066 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2067 Arg.getRegister()); 2068 } else 2069 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2070 } 2071 2072 /// Allocate implicit function VGPR arguments at the end of allocated user 2073 /// arguments. 2074 void SITargetLowering::allocateSpecialInputVGPRs( 2075 CCState &CCInfo, MachineFunction &MF, 2076 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2077 const unsigned Mask = 0x3ff; 2078 ArgDescriptor Arg; 2079 2080 if (Info.hasWorkItemIDX()) { 2081 Arg = allocateVGPR32Input(CCInfo, Mask); 2082 Info.setWorkItemIDX(Arg); 2083 } 2084 2085 if (Info.hasWorkItemIDY()) { 2086 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2087 Info.setWorkItemIDY(Arg); 2088 } 2089 2090 if (Info.hasWorkItemIDZ()) 2091 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2092 } 2093 2094 /// Allocate implicit function VGPR arguments in fixed registers. 2095 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2096 CCState &CCInfo, MachineFunction &MF, 2097 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2098 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2099 if (!Reg) 2100 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2101 2102 const unsigned Mask = 0x3ff; 2103 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2104 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2105 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2106 } 2107 2108 void SITargetLowering::allocateSpecialInputSGPRs( 2109 CCState &CCInfo, 2110 MachineFunction &MF, 2111 const SIRegisterInfo &TRI, 2112 SIMachineFunctionInfo &Info) const { 2113 auto &ArgInfo = Info.getArgInfo(); 2114 2115 // TODO: Unify handling with private memory pointers. 2116 if (Info.hasDispatchPtr()) 2117 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2118 2119 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2120 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2121 2122 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2123 // constant offset from the kernarg segment. 2124 if (Info.hasImplicitArgPtr()) 2125 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2126 2127 if (Info.hasDispatchID()) 2128 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2129 2130 // flat_scratch_init is not applicable for non-kernel functions. 2131 2132 if (Info.hasWorkGroupIDX()) 2133 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2134 2135 if (Info.hasWorkGroupIDY()) 2136 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2137 2138 if (Info.hasWorkGroupIDZ()) 2139 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2140 } 2141 2142 // Allocate special inputs passed in user SGPRs. 2143 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2144 MachineFunction &MF, 2145 const SIRegisterInfo &TRI, 2146 SIMachineFunctionInfo &Info) const { 2147 if (Info.hasImplicitBufferPtr()) { 2148 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2149 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2150 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2151 } 2152 2153 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2154 if (Info.hasPrivateSegmentBuffer()) { 2155 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2156 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2157 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2158 } 2159 2160 if (Info.hasDispatchPtr()) { 2161 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2162 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2163 CCInfo.AllocateReg(DispatchPtrReg); 2164 } 2165 2166 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2167 Register QueuePtrReg = Info.addQueuePtr(TRI); 2168 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2169 CCInfo.AllocateReg(QueuePtrReg); 2170 } 2171 2172 if (Info.hasKernargSegmentPtr()) { 2173 MachineRegisterInfo &MRI = MF.getRegInfo(); 2174 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2175 CCInfo.AllocateReg(InputPtrReg); 2176 2177 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2178 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2179 } 2180 2181 if (Info.hasDispatchID()) { 2182 Register DispatchIDReg = Info.addDispatchID(TRI); 2183 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2184 CCInfo.AllocateReg(DispatchIDReg); 2185 } 2186 2187 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2188 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2189 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2190 CCInfo.AllocateReg(FlatScratchInitReg); 2191 } 2192 2193 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2194 // these from the dispatch pointer. 2195 } 2196 2197 // Allocate special input registers that are initialized per-wave. 2198 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2199 MachineFunction &MF, 2200 SIMachineFunctionInfo &Info, 2201 CallingConv::ID CallConv, 2202 bool IsShader) const { 2203 if (Info.hasWorkGroupIDX()) { 2204 Register Reg = Info.addWorkGroupIDX(); 2205 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2206 CCInfo.AllocateReg(Reg); 2207 } 2208 2209 if (Info.hasWorkGroupIDY()) { 2210 Register Reg = Info.addWorkGroupIDY(); 2211 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2212 CCInfo.AllocateReg(Reg); 2213 } 2214 2215 if (Info.hasWorkGroupIDZ()) { 2216 Register Reg = Info.addWorkGroupIDZ(); 2217 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2218 CCInfo.AllocateReg(Reg); 2219 } 2220 2221 if (Info.hasWorkGroupInfo()) { 2222 Register Reg = Info.addWorkGroupInfo(); 2223 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2224 CCInfo.AllocateReg(Reg); 2225 } 2226 2227 if (Info.hasPrivateSegmentWaveByteOffset()) { 2228 // Scratch wave offset passed in system SGPR. 2229 unsigned PrivateSegmentWaveByteOffsetReg; 2230 2231 if (IsShader) { 2232 PrivateSegmentWaveByteOffsetReg = 2233 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2234 2235 // This is true if the scratch wave byte offset doesn't have a fixed 2236 // location. 2237 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2238 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2239 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2240 } 2241 } else 2242 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2243 2244 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2245 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2246 } 2247 } 2248 2249 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2250 MachineFunction &MF, 2251 const SIRegisterInfo &TRI, 2252 SIMachineFunctionInfo &Info) { 2253 // Now that we've figured out where the scratch register inputs are, see if 2254 // should reserve the arguments and use them directly. 2255 MachineFrameInfo &MFI = MF.getFrameInfo(); 2256 bool HasStackObjects = MFI.hasStackObjects(); 2257 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2258 2259 // Record that we know we have non-spill stack objects so we don't need to 2260 // check all stack objects later. 2261 if (HasStackObjects) 2262 Info.setHasNonSpillStackObjects(true); 2263 2264 // Everything live out of a block is spilled with fast regalloc, so it's 2265 // almost certain that spilling will be required. 2266 if (TM.getOptLevel() == CodeGenOpt::None) 2267 HasStackObjects = true; 2268 2269 // For now assume stack access is needed in any callee functions, so we need 2270 // the scratch registers to pass in. 2271 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2272 2273 if (!ST.enableFlatScratch()) { 2274 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2275 // If we have stack objects, we unquestionably need the private buffer 2276 // resource. For the Code Object V2 ABI, this will be the first 4 user 2277 // SGPR inputs. We can reserve those and use them directly. 2278 2279 Register PrivateSegmentBufferReg = 2280 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2281 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2282 } else { 2283 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2284 // We tentatively reserve the last registers (skipping the last registers 2285 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2286 // we'll replace these with the ones immediately after those which were 2287 // really allocated. In the prologue copies will be inserted from the 2288 // argument to these reserved registers. 2289 2290 // Without HSA, relocations are used for the scratch pointer and the 2291 // buffer resource setup is always inserted in the prologue. Scratch wave 2292 // offset is still in an input SGPR. 2293 Info.setScratchRSrcReg(ReservedBufferReg); 2294 } 2295 } 2296 2297 MachineRegisterInfo &MRI = MF.getRegInfo(); 2298 2299 // For entry functions we have to set up the stack pointer if we use it, 2300 // whereas non-entry functions get this "for free". This means there is no 2301 // intrinsic advantage to using S32 over S34 in cases where we do not have 2302 // calls but do need a frame pointer (i.e. if we are requested to have one 2303 // because frame pointer elimination is disabled). To keep things simple we 2304 // only ever use S32 as the call ABI stack pointer, and so using it does not 2305 // imply we need a separate frame pointer. 2306 // 2307 // Try to use s32 as the SP, but move it if it would interfere with input 2308 // arguments. This won't work with calls though. 2309 // 2310 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2311 // registers. 2312 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2313 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2314 } else { 2315 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2316 2317 if (MFI.hasCalls()) 2318 report_fatal_error("call in graphics shader with too many input SGPRs"); 2319 2320 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2321 if (!MRI.isLiveIn(Reg)) { 2322 Info.setStackPtrOffsetReg(Reg); 2323 break; 2324 } 2325 } 2326 2327 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2328 report_fatal_error("failed to find register for SP"); 2329 } 2330 2331 // hasFP should be accurate for entry functions even before the frame is 2332 // finalized, because it does not rely on the known stack size, only 2333 // properties like whether variable sized objects are present. 2334 if (ST.getFrameLowering()->hasFP(MF)) { 2335 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2336 } 2337 } 2338 2339 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2340 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2341 return !Info->isEntryFunction(); 2342 } 2343 2344 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2345 2346 } 2347 2348 void SITargetLowering::insertCopiesSplitCSR( 2349 MachineBasicBlock *Entry, 2350 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2351 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2352 2353 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2354 if (!IStart) 2355 return; 2356 2357 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2358 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2359 MachineBasicBlock::iterator MBBI = Entry->begin(); 2360 for (const MCPhysReg *I = IStart; *I; ++I) { 2361 const TargetRegisterClass *RC = nullptr; 2362 if (AMDGPU::SReg_64RegClass.contains(*I)) 2363 RC = &AMDGPU::SGPR_64RegClass; 2364 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2365 RC = &AMDGPU::SGPR_32RegClass; 2366 else 2367 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2368 2369 Register NewVR = MRI->createVirtualRegister(RC); 2370 // Create copy from CSR to a virtual register. 2371 Entry->addLiveIn(*I); 2372 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2373 .addReg(*I); 2374 2375 // Insert the copy-back instructions right before the terminator. 2376 for (auto *Exit : Exits) 2377 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2378 TII->get(TargetOpcode::COPY), *I) 2379 .addReg(NewVR); 2380 } 2381 } 2382 2383 SDValue SITargetLowering::LowerFormalArguments( 2384 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2385 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2386 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2387 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2388 2389 MachineFunction &MF = DAG.getMachineFunction(); 2390 const Function &Fn = MF.getFunction(); 2391 FunctionType *FType = MF.getFunction().getFunctionType(); 2392 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2393 2394 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2395 DiagnosticInfoUnsupported NoGraphicsHSA( 2396 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2397 DAG.getContext()->diagnose(NoGraphicsHSA); 2398 return DAG.getEntryNode(); 2399 } 2400 2401 Info->allocateModuleLDSGlobal(Fn.getParent()); 2402 2403 SmallVector<ISD::InputArg, 16> Splits; 2404 SmallVector<CCValAssign, 16> ArgLocs; 2405 BitVector Skipped(Ins.size()); 2406 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2407 *DAG.getContext()); 2408 2409 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2410 bool IsKernel = AMDGPU::isKernel(CallConv); 2411 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2412 2413 if (IsGraphics) { 2414 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2415 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2416 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2417 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2418 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2419 !Info->hasWorkItemIDZ()); 2420 } 2421 2422 if (CallConv == CallingConv::AMDGPU_PS) { 2423 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2424 2425 // At least one interpolation mode must be enabled or else the GPU will 2426 // hang. 2427 // 2428 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2429 // set PSInputAddr, the user wants to enable some bits after the compilation 2430 // based on run-time states. Since we can't know what the final PSInputEna 2431 // will look like, so we shouldn't do anything here and the user should take 2432 // responsibility for the correct programming. 2433 // 2434 // Otherwise, the following restrictions apply: 2435 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2436 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2437 // enabled too. 2438 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2439 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2440 CCInfo.AllocateReg(AMDGPU::VGPR0); 2441 CCInfo.AllocateReg(AMDGPU::VGPR1); 2442 Info->markPSInputAllocated(0); 2443 Info->markPSInputEnabled(0); 2444 } 2445 if (Subtarget->isAmdPalOS()) { 2446 // For isAmdPalOS, the user does not enable some bits after compilation 2447 // based on run-time states; the register values being generated here are 2448 // the final ones set in hardware. Therefore we need to apply the 2449 // workaround to PSInputAddr and PSInputEnable together. (The case where 2450 // a bit is set in PSInputAddr but not PSInputEnable is where the 2451 // frontend set up an input arg for a particular interpolation mode, but 2452 // nothing uses that input arg. Really we should have an earlier pass 2453 // that removes such an arg.) 2454 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2455 if ((PsInputBits & 0x7F) == 0 || 2456 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2457 Info->markPSInputEnabled( 2458 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2459 } 2460 } else if (IsKernel) { 2461 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2462 } else { 2463 Splits.append(Ins.begin(), Ins.end()); 2464 } 2465 2466 if (IsEntryFunc) { 2467 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2468 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2469 } else if (!IsGraphics) { 2470 // For the fixed ABI, pass workitem IDs in the last argument register. 2471 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2472 } 2473 2474 if (IsKernel) { 2475 analyzeFormalArgumentsCompute(CCInfo, Ins); 2476 } else { 2477 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2478 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2479 } 2480 2481 SmallVector<SDValue, 16> Chains; 2482 2483 // FIXME: This is the minimum kernel argument alignment. We should improve 2484 // this to the maximum alignment of the arguments. 2485 // 2486 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2487 // kern arg offset. 2488 const Align KernelArgBaseAlign = Align(16); 2489 2490 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2491 const ISD::InputArg &Arg = Ins[i]; 2492 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2493 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2494 continue; 2495 } 2496 2497 CCValAssign &VA = ArgLocs[ArgIdx++]; 2498 MVT VT = VA.getLocVT(); 2499 2500 if (IsEntryFunc && VA.isMemLoc()) { 2501 VT = Ins[i].VT; 2502 EVT MemVT = VA.getLocVT(); 2503 2504 const uint64_t Offset = VA.getLocMemOffset(); 2505 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2506 2507 if (Arg.Flags.isByRef()) { 2508 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2509 2510 const GCNTargetMachine &TM = 2511 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2512 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2513 Arg.Flags.getPointerAddrSpace())) { 2514 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2515 Arg.Flags.getPointerAddrSpace()); 2516 } 2517 2518 InVals.push_back(Ptr); 2519 continue; 2520 } 2521 2522 SDValue Arg = lowerKernargMemParameter( 2523 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2524 Chains.push_back(Arg.getValue(1)); 2525 2526 auto *ParamTy = 2527 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2528 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2529 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2530 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2531 // On SI local pointers are just offsets into LDS, so they are always 2532 // less than 16-bits. On CI and newer they could potentially be 2533 // real pointers, so we can't guarantee their size. 2534 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2535 DAG.getValueType(MVT::i16)); 2536 } 2537 2538 InVals.push_back(Arg); 2539 continue; 2540 } else if (!IsEntryFunc && VA.isMemLoc()) { 2541 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2542 InVals.push_back(Val); 2543 if (!Arg.Flags.isByVal()) 2544 Chains.push_back(Val.getValue(1)); 2545 continue; 2546 } 2547 2548 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2549 2550 Register Reg = VA.getLocReg(); 2551 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2552 EVT ValVT = VA.getValVT(); 2553 2554 Reg = MF.addLiveIn(Reg, RC); 2555 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2556 2557 if (Arg.Flags.isSRet()) { 2558 // The return object should be reasonably addressable. 2559 2560 // FIXME: This helps when the return is a real sret. If it is a 2561 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2562 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2563 unsigned NumBits 2564 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2565 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2566 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2567 } 2568 2569 // If this is an 8 or 16-bit value, it is really passed promoted 2570 // to 32 bits. Insert an assert[sz]ext to capture this, then 2571 // truncate to the right size. 2572 switch (VA.getLocInfo()) { 2573 case CCValAssign::Full: 2574 break; 2575 case CCValAssign::BCvt: 2576 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2577 break; 2578 case CCValAssign::SExt: 2579 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2580 DAG.getValueType(ValVT)); 2581 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2582 break; 2583 case CCValAssign::ZExt: 2584 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2585 DAG.getValueType(ValVT)); 2586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2587 break; 2588 case CCValAssign::AExt: 2589 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2590 break; 2591 default: 2592 llvm_unreachable("Unknown loc info!"); 2593 } 2594 2595 InVals.push_back(Val); 2596 } 2597 2598 // Start adding system SGPRs. 2599 if (IsEntryFunc) { 2600 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2601 } else { 2602 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2603 if (!IsGraphics) 2604 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2605 } 2606 2607 auto &ArgUsageInfo = 2608 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2609 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2610 2611 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2612 Info->setBytesInStackArgArea(StackArgSize); 2613 2614 return Chains.empty() ? Chain : 2615 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2616 } 2617 2618 // TODO: If return values can't fit in registers, we should return as many as 2619 // possible in registers before passing on stack. 2620 bool SITargetLowering::CanLowerReturn( 2621 CallingConv::ID CallConv, 2622 MachineFunction &MF, bool IsVarArg, 2623 const SmallVectorImpl<ISD::OutputArg> &Outs, 2624 LLVMContext &Context) const { 2625 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2626 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2627 // for shaders. Vector types should be explicitly handled by CC. 2628 if (AMDGPU::isEntryFunctionCC(CallConv)) 2629 return true; 2630 2631 SmallVector<CCValAssign, 16> RVLocs; 2632 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2633 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2634 } 2635 2636 SDValue 2637 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2638 bool isVarArg, 2639 const SmallVectorImpl<ISD::OutputArg> &Outs, 2640 const SmallVectorImpl<SDValue> &OutVals, 2641 const SDLoc &DL, SelectionDAG &DAG) const { 2642 MachineFunction &MF = DAG.getMachineFunction(); 2643 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2644 2645 if (AMDGPU::isKernel(CallConv)) { 2646 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2647 OutVals, DL, DAG); 2648 } 2649 2650 bool IsShader = AMDGPU::isShader(CallConv); 2651 2652 Info->setIfReturnsVoid(Outs.empty()); 2653 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2654 2655 // CCValAssign - represent the assignment of the return value to a location. 2656 SmallVector<CCValAssign, 48> RVLocs; 2657 SmallVector<ISD::OutputArg, 48> Splits; 2658 2659 // CCState - Info about the registers and stack slots. 2660 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2661 *DAG.getContext()); 2662 2663 // Analyze outgoing return values. 2664 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2665 2666 SDValue Flag; 2667 SmallVector<SDValue, 48> RetOps; 2668 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2669 2670 // Copy the result values into the output registers. 2671 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2672 ++I, ++RealRVLocIdx) { 2673 CCValAssign &VA = RVLocs[I]; 2674 assert(VA.isRegLoc() && "Can only return in registers!"); 2675 // TODO: Partially return in registers if return values don't fit. 2676 SDValue Arg = OutVals[RealRVLocIdx]; 2677 2678 // Copied from other backends. 2679 switch (VA.getLocInfo()) { 2680 case CCValAssign::Full: 2681 break; 2682 case CCValAssign::BCvt: 2683 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2684 break; 2685 case CCValAssign::SExt: 2686 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2687 break; 2688 case CCValAssign::ZExt: 2689 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2690 break; 2691 case CCValAssign::AExt: 2692 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2693 break; 2694 default: 2695 llvm_unreachable("Unknown loc info!"); 2696 } 2697 2698 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2699 Flag = Chain.getValue(1); 2700 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2701 } 2702 2703 // FIXME: Does sret work properly? 2704 if (!Info->isEntryFunction()) { 2705 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2706 const MCPhysReg *I = 2707 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2708 if (I) { 2709 for (; *I; ++I) { 2710 if (AMDGPU::SReg_64RegClass.contains(*I)) 2711 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2712 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2713 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2714 else 2715 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2716 } 2717 } 2718 } 2719 2720 // Update chain and glue. 2721 RetOps[0] = Chain; 2722 if (Flag.getNode()) 2723 RetOps.push_back(Flag); 2724 2725 unsigned Opc = AMDGPUISD::ENDPGM; 2726 if (!IsWaveEnd) 2727 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2728 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2729 } 2730 2731 SDValue SITargetLowering::LowerCallResult( 2732 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2733 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2734 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2735 SDValue ThisVal) const { 2736 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2737 2738 // Assign locations to each value returned by this call. 2739 SmallVector<CCValAssign, 16> RVLocs; 2740 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2741 *DAG.getContext()); 2742 CCInfo.AnalyzeCallResult(Ins, RetCC); 2743 2744 // Copy all of the result registers out of their specified physreg. 2745 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2746 CCValAssign VA = RVLocs[i]; 2747 SDValue Val; 2748 2749 if (VA.isRegLoc()) { 2750 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2751 Chain = Val.getValue(1); 2752 InFlag = Val.getValue(2); 2753 } else if (VA.isMemLoc()) { 2754 report_fatal_error("TODO: return values in memory"); 2755 } else 2756 llvm_unreachable("unknown argument location type"); 2757 2758 switch (VA.getLocInfo()) { 2759 case CCValAssign::Full: 2760 break; 2761 case CCValAssign::BCvt: 2762 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2763 break; 2764 case CCValAssign::ZExt: 2765 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2766 DAG.getValueType(VA.getValVT())); 2767 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2768 break; 2769 case CCValAssign::SExt: 2770 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2771 DAG.getValueType(VA.getValVT())); 2772 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2773 break; 2774 case CCValAssign::AExt: 2775 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2776 break; 2777 default: 2778 llvm_unreachable("Unknown loc info!"); 2779 } 2780 2781 InVals.push_back(Val); 2782 } 2783 2784 return Chain; 2785 } 2786 2787 // Add code to pass special inputs required depending on used features separate 2788 // from the explicit user arguments present in the IR. 2789 void SITargetLowering::passSpecialInputs( 2790 CallLoweringInfo &CLI, 2791 CCState &CCInfo, 2792 const SIMachineFunctionInfo &Info, 2793 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2794 SmallVectorImpl<SDValue> &MemOpChains, 2795 SDValue Chain) const { 2796 // If we don't have a call site, this was a call inserted by 2797 // legalization. These can never use special inputs. 2798 if (!CLI.CB) 2799 return; 2800 2801 SelectionDAG &DAG = CLI.DAG; 2802 const SDLoc &DL = CLI.DL; 2803 const Function &F = DAG.getMachineFunction().getFunction(); 2804 2805 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2806 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2807 2808 const AMDGPUFunctionArgInfo *CalleeArgInfo 2809 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2810 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2811 auto &ArgUsageInfo = 2812 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2813 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2814 } 2815 2816 // TODO: Unify with private memory register handling. This is complicated by 2817 // the fact that at least in kernels, the input argument is not necessarily 2818 // in the same location as the input. 2819 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2820 StringLiteral> ImplicitAttrs[] = { 2821 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2822 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2823 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2824 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2825 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2826 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2827 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2828 }; 2829 2830 for (auto Attr : ImplicitAttrs) { 2831 const ArgDescriptor *OutgoingArg; 2832 const TargetRegisterClass *ArgRC; 2833 LLT ArgTy; 2834 2835 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2836 2837 // If the callee does not use the attribute value, skip copying the value. 2838 if (CLI.CB->hasFnAttr(Attr.second)) 2839 continue; 2840 2841 std::tie(OutgoingArg, ArgRC, ArgTy) = 2842 CalleeArgInfo->getPreloadedValue(InputID); 2843 if (!OutgoingArg) 2844 continue; 2845 2846 const ArgDescriptor *IncomingArg; 2847 const TargetRegisterClass *IncomingArgRC; 2848 LLT Ty; 2849 std::tie(IncomingArg, IncomingArgRC, Ty) = 2850 CallerArgInfo.getPreloadedValue(InputID); 2851 assert(IncomingArgRC == ArgRC); 2852 2853 // All special arguments are ints for now. 2854 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2855 SDValue InputReg; 2856 2857 if (IncomingArg) { 2858 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2859 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2860 // The implicit arg ptr is special because it doesn't have a corresponding 2861 // input for kernels, and is computed from the kernarg segment pointer. 2862 InputReg = getImplicitArgPtr(DAG, DL); 2863 } else { 2864 // We may have proven the input wasn't needed, although the ABI is 2865 // requiring it. We just need to allocate the register appropriately. 2866 InputReg = DAG.getUNDEF(ArgVT); 2867 } 2868 2869 if (OutgoingArg->isRegister()) { 2870 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2871 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2872 report_fatal_error("failed to allocate implicit input argument"); 2873 } else { 2874 unsigned SpecialArgOffset = 2875 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2876 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2877 SpecialArgOffset); 2878 MemOpChains.push_back(ArgStore); 2879 } 2880 } 2881 2882 // Pack workitem IDs into a single register or pass it as is if already 2883 // packed. 2884 const ArgDescriptor *OutgoingArg; 2885 const TargetRegisterClass *ArgRC; 2886 LLT Ty; 2887 2888 std::tie(OutgoingArg, ArgRC, Ty) = 2889 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2890 if (!OutgoingArg) 2891 std::tie(OutgoingArg, ArgRC, Ty) = 2892 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2893 if (!OutgoingArg) 2894 std::tie(OutgoingArg, ArgRC, Ty) = 2895 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2896 if (!OutgoingArg) 2897 return; 2898 2899 const ArgDescriptor *IncomingArgX = std::get<0>( 2900 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2901 const ArgDescriptor *IncomingArgY = std::get<0>( 2902 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2903 const ArgDescriptor *IncomingArgZ = std::get<0>( 2904 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2905 2906 SDValue InputReg; 2907 SDLoc SL; 2908 2909 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2910 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2911 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2912 2913 // If incoming ids are not packed we need to pack them. 2914 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2915 NeedWorkItemIDX) { 2916 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2917 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2918 } else { 2919 InputReg = DAG.getConstant(0, DL, MVT::i32); 2920 } 2921 } 2922 2923 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2924 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2925 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2926 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2927 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2928 InputReg = InputReg.getNode() ? 2929 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2930 } 2931 2932 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2933 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2934 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2935 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2936 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2937 InputReg = InputReg.getNode() ? 2938 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2939 } 2940 2941 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2942 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2943 // We're in a situation where the outgoing function requires the workitem 2944 // ID, but the calling function does not have it (e.g a graphics function 2945 // calling a C calling convention function). This is illegal, but we need 2946 // to produce something. 2947 InputReg = DAG.getUNDEF(MVT::i32); 2948 } else { 2949 // Workitem ids are already packed, any of present incoming arguments 2950 // will carry all required fields. 2951 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2952 IncomingArgX ? *IncomingArgX : 2953 IncomingArgY ? *IncomingArgY : 2954 *IncomingArgZ, ~0u); 2955 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2956 } 2957 } 2958 2959 if (OutgoingArg->isRegister()) { 2960 if (InputReg) 2961 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2962 2963 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2964 } else { 2965 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2966 if (InputReg) { 2967 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2968 SpecialArgOffset); 2969 MemOpChains.push_back(ArgStore); 2970 } 2971 } 2972 } 2973 2974 static bool canGuaranteeTCO(CallingConv::ID CC) { 2975 return CC == CallingConv::Fast; 2976 } 2977 2978 /// Return true if we might ever do TCO for calls with this calling convention. 2979 static bool mayTailCallThisCC(CallingConv::ID CC) { 2980 switch (CC) { 2981 case CallingConv::C: 2982 case CallingConv::AMDGPU_Gfx: 2983 return true; 2984 default: 2985 return canGuaranteeTCO(CC); 2986 } 2987 } 2988 2989 bool SITargetLowering::isEligibleForTailCallOptimization( 2990 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2991 const SmallVectorImpl<ISD::OutputArg> &Outs, 2992 const SmallVectorImpl<SDValue> &OutVals, 2993 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2994 if (!mayTailCallThisCC(CalleeCC)) 2995 return false; 2996 2997 // For a divergent call target, we need to do a waterfall loop over the 2998 // possible callees which precludes us from using a simple jump. 2999 if (Callee->isDivergent()) 3000 return false; 3001 3002 MachineFunction &MF = DAG.getMachineFunction(); 3003 const Function &CallerF = MF.getFunction(); 3004 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3005 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3006 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3007 3008 // Kernels aren't callable, and don't have a live in return address so it 3009 // doesn't make sense to do a tail call with entry functions. 3010 if (!CallerPreserved) 3011 return false; 3012 3013 bool CCMatch = CallerCC == CalleeCC; 3014 3015 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 3016 if (canGuaranteeTCO(CalleeCC) && CCMatch) 3017 return true; 3018 return false; 3019 } 3020 3021 // TODO: Can we handle var args? 3022 if (IsVarArg) 3023 return false; 3024 3025 for (const Argument &Arg : CallerF.args()) { 3026 if (Arg.hasByValAttr()) 3027 return false; 3028 } 3029 3030 LLVMContext &Ctx = *DAG.getContext(); 3031 3032 // Check that the call results are passed in the same way. 3033 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3034 CCAssignFnForCall(CalleeCC, IsVarArg), 3035 CCAssignFnForCall(CallerCC, IsVarArg))) 3036 return false; 3037 3038 // The callee has to preserve all registers the caller needs to preserve. 3039 if (!CCMatch) { 3040 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3041 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3042 return false; 3043 } 3044 3045 // Nothing more to check if the callee is taking no arguments. 3046 if (Outs.empty()) 3047 return true; 3048 3049 SmallVector<CCValAssign, 16> ArgLocs; 3050 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3051 3052 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3053 3054 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3055 // If the stack arguments for this call do not fit into our own save area then 3056 // the call cannot be made tail. 3057 // TODO: Is this really necessary? 3058 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3059 return false; 3060 3061 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3062 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3063 } 3064 3065 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3066 if (!CI->isTailCall()) 3067 return false; 3068 3069 const Function *ParentFn = CI->getParent()->getParent(); 3070 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3071 return false; 3072 return true; 3073 } 3074 3075 // The wave scratch offset register is used as the global base pointer. 3076 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3077 SmallVectorImpl<SDValue> &InVals) const { 3078 SelectionDAG &DAG = CLI.DAG; 3079 const SDLoc &DL = CLI.DL; 3080 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3081 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3082 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3083 SDValue Chain = CLI.Chain; 3084 SDValue Callee = CLI.Callee; 3085 bool &IsTailCall = CLI.IsTailCall; 3086 CallingConv::ID CallConv = CLI.CallConv; 3087 bool IsVarArg = CLI.IsVarArg; 3088 bool IsSibCall = false; 3089 bool IsThisReturn = false; 3090 MachineFunction &MF = DAG.getMachineFunction(); 3091 3092 if (Callee.isUndef() || isNullConstant(Callee)) { 3093 if (!CLI.IsTailCall) { 3094 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3095 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3096 } 3097 3098 return Chain; 3099 } 3100 3101 if (IsVarArg) { 3102 return lowerUnhandledCall(CLI, InVals, 3103 "unsupported call to variadic function "); 3104 } 3105 3106 if (!CLI.CB) 3107 report_fatal_error("unsupported libcall legalization"); 3108 3109 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3110 return lowerUnhandledCall(CLI, InVals, 3111 "unsupported required tail call to function "); 3112 } 3113 3114 if (AMDGPU::isShader(CallConv)) { 3115 // Note the issue is with the CC of the called function, not of the call 3116 // itself. 3117 return lowerUnhandledCall(CLI, InVals, 3118 "unsupported call to a shader function "); 3119 } 3120 3121 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3122 CallConv != CallingConv::AMDGPU_Gfx) { 3123 // Only allow calls with specific calling conventions. 3124 return lowerUnhandledCall(CLI, InVals, 3125 "unsupported calling convention for call from " 3126 "graphics shader of function "); 3127 } 3128 3129 if (IsTailCall) { 3130 IsTailCall = isEligibleForTailCallOptimization( 3131 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3132 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3133 report_fatal_error("failed to perform tail call elimination on a call " 3134 "site marked musttail"); 3135 } 3136 3137 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3138 3139 // A sibling call is one where we're under the usual C ABI and not planning 3140 // to change that but can still do a tail call: 3141 if (!TailCallOpt && IsTailCall) 3142 IsSibCall = true; 3143 3144 if (IsTailCall) 3145 ++NumTailCalls; 3146 } 3147 3148 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3149 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3150 SmallVector<SDValue, 8> MemOpChains; 3151 3152 // Analyze operands of the call, assigning locations to each operand. 3153 SmallVector<CCValAssign, 16> ArgLocs; 3154 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3155 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3156 3157 if (CallConv != CallingConv::AMDGPU_Gfx) { 3158 // With a fixed ABI, allocate fixed registers before user arguments. 3159 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3160 } 3161 3162 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3163 3164 // Get a count of how many bytes are to be pushed on the stack. 3165 unsigned NumBytes = CCInfo.getNextStackOffset(); 3166 3167 if (IsSibCall) { 3168 // Since we're not changing the ABI to make this a tail call, the memory 3169 // operands are already available in the caller's incoming argument space. 3170 NumBytes = 0; 3171 } 3172 3173 // FPDiff is the byte offset of the call's argument area from the callee's. 3174 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3175 // by this amount for a tail call. In a sibling call it must be 0 because the 3176 // caller will deallocate the entire stack and the callee still expects its 3177 // arguments to begin at SP+0. Completely unused for non-tail calls. 3178 int32_t FPDiff = 0; 3179 MachineFrameInfo &MFI = MF.getFrameInfo(); 3180 3181 // Adjust the stack pointer for the new arguments... 3182 // These operations are automatically eliminated by the prolog/epilog pass 3183 if (!IsSibCall) { 3184 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3185 3186 if (!Subtarget->enableFlatScratch()) { 3187 SmallVector<SDValue, 4> CopyFromChains; 3188 3189 // In the HSA case, this should be an identity copy. 3190 SDValue ScratchRSrcReg 3191 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3192 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3193 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3194 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3195 } 3196 } 3197 3198 MVT PtrVT = MVT::i32; 3199 3200 // Walk the register/memloc assignments, inserting copies/loads. 3201 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3202 CCValAssign &VA = ArgLocs[i]; 3203 SDValue Arg = OutVals[i]; 3204 3205 // Promote the value if needed. 3206 switch (VA.getLocInfo()) { 3207 case CCValAssign::Full: 3208 break; 3209 case CCValAssign::BCvt: 3210 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3211 break; 3212 case CCValAssign::ZExt: 3213 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3214 break; 3215 case CCValAssign::SExt: 3216 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3217 break; 3218 case CCValAssign::AExt: 3219 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3220 break; 3221 case CCValAssign::FPExt: 3222 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3223 break; 3224 default: 3225 llvm_unreachable("Unknown loc info!"); 3226 } 3227 3228 if (VA.isRegLoc()) { 3229 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3230 } else { 3231 assert(VA.isMemLoc()); 3232 3233 SDValue DstAddr; 3234 MachinePointerInfo DstInfo; 3235 3236 unsigned LocMemOffset = VA.getLocMemOffset(); 3237 int32_t Offset = LocMemOffset; 3238 3239 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3240 MaybeAlign Alignment; 3241 3242 if (IsTailCall) { 3243 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3244 unsigned OpSize = Flags.isByVal() ? 3245 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3246 3247 // FIXME: We can have better than the minimum byval required alignment. 3248 Alignment = 3249 Flags.isByVal() 3250 ? Flags.getNonZeroByValAlign() 3251 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3252 3253 Offset = Offset + FPDiff; 3254 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3255 3256 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3257 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3258 3259 // Make sure any stack arguments overlapping with where we're storing 3260 // are loaded before this eventual operation. Otherwise they'll be 3261 // clobbered. 3262 3263 // FIXME: Why is this really necessary? This seems to just result in a 3264 // lot of code to copy the stack and write them back to the same 3265 // locations, which are supposed to be immutable? 3266 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3267 } else { 3268 // Stores to the argument stack area are relative to the stack pointer. 3269 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3270 MVT::i32); 3271 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3272 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3273 Alignment = 3274 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3275 } 3276 3277 if (Outs[i].Flags.isByVal()) { 3278 SDValue SizeNode = 3279 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3280 SDValue Cpy = 3281 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3282 Outs[i].Flags.getNonZeroByValAlign(), 3283 /*isVol = */ false, /*AlwaysInline = */ true, 3284 /*isTailCall = */ false, DstInfo, 3285 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3286 3287 MemOpChains.push_back(Cpy); 3288 } else { 3289 SDValue Store = 3290 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3291 MemOpChains.push_back(Store); 3292 } 3293 } 3294 } 3295 3296 if (!MemOpChains.empty()) 3297 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3298 3299 // Build a sequence of copy-to-reg nodes chained together with token chain 3300 // and flag operands which copy the outgoing args into the appropriate regs. 3301 SDValue InFlag; 3302 for (auto &RegToPass : RegsToPass) { 3303 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3304 RegToPass.second, InFlag); 3305 InFlag = Chain.getValue(1); 3306 } 3307 3308 3309 // We don't usually want to end the call-sequence here because we would tidy 3310 // the frame up *after* the call, however in the ABI-changing tail-call case 3311 // we've carefully laid out the parameters so that when sp is reset they'll be 3312 // in the correct location. 3313 if (IsTailCall && !IsSibCall) { 3314 Chain = DAG.getCALLSEQ_END(Chain, 3315 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3316 DAG.getTargetConstant(0, DL, MVT::i32), 3317 InFlag, DL); 3318 InFlag = Chain.getValue(1); 3319 } 3320 3321 std::vector<SDValue> Ops; 3322 Ops.push_back(Chain); 3323 Ops.push_back(Callee); 3324 // Add a redundant copy of the callee global which will not be legalized, as 3325 // we need direct access to the callee later. 3326 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3327 const GlobalValue *GV = GSD->getGlobal(); 3328 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3329 } else { 3330 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3331 } 3332 3333 if (IsTailCall) { 3334 // Each tail call may have to adjust the stack by a different amount, so 3335 // this information must travel along with the operation for eventual 3336 // consumption by emitEpilogue. 3337 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3338 } 3339 3340 // Add argument registers to the end of the list so that they are known live 3341 // into the call. 3342 for (auto &RegToPass : RegsToPass) { 3343 Ops.push_back(DAG.getRegister(RegToPass.first, 3344 RegToPass.second.getValueType())); 3345 } 3346 3347 // Add a register mask operand representing the call-preserved registers. 3348 3349 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3350 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3351 assert(Mask && "Missing call preserved mask for calling convention"); 3352 Ops.push_back(DAG.getRegisterMask(Mask)); 3353 3354 if (InFlag.getNode()) 3355 Ops.push_back(InFlag); 3356 3357 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3358 3359 // If we're doing a tall call, use a TC_RETURN here rather than an 3360 // actual call instruction. 3361 if (IsTailCall) { 3362 MFI.setHasTailCall(); 3363 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3364 } 3365 3366 // Returns a chain and a flag for retval copy to use. 3367 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3368 Chain = Call.getValue(0); 3369 InFlag = Call.getValue(1); 3370 3371 uint64_t CalleePopBytes = NumBytes; 3372 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3373 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3374 InFlag, DL); 3375 if (!Ins.empty()) 3376 InFlag = Chain.getValue(1); 3377 3378 // Handle result values, copying them out of physregs into vregs that we 3379 // return. 3380 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3381 InVals, IsThisReturn, 3382 IsThisReturn ? OutVals[0] : SDValue()); 3383 } 3384 3385 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3386 // except for applying the wave size scale to the increment amount. 3387 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3388 SDValue Op, SelectionDAG &DAG) const { 3389 const MachineFunction &MF = DAG.getMachineFunction(); 3390 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3391 3392 SDLoc dl(Op); 3393 EVT VT = Op.getValueType(); 3394 SDValue Tmp1 = Op; 3395 SDValue Tmp2 = Op.getValue(1); 3396 SDValue Tmp3 = Op.getOperand(2); 3397 SDValue Chain = Tmp1.getOperand(0); 3398 3399 Register SPReg = Info->getStackPtrOffsetReg(); 3400 3401 // Chain the dynamic stack allocation so that it doesn't modify the stack 3402 // pointer when other instructions are using the stack. 3403 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3404 3405 SDValue Size = Tmp2.getOperand(1); 3406 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3407 Chain = SP.getValue(1); 3408 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3409 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3410 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3411 unsigned Opc = 3412 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3413 ISD::ADD : ISD::SUB; 3414 3415 SDValue ScaledSize = DAG.getNode( 3416 ISD::SHL, dl, VT, Size, 3417 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3418 3419 Align StackAlign = TFL->getStackAlign(); 3420 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3421 if (Alignment && *Alignment > StackAlign) { 3422 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3423 DAG.getConstant(-(uint64_t)Alignment->value() 3424 << ST.getWavefrontSizeLog2(), 3425 dl, VT)); 3426 } 3427 3428 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3429 Tmp2 = DAG.getCALLSEQ_END( 3430 Chain, DAG.getIntPtrConstant(0, dl, true), 3431 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3432 3433 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3434 } 3435 3436 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3437 SelectionDAG &DAG) const { 3438 // We only handle constant sizes here to allow non-entry block, static sized 3439 // allocas. A truly dynamic value is more difficult to support because we 3440 // don't know if the size value is uniform or not. If the size isn't uniform, 3441 // we would need to do a wave reduction to get the maximum size to know how 3442 // much to increment the uniform stack pointer. 3443 SDValue Size = Op.getOperand(1); 3444 if (isa<ConstantSDNode>(Size)) 3445 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3446 3447 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3448 } 3449 3450 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3451 const MachineFunction &MF) const { 3452 Register Reg = StringSwitch<Register>(RegName) 3453 .Case("m0", AMDGPU::M0) 3454 .Case("exec", AMDGPU::EXEC) 3455 .Case("exec_lo", AMDGPU::EXEC_LO) 3456 .Case("exec_hi", AMDGPU::EXEC_HI) 3457 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3458 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3459 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3460 .Default(Register()); 3461 3462 if (Reg == AMDGPU::NoRegister) { 3463 report_fatal_error(Twine("invalid register name \"" 3464 + StringRef(RegName) + "\".")); 3465 3466 } 3467 3468 if (!Subtarget->hasFlatScrRegister() && 3469 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3470 report_fatal_error(Twine("invalid register \"" 3471 + StringRef(RegName) + "\" for subtarget.")); 3472 } 3473 3474 switch (Reg) { 3475 case AMDGPU::M0: 3476 case AMDGPU::EXEC_LO: 3477 case AMDGPU::EXEC_HI: 3478 case AMDGPU::FLAT_SCR_LO: 3479 case AMDGPU::FLAT_SCR_HI: 3480 if (VT.getSizeInBits() == 32) 3481 return Reg; 3482 break; 3483 case AMDGPU::EXEC: 3484 case AMDGPU::FLAT_SCR: 3485 if (VT.getSizeInBits() == 64) 3486 return Reg; 3487 break; 3488 default: 3489 llvm_unreachable("missing register type checking"); 3490 } 3491 3492 report_fatal_error(Twine("invalid type for register \"" 3493 + StringRef(RegName) + "\".")); 3494 } 3495 3496 // If kill is not the last instruction, split the block so kill is always a 3497 // proper terminator. 3498 MachineBasicBlock * 3499 SITargetLowering::splitKillBlock(MachineInstr &MI, 3500 MachineBasicBlock *BB) const { 3501 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3502 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3503 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3504 return SplitBB; 3505 } 3506 3507 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3508 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3509 // be the first instruction in the remainder block. 3510 // 3511 /// \returns { LoopBody, Remainder } 3512 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3513 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3514 MachineFunction *MF = MBB.getParent(); 3515 MachineBasicBlock::iterator I(&MI); 3516 3517 // To insert the loop we need to split the block. Move everything after this 3518 // point to a new block, and insert a new empty block between the two. 3519 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3520 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3521 MachineFunction::iterator MBBI(MBB); 3522 ++MBBI; 3523 3524 MF->insert(MBBI, LoopBB); 3525 MF->insert(MBBI, RemainderBB); 3526 3527 LoopBB->addSuccessor(LoopBB); 3528 LoopBB->addSuccessor(RemainderBB); 3529 3530 // Move the rest of the block into a new block. 3531 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3532 3533 if (InstInLoop) { 3534 auto Next = std::next(I); 3535 3536 // Move instruction to loop body. 3537 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3538 3539 // Move the rest of the block. 3540 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3541 } else { 3542 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3543 } 3544 3545 MBB.addSuccessor(LoopBB); 3546 3547 return std::make_pair(LoopBB, RemainderBB); 3548 } 3549 3550 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3551 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3552 MachineBasicBlock *MBB = MI.getParent(); 3553 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3554 auto I = MI.getIterator(); 3555 auto E = std::next(I); 3556 3557 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3558 .addImm(0); 3559 3560 MIBundleBuilder Bundler(*MBB, I, E); 3561 finalizeBundle(*MBB, Bundler.begin()); 3562 } 3563 3564 MachineBasicBlock * 3565 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3566 MachineBasicBlock *BB) const { 3567 const DebugLoc &DL = MI.getDebugLoc(); 3568 3569 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3570 3571 MachineBasicBlock *LoopBB; 3572 MachineBasicBlock *RemainderBB; 3573 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3574 3575 // Apparently kill flags are only valid if the def is in the same block? 3576 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3577 Src->setIsKill(false); 3578 3579 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3580 3581 MachineBasicBlock::iterator I = LoopBB->end(); 3582 3583 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3584 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3585 3586 // Clear TRAP_STS.MEM_VIOL 3587 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3588 .addImm(0) 3589 .addImm(EncodedReg); 3590 3591 bundleInstWithWaitcnt(MI); 3592 3593 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3594 3595 // Load and check TRAP_STS.MEM_VIOL 3596 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3597 .addImm(EncodedReg); 3598 3599 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3600 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3601 .addReg(Reg, RegState::Kill) 3602 .addImm(0); 3603 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3604 .addMBB(LoopBB); 3605 3606 return RemainderBB; 3607 } 3608 3609 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3610 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3611 // will only do one iteration. In the worst case, this will loop 64 times. 3612 // 3613 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3614 static MachineBasicBlock::iterator 3615 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3616 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3617 const DebugLoc &DL, const MachineOperand &Idx, 3618 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3619 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3620 Register &SGPRIdxReg) { 3621 3622 MachineFunction *MF = OrigBB.getParent(); 3623 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3624 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3625 MachineBasicBlock::iterator I = LoopBB.begin(); 3626 3627 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3628 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3629 Register NewExec = MRI.createVirtualRegister(BoolRC); 3630 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3631 Register CondReg = MRI.createVirtualRegister(BoolRC); 3632 3633 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3634 .addReg(InitReg) 3635 .addMBB(&OrigBB) 3636 .addReg(ResultReg) 3637 .addMBB(&LoopBB); 3638 3639 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3640 .addReg(InitSaveExecReg) 3641 .addMBB(&OrigBB) 3642 .addReg(NewExec) 3643 .addMBB(&LoopBB); 3644 3645 // Read the next variant <- also loop target. 3646 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3647 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3648 3649 // Compare the just read M0 value to all possible Idx values. 3650 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3651 .addReg(CurrentIdxReg) 3652 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3653 3654 // Update EXEC, save the original EXEC value to VCC. 3655 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3656 : AMDGPU::S_AND_SAVEEXEC_B64), 3657 NewExec) 3658 .addReg(CondReg, RegState::Kill); 3659 3660 MRI.setSimpleHint(NewExec, CondReg); 3661 3662 if (UseGPRIdxMode) { 3663 if (Offset == 0) { 3664 SGPRIdxReg = CurrentIdxReg; 3665 } else { 3666 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3667 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3668 .addReg(CurrentIdxReg, RegState::Kill) 3669 .addImm(Offset); 3670 } 3671 } else { 3672 // Move index from VCC into M0 3673 if (Offset == 0) { 3674 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3675 .addReg(CurrentIdxReg, RegState::Kill); 3676 } else { 3677 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3678 .addReg(CurrentIdxReg, RegState::Kill) 3679 .addImm(Offset); 3680 } 3681 } 3682 3683 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3684 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3685 MachineInstr *InsertPt = 3686 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3687 : AMDGPU::S_XOR_B64_term), Exec) 3688 .addReg(Exec) 3689 .addReg(NewExec); 3690 3691 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3692 // s_cbranch_scc0? 3693 3694 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3695 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3696 .addMBB(&LoopBB); 3697 3698 return InsertPt->getIterator(); 3699 } 3700 3701 // This has slightly sub-optimal regalloc when the source vector is killed by 3702 // the read. The register allocator does not understand that the kill is 3703 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3704 // subregister from it, using 1 more VGPR than necessary. This was saved when 3705 // this was expanded after register allocation. 3706 static MachineBasicBlock::iterator 3707 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3708 unsigned InitResultReg, unsigned PhiReg, int Offset, 3709 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3710 MachineFunction *MF = MBB.getParent(); 3711 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3712 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3713 MachineRegisterInfo &MRI = MF->getRegInfo(); 3714 const DebugLoc &DL = MI.getDebugLoc(); 3715 MachineBasicBlock::iterator I(&MI); 3716 3717 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3718 Register DstReg = MI.getOperand(0).getReg(); 3719 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3720 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3721 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3722 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3723 3724 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3725 3726 // Save the EXEC mask 3727 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3728 .addReg(Exec); 3729 3730 MachineBasicBlock *LoopBB; 3731 MachineBasicBlock *RemainderBB; 3732 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3733 3734 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3735 3736 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3737 InitResultReg, DstReg, PhiReg, TmpExec, 3738 Offset, UseGPRIdxMode, SGPRIdxReg); 3739 3740 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3741 MachineFunction::iterator MBBI(LoopBB); 3742 ++MBBI; 3743 MF->insert(MBBI, LandingPad); 3744 LoopBB->removeSuccessor(RemainderBB); 3745 LandingPad->addSuccessor(RemainderBB); 3746 LoopBB->addSuccessor(LandingPad); 3747 MachineBasicBlock::iterator First = LandingPad->begin(); 3748 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3749 .addReg(SaveExec); 3750 3751 return InsPt; 3752 } 3753 3754 // Returns subreg index, offset 3755 static std::pair<unsigned, int> 3756 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3757 const TargetRegisterClass *SuperRC, 3758 unsigned VecReg, 3759 int Offset) { 3760 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3761 3762 // Skip out of bounds offsets, or else we would end up using an undefined 3763 // register. 3764 if (Offset >= NumElts || Offset < 0) 3765 return std::make_pair(AMDGPU::sub0, Offset); 3766 3767 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3768 } 3769 3770 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3771 MachineRegisterInfo &MRI, MachineInstr &MI, 3772 int Offset) { 3773 MachineBasicBlock *MBB = MI.getParent(); 3774 const DebugLoc &DL = MI.getDebugLoc(); 3775 MachineBasicBlock::iterator I(&MI); 3776 3777 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3778 3779 assert(Idx->getReg() != AMDGPU::NoRegister); 3780 3781 if (Offset == 0) { 3782 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3783 } else { 3784 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3785 .add(*Idx) 3786 .addImm(Offset); 3787 } 3788 } 3789 3790 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3791 MachineRegisterInfo &MRI, MachineInstr &MI, 3792 int Offset) { 3793 MachineBasicBlock *MBB = MI.getParent(); 3794 const DebugLoc &DL = MI.getDebugLoc(); 3795 MachineBasicBlock::iterator I(&MI); 3796 3797 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3798 3799 if (Offset == 0) 3800 return Idx->getReg(); 3801 3802 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3803 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3804 .add(*Idx) 3805 .addImm(Offset); 3806 return Tmp; 3807 } 3808 3809 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3810 MachineBasicBlock &MBB, 3811 const GCNSubtarget &ST) { 3812 const SIInstrInfo *TII = ST.getInstrInfo(); 3813 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3814 MachineFunction *MF = MBB.getParent(); 3815 MachineRegisterInfo &MRI = MF->getRegInfo(); 3816 3817 Register Dst = MI.getOperand(0).getReg(); 3818 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3819 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3820 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3821 3822 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3823 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3824 3825 unsigned SubReg; 3826 std::tie(SubReg, Offset) 3827 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3828 3829 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3830 3831 // Check for a SGPR index. 3832 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3833 MachineBasicBlock::iterator I(&MI); 3834 const DebugLoc &DL = MI.getDebugLoc(); 3835 3836 if (UseGPRIdxMode) { 3837 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3838 // to avoid interfering with other uses, so probably requires a new 3839 // optimization pass. 3840 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3841 3842 const MCInstrDesc &GPRIDXDesc = 3843 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3844 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3845 .addReg(SrcReg) 3846 .addReg(Idx) 3847 .addImm(SubReg); 3848 } else { 3849 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3850 3851 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3852 .addReg(SrcReg, 0, SubReg) 3853 .addReg(SrcReg, RegState::Implicit); 3854 } 3855 3856 MI.eraseFromParent(); 3857 3858 return &MBB; 3859 } 3860 3861 // Control flow needs to be inserted if indexing with a VGPR. 3862 const DebugLoc &DL = MI.getDebugLoc(); 3863 MachineBasicBlock::iterator I(&MI); 3864 3865 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3866 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3867 3868 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3869 3870 Register SGPRIdxReg; 3871 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3872 UseGPRIdxMode, SGPRIdxReg); 3873 3874 MachineBasicBlock *LoopBB = InsPt->getParent(); 3875 3876 if (UseGPRIdxMode) { 3877 const MCInstrDesc &GPRIDXDesc = 3878 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3879 3880 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3881 .addReg(SrcReg) 3882 .addReg(SGPRIdxReg) 3883 .addImm(SubReg); 3884 } else { 3885 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3886 .addReg(SrcReg, 0, SubReg) 3887 .addReg(SrcReg, RegState::Implicit); 3888 } 3889 3890 MI.eraseFromParent(); 3891 3892 return LoopBB; 3893 } 3894 3895 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3896 MachineBasicBlock &MBB, 3897 const GCNSubtarget &ST) { 3898 const SIInstrInfo *TII = ST.getInstrInfo(); 3899 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3900 MachineFunction *MF = MBB.getParent(); 3901 MachineRegisterInfo &MRI = MF->getRegInfo(); 3902 3903 Register Dst = MI.getOperand(0).getReg(); 3904 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3905 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3906 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3907 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3908 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3909 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3910 3911 // This can be an immediate, but will be folded later. 3912 assert(Val->getReg()); 3913 3914 unsigned SubReg; 3915 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3916 SrcVec->getReg(), 3917 Offset); 3918 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3919 3920 if (Idx->getReg() == AMDGPU::NoRegister) { 3921 MachineBasicBlock::iterator I(&MI); 3922 const DebugLoc &DL = MI.getDebugLoc(); 3923 3924 assert(Offset == 0); 3925 3926 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3927 .add(*SrcVec) 3928 .add(*Val) 3929 .addImm(SubReg); 3930 3931 MI.eraseFromParent(); 3932 return &MBB; 3933 } 3934 3935 // Check for a SGPR index. 3936 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3937 MachineBasicBlock::iterator I(&MI); 3938 const DebugLoc &DL = MI.getDebugLoc(); 3939 3940 if (UseGPRIdxMode) { 3941 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3942 3943 const MCInstrDesc &GPRIDXDesc = 3944 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3945 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3946 .addReg(SrcVec->getReg()) 3947 .add(*Val) 3948 .addReg(Idx) 3949 .addImm(SubReg); 3950 } else { 3951 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3952 3953 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3954 TRI.getRegSizeInBits(*VecRC), 32, false); 3955 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3956 .addReg(SrcVec->getReg()) 3957 .add(*Val) 3958 .addImm(SubReg); 3959 } 3960 MI.eraseFromParent(); 3961 return &MBB; 3962 } 3963 3964 // Control flow needs to be inserted if indexing with a VGPR. 3965 if (Val->isReg()) 3966 MRI.clearKillFlags(Val->getReg()); 3967 3968 const DebugLoc &DL = MI.getDebugLoc(); 3969 3970 Register PhiReg = MRI.createVirtualRegister(VecRC); 3971 3972 Register SGPRIdxReg; 3973 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3974 UseGPRIdxMode, SGPRIdxReg); 3975 MachineBasicBlock *LoopBB = InsPt->getParent(); 3976 3977 if (UseGPRIdxMode) { 3978 const MCInstrDesc &GPRIDXDesc = 3979 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3980 3981 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3982 .addReg(PhiReg) 3983 .add(*Val) 3984 .addReg(SGPRIdxReg) 3985 .addImm(AMDGPU::sub0); 3986 } else { 3987 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3988 TRI.getRegSizeInBits(*VecRC), 32, false); 3989 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3990 .addReg(PhiReg) 3991 .add(*Val) 3992 .addImm(AMDGPU::sub0); 3993 } 3994 3995 MI.eraseFromParent(); 3996 return LoopBB; 3997 } 3998 3999 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 4000 MachineInstr &MI, MachineBasicBlock *BB) const { 4001 4002 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4003 MachineFunction *MF = BB->getParent(); 4004 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 4005 4006 switch (MI.getOpcode()) { 4007 case AMDGPU::S_UADDO_PSEUDO: 4008 case AMDGPU::S_USUBO_PSEUDO: { 4009 const DebugLoc &DL = MI.getDebugLoc(); 4010 MachineOperand &Dest0 = MI.getOperand(0); 4011 MachineOperand &Dest1 = MI.getOperand(1); 4012 MachineOperand &Src0 = MI.getOperand(2); 4013 MachineOperand &Src1 = MI.getOperand(3); 4014 4015 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4016 ? AMDGPU::S_ADD_I32 4017 : AMDGPU::S_SUB_I32; 4018 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4019 4020 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4021 .addImm(1) 4022 .addImm(0); 4023 4024 MI.eraseFromParent(); 4025 return BB; 4026 } 4027 case AMDGPU::S_ADD_U64_PSEUDO: 4028 case AMDGPU::S_SUB_U64_PSEUDO: { 4029 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4030 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4031 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4032 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4033 const DebugLoc &DL = MI.getDebugLoc(); 4034 4035 MachineOperand &Dest = MI.getOperand(0); 4036 MachineOperand &Src0 = MI.getOperand(1); 4037 MachineOperand &Src1 = MI.getOperand(2); 4038 4039 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4040 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4041 4042 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4043 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4044 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4045 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4046 4047 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4048 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4049 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4050 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4051 4052 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4053 4054 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4055 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4056 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4057 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4058 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4059 .addReg(DestSub0) 4060 .addImm(AMDGPU::sub0) 4061 .addReg(DestSub1) 4062 .addImm(AMDGPU::sub1); 4063 MI.eraseFromParent(); 4064 return BB; 4065 } 4066 case AMDGPU::V_ADD_U64_PSEUDO: 4067 case AMDGPU::V_SUB_U64_PSEUDO: { 4068 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4069 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4070 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4071 const DebugLoc &DL = MI.getDebugLoc(); 4072 4073 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4074 4075 MachineOperand &Dest = MI.getOperand(0); 4076 MachineOperand &Src0 = MI.getOperand(1); 4077 MachineOperand &Src1 = MI.getOperand(2); 4078 4079 if (IsAdd && ST.hasLshlAddB64()) { 4080 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 4081 Dest.getReg()) 4082 .add(Src0) 4083 .addImm(0) 4084 .add(Src1); 4085 TII->legalizeOperands(*Add); 4086 MI.eraseFromParent(); 4087 return BB; 4088 } 4089 4090 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4091 4092 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4093 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4094 4095 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4096 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4097 4098 const TargetRegisterClass *Src0RC = Src0.isReg() 4099 ? MRI.getRegClass(Src0.getReg()) 4100 : &AMDGPU::VReg_64RegClass; 4101 const TargetRegisterClass *Src1RC = Src1.isReg() 4102 ? MRI.getRegClass(Src1.getReg()) 4103 : &AMDGPU::VReg_64RegClass; 4104 4105 const TargetRegisterClass *Src0SubRC = 4106 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4107 const TargetRegisterClass *Src1SubRC = 4108 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4109 4110 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4111 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4112 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4113 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4114 4115 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4116 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4117 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4118 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4119 4120 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4121 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4122 .addReg(CarryReg, RegState::Define) 4123 .add(SrcReg0Sub0) 4124 .add(SrcReg1Sub0) 4125 .addImm(0); // clamp bit 4126 4127 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4128 MachineInstr *HiHalf = 4129 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4130 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4131 .add(SrcReg0Sub1) 4132 .add(SrcReg1Sub1) 4133 .addReg(CarryReg, RegState::Kill) 4134 .addImm(0); // clamp bit 4135 4136 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4137 .addReg(DestSub0) 4138 .addImm(AMDGPU::sub0) 4139 .addReg(DestSub1) 4140 .addImm(AMDGPU::sub1); 4141 TII->legalizeOperands(*LoHalf); 4142 TII->legalizeOperands(*HiHalf); 4143 MI.eraseFromParent(); 4144 return BB; 4145 } 4146 case AMDGPU::S_ADD_CO_PSEUDO: 4147 case AMDGPU::S_SUB_CO_PSEUDO: { 4148 // This pseudo has a chance to be selected 4149 // only from uniform add/subcarry node. All the VGPR operands 4150 // therefore assumed to be splat vectors. 4151 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4152 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4153 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4154 MachineBasicBlock::iterator MII = MI; 4155 const DebugLoc &DL = MI.getDebugLoc(); 4156 MachineOperand &Dest = MI.getOperand(0); 4157 MachineOperand &CarryDest = MI.getOperand(1); 4158 MachineOperand &Src0 = MI.getOperand(2); 4159 MachineOperand &Src1 = MI.getOperand(3); 4160 MachineOperand &Src2 = MI.getOperand(4); 4161 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4162 ? AMDGPU::S_ADDC_U32 4163 : AMDGPU::S_SUBB_U32; 4164 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4165 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4166 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4167 .addReg(Src0.getReg()); 4168 Src0.setReg(RegOp0); 4169 } 4170 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4171 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4172 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4173 .addReg(Src1.getReg()); 4174 Src1.setReg(RegOp1); 4175 } 4176 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4177 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4178 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4179 .addReg(Src2.getReg()); 4180 Src2.setReg(RegOp2); 4181 } 4182 4183 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4184 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4185 assert(WaveSize == 64 || WaveSize == 32); 4186 4187 if (WaveSize == 64) { 4188 if (ST.hasScalarCompareEq64()) { 4189 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4190 .addReg(Src2.getReg()) 4191 .addImm(0); 4192 } else { 4193 const TargetRegisterClass *SubRC = 4194 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4195 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4196 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4197 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4198 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4199 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4200 4201 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4202 .add(Src2Sub0) 4203 .add(Src2Sub1); 4204 4205 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4206 .addReg(Src2_32, RegState::Kill) 4207 .addImm(0); 4208 } 4209 } else { 4210 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4211 .addReg(Src2.getReg()) 4212 .addImm(0); 4213 } 4214 4215 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4216 4217 unsigned SelOpc = 4218 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4219 4220 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4221 .addImm(-1) 4222 .addImm(0); 4223 4224 MI.eraseFromParent(); 4225 return BB; 4226 } 4227 case AMDGPU::SI_INIT_M0: { 4228 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4229 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4230 .add(MI.getOperand(0)); 4231 MI.eraseFromParent(); 4232 return BB; 4233 } 4234 case AMDGPU::GET_GROUPSTATICSIZE: { 4235 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4236 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4237 DebugLoc DL = MI.getDebugLoc(); 4238 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4239 .add(MI.getOperand(0)) 4240 .addImm(MFI->getLDSSize()); 4241 MI.eraseFromParent(); 4242 return BB; 4243 } 4244 case AMDGPU::SI_INDIRECT_SRC_V1: 4245 case AMDGPU::SI_INDIRECT_SRC_V2: 4246 case AMDGPU::SI_INDIRECT_SRC_V4: 4247 case AMDGPU::SI_INDIRECT_SRC_V8: 4248 case AMDGPU::SI_INDIRECT_SRC_V16: 4249 case AMDGPU::SI_INDIRECT_SRC_V32: 4250 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4251 case AMDGPU::SI_INDIRECT_DST_V1: 4252 case AMDGPU::SI_INDIRECT_DST_V2: 4253 case AMDGPU::SI_INDIRECT_DST_V4: 4254 case AMDGPU::SI_INDIRECT_DST_V8: 4255 case AMDGPU::SI_INDIRECT_DST_V16: 4256 case AMDGPU::SI_INDIRECT_DST_V32: 4257 return emitIndirectDst(MI, *BB, *getSubtarget()); 4258 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4259 case AMDGPU::SI_KILL_I1_PSEUDO: 4260 return splitKillBlock(MI, BB); 4261 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4262 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4263 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4264 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4265 4266 Register Dst = MI.getOperand(0).getReg(); 4267 Register Src0 = MI.getOperand(1).getReg(); 4268 Register Src1 = MI.getOperand(2).getReg(); 4269 const DebugLoc &DL = MI.getDebugLoc(); 4270 Register SrcCond = MI.getOperand(3).getReg(); 4271 4272 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4273 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4274 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4275 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4276 4277 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4278 .addReg(SrcCond); 4279 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4280 .addImm(0) 4281 .addReg(Src0, 0, AMDGPU::sub0) 4282 .addImm(0) 4283 .addReg(Src1, 0, AMDGPU::sub0) 4284 .addReg(SrcCondCopy); 4285 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4286 .addImm(0) 4287 .addReg(Src0, 0, AMDGPU::sub1) 4288 .addImm(0) 4289 .addReg(Src1, 0, AMDGPU::sub1) 4290 .addReg(SrcCondCopy); 4291 4292 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4293 .addReg(DstLo) 4294 .addImm(AMDGPU::sub0) 4295 .addReg(DstHi) 4296 .addImm(AMDGPU::sub1); 4297 MI.eraseFromParent(); 4298 return BB; 4299 } 4300 case AMDGPU::SI_BR_UNDEF: { 4301 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4302 const DebugLoc &DL = MI.getDebugLoc(); 4303 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4304 .add(MI.getOperand(0)); 4305 Br->getOperand(1).setIsUndef(true); // read undef SCC 4306 MI.eraseFromParent(); 4307 return BB; 4308 } 4309 case AMDGPU::ADJCALLSTACKUP: 4310 case AMDGPU::ADJCALLSTACKDOWN: { 4311 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4312 MachineInstrBuilder MIB(*MF, &MI); 4313 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4314 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4315 return BB; 4316 } 4317 case AMDGPU::SI_CALL_ISEL: { 4318 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4319 const DebugLoc &DL = MI.getDebugLoc(); 4320 4321 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4322 4323 MachineInstrBuilder MIB; 4324 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4325 4326 for (const MachineOperand &MO : MI.operands()) 4327 MIB.add(MO); 4328 4329 MIB.cloneMemRefs(MI); 4330 MI.eraseFromParent(); 4331 return BB; 4332 } 4333 case AMDGPU::V_ADD_CO_U32_e32: 4334 case AMDGPU::V_SUB_CO_U32_e32: 4335 case AMDGPU::V_SUBREV_CO_U32_e32: { 4336 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4337 const DebugLoc &DL = MI.getDebugLoc(); 4338 unsigned Opc = MI.getOpcode(); 4339 4340 bool NeedClampOperand = false; 4341 if (TII->pseudoToMCOpcode(Opc) == -1) { 4342 Opc = AMDGPU::getVOPe64(Opc); 4343 NeedClampOperand = true; 4344 } 4345 4346 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4347 if (TII->isVOP3(*I)) { 4348 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4349 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4350 I.addReg(TRI->getVCC(), RegState::Define); 4351 } 4352 I.add(MI.getOperand(1)) 4353 .add(MI.getOperand(2)); 4354 if (NeedClampOperand) 4355 I.addImm(0); // clamp bit for e64 encoding 4356 4357 TII->legalizeOperands(*I); 4358 4359 MI.eraseFromParent(); 4360 return BB; 4361 } 4362 case AMDGPU::V_ADDC_U32_e32: 4363 case AMDGPU::V_SUBB_U32_e32: 4364 case AMDGPU::V_SUBBREV_U32_e32: 4365 // These instructions have an implicit use of vcc which counts towards the 4366 // constant bus limit. 4367 TII->legalizeOperands(MI); 4368 return BB; 4369 case AMDGPU::DS_GWS_INIT: 4370 case AMDGPU::DS_GWS_SEMA_BR: 4371 case AMDGPU::DS_GWS_BARRIER: 4372 if (Subtarget->needsAlignedVGPRs()) { 4373 // Add implicit aligned super-reg to force alignment on the data operand. 4374 const DebugLoc &DL = MI.getDebugLoc(); 4375 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4376 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4377 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4378 Register DataReg = Op->getReg(); 4379 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4380 Register Undef = MRI.createVirtualRegister( 4381 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4382 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4383 Register NewVR = 4384 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4385 : &AMDGPU::VReg_64_Align2RegClass); 4386 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4387 .addReg(DataReg, 0, Op->getSubReg()) 4388 .addImm(AMDGPU::sub0) 4389 .addReg(Undef) 4390 .addImm(AMDGPU::sub1); 4391 Op->setReg(NewVR); 4392 Op->setSubReg(AMDGPU::sub0); 4393 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4394 } 4395 LLVM_FALLTHROUGH; 4396 case AMDGPU::DS_GWS_SEMA_V: 4397 case AMDGPU::DS_GWS_SEMA_P: 4398 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4399 // A s_waitcnt 0 is required to be the instruction immediately following. 4400 if (getSubtarget()->hasGWSAutoReplay()) { 4401 bundleInstWithWaitcnt(MI); 4402 return BB; 4403 } 4404 4405 return emitGWSMemViolTestLoop(MI, BB); 4406 case AMDGPU::S_SETREG_B32: { 4407 // Try to optimize cases that only set the denormal mode or rounding mode. 4408 // 4409 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4410 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4411 // instead. 4412 // 4413 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4414 // allow you to have a no side effect instruction in the output of a 4415 // sideeffecting pattern. 4416 unsigned ID, Offset, Width; 4417 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4418 if (ID != AMDGPU::Hwreg::ID_MODE) 4419 return BB; 4420 4421 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4422 const unsigned SetMask = WidthMask << Offset; 4423 4424 if (getSubtarget()->hasDenormModeInst()) { 4425 unsigned SetDenormOp = 0; 4426 unsigned SetRoundOp = 0; 4427 4428 // The dedicated instructions can only set the whole denorm or round mode 4429 // at once, not a subset of bits in either. 4430 if (SetMask == 4431 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4432 // If this fully sets both the round and denorm mode, emit the two 4433 // dedicated instructions for these. 4434 SetRoundOp = AMDGPU::S_ROUND_MODE; 4435 SetDenormOp = AMDGPU::S_DENORM_MODE; 4436 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4437 SetRoundOp = AMDGPU::S_ROUND_MODE; 4438 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4439 SetDenormOp = AMDGPU::S_DENORM_MODE; 4440 } 4441 4442 if (SetRoundOp || SetDenormOp) { 4443 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4444 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4445 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4446 unsigned ImmVal = Def->getOperand(1).getImm(); 4447 if (SetRoundOp) { 4448 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4449 .addImm(ImmVal & 0xf); 4450 4451 // If we also have the denorm mode, get just the denorm mode bits. 4452 ImmVal >>= 4; 4453 } 4454 4455 if (SetDenormOp) { 4456 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4457 .addImm(ImmVal & 0xf); 4458 } 4459 4460 MI.eraseFromParent(); 4461 return BB; 4462 } 4463 } 4464 } 4465 4466 // If only FP bits are touched, used the no side effects pseudo. 4467 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4468 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4469 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4470 4471 return BB; 4472 } 4473 default: 4474 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4475 } 4476 } 4477 4478 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4479 return isTypeLegal(VT.getScalarType()); 4480 } 4481 4482 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4483 // This currently forces unfolding various combinations of fsub into fma with 4484 // free fneg'd operands. As long as we have fast FMA (controlled by 4485 // isFMAFasterThanFMulAndFAdd), we should perform these. 4486 4487 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4488 // most of these combines appear to be cycle neutral but save on instruction 4489 // count / code size. 4490 return true; 4491 } 4492 4493 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4494 4495 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4496 EVT VT) const { 4497 if (!VT.isVector()) { 4498 return MVT::i1; 4499 } 4500 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4501 } 4502 4503 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4504 // TODO: Should i16 be used always if legal? For now it would force VALU 4505 // shifts. 4506 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4507 } 4508 4509 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4510 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4511 ? Ty.changeElementSize(16) 4512 : Ty.changeElementSize(32); 4513 } 4514 4515 // Answering this is somewhat tricky and depends on the specific device which 4516 // have different rates for fma or all f64 operations. 4517 // 4518 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4519 // regardless of which device (although the number of cycles differs between 4520 // devices), so it is always profitable for f64. 4521 // 4522 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4523 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4524 // which we can always do even without fused FP ops since it returns the same 4525 // result as the separate operations and since it is always full 4526 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4527 // however does not support denormals, so we do report fma as faster if we have 4528 // a fast fma device and require denormals. 4529 // 4530 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4531 EVT VT) const { 4532 VT = VT.getScalarType(); 4533 4534 switch (VT.getSimpleVT().SimpleTy) { 4535 case MVT::f32: { 4536 // If mad is not available this depends only on if f32 fma is full rate. 4537 if (!Subtarget->hasMadMacF32Insts()) 4538 return Subtarget->hasFastFMAF32(); 4539 4540 // Otherwise f32 mad is always full rate and returns the same result as 4541 // the separate operations so should be preferred over fma. 4542 // However does not support denormals. 4543 if (hasFP32Denormals(MF)) 4544 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4545 4546 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4547 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4548 } 4549 case MVT::f64: 4550 return true; 4551 case MVT::f16: 4552 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4553 default: 4554 break; 4555 } 4556 4557 return false; 4558 } 4559 4560 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4561 LLT Ty) const { 4562 switch (Ty.getScalarSizeInBits()) { 4563 case 16: 4564 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4565 case 32: 4566 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4567 case 64: 4568 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4569 default: 4570 break; 4571 } 4572 4573 return false; 4574 } 4575 4576 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4577 if (!Ty.isScalar()) 4578 return false; 4579 4580 if (Ty.getScalarSizeInBits() == 16) 4581 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4582 if (Ty.getScalarSizeInBits() == 32) 4583 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4584 4585 return false; 4586 } 4587 4588 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4589 const SDNode *N) const { 4590 // TODO: Check future ftz flag 4591 // v_mad_f32/v_mac_f32 do not support denormals. 4592 EVT VT = N->getValueType(0); 4593 if (VT == MVT::f32) 4594 return Subtarget->hasMadMacF32Insts() && 4595 !hasFP32Denormals(DAG.getMachineFunction()); 4596 if (VT == MVT::f16) { 4597 return Subtarget->hasMadF16() && 4598 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4599 } 4600 4601 return false; 4602 } 4603 4604 //===----------------------------------------------------------------------===// 4605 // Custom DAG Lowering Operations 4606 //===----------------------------------------------------------------------===// 4607 4608 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4609 // wider vector type is legal. 4610 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4611 SelectionDAG &DAG) const { 4612 unsigned Opc = Op.getOpcode(); 4613 EVT VT = Op.getValueType(); 4614 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4615 4616 SDValue Lo, Hi; 4617 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4618 4619 SDLoc SL(Op); 4620 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4621 Op->getFlags()); 4622 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4623 Op->getFlags()); 4624 4625 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4626 } 4627 4628 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4629 // wider vector type is legal. 4630 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4631 SelectionDAG &DAG) const { 4632 unsigned Opc = Op.getOpcode(); 4633 EVT VT = Op.getValueType(); 4634 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4635 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4636 VT == MVT::v16f32 || VT == MVT::v32f32); 4637 4638 SDValue Lo0, Hi0; 4639 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4640 SDValue Lo1, Hi1; 4641 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4642 4643 SDLoc SL(Op); 4644 4645 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4646 Op->getFlags()); 4647 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4648 Op->getFlags()); 4649 4650 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4651 } 4652 4653 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4654 SelectionDAG &DAG) const { 4655 unsigned Opc = Op.getOpcode(); 4656 EVT VT = Op.getValueType(); 4657 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4658 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4659 VT == MVT::v16f32 || VT == MVT::v32f32); 4660 4661 SDValue Lo0, Hi0; 4662 SDValue Op0 = Op.getOperand(0); 4663 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4664 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4665 : std::make_pair(Op0, Op0); 4666 SDValue Lo1, Hi1; 4667 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4668 SDValue Lo2, Hi2; 4669 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4670 4671 SDLoc SL(Op); 4672 auto ResVT = DAG.GetSplitDestVTs(VT); 4673 4674 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4675 Op->getFlags()); 4676 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4677 Op->getFlags()); 4678 4679 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4680 } 4681 4682 4683 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4684 switch (Op.getOpcode()) { 4685 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4686 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4687 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4688 case ISD::LOAD: { 4689 SDValue Result = LowerLOAD(Op, DAG); 4690 assert((!Result.getNode() || 4691 Result.getNode()->getNumValues() == 2) && 4692 "Load should return a value and a chain"); 4693 return Result; 4694 } 4695 4696 case ISD::FSIN: 4697 case ISD::FCOS: 4698 return LowerTrig(Op, DAG); 4699 case ISD::SELECT: return LowerSELECT(Op, DAG); 4700 case ISD::FDIV: return LowerFDIV(Op, DAG); 4701 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4702 case ISD::STORE: return LowerSTORE(Op, DAG); 4703 case ISD::GlobalAddress: { 4704 MachineFunction &MF = DAG.getMachineFunction(); 4705 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4706 return LowerGlobalAddress(MFI, Op, DAG); 4707 } 4708 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4709 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4710 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4711 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4712 case ISD::INSERT_SUBVECTOR: 4713 return lowerINSERT_SUBVECTOR(Op, DAG); 4714 case ISD::INSERT_VECTOR_ELT: 4715 return lowerINSERT_VECTOR_ELT(Op, DAG); 4716 case ISD::EXTRACT_VECTOR_ELT: 4717 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4718 case ISD::VECTOR_SHUFFLE: 4719 return lowerVECTOR_SHUFFLE(Op, DAG); 4720 case ISD::BUILD_VECTOR: 4721 return lowerBUILD_VECTOR(Op, DAG); 4722 case ISD::FP_ROUND: 4723 return lowerFP_ROUND(Op, DAG); 4724 case ISD::FPTRUNC_ROUND: { 4725 unsigned Opc; 4726 SDLoc DL(Op); 4727 4728 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4729 return SDValue(); 4730 4731 // Get the rounding mode from the last operand 4732 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4733 if (RoundMode == (int)RoundingMode::TowardPositive) 4734 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4735 else if (RoundMode == (int)RoundingMode::TowardNegative) 4736 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4737 else 4738 return SDValue(); 4739 4740 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4741 } 4742 case ISD::TRAP: 4743 return lowerTRAP(Op, DAG); 4744 case ISD::DEBUGTRAP: 4745 return lowerDEBUGTRAP(Op, DAG); 4746 case ISD::FABS: 4747 case ISD::FNEG: 4748 case ISD::FCANONICALIZE: 4749 case ISD::BSWAP: 4750 return splitUnaryVectorOp(Op, DAG); 4751 case ISD::FMINNUM: 4752 case ISD::FMAXNUM: 4753 return lowerFMINNUM_FMAXNUM(Op, DAG); 4754 case ISD::FMA: 4755 return splitTernaryVectorOp(Op, DAG); 4756 case ISD::FP_TO_SINT: 4757 case ISD::FP_TO_UINT: 4758 return LowerFP_TO_INT(Op, DAG); 4759 case ISD::SHL: 4760 case ISD::SRA: 4761 case ISD::SRL: 4762 case ISD::ADD: 4763 case ISD::SUB: 4764 case ISD::MUL: 4765 case ISD::SMIN: 4766 case ISD::SMAX: 4767 case ISD::UMIN: 4768 case ISD::UMAX: 4769 case ISD::FADD: 4770 case ISD::FMUL: 4771 case ISD::FMINNUM_IEEE: 4772 case ISD::FMAXNUM_IEEE: 4773 case ISD::UADDSAT: 4774 case ISD::USUBSAT: 4775 case ISD::SADDSAT: 4776 case ISD::SSUBSAT: 4777 return splitBinaryVectorOp(Op, DAG); 4778 case ISD::SMULO: 4779 case ISD::UMULO: 4780 return lowerXMULO(Op, DAG); 4781 case ISD::SMUL_LOHI: 4782 case ISD::UMUL_LOHI: 4783 return lowerXMUL_LOHI(Op, DAG); 4784 case ISD::DYNAMIC_STACKALLOC: 4785 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4786 } 4787 return SDValue(); 4788 } 4789 4790 // Used for D16: Casts the result of an instruction into the right vector, 4791 // packs values if loads return unpacked values. 4792 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4793 const SDLoc &DL, 4794 SelectionDAG &DAG, bool Unpacked) { 4795 if (!LoadVT.isVector()) 4796 return Result; 4797 4798 // Cast back to the original packed type or to a larger type that is a 4799 // multiple of 32 bit for D16. Widening the return type is a required for 4800 // legalization. 4801 EVT FittingLoadVT = LoadVT; 4802 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4803 FittingLoadVT = 4804 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4805 LoadVT.getVectorNumElements() + 1); 4806 } 4807 4808 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4809 // Truncate to v2i16/v4i16. 4810 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4811 4812 // Workaround legalizer not scalarizing truncate after vector op 4813 // legalization but not creating intermediate vector trunc. 4814 SmallVector<SDValue, 4> Elts; 4815 DAG.ExtractVectorElements(Result, Elts); 4816 for (SDValue &Elt : Elts) 4817 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4818 4819 // Pad illegal v1i16/v3fi6 to v4i16 4820 if ((LoadVT.getVectorNumElements() % 2) == 1) 4821 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4822 4823 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4824 4825 // Bitcast to original type (v2f16/v4f16). 4826 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4827 } 4828 4829 // Cast back to the original packed type. 4830 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4831 } 4832 4833 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4834 MemSDNode *M, 4835 SelectionDAG &DAG, 4836 ArrayRef<SDValue> Ops, 4837 bool IsIntrinsic) const { 4838 SDLoc DL(M); 4839 4840 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4841 EVT LoadVT = M->getValueType(0); 4842 4843 EVT EquivLoadVT = LoadVT; 4844 if (LoadVT.isVector()) { 4845 if (Unpacked) { 4846 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4847 LoadVT.getVectorNumElements()); 4848 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4849 // Widen v3f16 to legal type 4850 EquivLoadVT = 4851 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4852 LoadVT.getVectorNumElements() + 1); 4853 } 4854 } 4855 4856 // Change from v4f16/v2f16 to EquivLoadVT. 4857 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4858 4859 SDValue Load 4860 = DAG.getMemIntrinsicNode( 4861 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4862 VTList, Ops, M->getMemoryVT(), 4863 M->getMemOperand()); 4864 4865 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4866 4867 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4868 } 4869 4870 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4871 SelectionDAG &DAG, 4872 ArrayRef<SDValue> Ops) const { 4873 SDLoc DL(M); 4874 EVT LoadVT = M->getValueType(0); 4875 EVT EltType = LoadVT.getScalarType(); 4876 EVT IntVT = LoadVT.changeTypeToInteger(); 4877 4878 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4879 4880 unsigned Opc = 4881 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4882 4883 if (IsD16) { 4884 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4885 } 4886 4887 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4888 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4889 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4890 4891 if (isTypeLegal(LoadVT)) { 4892 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4893 M->getMemOperand(), DAG); 4894 } 4895 4896 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4897 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4898 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4899 M->getMemOperand(), DAG); 4900 return DAG.getMergeValues( 4901 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4902 DL); 4903 } 4904 4905 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4906 SDNode *N, SelectionDAG &DAG) { 4907 EVT VT = N->getValueType(0); 4908 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4909 unsigned CondCode = CD->getZExtValue(); 4910 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4911 return DAG.getUNDEF(VT); 4912 4913 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4914 4915 SDValue LHS = N->getOperand(1); 4916 SDValue RHS = N->getOperand(2); 4917 4918 SDLoc DL(N); 4919 4920 EVT CmpVT = LHS.getValueType(); 4921 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4922 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4923 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4924 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4925 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4926 } 4927 4928 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4929 4930 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4931 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4932 4933 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4934 DAG.getCondCode(CCOpcode)); 4935 if (VT.bitsEq(CCVT)) 4936 return SetCC; 4937 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4938 } 4939 4940 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4941 SDNode *N, SelectionDAG &DAG) { 4942 EVT VT = N->getValueType(0); 4943 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4944 4945 unsigned CondCode = CD->getZExtValue(); 4946 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4947 return DAG.getUNDEF(VT); 4948 4949 SDValue Src0 = N->getOperand(1); 4950 SDValue Src1 = N->getOperand(2); 4951 EVT CmpVT = Src0.getValueType(); 4952 SDLoc SL(N); 4953 4954 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4955 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4956 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4957 } 4958 4959 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4960 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4961 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4962 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4963 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4964 Src1, DAG.getCondCode(CCOpcode)); 4965 if (VT.bitsEq(CCVT)) 4966 return SetCC; 4967 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4968 } 4969 4970 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4971 SelectionDAG &DAG) { 4972 EVT VT = N->getValueType(0); 4973 SDValue Src = N->getOperand(1); 4974 SDLoc SL(N); 4975 4976 if (Src.getOpcode() == ISD::SETCC) { 4977 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4978 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4979 Src.getOperand(1), Src.getOperand(2)); 4980 } 4981 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4982 // (ballot 0) -> 0 4983 if (Arg->isZero()) 4984 return DAG.getConstant(0, SL, VT); 4985 4986 // (ballot 1) -> EXEC/EXEC_LO 4987 if (Arg->isOne()) { 4988 Register Exec; 4989 if (VT.getScalarSizeInBits() == 32) 4990 Exec = AMDGPU::EXEC_LO; 4991 else if (VT.getScalarSizeInBits() == 64) 4992 Exec = AMDGPU::EXEC; 4993 else 4994 return SDValue(); 4995 4996 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4997 } 4998 } 4999 5000 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 5001 // ISD::SETNE) 5002 return DAG.getNode( 5003 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 5004 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 5005 } 5006 5007 void SITargetLowering::ReplaceNodeResults(SDNode *N, 5008 SmallVectorImpl<SDValue> &Results, 5009 SelectionDAG &DAG) const { 5010 switch (N->getOpcode()) { 5011 case ISD::INSERT_VECTOR_ELT: { 5012 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 5013 Results.push_back(Res); 5014 return; 5015 } 5016 case ISD::EXTRACT_VECTOR_ELT: { 5017 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 5018 Results.push_back(Res); 5019 return; 5020 } 5021 case ISD::INTRINSIC_WO_CHAIN: { 5022 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5023 switch (IID) { 5024 case Intrinsic::amdgcn_cvt_pkrtz: { 5025 SDValue Src0 = N->getOperand(1); 5026 SDValue Src1 = N->getOperand(2); 5027 SDLoc SL(N); 5028 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 5029 Src0, Src1); 5030 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 5031 return; 5032 } 5033 case Intrinsic::amdgcn_cvt_pknorm_i16: 5034 case Intrinsic::amdgcn_cvt_pknorm_u16: 5035 case Intrinsic::amdgcn_cvt_pk_i16: 5036 case Intrinsic::amdgcn_cvt_pk_u16: { 5037 SDValue Src0 = N->getOperand(1); 5038 SDValue Src1 = N->getOperand(2); 5039 SDLoc SL(N); 5040 unsigned Opcode; 5041 5042 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 5043 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5044 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 5045 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5046 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5047 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5048 else 5049 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5050 5051 EVT VT = N->getValueType(0); 5052 if (isTypeLegal(VT)) 5053 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5054 else { 5055 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5056 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5057 } 5058 return; 5059 } 5060 } 5061 break; 5062 } 5063 case ISD::INTRINSIC_W_CHAIN: { 5064 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5065 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5066 // FIXME: Hacky 5067 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5068 Results.push_back(Res.getOperand(I)); 5069 } 5070 } else { 5071 Results.push_back(Res); 5072 Results.push_back(Res.getValue(1)); 5073 } 5074 return; 5075 } 5076 5077 break; 5078 } 5079 case ISD::SELECT: { 5080 SDLoc SL(N); 5081 EVT VT = N->getValueType(0); 5082 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5083 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5084 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5085 5086 EVT SelectVT = NewVT; 5087 if (NewVT.bitsLT(MVT::i32)) { 5088 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5089 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5090 SelectVT = MVT::i32; 5091 } 5092 5093 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5094 N->getOperand(0), LHS, RHS); 5095 5096 if (NewVT != SelectVT) 5097 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5098 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5099 return; 5100 } 5101 case ISD::FNEG: { 5102 if (N->getValueType(0) != MVT::v2f16) 5103 break; 5104 5105 SDLoc SL(N); 5106 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5107 5108 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5109 BC, 5110 DAG.getConstant(0x80008000, SL, MVT::i32)); 5111 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5112 return; 5113 } 5114 case ISD::FABS: { 5115 if (N->getValueType(0) != MVT::v2f16) 5116 break; 5117 5118 SDLoc SL(N); 5119 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5120 5121 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5122 BC, 5123 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5124 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5125 return; 5126 } 5127 default: 5128 break; 5129 } 5130 } 5131 5132 /// Helper function for LowerBRCOND 5133 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5134 5135 SDNode *Parent = Value.getNode(); 5136 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5137 I != E; ++I) { 5138 5139 if (I.getUse().get() != Value) 5140 continue; 5141 5142 if (I->getOpcode() == Opcode) 5143 return *I; 5144 } 5145 return nullptr; 5146 } 5147 5148 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5149 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5150 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5151 case Intrinsic::amdgcn_if: 5152 return AMDGPUISD::IF; 5153 case Intrinsic::amdgcn_else: 5154 return AMDGPUISD::ELSE; 5155 case Intrinsic::amdgcn_loop: 5156 return AMDGPUISD::LOOP; 5157 case Intrinsic::amdgcn_end_cf: 5158 llvm_unreachable("should not occur"); 5159 default: 5160 return 0; 5161 } 5162 } 5163 5164 // break, if_break, else_break are all only used as inputs to loop, not 5165 // directly as branch conditions. 5166 return 0; 5167 } 5168 5169 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5170 const Triple &TT = getTargetMachine().getTargetTriple(); 5171 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5172 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5173 AMDGPU::shouldEmitConstantsToTextSection(TT); 5174 } 5175 5176 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5177 // FIXME: Either avoid relying on address space here or change the default 5178 // address space for functions to avoid the explicit check. 5179 return (GV->getValueType()->isFunctionTy() || 5180 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5181 !shouldEmitFixup(GV) && 5182 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5183 } 5184 5185 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5186 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5187 } 5188 5189 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5190 if (!GV->hasExternalLinkage()) 5191 return true; 5192 5193 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5194 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5195 } 5196 5197 /// This transforms the control flow intrinsics to get the branch destination as 5198 /// last parameter, also switches branch target with BR if the need arise 5199 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5200 SelectionDAG &DAG) const { 5201 SDLoc DL(BRCOND); 5202 5203 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5204 SDValue Target = BRCOND.getOperand(2); 5205 SDNode *BR = nullptr; 5206 SDNode *SetCC = nullptr; 5207 5208 if (Intr->getOpcode() == ISD::SETCC) { 5209 // As long as we negate the condition everything is fine 5210 SetCC = Intr; 5211 Intr = SetCC->getOperand(0).getNode(); 5212 5213 } else { 5214 // Get the target from BR if we don't negate the condition 5215 BR = findUser(BRCOND, ISD::BR); 5216 assert(BR && "brcond missing unconditional branch user"); 5217 Target = BR->getOperand(1); 5218 } 5219 5220 unsigned CFNode = isCFIntrinsic(Intr); 5221 if (CFNode == 0) { 5222 // This is a uniform branch so we don't need to legalize. 5223 return BRCOND; 5224 } 5225 5226 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5227 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5228 5229 assert(!SetCC || 5230 (SetCC->getConstantOperandVal(1) == 1 && 5231 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5232 ISD::SETNE)); 5233 5234 // operands of the new intrinsic call 5235 SmallVector<SDValue, 4> Ops; 5236 if (HaveChain) 5237 Ops.push_back(BRCOND.getOperand(0)); 5238 5239 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5240 Ops.push_back(Target); 5241 5242 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5243 5244 // build the new intrinsic call 5245 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5246 5247 if (!HaveChain) { 5248 SDValue Ops[] = { 5249 SDValue(Result, 0), 5250 BRCOND.getOperand(0) 5251 }; 5252 5253 Result = DAG.getMergeValues(Ops, DL).getNode(); 5254 } 5255 5256 if (BR) { 5257 // Give the branch instruction our target 5258 SDValue Ops[] = { 5259 BR->getOperand(0), 5260 BRCOND.getOperand(2) 5261 }; 5262 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5263 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5264 } 5265 5266 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5267 5268 // Copy the intrinsic results to registers 5269 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5270 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5271 if (!CopyToReg) 5272 continue; 5273 5274 Chain = DAG.getCopyToReg( 5275 Chain, DL, 5276 CopyToReg->getOperand(1), 5277 SDValue(Result, i - 1), 5278 SDValue()); 5279 5280 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5281 } 5282 5283 // Remove the old intrinsic from the chain 5284 DAG.ReplaceAllUsesOfValueWith( 5285 SDValue(Intr, Intr->getNumValues() - 1), 5286 Intr->getOperand(0)); 5287 5288 return Chain; 5289 } 5290 5291 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5292 SelectionDAG &DAG) const { 5293 MVT VT = Op.getSimpleValueType(); 5294 SDLoc DL(Op); 5295 // Checking the depth 5296 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5297 return DAG.getConstant(0, DL, VT); 5298 5299 MachineFunction &MF = DAG.getMachineFunction(); 5300 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5301 // Check for kernel and shader functions 5302 if (Info->isEntryFunction()) 5303 return DAG.getConstant(0, DL, VT); 5304 5305 MachineFrameInfo &MFI = MF.getFrameInfo(); 5306 // There is a call to @llvm.returnaddress in this function 5307 MFI.setReturnAddressIsTaken(true); 5308 5309 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5310 // Get the return address reg and mark it as an implicit live-in 5311 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5312 5313 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5314 } 5315 5316 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5317 SDValue Op, 5318 const SDLoc &DL, 5319 EVT VT) const { 5320 return Op.getValueType().bitsLE(VT) ? 5321 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5322 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5323 DAG.getTargetConstant(0, DL, MVT::i32)); 5324 } 5325 5326 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5327 assert(Op.getValueType() == MVT::f16 && 5328 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5329 5330 SDValue Src = Op.getOperand(0); 5331 EVT SrcVT = Src.getValueType(); 5332 if (SrcVT != MVT::f64) 5333 return Op; 5334 5335 SDLoc DL(Op); 5336 5337 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5338 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5339 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5340 } 5341 5342 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5343 SelectionDAG &DAG) const { 5344 EVT VT = Op.getValueType(); 5345 const MachineFunction &MF = DAG.getMachineFunction(); 5346 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5347 bool IsIEEEMode = Info->getMode().IEEE; 5348 5349 // FIXME: Assert during selection that this is only selected for 5350 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5351 // mode functions, but this happens to be OK since it's only done in cases 5352 // where there is known no sNaN. 5353 if (IsIEEEMode) 5354 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5355 5356 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5357 return splitBinaryVectorOp(Op, DAG); 5358 return Op; 5359 } 5360 5361 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5362 EVT VT = Op.getValueType(); 5363 SDLoc SL(Op); 5364 SDValue LHS = Op.getOperand(0); 5365 SDValue RHS = Op.getOperand(1); 5366 bool isSigned = Op.getOpcode() == ISD::SMULO; 5367 5368 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5369 const APInt &C = RHSC->getAPIntValue(); 5370 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5371 if (C.isPowerOf2()) { 5372 // smulo(x, signed_min) is same as umulo(x, signed_min). 5373 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5374 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5375 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5376 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5377 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5378 SL, VT, Result, ShiftAmt), 5379 LHS, ISD::SETNE); 5380 return DAG.getMergeValues({ Result, Overflow }, SL); 5381 } 5382 } 5383 5384 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5385 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5386 SL, VT, LHS, RHS); 5387 5388 SDValue Sign = isSigned 5389 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5390 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5391 : DAG.getConstant(0, SL, VT); 5392 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5393 5394 return DAG.getMergeValues({ Result, Overflow }, SL); 5395 } 5396 5397 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5398 if (Op->isDivergent()) { 5399 // Select to V_MAD_[IU]64_[IU]32. 5400 return Op; 5401 } 5402 if (Subtarget->hasSMulHi()) { 5403 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5404 return SDValue(); 5405 } 5406 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5407 // calculate the high part, so we might as well do the whole thing with 5408 // V_MAD_[IU]64_[IU]32. 5409 return Op; 5410 } 5411 5412 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5413 if (!Subtarget->isTrapHandlerEnabled() || 5414 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5415 return lowerTrapEndpgm(Op, DAG); 5416 5417 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5418 switch (*HsaAbiVer) { 5419 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5420 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5421 return lowerTrapHsaQueuePtr(Op, DAG); 5422 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5423 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5424 return Subtarget->supportsGetDoorbellID() ? 5425 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5426 } 5427 } 5428 5429 llvm_unreachable("Unknown trap handler"); 5430 } 5431 5432 SDValue SITargetLowering::lowerTrapEndpgm( 5433 SDValue Op, SelectionDAG &DAG) const { 5434 SDLoc SL(Op); 5435 SDValue Chain = Op.getOperand(0); 5436 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5437 } 5438 5439 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5440 SDValue Op, SelectionDAG &DAG) const { 5441 SDLoc SL(Op); 5442 SDValue Chain = Op.getOperand(0); 5443 5444 MachineFunction &MF = DAG.getMachineFunction(); 5445 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5446 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5447 5448 SDValue QueuePtr; 5449 if (UserSGPR == AMDGPU::NoRegister) { 5450 // We probably are in a function incorrectly marked with 5451 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5452 // so just use a null pointer. 5453 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5454 } else { 5455 QueuePtr = CreateLiveInRegister( 5456 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5457 } 5458 5459 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5460 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5461 QueuePtr, SDValue()); 5462 5463 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5464 SDValue Ops[] = { 5465 ToReg, 5466 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5467 SGPR01, 5468 ToReg.getValue(1) 5469 }; 5470 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5471 } 5472 5473 SDValue SITargetLowering::lowerTrapHsa( 5474 SDValue Op, SelectionDAG &DAG) const { 5475 SDLoc SL(Op); 5476 SDValue Chain = Op.getOperand(0); 5477 5478 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5479 SDValue Ops[] = { 5480 Chain, 5481 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5482 }; 5483 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5484 } 5485 5486 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5487 SDLoc SL(Op); 5488 SDValue Chain = Op.getOperand(0); 5489 MachineFunction &MF = DAG.getMachineFunction(); 5490 5491 if (!Subtarget->isTrapHandlerEnabled() || 5492 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5493 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5494 "debugtrap handler not supported", 5495 Op.getDebugLoc(), 5496 DS_Warning); 5497 LLVMContext &Ctx = MF.getFunction().getContext(); 5498 Ctx.diagnose(NoTrap); 5499 return Chain; 5500 } 5501 5502 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5503 SDValue Ops[] = { 5504 Chain, 5505 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5506 }; 5507 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5508 } 5509 5510 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5511 SelectionDAG &DAG) const { 5512 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5513 if (Subtarget->hasApertureRegs()) { 5514 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5515 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5516 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5517 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5518 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5519 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5520 unsigned Encoding = 5521 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5522 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5523 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5524 5525 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5526 SDValue ApertureReg = SDValue( 5527 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5528 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5529 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5530 } 5531 5532 MachineFunction &MF = DAG.getMachineFunction(); 5533 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5534 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5535 if (UserSGPR == AMDGPU::NoRegister) { 5536 // We probably are in a function incorrectly marked with 5537 // amdgpu-no-queue-ptr. This is undefined. 5538 return DAG.getUNDEF(MVT::i32); 5539 } 5540 5541 SDValue QueuePtr = CreateLiveInRegister( 5542 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5543 5544 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5545 // private_segment_aperture_base_hi. 5546 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5547 5548 SDValue Ptr = 5549 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5550 5551 // TODO: Use custom target PseudoSourceValue. 5552 // TODO: We should use the value from the IR intrinsic call, but it might not 5553 // be available and how do we get it? 5554 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5555 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5556 commonAlignment(Align(64), StructOffset), 5557 MachineMemOperand::MODereferenceable | 5558 MachineMemOperand::MOInvariant); 5559 } 5560 5561 /// Return true if the value is a known valid address, such that a null check is 5562 /// not necessary. 5563 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5564 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5565 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5566 isa<BasicBlockSDNode>(Val)) 5567 return true; 5568 5569 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5570 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5571 5572 // TODO: Search through arithmetic, handle arguments and loads 5573 // marked nonnull. 5574 return false; 5575 } 5576 5577 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5578 SelectionDAG &DAG) const { 5579 SDLoc SL(Op); 5580 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5581 5582 SDValue Src = ASC->getOperand(0); 5583 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5584 unsigned SrcAS = ASC->getSrcAddressSpace(); 5585 5586 const AMDGPUTargetMachine &TM = 5587 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5588 5589 // flat -> local/private 5590 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5591 unsigned DestAS = ASC->getDestAddressSpace(); 5592 5593 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5594 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5595 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5596 5597 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5598 return Ptr; 5599 5600 unsigned NullVal = TM.getNullPointerValue(DestAS); 5601 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5602 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5603 5604 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5605 SegmentNullPtr); 5606 } 5607 } 5608 5609 // local/private -> flat 5610 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5611 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5612 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5613 5614 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5615 SDValue CvtPtr = 5616 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5617 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5618 5619 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5620 return CvtPtr; 5621 5622 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5623 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5624 5625 SDValue NonNull 5626 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5627 5628 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5629 FlatNullPtr); 5630 } 5631 } 5632 5633 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5634 Op.getValueType() == MVT::i64) { 5635 const SIMachineFunctionInfo *Info = 5636 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5637 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5638 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5639 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5640 } 5641 5642 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5643 Src.getValueType() == MVT::i64) 5644 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5645 5646 // global <-> flat are no-ops and never emitted. 5647 5648 const MachineFunction &MF = DAG.getMachineFunction(); 5649 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5650 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5651 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5652 5653 return DAG.getUNDEF(ASC->getValueType(0)); 5654 } 5655 5656 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5657 // the small vector and inserting them into the big vector. That is better than 5658 // the default expansion of doing it via a stack slot. Even though the use of 5659 // the stack slot would be optimized away afterwards, the stack slot itself 5660 // remains. 5661 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5662 SelectionDAG &DAG) const { 5663 SDValue Vec = Op.getOperand(0); 5664 SDValue Ins = Op.getOperand(1); 5665 SDValue Idx = Op.getOperand(2); 5666 EVT VecVT = Vec.getValueType(); 5667 EVT InsVT = Ins.getValueType(); 5668 EVT EltVT = VecVT.getVectorElementType(); 5669 unsigned InsNumElts = InsVT.getVectorNumElements(); 5670 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5671 SDLoc SL(Op); 5672 5673 for (unsigned I = 0; I != InsNumElts; ++I) { 5674 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5675 DAG.getConstant(I, SL, MVT::i32)); 5676 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5677 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5678 } 5679 return Vec; 5680 } 5681 5682 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5683 SelectionDAG &DAG) const { 5684 SDValue Vec = Op.getOperand(0); 5685 SDValue InsVal = Op.getOperand(1); 5686 SDValue Idx = Op.getOperand(2); 5687 EVT VecVT = Vec.getValueType(); 5688 EVT EltVT = VecVT.getVectorElementType(); 5689 unsigned VecSize = VecVT.getSizeInBits(); 5690 unsigned EltSize = EltVT.getSizeInBits(); 5691 5692 5693 assert(VecSize <= 64); 5694 5695 unsigned NumElts = VecVT.getVectorNumElements(); 5696 SDLoc SL(Op); 5697 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5698 5699 if (NumElts == 4 && EltSize == 16 && KIdx) { 5700 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5701 5702 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5703 DAG.getConstant(0, SL, MVT::i32)); 5704 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5705 DAG.getConstant(1, SL, MVT::i32)); 5706 5707 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5708 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5709 5710 unsigned Idx = KIdx->getZExtValue(); 5711 bool InsertLo = Idx < 2; 5712 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5713 InsertLo ? LoVec : HiVec, 5714 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5715 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5716 5717 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5718 5719 SDValue Concat = InsertLo ? 5720 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5721 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5722 5723 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5724 } 5725 5726 if (isa<ConstantSDNode>(Idx)) 5727 return SDValue(); 5728 5729 MVT IntVT = MVT::getIntegerVT(VecSize); 5730 5731 // Avoid stack access for dynamic indexing. 5732 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5733 5734 // Create a congruent vector with the target value in each element so that 5735 // the required element can be masked and ORed into the target vector. 5736 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5737 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5738 5739 assert(isPowerOf2_32(EltSize)); 5740 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5741 5742 // Convert vector index to bit-index. 5743 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5744 5745 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5746 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5747 DAG.getConstant(0xffff, SL, IntVT), 5748 ScaledIdx); 5749 5750 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5751 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5752 DAG.getNOT(SL, BFM, IntVT), BCVec); 5753 5754 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5755 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5756 } 5757 5758 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5759 SelectionDAG &DAG) const { 5760 SDLoc SL(Op); 5761 5762 EVT ResultVT = Op.getValueType(); 5763 SDValue Vec = Op.getOperand(0); 5764 SDValue Idx = Op.getOperand(1); 5765 EVT VecVT = Vec.getValueType(); 5766 unsigned VecSize = VecVT.getSizeInBits(); 5767 EVT EltVT = VecVT.getVectorElementType(); 5768 5769 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5770 5771 // Make sure we do any optimizations that will make it easier to fold 5772 // source modifiers before obscuring it with bit operations. 5773 5774 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5775 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5776 return Combined; 5777 5778 if (VecSize == 128) { 5779 SDValue Lo, Hi; 5780 EVT LoVT, HiVT; 5781 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5782 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5783 Lo = 5784 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5785 V2, DAG.getConstant(0, SL, MVT::i32))); 5786 Hi = 5787 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5788 V2, DAG.getConstant(1, SL, MVT::i32))); 5789 EVT IdxVT = Idx.getValueType(); 5790 unsigned NElem = VecVT.getVectorNumElements(); 5791 assert(isPowerOf2_32(NElem)); 5792 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5793 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5794 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5795 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5796 } 5797 5798 assert(VecSize <= 64); 5799 5800 unsigned EltSize = EltVT.getSizeInBits(); 5801 assert(isPowerOf2_32(EltSize)); 5802 5803 MVT IntVT = MVT::getIntegerVT(VecSize); 5804 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5805 5806 // Convert vector index to bit-index (* EltSize) 5807 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5808 5809 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5810 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5811 5812 if (ResultVT == MVT::f16) { 5813 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5814 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5815 } 5816 5817 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5818 } 5819 5820 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5821 assert(Elt % 2 == 0); 5822 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5823 } 5824 5825 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5826 SelectionDAG &DAG) const { 5827 SDLoc SL(Op); 5828 EVT ResultVT = Op.getValueType(); 5829 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5830 5831 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5832 EVT EltVT = PackVT.getVectorElementType(); 5833 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5834 5835 // vector_shuffle <0,1,6,7> lhs, rhs 5836 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5837 // 5838 // vector_shuffle <6,7,2,3> lhs, rhs 5839 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5840 // 5841 // vector_shuffle <6,7,0,1> lhs, rhs 5842 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5843 5844 // Avoid scalarizing when both halves are reading from consecutive elements. 5845 SmallVector<SDValue, 4> Pieces; 5846 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5847 if (elementPairIsContiguous(SVN->getMask(), I)) { 5848 const int Idx = SVN->getMaskElt(I); 5849 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5850 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5851 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5852 PackVT, SVN->getOperand(VecIdx), 5853 DAG.getConstant(EltIdx, SL, MVT::i32)); 5854 Pieces.push_back(SubVec); 5855 } else { 5856 const int Idx0 = SVN->getMaskElt(I); 5857 const int Idx1 = SVN->getMaskElt(I + 1); 5858 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5859 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5860 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5861 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5862 5863 SDValue Vec0 = SVN->getOperand(VecIdx0); 5864 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5865 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5866 5867 SDValue Vec1 = SVN->getOperand(VecIdx1); 5868 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5869 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5870 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5871 } 5872 } 5873 5874 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5875 } 5876 5877 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5878 SelectionDAG &DAG) const { 5879 SDLoc SL(Op); 5880 EVT VT = Op.getValueType(); 5881 5882 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5883 VT == MVT::v8i16 || VT == MVT::v8f16) { 5884 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5885 VT.getVectorNumElements() / 2); 5886 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5887 5888 // Turn into pair of packed build_vectors. 5889 // TODO: Special case for constants that can be materialized with s_mov_b64. 5890 SmallVector<SDValue, 4> LoOps, HiOps; 5891 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5892 LoOps.push_back(Op.getOperand(I)); 5893 HiOps.push_back(Op.getOperand(I + E)); 5894 } 5895 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5896 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5897 5898 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5899 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5900 5901 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5902 { CastLo, CastHi }); 5903 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5904 } 5905 5906 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5907 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5908 5909 SDValue Lo = Op.getOperand(0); 5910 SDValue Hi = Op.getOperand(1); 5911 5912 // Avoid adding defined bits with the zero_extend. 5913 if (Hi.isUndef()) { 5914 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5915 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5916 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5917 } 5918 5919 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5920 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5921 5922 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5923 DAG.getConstant(16, SL, MVT::i32)); 5924 if (Lo.isUndef()) 5925 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5926 5927 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5928 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5929 5930 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5931 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5932 } 5933 5934 bool 5935 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5936 // We can fold offsets for anything that doesn't require a GOT relocation. 5937 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5938 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5939 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5940 !shouldEmitGOTReloc(GA->getGlobal()); 5941 } 5942 5943 static SDValue 5944 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5945 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5946 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5947 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5948 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5949 // lowered to the following code sequence: 5950 // 5951 // For constant address space: 5952 // s_getpc_b64 s[0:1] 5953 // s_add_u32 s0, s0, $symbol 5954 // s_addc_u32 s1, s1, 0 5955 // 5956 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5957 // a fixup or relocation is emitted to replace $symbol with a literal 5958 // constant, which is a pc-relative offset from the encoding of the $symbol 5959 // operand to the global variable. 5960 // 5961 // For global address space: 5962 // s_getpc_b64 s[0:1] 5963 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5964 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5965 // 5966 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5967 // fixups or relocations are emitted to replace $symbol@*@lo and 5968 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5969 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5970 // operand to the global variable. 5971 // 5972 // What we want here is an offset from the value returned by s_getpc 5973 // (which is the address of the s_add_u32 instruction) to the global 5974 // variable, but since the encoding of $symbol starts 4 bytes after the start 5975 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5976 // small. This requires us to add 4 to the global variable offset in order to 5977 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5978 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5979 // instruction. 5980 SDValue PtrLo = 5981 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5982 SDValue PtrHi; 5983 if (GAFlags == SIInstrInfo::MO_NONE) { 5984 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5985 } else { 5986 PtrHi = 5987 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5988 } 5989 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5990 } 5991 5992 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5993 SDValue Op, 5994 SelectionDAG &DAG) const { 5995 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5996 SDLoc DL(GSD); 5997 EVT PtrVT = Op.getValueType(); 5998 5999 const GlobalValue *GV = GSD->getGlobal(); 6000 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6001 shouldUseLDSConstAddress(GV)) || 6002 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 6003 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 6004 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6005 GV->hasExternalLinkage()) { 6006 Type *Ty = GV->getValueType(); 6007 // HIP uses an unsized array `extern __shared__ T s[]` or similar 6008 // zero-sized type in other languages to declare the dynamic shared 6009 // memory which size is not known at the compile time. They will be 6010 // allocated by the runtime and placed directly after the static 6011 // allocated ones. They all share the same offset. 6012 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 6013 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 6014 // Adjust alignment for that dynamic shared memory array. 6015 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 6016 return SDValue( 6017 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 6018 } 6019 } 6020 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 6021 } 6022 6023 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 6024 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 6025 SIInstrInfo::MO_ABS32_LO); 6026 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 6027 } 6028 6029 if (shouldEmitFixup(GV)) 6030 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 6031 else if (shouldEmitPCReloc(GV)) 6032 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 6033 SIInstrInfo::MO_REL32); 6034 6035 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 6036 SIInstrInfo::MO_GOTPCREL32); 6037 6038 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 6039 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 6040 const DataLayout &DataLayout = DAG.getDataLayout(); 6041 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 6042 MachinePointerInfo PtrInfo 6043 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 6044 6045 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 6046 MachineMemOperand::MODereferenceable | 6047 MachineMemOperand::MOInvariant); 6048 } 6049 6050 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6051 const SDLoc &DL, SDValue V) const { 6052 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6053 // the destination register. 6054 // 6055 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6056 // so we will end up with redundant moves to m0. 6057 // 6058 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6059 6060 // A Null SDValue creates a glue result. 6061 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6062 V, Chain); 6063 return SDValue(M0, 0); 6064 } 6065 6066 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6067 SDValue Op, 6068 MVT VT, 6069 unsigned Offset) const { 6070 SDLoc SL(Op); 6071 SDValue Param = lowerKernargMemParameter( 6072 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6073 // The local size values will have the hi 16-bits as zero. 6074 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6075 DAG.getValueType(VT)); 6076 } 6077 6078 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6079 EVT VT) { 6080 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6081 "non-hsa intrinsic with hsa target", 6082 DL.getDebugLoc()); 6083 DAG.getContext()->diagnose(BadIntrin); 6084 return DAG.getUNDEF(VT); 6085 } 6086 6087 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6088 EVT VT) { 6089 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6090 "intrinsic not supported on subtarget", 6091 DL.getDebugLoc()); 6092 DAG.getContext()->diagnose(BadIntrin); 6093 return DAG.getUNDEF(VT); 6094 } 6095 6096 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6097 ArrayRef<SDValue> Elts) { 6098 assert(!Elts.empty()); 6099 MVT Type; 6100 unsigned NumElts = Elts.size(); 6101 6102 if (NumElts <= 8) { 6103 Type = MVT::getVectorVT(MVT::f32, NumElts); 6104 } else { 6105 assert(Elts.size() <= 16); 6106 Type = MVT::v16f32; 6107 NumElts = 16; 6108 } 6109 6110 SmallVector<SDValue, 16> VecElts(NumElts); 6111 for (unsigned i = 0; i < Elts.size(); ++i) { 6112 SDValue Elt = Elts[i]; 6113 if (Elt.getValueType() != MVT::f32) 6114 Elt = DAG.getBitcast(MVT::f32, Elt); 6115 VecElts[i] = Elt; 6116 } 6117 for (unsigned i = Elts.size(); i < NumElts; ++i) 6118 VecElts[i] = DAG.getUNDEF(MVT::f32); 6119 6120 if (NumElts == 1) 6121 return VecElts[0]; 6122 return DAG.getBuildVector(Type, DL, VecElts); 6123 } 6124 6125 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6126 SDValue Src, int ExtraElts) { 6127 EVT SrcVT = Src.getValueType(); 6128 6129 SmallVector<SDValue, 8> Elts; 6130 6131 if (SrcVT.isVector()) 6132 DAG.ExtractVectorElements(Src, Elts); 6133 else 6134 Elts.push_back(Src); 6135 6136 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6137 while (ExtraElts--) 6138 Elts.push_back(Undef); 6139 6140 return DAG.getBuildVector(CastVT, DL, Elts); 6141 } 6142 6143 // Re-construct the required return value for a image load intrinsic. 6144 // This is more complicated due to the optional use TexFailCtrl which means the required 6145 // return type is an aggregate 6146 static SDValue constructRetValue(SelectionDAG &DAG, 6147 MachineSDNode *Result, 6148 ArrayRef<EVT> ResultTypes, 6149 bool IsTexFail, bool Unpacked, bool IsD16, 6150 int DMaskPop, int NumVDataDwords, 6151 const SDLoc &DL) { 6152 // Determine the required return type. This is the same regardless of IsTexFail flag 6153 EVT ReqRetVT = ResultTypes[0]; 6154 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6155 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6156 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6157 6158 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6159 DMaskPop : (DMaskPop + 1) / 2; 6160 6161 MVT DataDwordVT = NumDataDwords == 1 ? 6162 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6163 6164 MVT MaskPopVT = MaskPopDwords == 1 ? 6165 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6166 6167 SDValue Data(Result, 0); 6168 SDValue TexFail; 6169 6170 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6171 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6172 if (MaskPopVT.isVector()) { 6173 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6174 SDValue(Result, 0), ZeroIdx); 6175 } else { 6176 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6177 SDValue(Result, 0), ZeroIdx); 6178 } 6179 } 6180 6181 if (DataDwordVT.isVector()) 6182 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6183 NumDataDwords - MaskPopDwords); 6184 6185 if (IsD16) 6186 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6187 6188 EVT LegalReqRetVT = ReqRetVT; 6189 if (!ReqRetVT.isVector()) { 6190 if (!Data.getValueType().isInteger()) 6191 Data = DAG.getNode(ISD::BITCAST, DL, 6192 Data.getValueType().changeTypeToInteger(), Data); 6193 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6194 } else { 6195 // We need to widen the return vector to a legal type 6196 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6197 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6198 LegalReqRetVT = 6199 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6200 ReqRetVT.getVectorNumElements() + 1); 6201 } 6202 } 6203 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6204 6205 if (IsTexFail) { 6206 TexFail = 6207 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6208 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6209 6210 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6211 } 6212 6213 if (Result->getNumValues() == 1) 6214 return Data; 6215 6216 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6217 } 6218 6219 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6220 SDValue *LWE, bool &IsTexFail) { 6221 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6222 6223 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6224 if (Value) { 6225 IsTexFail = true; 6226 } 6227 6228 SDLoc DL(TexFailCtrlConst); 6229 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6230 Value &= ~(uint64_t)0x1; 6231 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6232 Value &= ~(uint64_t)0x2; 6233 6234 return Value == 0; 6235 } 6236 6237 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6238 MVT PackVectorVT, 6239 SmallVectorImpl<SDValue> &PackedAddrs, 6240 unsigned DimIdx, unsigned EndIdx, 6241 unsigned NumGradients) { 6242 SDLoc DL(Op); 6243 for (unsigned I = DimIdx; I < EndIdx; I++) { 6244 SDValue Addr = Op.getOperand(I); 6245 6246 // Gradients are packed with undef for each coordinate. 6247 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6248 // 1D: undef,dx/dh; undef,dx/dv 6249 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6250 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6251 if (((I + 1) >= EndIdx) || 6252 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6253 I == DimIdx + NumGradients - 1))) { 6254 if (Addr.getValueType() != MVT::i16) 6255 Addr = DAG.getBitcast(MVT::i16, Addr); 6256 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6257 } else { 6258 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6259 I++; 6260 } 6261 Addr = DAG.getBitcast(MVT::f32, Addr); 6262 PackedAddrs.push_back(Addr); 6263 } 6264 } 6265 6266 SDValue SITargetLowering::lowerImage(SDValue Op, 6267 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6268 SelectionDAG &DAG, bool WithChain) const { 6269 SDLoc DL(Op); 6270 MachineFunction &MF = DAG.getMachineFunction(); 6271 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6272 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6273 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6274 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6275 unsigned IntrOpcode = Intr->BaseOpcode; 6276 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6277 6278 SmallVector<EVT, 3> ResultTypes(Op->values()); 6279 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6280 bool IsD16 = false; 6281 bool IsG16 = false; 6282 bool IsA16 = false; 6283 SDValue VData; 6284 int NumVDataDwords; 6285 bool AdjustRetType = false; 6286 6287 // Offset of intrinsic arguments 6288 const unsigned ArgOffset = WithChain ? 2 : 1; 6289 6290 unsigned DMask; 6291 unsigned DMaskLanes = 0; 6292 6293 if (BaseOpcode->Atomic) { 6294 VData = Op.getOperand(2); 6295 6296 bool Is64Bit = VData.getValueType() == MVT::i64; 6297 if (BaseOpcode->AtomicX2) { 6298 SDValue VData2 = Op.getOperand(3); 6299 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6300 {VData, VData2}); 6301 if (Is64Bit) 6302 VData = DAG.getBitcast(MVT::v4i32, VData); 6303 6304 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6305 DMask = Is64Bit ? 0xf : 0x3; 6306 NumVDataDwords = Is64Bit ? 4 : 2; 6307 } else { 6308 DMask = Is64Bit ? 0x3 : 0x1; 6309 NumVDataDwords = Is64Bit ? 2 : 1; 6310 } 6311 } else { 6312 auto *DMaskConst = 6313 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6314 DMask = DMaskConst->getZExtValue(); 6315 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6316 6317 if (BaseOpcode->Store) { 6318 VData = Op.getOperand(2); 6319 6320 MVT StoreVT = VData.getSimpleValueType(); 6321 if (StoreVT.getScalarType() == MVT::f16) { 6322 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6323 return Op; // D16 is unsupported for this instruction 6324 6325 IsD16 = true; 6326 VData = handleD16VData(VData, DAG, true); 6327 } 6328 6329 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6330 } else { 6331 // Work out the num dwords based on the dmask popcount and underlying type 6332 // and whether packing is supported. 6333 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6334 if (LoadVT.getScalarType() == MVT::f16) { 6335 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6336 return Op; // D16 is unsupported for this instruction 6337 6338 IsD16 = true; 6339 } 6340 6341 // Confirm that the return type is large enough for the dmask specified 6342 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6343 (!LoadVT.isVector() && DMaskLanes > 1)) 6344 return Op; 6345 6346 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6347 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6348 // instructions. 6349 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6350 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6351 NumVDataDwords = (DMaskLanes + 1) / 2; 6352 else 6353 NumVDataDwords = DMaskLanes; 6354 6355 AdjustRetType = true; 6356 } 6357 } 6358 6359 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6360 SmallVector<SDValue, 4> VAddrs; 6361 6362 // Check for 16 bit addresses or derivatives and pack if true. 6363 MVT VAddrVT = 6364 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6365 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6366 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6367 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6368 6369 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6370 VAddrScalarVT = VAddrVT.getScalarType(); 6371 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6372 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6373 6374 // Push back extra arguments. 6375 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6376 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6377 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6378 // Special handling of bias when A16 is on. Bias is of type half but 6379 // occupies full 32-bit. 6380 SDValue Bias = DAG.getBuildVector( 6381 MVT::v2f16, DL, 6382 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6383 VAddrs.push_back(Bias); 6384 } else { 6385 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6386 "Bias needs to be converted to 16 bit in A16 mode"); 6387 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6388 } 6389 } 6390 6391 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6392 // 16 bit gradients are supported, but are tied to the A16 control 6393 // so both gradients and addresses must be 16 bit 6394 LLVM_DEBUG( 6395 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6396 "require 16 bit args for both gradients and addresses"); 6397 return Op; 6398 } 6399 6400 if (IsA16) { 6401 if (!ST->hasA16()) { 6402 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6403 "support 16 bit addresses\n"); 6404 return Op; 6405 } 6406 } 6407 6408 // We've dealt with incorrect input so we know that if IsA16, IsG16 6409 // are set then we have to compress/pack operands (either address, 6410 // gradient or both) 6411 // In the case where a16 and gradients are tied (no G16 support) then we 6412 // have already verified that both IsA16 and IsG16 are true 6413 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6414 // Activate g16 6415 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6416 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6417 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6418 } 6419 6420 // Add gradients (packed or unpacked) 6421 if (IsG16) { 6422 // Pack the gradients 6423 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6424 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6425 ArgOffset + Intr->GradientStart, 6426 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6427 } else { 6428 for (unsigned I = ArgOffset + Intr->GradientStart; 6429 I < ArgOffset + Intr->CoordStart; I++) 6430 VAddrs.push_back(Op.getOperand(I)); 6431 } 6432 6433 // Add addresses (packed or unpacked) 6434 if (IsA16) { 6435 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6436 ArgOffset + Intr->CoordStart, VAddrEnd, 6437 0 /* No gradients */); 6438 } else { 6439 // Add uncompressed address 6440 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6441 VAddrs.push_back(Op.getOperand(I)); 6442 } 6443 6444 // If the register allocator cannot place the address registers contiguously 6445 // without introducing moves, then using the non-sequential address encoding 6446 // is always preferable, since it saves VALU instructions and is usually a 6447 // wash in terms of code size or even better. 6448 // 6449 // However, we currently have no way of hinting to the register allocator that 6450 // MIMG addresses should be placed contiguously when it is possible to do so, 6451 // so force non-NSA for the common 2-address case as a heuristic. 6452 // 6453 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6454 // allocation when possible. 6455 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6456 VAddrs.size() >= 3 && 6457 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6458 SDValue VAddr; 6459 if (!UseNSA) 6460 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6461 6462 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6463 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6464 SDValue Unorm; 6465 if (!BaseOpcode->Sampler) { 6466 Unorm = True; 6467 } else { 6468 auto UnormConst = 6469 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6470 6471 Unorm = UnormConst->getZExtValue() ? True : False; 6472 } 6473 6474 SDValue TFE; 6475 SDValue LWE; 6476 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6477 bool IsTexFail = false; 6478 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6479 return Op; 6480 6481 if (IsTexFail) { 6482 if (!DMaskLanes) { 6483 // Expecting to get an error flag since TFC is on - and dmask is 0 6484 // Force dmask to be at least 1 otherwise the instruction will fail 6485 DMask = 0x1; 6486 DMaskLanes = 1; 6487 NumVDataDwords = 1; 6488 } 6489 NumVDataDwords += 1; 6490 AdjustRetType = true; 6491 } 6492 6493 // Has something earlier tagged that the return type needs adjusting 6494 // This happens if the instruction is a load or has set TexFailCtrl flags 6495 if (AdjustRetType) { 6496 // NumVDataDwords reflects the true number of dwords required in the return type 6497 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6498 // This is a no-op load. This can be eliminated 6499 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6500 if (isa<MemSDNode>(Op)) 6501 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6502 return Undef; 6503 } 6504 6505 EVT NewVT = NumVDataDwords > 1 ? 6506 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6507 : MVT::i32; 6508 6509 ResultTypes[0] = NewVT; 6510 if (ResultTypes.size() == 3) { 6511 // Original result was aggregate type used for TexFailCtrl results 6512 // The actual instruction returns as a vector type which has now been 6513 // created. Remove the aggregate result. 6514 ResultTypes.erase(&ResultTypes[1]); 6515 } 6516 } 6517 6518 unsigned CPol = cast<ConstantSDNode>( 6519 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6520 if (BaseOpcode->Atomic) 6521 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6522 if (CPol & ~AMDGPU::CPol::ALL) 6523 return Op; 6524 6525 SmallVector<SDValue, 26> Ops; 6526 if (BaseOpcode->Store || BaseOpcode->Atomic) 6527 Ops.push_back(VData); // vdata 6528 if (UseNSA) 6529 append_range(Ops, VAddrs); 6530 else 6531 Ops.push_back(VAddr); 6532 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6533 if (BaseOpcode->Sampler) 6534 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6535 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6536 if (IsGFX10Plus) 6537 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6538 Ops.push_back(Unorm); 6539 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6540 Ops.push_back(IsA16 && // r128, a16 for gfx9 6541 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6542 if (IsGFX10Plus) 6543 Ops.push_back(IsA16 ? True : False); 6544 if (!Subtarget->hasGFX90AInsts()) { 6545 Ops.push_back(TFE); //tfe 6546 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6547 report_fatal_error("TFE is not supported on this GPU"); 6548 } 6549 Ops.push_back(LWE); // lwe 6550 if (!IsGFX10Plus) 6551 Ops.push_back(DimInfo->DA ? True : False); 6552 if (BaseOpcode->HasD16) 6553 Ops.push_back(IsD16 ? True : False); 6554 if (isa<MemSDNode>(Op)) 6555 Ops.push_back(Op.getOperand(0)); // chain 6556 6557 int NumVAddrDwords = 6558 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6559 int Opcode = -1; 6560 6561 if (IsGFX10Plus) { 6562 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6563 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6564 : AMDGPU::MIMGEncGfx10Default, 6565 NumVDataDwords, NumVAddrDwords); 6566 } else { 6567 if (Subtarget->hasGFX90AInsts()) { 6568 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6569 NumVDataDwords, NumVAddrDwords); 6570 if (Opcode == -1) 6571 report_fatal_error( 6572 "requested image instruction is not supported on this GPU"); 6573 } 6574 if (Opcode == -1 && 6575 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6576 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6577 NumVDataDwords, NumVAddrDwords); 6578 if (Opcode == -1) 6579 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6580 NumVDataDwords, NumVAddrDwords); 6581 } 6582 assert(Opcode != -1); 6583 6584 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6585 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6586 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6587 DAG.setNodeMemRefs(NewNode, {MemRef}); 6588 } 6589 6590 if (BaseOpcode->AtomicX2) { 6591 SmallVector<SDValue, 1> Elt; 6592 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6593 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6594 } 6595 if (BaseOpcode->Store) 6596 return SDValue(NewNode, 0); 6597 return constructRetValue(DAG, NewNode, 6598 OrigResultTypes, IsTexFail, 6599 Subtarget->hasUnpackedD16VMem(), IsD16, 6600 DMaskLanes, NumVDataDwords, DL); 6601 } 6602 6603 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6604 SDValue Offset, SDValue CachePolicy, 6605 SelectionDAG &DAG) const { 6606 MachineFunction &MF = DAG.getMachineFunction(); 6607 6608 const DataLayout &DataLayout = DAG.getDataLayout(); 6609 Align Alignment = 6610 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6611 6612 MachineMemOperand *MMO = MF.getMachineMemOperand( 6613 MachinePointerInfo(), 6614 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6615 MachineMemOperand::MOInvariant, 6616 VT.getStoreSize(), Alignment); 6617 6618 if (!Offset->isDivergent()) { 6619 SDValue Ops[] = { 6620 Rsrc, 6621 Offset, // Offset 6622 CachePolicy 6623 }; 6624 6625 // Widen vec3 load to vec4. 6626 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6627 EVT WidenedVT = 6628 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6629 auto WidenedOp = DAG.getMemIntrinsicNode( 6630 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6631 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6632 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6633 DAG.getVectorIdxConstant(0, DL)); 6634 return Subvector; 6635 } 6636 6637 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6638 DAG.getVTList(VT), Ops, VT, MMO); 6639 } 6640 6641 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6642 // assume that the buffer is unswizzled. 6643 SmallVector<SDValue, 4> Loads; 6644 unsigned NumLoads = 1; 6645 MVT LoadVT = VT.getSimpleVT(); 6646 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6647 assert((LoadVT.getScalarType() == MVT::i32 || 6648 LoadVT.getScalarType() == MVT::f32)); 6649 6650 if (NumElts == 8 || NumElts == 16) { 6651 NumLoads = NumElts / 4; 6652 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6653 } 6654 6655 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6656 SDValue Ops[] = { 6657 DAG.getEntryNode(), // Chain 6658 Rsrc, // rsrc 6659 DAG.getConstant(0, DL, MVT::i32), // vindex 6660 {}, // voffset 6661 {}, // soffset 6662 {}, // offset 6663 CachePolicy, // cachepolicy 6664 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6665 }; 6666 6667 // Use the alignment to ensure that the required offsets will fit into the 6668 // immediate offsets. 6669 setBufferOffsets(Offset, DAG, &Ops[3], 6670 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6671 6672 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6673 for (unsigned i = 0; i < NumLoads; ++i) { 6674 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6675 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6676 LoadVT, MMO, DAG)); 6677 } 6678 6679 if (NumElts == 8 || NumElts == 16) 6680 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6681 6682 return Loads[0]; 6683 } 6684 6685 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6686 SelectionDAG &DAG) const { 6687 MachineFunction &MF = DAG.getMachineFunction(); 6688 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6689 6690 EVT VT = Op.getValueType(); 6691 SDLoc DL(Op); 6692 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6693 6694 // TODO: Should this propagate fast-math-flags? 6695 6696 switch (IntrinsicID) { 6697 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6698 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6699 return emitNonHSAIntrinsicError(DAG, DL, VT); 6700 return getPreloadedValue(DAG, *MFI, VT, 6701 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6702 } 6703 case Intrinsic::amdgcn_dispatch_ptr: 6704 case Intrinsic::amdgcn_queue_ptr: { 6705 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6706 DiagnosticInfoUnsupported BadIntrin( 6707 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6708 DL.getDebugLoc()); 6709 DAG.getContext()->diagnose(BadIntrin); 6710 return DAG.getUNDEF(VT); 6711 } 6712 6713 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6714 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6715 return getPreloadedValue(DAG, *MFI, VT, RegID); 6716 } 6717 case Intrinsic::amdgcn_implicitarg_ptr: { 6718 if (MFI->isEntryFunction()) 6719 return getImplicitArgPtr(DAG, DL); 6720 return getPreloadedValue(DAG, *MFI, VT, 6721 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6722 } 6723 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6724 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6725 // This only makes sense to call in a kernel, so just lower to null. 6726 return DAG.getConstant(0, DL, VT); 6727 } 6728 6729 return getPreloadedValue(DAG, *MFI, VT, 6730 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6731 } 6732 case Intrinsic::amdgcn_dispatch_id: { 6733 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6734 } 6735 case Intrinsic::amdgcn_rcp: 6736 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6737 case Intrinsic::amdgcn_rsq: 6738 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6739 case Intrinsic::amdgcn_rsq_legacy: 6740 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6741 return emitRemovedIntrinsicError(DAG, DL, VT); 6742 return SDValue(); 6743 case Intrinsic::amdgcn_rcp_legacy: 6744 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6745 return emitRemovedIntrinsicError(DAG, DL, VT); 6746 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6747 case Intrinsic::amdgcn_rsq_clamp: { 6748 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6749 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6750 6751 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6752 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6753 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6754 6755 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6756 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6757 DAG.getConstantFP(Max, DL, VT)); 6758 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6759 DAG.getConstantFP(Min, DL, VT)); 6760 } 6761 case Intrinsic::r600_read_ngroups_x: 6762 if (Subtarget->isAmdHsaOS()) 6763 return emitNonHSAIntrinsicError(DAG, DL, VT); 6764 6765 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6766 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6767 false); 6768 case Intrinsic::r600_read_ngroups_y: 6769 if (Subtarget->isAmdHsaOS()) 6770 return emitNonHSAIntrinsicError(DAG, DL, VT); 6771 6772 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6773 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6774 false); 6775 case Intrinsic::r600_read_ngroups_z: 6776 if (Subtarget->isAmdHsaOS()) 6777 return emitNonHSAIntrinsicError(DAG, DL, VT); 6778 6779 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6780 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6781 false); 6782 case Intrinsic::r600_read_global_size_x: 6783 if (Subtarget->isAmdHsaOS()) 6784 return emitNonHSAIntrinsicError(DAG, DL, VT); 6785 6786 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6787 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6788 Align(4), false); 6789 case Intrinsic::r600_read_global_size_y: 6790 if (Subtarget->isAmdHsaOS()) 6791 return emitNonHSAIntrinsicError(DAG, DL, VT); 6792 6793 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6794 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6795 Align(4), false); 6796 case Intrinsic::r600_read_global_size_z: 6797 if (Subtarget->isAmdHsaOS()) 6798 return emitNonHSAIntrinsicError(DAG, DL, VT); 6799 6800 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6801 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6802 Align(4), false); 6803 case Intrinsic::r600_read_local_size_x: 6804 if (Subtarget->isAmdHsaOS()) 6805 return emitNonHSAIntrinsicError(DAG, DL, VT); 6806 6807 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6808 SI::KernelInputOffsets::LOCAL_SIZE_X); 6809 case Intrinsic::r600_read_local_size_y: 6810 if (Subtarget->isAmdHsaOS()) 6811 return emitNonHSAIntrinsicError(DAG, DL, VT); 6812 6813 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6814 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6815 case Intrinsic::r600_read_local_size_z: 6816 if (Subtarget->isAmdHsaOS()) 6817 return emitNonHSAIntrinsicError(DAG, DL, VT); 6818 6819 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6820 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6821 case Intrinsic::amdgcn_workgroup_id_x: 6822 return getPreloadedValue(DAG, *MFI, VT, 6823 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6824 case Intrinsic::amdgcn_workgroup_id_y: 6825 return getPreloadedValue(DAG, *MFI, VT, 6826 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6827 case Intrinsic::amdgcn_workgroup_id_z: 6828 return getPreloadedValue(DAG, *MFI, VT, 6829 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6830 case Intrinsic::amdgcn_workitem_id_x: 6831 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0) 6832 return DAG.getConstant(0, DL, MVT::i32); 6833 6834 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6835 SDLoc(DAG.getEntryNode()), 6836 MFI->getArgInfo().WorkItemIDX); 6837 case Intrinsic::amdgcn_workitem_id_y: 6838 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0) 6839 return DAG.getConstant(0, DL, MVT::i32); 6840 6841 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6842 SDLoc(DAG.getEntryNode()), 6843 MFI->getArgInfo().WorkItemIDY); 6844 case Intrinsic::amdgcn_workitem_id_z: 6845 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0) 6846 return DAG.getConstant(0, DL, MVT::i32); 6847 6848 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6849 SDLoc(DAG.getEntryNode()), 6850 MFI->getArgInfo().WorkItemIDZ); 6851 case Intrinsic::amdgcn_wavefrontsize: 6852 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6853 SDLoc(Op), MVT::i32); 6854 case Intrinsic::amdgcn_s_buffer_load: { 6855 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6856 if (CPol & ~AMDGPU::CPol::ALL) 6857 return Op; 6858 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6859 DAG); 6860 } 6861 case Intrinsic::amdgcn_fdiv_fast: 6862 return lowerFDIV_FAST(Op, DAG); 6863 case Intrinsic::amdgcn_sin: 6864 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6865 6866 case Intrinsic::amdgcn_cos: 6867 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6868 6869 case Intrinsic::amdgcn_mul_u24: 6870 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6871 case Intrinsic::amdgcn_mul_i24: 6872 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6873 6874 case Intrinsic::amdgcn_log_clamp: { 6875 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6876 return SDValue(); 6877 6878 return emitRemovedIntrinsicError(DAG, DL, VT); 6879 } 6880 case Intrinsic::amdgcn_ldexp: 6881 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6882 Op.getOperand(1), Op.getOperand(2)); 6883 6884 case Intrinsic::amdgcn_fract: 6885 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6886 6887 case Intrinsic::amdgcn_class: 6888 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6889 Op.getOperand(1), Op.getOperand(2)); 6890 case Intrinsic::amdgcn_div_fmas: 6891 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6892 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6893 Op.getOperand(4)); 6894 6895 case Intrinsic::amdgcn_div_fixup: 6896 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6897 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6898 6899 case Intrinsic::amdgcn_div_scale: { 6900 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6901 6902 // Translate to the operands expected by the machine instruction. The 6903 // first parameter must be the same as the first instruction. 6904 SDValue Numerator = Op.getOperand(1); 6905 SDValue Denominator = Op.getOperand(2); 6906 6907 // Note this order is opposite of the machine instruction's operations, 6908 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6909 // intrinsic has the numerator as the first operand to match a normal 6910 // division operation. 6911 6912 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6913 6914 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6915 Denominator, Numerator); 6916 } 6917 case Intrinsic::amdgcn_icmp: { 6918 // There is a Pat that handles this variant, so return it as-is. 6919 if (Op.getOperand(1).getValueType() == MVT::i1 && 6920 Op.getConstantOperandVal(2) == 0 && 6921 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6922 return Op; 6923 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6924 } 6925 case Intrinsic::amdgcn_fcmp: { 6926 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6927 } 6928 case Intrinsic::amdgcn_ballot: 6929 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6930 case Intrinsic::amdgcn_fmed3: 6931 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6932 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6933 case Intrinsic::amdgcn_fdot2: 6934 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6935 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6936 Op.getOperand(4)); 6937 case Intrinsic::amdgcn_fmul_legacy: 6938 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6939 Op.getOperand(1), Op.getOperand(2)); 6940 case Intrinsic::amdgcn_sffbh: 6941 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6942 case Intrinsic::amdgcn_sbfe: 6943 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6944 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6945 case Intrinsic::amdgcn_ubfe: 6946 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6947 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6948 case Intrinsic::amdgcn_cvt_pkrtz: 6949 case Intrinsic::amdgcn_cvt_pknorm_i16: 6950 case Intrinsic::amdgcn_cvt_pknorm_u16: 6951 case Intrinsic::amdgcn_cvt_pk_i16: 6952 case Intrinsic::amdgcn_cvt_pk_u16: { 6953 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6954 EVT VT = Op.getValueType(); 6955 unsigned Opcode; 6956 6957 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6958 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6959 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6960 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6961 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6962 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6963 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6964 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6965 else 6966 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6967 6968 if (isTypeLegal(VT)) 6969 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6970 6971 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6972 Op.getOperand(1), Op.getOperand(2)); 6973 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6974 } 6975 case Intrinsic::amdgcn_fmad_ftz: 6976 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6977 Op.getOperand(2), Op.getOperand(3)); 6978 6979 case Intrinsic::amdgcn_if_break: 6980 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6981 Op->getOperand(1), Op->getOperand(2)), 0); 6982 6983 case Intrinsic::amdgcn_groupstaticsize: { 6984 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6985 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6986 return Op; 6987 6988 const Module *M = MF.getFunction().getParent(); 6989 const GlobalValue *GV = 6990 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6991 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6992 SIInstrInfo::MO_ABS32_LO); 6993 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6994 } 6995 case Intrinsic::amdgcn_is_shared: 6996 case Intrinsic::amdgcn_is_private: { 6997 SDLoc SL(Op); 6998 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6999 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 7000 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 7001 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 7002 Op.getOperand(1)); 7003 7004 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 7005 DAG.getConstant(1, SL, MVT::i32)); 7006 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 7007 } 7008 case Intrinsic::amdgcn_perm: 7009 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 7010 Op.getOperand(2), Op.getOperand(3)); 7011 case Intrinsic::amdgcn_reloc_constant: { 7012 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 7013 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 7014 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 7015 auto RelocSymbol = cast<GlobalVariable>( 7016 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 7017 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 7018 SIInstrInfo::MO_ABS32_LO); 7019 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7020 } 7021 default: 7022 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7023 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7024 return lowerImage(Op, ImageDimIntr, DAG, false); 7025 7026 return Op; 7027 } 7028 } 7029 7030 /// Update \p MMO based on the offset inputs to an intrinsic. 7031 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7032 SDValue SOffset, SDValue Offset, 7033 SDValue VIndex = SDValue()) { 7034 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7035 !isa<ConstantSDNode>(Offset)) { 7036 // The combined offset is not known to be constant, so we cannot represent 7037 // it in the MMO. Give up. 7038 MMO->setValue((Value *)nullptr); 7039 return; 7040 } 7041 7042 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7043 !cast<ConstantSDNode>(VIndex)->isZero())) { 7044 // The strided index component of the address is not known to be zero, so we 7045 // cannot represent it in the MMO. Give up. 7046 MMO->setValue((Value *)nullptr); 7047 return; 7048 } 7049 7050 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7051 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7052 cast<ConstantSDNode>(Offset)->getSExtValue()); 7053 } 7054 7055 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7056 SelectionDAG &DAG, 7057 unsigned NewOpcode) const { 7058 SDLoc DL(Op); 7059 7060 SDValue VData = Op.getOperand(2); 7061 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7062 SDValue Ops[] = { 7063 Op.getOperand(0), // Chain 7064 VData, // vdata 7065 Op.getOperand(3), // rsrc 7066 DAG.getConstant(0, DL, MVT::i32), // vindex 7067 Offsets.first, // voffset 7068 Op.getOperand(5), // soffset 7069 Offsets.second, // offset 7070 Op.getOperand(6), // cachepolicy 7071 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7072 }; 7073 7074 auto *M = cast<MemSDNode>(Op); 7075 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7076 7077 EVT MemVT = VData.getValueType(); 7078 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7079 M->getMemOperand()); 7080 } 7081 7082 // Return a value to use for the idxen operand by examining the vindex operand. 7083 static unsigned getIdxEn(SDValue VIndex) { 7084 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7085 // No need to set idxen if vindex is known to be zero. 7086 return VIndexC->getZExtValue() != 0; 7087 return 1; 7088 } 7089 7090 SDValue 7091 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7092 unsigned NewOpcode) const { 7093 SDLoc DL(Op); 7094 7095 SDValue VData = Op.getOperand(2); 7096 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7097 SDValue Ops[] = { 7098 Op.getOperand(0), // Chain 7099 VData, // vdata 7100 Op.getOperand(3), // rsrc 7101 Op.getOperand(4), // vindex 7102 Offsets.first, // voffset 7103 Op.getOperand(6), // soffset 7104 Offsets.second, // offset 7105 Op.getOperand(7), // cachepolicy 7106 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7107 }; 7108 7109 auto *M = cast<MemSDNode>(Op); 7110 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7111 7112 EVT MemVT = VData.getValueType(); 7113 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7114 M->getMemOperand()); 7115 } 7116 7117 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7118 SelectionDAG &DAG) const { 7119 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7120 SDLoc DL(Op); 7121 7122 switch (IntrID) { 7123 case Intrinsic::amdgcn_ds_ordered_add: 7124 case Intrinsic::amdgcn_ds_ordered_swap: { 7125 MemSDNode *M = cast<MemSDNode>(Op); 7126 SDValue Chain = M->getOperand(0); 7127 SDValue M0 = M->getOperand(2); 7128 SDValue Value = M->getOperand(3); 7129 unsigned IndexOperand = M->getConstantOperandVal(7); 7130 unsigned WaveRelease = M->getConstantOperandVal(8); 7131 unsigned WaveDone = M->getConstantOperandVal(9); 7132 7133 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7134 IndexOperand &= ~0x3f; 7135 unsigned CountDw = 0; 7136 7137 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7138 CountDw = (IndexOperand >> 24) & 0xf; 7139 IndexOperand &= ~(0xf << 24); 7140 7141 if (CountDw < 1 || CountDw > 4) { 7142 report_fatal_error( 7143 "ds_ordered_count: dword count must be between 1 and 4"); 7144 } 7145 } 7146 7147 if (IndexOperand) 7148 report_fatal_error("ds_ordered_count: bad index operand"); 7149 7150 if (WaveDone && !WaveRelease) 7151 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7152 7153 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7154 unsigned ShaderType = 7155 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7156 unsigned Offset0 = OrderedCountIndex << 2; 7157 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7158 (Instruction << 4); 7159 7160 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7161 Offset1 |= (CountDw - 1) << 6; 7162 7163 unsigned Offset = Offset0 | (Offset1 << 8); 7164 7165 SDValue Ops[] = { 7166 Chain, 7167 Value, 7168 DAG.getTargetConstant(Offset, DL, MVT::i16), 7169 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7170 }; 7171 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7172 M->getVTList(), Ops, M->getMemoryVT(), 7173 M->getMemOperand()); 7174 } 7175 case Intrinsic::amdgcn_ds_fadd: { 7176 MemSDNode *M = cast<MemSDNode>(Op); 7177 unsigned Opc; 7178 switch (IntrID) { 7179 case Intrinsic::amdgcn_ds_fadd: 7180 Opc = ISD::ATOMIC_LOAD_FADD; 7181 break; 7182 } 7183 7184 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7185 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7186 M->getMemOperand()); 7187 } 7188 case Intrinsic::amdgcn_atomic_inc: 7189 case Intrinsic::amdgcn_atomic_dec: 7190 case Intrinsic::amdgcn_ds_fmin: 7191 case Intrinsic::amdgcn_ds_fmax: { 7192 MemSDNode *M = cast<MemSDNode>(Op); 7193 unsigned Opc; 7194 switch (IntrID) { 7195 case Intrinsic::amdgcn_atomic_inc: 7196 Opc = AMDGPUISD::ATOMIC_INC; 7197 break; 7198 case Intrinsic::amdgcn_atomic_dec: 7199 Opc = AMDGPUISD::ATOMIC_DEC; 7200 break; 7201 case Intrinsic::amdgcn_ds_fmin: 7202 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7203 break; 7204 case Intrinsic::amdgcn_ds_fmax: 7205 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7206 break; 7207 default: 7208 llvm_unreachable("Unknown intrinsic!"); 7209 } 7210 SDValue Ops[] = { 7211 M->getOperand(0), // Chain 7212 M->getOperand(2), // Ptr 7213 M->getOperand(3) // Value 7214 }; 7215 7216 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7217 M->getMemoryVT(), M->getMemOperand()); 7218 } 7219 case Intrinsic::amdgcn_buffer_load: 7220 case Intrinsic::amdgcn_buffer_load_format: { 7221 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7222 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7223 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7224 SDValue Ops[] = { 7225 Op.getOperand(0), // Chain 7226 Op.getOperand(2), // rsrc 7227 Op.getOperand(3), // vindex 7228 SDValue(), // voffset -- will be set by setBufferOffsets 7229 SDValue(), // soffset -- will be set by setBufferOffsets 7230 SDValue(), // offset -- will be set by setBufferOffsets 7231 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7232 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7233 }; 7234 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7235 7236 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7237 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7238 7239 EVT VT = Op.getValueType(); 7240 EVT IntVT = VT.changeTypeToInteger(); 7241 auto *M = cast<MemSDNode>(Op); 7242 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7243 EVT LoadVT = Op.getValueType(); 7244 7245 if (LoadVT.getScalarType() == MVT::f16) 7246 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7247 M, DAG, Ops); 7248 7249 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7250 if (LoadVT.getScalarType() == MVT::i8 || 7251 LoadVT.getScalarType() == MVT::i16) 7252 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7253 7254 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7255 M->getMemOperand(), DAG); 7256 } 7257 case Intrinsic::amdgcn_raw_buffer_load: 7258 case Intrinsic::amdgcn_raw_buffer_load_format: { 7259 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7260 7261 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7262 SDValue Ops[] = { 7263 Op.getOperand(0), // Chain 7264 Op.getOperand(2), // rsrc 7265 DAG.getConstant(0, DL, MVT::i32), // vindex 7266 Offsets.first, // voffset 7267 Op.getOperand(4), // soffset 7268 Offsets.second, // offset 7269 Op.getOperand(5), // cachepolicy, swizzled buffer 7270 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7271 }; 7272 7273 auto *M = cast<MemSDNode>(Op); 7274 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7275 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7276 } 7277 case Intrinsic::amdgcn_struct_buffer_load: 7278 case Intrinsic::amdgcn_struct_buffer_load_format: { 7279 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7280 7281 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7282 SDValue Ops[] = { 7283 Op.getOperand(0), // Chain 7284 Op.getOperand(2), // rsrc 7285 Op.getOperand(3), // vindex 7286 Offsets.first, // voffset 7287 Op.getOperand(5), // soffset 7288 Offsets.second, // offset 7289 Op.getOperand(6), // cachepolicy, swizzled buffer 7290 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7291 }; 7292 7293 auto *M = cast<MemSDNode>(Op); 7294 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7295 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7296 } 7297 case Intrinsic::amdgcn_tbuffer_load: { 7298 MemSDNode *M = cast<MemSDNode>(Op); 7299 EVT LoadVT = Op.getValueType(); 7300 7301 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7302 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7303 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7304 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7305 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7306 SDValue Ops[] = { 7307 Op.getOperand(0), // Chain 7308 Op.getOperand(2), // rsrc 7309 Op.getOperand(3), // vindex 7310 Op.getOperand(4), // voffset 7311 Op.getOperand(5), // soffset 7312 Op.getOperand(6), // offset 7313 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7314 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7315 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7316 }; 7317 7318 if (LoadVT.getScalarType() == MVT::f16) 7319 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7320 M, DAG, Ops); 7321 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7322 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7323 DAG); 7324 } 7325 case Intrinsic::amdgcn_raw_tbuffer_load: { 7326 MemSDNode *M = cast<MemSDNode>(Op); 7327 EVT LoadVT = Op.getValueType(); 7328 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7329 7330 SDValue Ops[] = { 7331 Op.getOperand(0), // Chain 7332 Op.getOperand(2), // rsrc 7333 DAG.getConstant(0, DL, MVT::i32), // vindex 7334 Offsets.first, // voffset 7335 Op.getOperand(4), // soffset 7336 Offsets.second, // offset 7337 Op.getOperand(5), // format 7338 Op.getOperand(6), // cachepolicy, swizzled buffer 7339 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7340 }; 7341 7342 if (LoadVT.getScalarType() == MVT::f16) 7343 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7344 M, DAG, Ops); 7345 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7346 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7347 DAG); 7348 } 7349 case Intrinsic::amdgcn_struct_tbuffer_load: { 7350 MemSDNode *M = cast<MemSDNode>(Op); 7351 EVT LoadVT = Op.getValueType(); 7352 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7353 7354 SDValue Ops[] = { 7355 Op.getOperand(0), // Chain 7356 Op.getOperand(2), // rsrc 7357 Op.getOperand(3), // vindex 7358 Offsets.first, // voffset 7359 Op.getOperand(5), // soffset 7360 Offsets.second, // offset 7361 Op.getOperand(6), // format 7362 Op.getOperand(7), // cachepolicy, swizzled buffer 7363 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7364 }; 7365 7366 if (LoadVT.getScalarType() == MVT::f16) 7367 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7368 M, DAG, Ops); 7369 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7370 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7371 DAG); 7372 } 7373 case Intrinsic::amdgcn_buffer_atomic_swap: 7374 case Intrinsic::amdgcn_buffer_atomic_add: 7375 case Intrinsic::amdgcn_buffer_atomic_sub: 7376 case Intrinsic::amdgcn_buffer_atomic_csub: 7377 case Intrinsic::amdgcn_buffer_atomic_smin: 7378 case Intrinsic::amdgcn_buffer_atomic_umin: 7379 case Intrinsic::amdgcn_buffer_atomic_smax: 7380 case Intrinsic::amdgcn_buffer_atomic_umax: 7381 case Intrinsic::amdgcn_buffer_atomic_and: 7382 case Intrinsic::amdgcn_buffer_atomic_or: 7383 case Intrinsic::amdgcn_buffer_atomic_xor: 7384 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7385 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7386 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7387 SDValue Ops[] = { 7388 Op.getOperand(0), // Chain 7389 Op.getOperand(2), // vdata 7390 Op.getOperand(3), // rsrc 7391 Op.getOperand(4), // vindex 7392 SDValue(), // voffset -- will be set by setBufferOffsets 7393 SDValue(), // soffset -- will be set by setBufferOffsets 7394 SDValue(), // offset -- will be set by setBufferOffsets 7395 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7396 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7397 }; 7398 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7399 7400 EVT VT = Op.getValueType(); 7401 7402 auto *M = cast<MemSDNode>(Op); 7403 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7404 unsigned Opcode = 0; 7405 7406 switch (IntrID) { 7407 case Intrinsic::amdgcn_buffer_atomic_swap: 7408 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7409 break; 7410 case Intrinsic::amdgcn_buffer_atomic_add: 7411 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7412 break; 7413 case Intrinsic::amdgcn_buffer_atomic_sub: 7414 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7415 break; 7416 case Intrinsic::amdgcn_buffer_atomic_csub: 7417 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7418 break; 7419 case Intrinsic::amdgcn_buffer_atomic_smin: 7420 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7421 break; 7422 case Intrinsic::amdgcn_buffer_atomic_umin: 7423 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7424 break; 7425 case Intrinsic::amdgcn_buffer_atomic_smax: 7426 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7427 break; 7428 case Intrinsic::amdgcn_buffer_atomic_umax: 7429 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7430 break; 7431 case Intrinsic::amdgcn_buffer_atomic_and: 7432 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7433 break; 7434 case Intrinsic::amdgcn_buffer_atomic_or: 7435 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7436 break; 7437 case Intrinsic::amdgcn_buffer_atomic_xor: 7438 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7439 break; 7440 case Intrinsic::amdgcn_buffer_atomic_fadd: 7441 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7442 DiagnosticInfoUnsupported 7443 NoFpRet(DAG.getMachineFunction().getFunction(), 7444 "return versions of fp atomics not supported", 7445 DL.getDebugLoc(), DS_Error); 7446 DAG.getContext()->diagnose(NoFpRet); 7447 return SDValue(); 7448 } 7449 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7450 break; 7451 default: 7452 llvm_unreachable("unhandled atomic opcode"); 7453 } 7454 7455 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7456 M->getMemOperand()); 7457 } 7458 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7459 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7460 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7461 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7462 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7463 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7464 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7465 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7466 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7467 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7468 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7469 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7470 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7471 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7472 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7473 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7474 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7475 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7476 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7477 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7478 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7479 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7480 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7481 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7482 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7483 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7484 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7485 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7486 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7487 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7488 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7489 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7490 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7491 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7492 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7493 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7494 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7495 return lowerStructBufferAtomicIntrin(Op, DAG, 7496 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7497 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7498 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7499 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7500 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7501 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7502 return lowerStructBufferAtomicIntrin(Op, DAG, 7503 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7504 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7505 return lowerStructBufferAtomicIntrin(Op, DAG, 7506 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7507 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7508 return lowerStructBufferAtomicIntrin(Op, DAG, 7509 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7510 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7511 return lowerStructBufferAtomicIntrin(Op, DAG, 7512 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7513 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7514 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7515 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7516 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7517 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7518 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7519 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7520 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7521 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7522 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7523 7524 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7525 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7526 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7527 SDValue Ops[] = { 7528 Op.getOperand(0), // Chain 7529 Op.getOperand(2), // src 7530 Op.getOperand(3), // cmp 7531 Op.getOperand(4), // rsrc 7532 Op.getOperand(5), // vindex 7533 SDValue(), // voffset -- will be set by setBufferOffsets 7534 SDValue(), // soffset -- will be set by setBufferOffsets 7535 SDValue(), // offset -- will be set by setBufferOffsets 7536 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7537 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7538 }; 7539 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7540 7541 EVT VT = Op.getValueType(); 7542 auto *M = cast<MemSDNode>(Op); 7543 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7544 7545 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7546 Op->getVTList(), Ops, VT, M->getMemOperand()); 7547 } 7548 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7549 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7550 SDValue Ops[] = { 7551 Op.getOperand(0), // Chain 7552 Op.getOperand(2), // src 7553 Op.getOperand(3), // cmp 7554 Op.getOperand(4), // rsrc 7555 DAG.getConstant(0, DL, MVT::i32), // vindex 7556 Offsets.first, // voffset 7557 Op.getOperand(6), // soffset 7558 Offsets.second, // offset 7559 Op.getOperand(7), // cachepolicy 7560 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7561 }; 7562 EVT VT = Op.getValueType(); 7563 auto *M = cast<MemSDNode>(Op); 7564 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7565 7566 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7567 Op->getVTList(), Ops, VT, M->getMemOperand()); 7568 } 7569 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7570 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7571 SDValue Ops[] = { 7572 Op.getOperand(0), // Chain 7573 Op.getOperand(2), // src 7574 Op.getOperand(3), // cmp 7575 Op.getOperand(4), // rsrc 7576 Op.getOperand(5), // vindex 7577 Offsets.first, // voffset 7578 Op.getOperand(7), // soffset 7579 Offsets.second, // offset 7580 Op.getOperand(8), // cachepolicy 7581 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7582 }; 7583 EVT VT = Op.getValueType(); 7584 auto *M = cast<MemSDNode>(Op); 7585 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7586 7587 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7588 Op->getVTList(), Ops, VT, M->getMemOperand()); 7589 } 7590 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7591 MemSDNode *M = cast<MemSDNode>(Op); 7592 SDValue NodePtr = M->getOperand(2); 7593 SDValue RayExtent = M->getOperand(3); 7594 SDValue RayOrigin = M->getOperand(4); 7595 SDValue RayDir = M->getOperand(5); 7596 SDValue RayInvDir = M->getOperand(6); 7597 SDValue TDescr = M->getOperand(7); 7598 7599 assert(NodePtr.getValueType() == MVT::i32 || 7600 NodePtr.getValueType() == MVT::i64); 7601 assert(RayDir.getValueType() == MVT::v3f16 || 7602 RayDir.getValueType() == MVT::v3f32); 7603 7604 if (!Subtarget->hasGFX10_AEncoding()) { 7605 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7606 return SDValue(); 7607 } 7608 7609 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7610 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7611 const unsigned NumVDataDwords = 4; 7612 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7613 const bool UseNSA = Subtarget->hasNSAEncoding() && 7614 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7615 const unsigned BaseOpcodes[2][2] = { 7616 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7617 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7618 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7619 int Opcode; 7620 if (UseNSA) { 7621 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7622 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7623 NumVAddrDwords); 7624 } else { 7625 Opcode = AMDGPU::getMIMGOpcode( 7626 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7627 PowerOf2Ceil(NumVAddrDwords)); 7628 } 7629 assert(Opcode != -1); 7630 7631 SmallVector<SDValue, 16> Ops; 7632 7633 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7634 SmallVector<SDValue, 3> Lanes; 7635 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7636 if (Lanes[0].getValueSizeInBits() == 32) { 7637 for (unsigned I = 0; I < 3; ++I) 7638 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7639 } else { 7640 if (IsAligned) { 7641 Ops.push_back( 7642 DAG.getBitcast(MVT::i32, 7643 DAG.getBuildVector(MVT::v2f16, DL, 7644 { Lanes[0], Lanes[1] }))); 7645 Ops.push_back(Lanes[2]); 7646 } else { 7647 SDValue Elt0 = Ops.pop_back_val(); 7648 Ops.push_back( 7649 DAG.getBitcast(MVT::i32, 7650 DAG.getBuildVector(MVT::v2f16, DL, 7651 { Elt0, Lanes[0] }))); 7652 Ops.push_back( 7653 DAG.getBitcast(MVT::i32, 7654 DAG.getBuildVector(MVT::v2f16, DL, 7655 { Lanes[1], Lanes[2] }))); 7656 } 7657 } 7658 }; 7659 7660 if (Is64) 7661 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7662 else 7663 Ops.push_back(NodePtr); 7664 7665 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7666 packLanes(RayOrigin, true); 7667 packLanes(RayDir, true); 7668 packLanes(RayInvDir, false); 7669 7670 if (!UseNSA) { 7671 // Build a single vector containing all the operands so far prepared. 7672 if (NumVAddrDwords > 8) { 7673 SDValue Undef = DAG.getUNDEF(MVT::i32); 7674 Ops.append(16 - Ops.size(), Undef); 7675 } 7676 assert(Ops.size() == 8 || Ops.size() == 16); 7677 SDValue MergedOps = DAG.getBuildVector( 7678 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7679 Ops.clear(); 7680 Ops.push_back(MergedOps); 7681 } 7682 7683 Ops.push_back(TDescr); 7684 if (IsA16) 7685 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7686 Ops.push_back(M->getChain()); 7687 7688 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7689 MachineMemOperand *MemRef = M->getMemOperand(); 7690 DAG.setNodeMemRefs(NewNode, {MemRef}); 7691 return SDValue(NewNode, 0); 7692 } 7693 case Intrinsic::amdgcn_global_atomic_fadd: 7694 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7695 DiagnosticInfoUnsupported 7696 NoFpRet(DAG.getMachineFunction().getFunction(), 7697 "return versions of fp atomics not supported", 7698 DL.getDebugLoc(), DS_Error); 7699 DAG.getContext()->diagnose(NoFpRet); 7700 return SDValue(); 7701 } 7702 LLVM_FALLTHROUGH; 7703 case Intrinsic::amdgcn_global_atomic_fmin: 7704 case Intrinsic::amdgcn_global_atomic_fmax: 7705 case Intrinsic::amdgcn_flat_atomic_fadd: 7706 case Intrinsic::amdgcn_flat_atomic_fmin: 7707 case Intrinsic::amdgcn_flat_atomic_fmax: { 7708 MemSDNode *M = cast<MemSDNode>(Op); 7709 SDValue Ops[] = { 7710 M->getOperand(0), // Chain 7711 M->getOperand(2), // Ptr 7712 M->getOperand(3) // Value 7713 }; 7714 unsigned Opcode = 0; 7715 switch (IntrID) { 7716 case Intrinsic::amdgcn_global_atomic_fadd: 7717 case Intrinsic::amdgcn_flat_atomic_fadd: { 7718 EVT VT = Op.getOperand(3).getValueType(); 7719 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7720 DAG.getVTList(VT, MVT::Other), Ops, 7721 M->getMemOperand()); 7722 } 7723 case Intrinsic::amdgcn_global_atomic_fmin: 7724 case Intrinsic::amdgcn_flat_atomic_fmin: { 7725 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7726 break; 7727 } 7728 case Intrinsic::amdgcn_global_atomic_fmax: 7729 case Intrinsic::amdgcn_flat_atomic_fmax: { 7730 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7731 break; 7732 } 7733 default: 7734 llvm_unreachable("unhandled atomic opcode"); 7735 } 7736 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7737 M->getVTList(), Ops, M->getMemoryVT(), 7738 M->getMemOperand()); 7739 } 7740 default: 7741 7742 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7743 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7744 return lowerImage(Op, ImageDimIntr, DAG, true); 7745 7746 return SDValue(); 7747 } 7748 } 7749 7750 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7751 // dwordx4 if on SI. 7752 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7753 SDVTList VTList, 7754 ArrayRef<SDValue> Ops, EVT MemVT, 7755 MachineMemOperand *MMO, 7756 SelectionDAG &DAG) const { 7757 EVT VT = VTList.VTs[0]; 7758 EVT WidenedVT = VT; 7759 EVT WidenedMemVT = MemVT; 7760 if (!Subtarget->hasDwordx3LoadStores() && 7761 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7762 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7763 WidenedVT.getVectorElementType(), 4); 7764 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7765 WidenedMemVT.getVectorElementType(), 4); 7766 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7767 } 7768 7769 assert(VTList.NumVTs == 2); 7770 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7771 7772 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7773 WidenedMemVT, MMO); 7774 if (WidenedVT != VT) { 7775 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7776 DAG.getVectorIdxConstant(0, DL)); 7777 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7778 } 7779 return NewOp; 7780 } 7781 7782 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7783 bool ImageStore) const { 7784 EVT StoreVT = VData.getValueType(); 7785 7786 // No change for f16 and legal vector D16 types. 7787 if (!StoreVT.isVector()) 7788 return VData; 7789 7790 SDLoc DL(VData); 7791 unsigned NumElements = StoreVT.getVectorNumElements(); 7792 7793 if (Subtarget->hasUnpackedD16VMem()) { 7794 // We need to unpack the packed data to store. 7795 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7796 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7797 7798 EVT EquivStoreVT = 7799 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7800 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7801 return DAG.UnrollVectorOp(ZExt.getNode()); 7802 } 7803 7804 // The sq block of gfx8.1 does not estimate register use correctly for d16 7805 // image store instructions. The data operand is computed as if it were not a 7806 // d16 image instruction. 7807 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7808 // Bitcast to i16 7809 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7810 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7811 7812 // Decompose into scalars 7813 SmallVector<SDValue, 4> Elts; 7814 DAG.ExtractVectorElements(IntVData, Elts); 7815 7816 // Group pairs of i16 into v2i16 and bitcast to i32 7817 SmallVector<SDValue, 4> PackedElts; 7818 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7819 SDValue Pair = 7820 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7821 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7822 PackedElts.push_back(IntPair); 7823 } 7824 if ((NumElements % 2) == 1) { 7825 // Handle v3i16 7826 unsigned I = Elts.size() / 2; 7827 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7828 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7829 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7830 PackedElts.push_back(IntPair); 7831 } 7832 7833 // Pad using UNDEF 7834 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7835 7836 // Build final vector 7837 EVT VecVT = 7838 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7839 return DAG.getBuildVector(VecVT, DL, PackedElts); 7840 } 7841 7842 if (NumElements == 3) { 7843 EVT IntStoreVT = 7844 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7845 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7846 7847 EVT WidenedStoreVT = EVT::getVectorVT( 7848 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7849 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7850 WidenedStoreVT.getStoreSizeInBits()); 7851 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7852 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7853 } 7854 7855 assert(isTypeLegal(StoreVT)); 7856 return VData; 7857 } 7858 7859 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7860 SelectionDAG &DAG) const { 7861 SDLoc DL(Op); 7862 SDValue Chain = Op.getOperand(0); 7863 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7864 MachineFunction &MF = DAG.getMachineFunction(); 7865 7866 switch (IntrinsicID) { 7867 case Intrinsic::amdgcn_exp_compr: { 7868 SDValue Src0 = Op.getOperand(4); 7869 SDValue Src1 = Op.getOperand(5); 7870 // Hack around illegal type on SI by directly selecting it. 7871 if (isTypeLegal(Src0.getValueType())) 7872 return SDValue(); 7873 7874 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7875 SDValue Undef = DAG.getUNDEF(MVT::f32); 7876 const SDValue Ops[] = { 7877 Op.getOperand(2), // tgt 7878 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7879 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7880 Undef, // src2 7881 Undef, // src3 7882 Op.getOperand(7), // vm 7883 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7884 Op.getOperand(3), // en 7885 Op.getOperand(0) // Chain 7886 }; 7887 7888 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7889 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7890 } 7891 case Intrinsic::amdgcn_s_barrier: { 7892 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7893 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7894 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7895 if (WGSize <= ST.getWavefrontSize()) 7896 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7897 Op.getOperand(0)), 0); 7898 } 7899 return SDValue(); 7900 }; 7901 case Intrinsic::amdgcn_tbuffer_store: { 7902 SDValue VData = Op.getOperand(2); 7903 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7904 if (IsD16) 7905 VData = handleD16VData(VData, DAG); 7906 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7907 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7908 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7909 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7910 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7911 SDValue Ops[] = { 7912 Chain, 7913 VData, // vdata 7914 Op.getOperand(3), // rsrc 7915 Op.getOperand(4), // vindex 7916 Op.getOperand(5), // voffset 7917 Op.getOperand(6), // soffset 7918 Op.getOperand(7), // offset 7919 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7920 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7921 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7922 }; 7923 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7924 AMDGPUISD::TBUFFER_STORE_FORMAT; 7925 MemSDNode *M = cast<MemSDNode>(Op); 7926 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7927 M->getMemoryVT(), M->getMemOperand()); 7928 } 7929 7930 case Intrinsic::amdgcn_struct_tbuffer_store: { 7931 SDValue VData = Op.getOperand(2); 7932 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7933 if (IsD16) 7934 VData = handleD16VData(VData, DAG); 7935 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7936 SDValue Ops[] = { 7937 Chain, 7938 VData, // vdata 7939 Op.getOperand(3), // rsrc 7940 Op.getOperand(4), // vindex 7941 Offsets.first, // voffset 7942 Op.getOperand(6), // soffset 7943 Offsets.second, // offset 7944 Op.getOperand(7), // format 7945 Op.getOperand(8), // cachepolicy, swizzled buffer 7946 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7947 }; 7948 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7949 AMDGPUISD::TBUFFER_STORE_FORMAT; 7950 MemSDNode *M = cast<MemSDNode>(Op); 7951 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7952 M->getMemoryVT(), M->getMemOperand()); 7953 } 7954 7955 case Intrinsic::amdgcn_raw_tbuffer_store: { 7956 SDValue VData = Op.getOperand(2); 7957 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7958 if (IsD16) 7959 VData = handleD16VData(VData, DAG); 7960 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7961 SDValue Ops[] = { 7962 Chain, 7963 VData, // vdata 7964 Op.getOperand(3), // rsrc 7965 DAG.getConstant(0, DL, MVT::i32), // vindex 7966 Offsets.first, // voffset 7967 Op.getOperand(5), // soffset 7968 Offsets.second, // offset 7969 Op.getOperand(6), // format 7970 Op.getOperand(7), // cachepolicy, swizzled buffer 7971 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7972 }; 7973 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7974 AMDGPUISD::TBUFFER_STORE_FORMAT; 7975 MemSDNode *M = cast<MemSDNode>(Op); 7976 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7977 M->getMemoryVT(), M->getMemOperand()); 7978 } 7979 7980 case Intrinsic::amdgcn_buffer_store: 7981 case Intrinsic::amdgcn_buffer_store_format: { 7982 SDValue VData = Op.getOperand(2); 7983 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7984 if (IsD16) 7985 VData = handleD16VData(VData, DAG); 7986 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7987 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7988 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7989 SDValue Ops[] = { 7990 Chain, 7991 VData, 7992 Op.getOperand(3), // rsrc 7993 Op.getOperand(4), // vindex 7994 SDValue(), // voffset -- will be set by setBufferOffsets 7995 SDValue(), // soffset -- will be set by setBufferOffsets 7996 SDValue(), // offset -- will be set by setBufferOffsets 7997 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7998 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7999 }; 8000 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8001 8002 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8003 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8004 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8005 MemSDNode *M = cast<MemSDNode>(Op); 8006 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8007 8008 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8009 EVT VDataType = VData.getValueType().getScalarType(); 8010 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8011 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8012 8013 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8014 M->getMemoryVT(), M->getMemOperand()); 8015 } 8016 8017 case Intrinsic::amdgcn_raw_buffer_store: 8018 case Intrinsic::amdgcn_raw_buffer_store_format: { 8019 const bool IsFormat = 8020 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8021 8022 SDValue VData = Op.getOperand(2); 8023 EVT VDataVT = VData.getValueType(); 8024 EVT EltType = VDataVT.getScalarType(); 8025 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8026 if (IsD16) { 8027 VData = handleD16VData(VData, DAG); 8028 VDataVT = VData.getValueType(); 8029 } 8030 8031 if (!isTypeLegal(VDataVT)) { 8032 VData = 8033 DAG.getNode(ISD::BITCAST, DL, 8034 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8035 } 8036 8037 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8038 SDValue Ops[] = { 8039 Chain, 8040 VData, 8041 Op.getOperand(3), // rsrc 8042 DAG.getConstant(0, DL, MVT::i32), // vindex 8043 Offsets.first, // voffset 8044 Op.getOperand(5), // soffset 8045 Offsets.second, // offset 8046 Op.getOperand(6), // cachepolicy, swizzled buffer 8047 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8048 }; 8049 unsigned Opc = 8050 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8051 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8052 MemSDNode *M = cast<MemSDNode>(Op); 8053 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8054 8055 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8056 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8057 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8058 8059 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8060 M->getMemoryVT(), M->getMemOperand()); 8061 } 8062 8063 case Intrinsic::amdgcn_struct_buffer_store: 8064 case Intrinsic::amdgcn_struct_buffer_store_format: { 8065 const bool IsFormat = 8066 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8067 8068 SDValue VData = Op.getOperand(2); 8069 EVT VDataVT = VData.getValueType(); 8070 EVT EltType = VDataVT.getScalarType(); 8071 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8072 8073 if (IsD16) { 8074 VData = handleD16VData(VData, DAG); 8075 VDataVT = VData.getValueType(); 8076 } 8077 8078 if (!isTypeLegal(VDataVT)) { 8079 VData = 8080 DAG.getNode(ISD::BITCAST, DL, 8081 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8082 } 8083 8084 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8085 SDValue Ops[] = { 8086 Chain, 8087 VData, 8088 Op.getOperand(3), // rsrc 8089 Op.getOperand(4), // vindex 8090 Offsets.first, // voffset 8091 Op.getOperand(6), // soffset 8092 Offsets.second, // offset 8093 Op.getOperand(7), // cachepolicy, swizzled buffer 8094 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8095 }; 8096 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8097 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8098 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8099 MemSDNode *M = cast<MemSDNode>(Op); 8100 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8101 8102 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8103 EVT VDataType = VData.getValueType().getScalarType(); 8104 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8105 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8106 8107 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8108 M->getMemoryVT(), M->getMemOperand()); 8109 } 8110 case Intrinsic::amdgcn_end_cf: 8111 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8112 Op->getOperand(2), Chain), 0); 8113 8114 default: { 8115 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8116 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8117 return lowerImage(Op, ImageDimIntr, DAG, true); 8118 8119 return Op; 8120 } 8121 } 8122 } 8123 8124 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8125 // offset (the offset that is included in bounds checking and swizzling, to be 8126 // split between the instruction's voffset and immoffset fields) and soffset 8127 // (the offset that is excluded from bounds checking and swizzling, to go in 8128 // the instruction's soffset field). This function takes the first kind of 8129 // offset and figures out how to split it between voffset and immoffset. 8130 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8131 SDValue Offset, SelectionDAG &DAG) const { 8132 SDLoc DL(Offset); 8133 const unsigned MaxImm = 4095; 8134 SDValue N0 = Offset; 8135 ConstantSDNode *C1 = nullptr; 8136 8137 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8138 N0 = SDValue(); 8139 else if (DAG.isBaseWithConstantOffset(N0)) { 8140 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8141 N0 = N0.getOperand(0); 8142 } 8143 8144 if (C1) { 8145 unsigned ImmOffset = C1->getZExtValue(); 8146 // If the immediate value is too big for the immoffset field, put the value 8147 // and -4096 into the immoffset field so that the value that is copied/added 8148 // for the voffset field is a multiple of 4096, and it stands more chance 8149 // of being CSEd with the copy/add for another similar load/store. 8150 // However, do not do that rounding down to a multiple of 4096 if that is a 8151 // negative number, as it appears to be illegal to have a negative offset 8152 // in the vgpr, even if adding the immediate offset makes it positive. 8153 unsigned Overflow = ImmOffset & ~MaxImm; 8154 ImmOffset -= Overflow; 8155 if ((int32_t)Overflow < 0) { 8156 Overflow += ImmOffset; 8157 ImmOffset = 0; 8158 } 8159 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8160 if (Overflow) { 8161 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8162 if (!N0) 8163 N0 = OverflowVal; 8164 else { 8165 SDValue Ops[] = { N0, OverflowVal }; 8166 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8167 } 8168 } 8169 } 8170 if (!N0) 8171 N0 = DAG.getConstant(0, DL, MVT::i32); 8172 if (!C1) 8173 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8174 return {N0, SDValue(C1, 0)}; 8175 } 8176 8177 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8178 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8179 // pointed to by Offsets. 8180 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8181 SelectionDAG &DAG, SDValue *Offsets, 8182 Align Alignment) const { 8183 SDLoc DL(CombinedOffset); 8184 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8185 uint32_t Imm = C->getZExtValue(); 8186 uint32_t SOffset, ImmOffset; 8187 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8188 Alignment)) { 8189 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8190 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8191 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8192 return; 8193 } 8194 } 8195 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8196 SDValue N0 = CombinedOffset.getOperand(0); 8197 SDValue N1 = CombinedOffset.getOperand(1); 8198 uint32_t SOffset, ImmOffset; 8199 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8200 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8201 Subtarget, Alignment)) { 8202 Offsets[0] = N0; 8203 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8204 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8205 return; 8206 } 8207 } 8208 Offsets[0] = CombinedOffset; 8209 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8210 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8211 } 8212 8213 // Handle 8 bit and 16 bit buffer loads 8214 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8215 EVT LoadVT, SDLoc DL, 8216 ArrayRef<SDValue> Ops, 8217 MemSDNode *M) const { 8218 EVT IntVT = LoadVT.changeTypeToInteger(); 8219 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8220 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8221 8222 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8223 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8224 Ops, IntVT, 8225 M->getMemOperand()); 8226 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8227 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8228 8229 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8230 } 8231 8232 // Handle 8 bit and 16 bit buffer stores 8233 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8234 EVT VDataType, SDLoc DL, 8235 SDValue Ops[], 8236 MemSDNode *M) const { 8237 if (VDataType == MVT::f16) 8238 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8239 8240 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8241 Ops[1] = BufferStoreExt; 8242 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8243 AMDGPUISD::BUFFER_STORE_SHORT; 8244 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8245 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8246 M->getMemOperand()); 8247 } 8248 8249 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8250 ISD::LoadExtType ExtType, SDValue Op, 8251 const SDLoc &SL, EVT VT) { 8252 if (VT.bitsLT(Op.getValueType())) 8253 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8254 8255 switch (ExtType) { 8256 case ISD::SEXTLOAD: 8257 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8258 case ISD::ZEXTLOAD: 8259 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8260 case ISD::EXTLOAD: 8261 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8262 case ISD::NON_EXTLOAD: 8263 return Op; 8264 } 8265 8266 llvm_unreachable("invalid ext type"); 8267 } 8268 8269 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8270 SelectionDAG &DAG = DCI.DAG; 8271 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8272 return SDValue(); 8273 8274 // FIXME: Constant loads should all be marked invariant. 8275 unsigned AS = Ld->getAddressSpace(); 8276 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8277 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8278 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8279 return SDValue(); 8280 8281 // Don't do this early, since it may interfere with adjacent load merging for 8282 // illegal types. We can avoid losing alignment information for exotic types 8283 // pre-legalize. 8284 EVT MemVT = Ld->getMemoryVT(); 8285 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8286 MemVT.getSizeInBits() >= 32) 8287 return SDValue(); 8288 8289 SDLoc SL(Ld); 8290 8291 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8292 "unexpected vector extload"); 8293 8294 // TODO: Drop only high part of range. 8295 SDValue Ptr = Ld->getBasePtr(); 8296 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8297 MVT::i32, SL, Ld->getChain(), Ptr, 8298 Ld->getOffset(), 8299 Ld->getPointerInfo(), MVT::i32, 8300 Ld->getAlignment(), 8301 Ld->getMemOperand()->getFlags(), 8302 Ld->getAAInfo(), 8303 nullptr); // Drop ranges 8304 8305 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8306 if (MemVT.isFloatingPoint()) { 8307 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8308 "unexpected fp extload"); 8309 TruncVT = MemVT.changeTypeToInteger(); 8310 } 8311 8312 SDValue Cvt = NewLoad; 8313 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8314 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8315 DAG.getValueType(TruncVT)); 8316 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8317 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8318 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8319 } else { 8320 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8321 } 8322 8323 EVT VT = Ld->getValueType(0); 8324 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8325 8326 DCI.AddToWorklist(Cvt.getNode()); 8327 8328 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8329 // the appropriate extension from the 32-bit load. 8330 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8331 DCI.AddToWorklist(Cvt.getNode()); 8332 8333 // Handle conversion back to floating point if necessary. 8334 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8335 8336 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8337 } 8338 8339 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8340 SDLoc DL(Op); 8341 LoadSDNode *Load = cast<LoadSDNode>(Op); 8342 ISD::LoadExtType ExtType = Load->getExtensionType(); 8343 EVT MemVT = Load->getMemoryVT(); 8344 8345 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8346 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8347 return SDValue(); 8348 8349 // FIXME: Copied from PPC 8350 // First, load into 32 bits, then truncate to 1 bit. 8351 8352 SDValue Chain = Load->getChain(); 8353 SDValue BasePtr = Load->getBasePtr(); 8354 MachineMemOperand *MMO = Load->getMemOperand(); 8355 8356 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8357 8358 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8359 BasePtr, RealMemVT, MMO); 8360 8361 if (!MemVT.isVector()) { 8362 SDValue Ops[] = { 8363 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8364 NewLD.getValue(1) 8365 }; 8366 8367 return DAG.getMergeValues(Ops, DL); 8368 } 8369 8370 SmallVector<SDValue, 3> Elts; 8371 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8372 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8373 DAG.getConstant(I, DL, MVT::i32)); 8374 8375 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8376 } 8377 8378 SDValue Ops[] = { 8379 DAG.getBuildVector(MemVT, DL, Elts), 8380 NewLD.getValue(1) 8381 }; 8382 8383 return DAG.getMergeValues(Ops, DL); 8384 } 8385 8386 if (!MemVT.isVector()) 8387 return SDValue(); 8388 8389 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8390 "Custom lowering for non-i32 vectors hasn't been implemented."); 8391 8392 unsigned Alignment = Load->getAlignment(); 8393 unsigned AS = Load->getAddressSpace(); 8394 if (Subtarget->hasLDSMisalignedBug() && 8395 AS == AMDGPUAS::FLAT_ADDRESS && 8396 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8397 return SplitVectorLoad(Op, DAG); 8398 } 8399 8400 MachineFunction &MF = DAG.getMachineFunction(); 8401 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8402 // If there is a possibility that flat instruction access scratch memory 8403 // then we need to use the same legalization rules we use for private. 8404 if (AS == AMDGPUAS::FLAT_ADDRESS && 8405 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8406 AS = MFI->hasFlatScratchInit() ? 8407 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8408 8409 unsigned NumElements = MemVT.getVectorNumElements(); 8410 8411 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8412 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8413 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8414 if (MemVT.isPow2VectorType()) 8415 return SDValue(); 8416 return WidenOrSplitVectorLoad(Op, DAG); 8417 } 8418 // Non-uniform loads will be selected to MUBUF instructions, so they 8419 // have the same legalization requirements as global and private 8420 // loads. 8421 // 8422 } 8423 8424 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8425 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8426 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8427 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8428 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8429 Alignment >= 4 && NumElements < 32) { 8430 if (MemVT.isPow2VectorType()) 8431 return SDValue(); 8432 return WidenOrSplitVectorLoad(Op, DAG); 8433 } 8434 // Non-uniform loads will be selected to MUBUF instructions, so they 8435 // have the same legalization requirements as global and private 8436 // loads. 8437 // 8438 } 8439 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8440 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8441 AS == AMDGPUAS::GLOBAL_ADDRESS || 8442 AS == AMDGPUAS::FLAT_ADDRESS) { 8443 if (NumElements > 4) 8444 return SplitVectorLoad(Op, DAG); 8445 // v3 loads not supported on SI. 8446 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8447 return WidenOrSplitVectorLoad(Op, DAG); 8448 8449 // v3 and v4 loads are supported for private and global memory. 8450 return SDValue(); 8451 } 8452 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8453 // Depending on the setting of the private_element_size field in the 8454 // resource descriptor, we can only make private accesses up to a certain 8455 // size. 8456 switch (Subtarget->getMaxPrivateElementSize()) { 8457 case 4: { 8458 SDValue Ops[2]; 8459 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8460 return DAG.getMergeValues(Ops, DL); 8461 } 8462 case 8: 8463 if (NumElements > 2) 8464 return SplitVectorLoad(Op, DAG); 8465 return SDValue(); 8466 case 16: 8467 // Same as global/flat 8468 if (NumElements > 4) 8469 return SplitVectorLoad(Op, DAG); 8470 // v3 loads not supported on SI. 8471 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8472 return WidenOrSplitVectorLoad(Op, DAG); 8473 8474 return SDValue(); 8475 default: 8476 llvm_unreachable("unsupported private_element_size"); 8477 } 8478 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8479 // Use ds_read_b128 or ds_read_b96 when possible. 8480 if (Subtarget->hasDS96AndDS128() && 8481 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8482 MemVT.getStoreSize() == 12) && 8483 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8484 Load->getAlign())) 8485 return SDValue(); 8486 8487 if (NumElements > 2) 8488 return SplitVectorLoad(Op, DAG); 8489 8490 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 8491 // address is negative, then the instruction is incorrectly treated as 8492 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8493 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8494 // load later in the SILoadStoreOptimizer. 8495 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8496 NumElements == 2 && MemVT.getStoreSize() == 8 && 8497 Load->getAlignment() < 8) { 8498 return SplitVectorLoad(Op, DAG); 8499 } 8500 } 8501 8502 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8503 MemVT, *Load->getMemOperand())) { 8504 SDValue Ops[2]; 8505 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8506 return DAG.getMergeValues(Ops, DL); 8507 } 8508 8509 return SDValue(); 8510 } 8511 8512 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8513 EVT VT = Op.getValueType(); 8514 if (VT.getSizeInBits() == 128) 8515 return splitTernaryVectorOp(Op, DAG); 8516 8517 assert(VT.getSizeInBits() == 64); 8518 8519 SDLoc DL(Op); 8520 SDValue Cond = Op.getOperand(0); 8521 8522 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8523 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8524 8525 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8526 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8527 8528 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8529 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8530 8531 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8532 8533 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8534 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8535 8536 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8537 8538 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8539 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8540 } 8541 8542 // Catch division cases where we can use shortcuts with rcp and rsq 8543 // instructions. 8544 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8545 SelectionDAG &DAG) const { 8546 SDLoc SL(Op); 8547 SDValue LHS = Op.getOperand(0); 8548 SDValue RHS = Op.getOperand(1); 8549 EVT VT = Op.getValueType(); 8550 const SDNodeFlags Flags = Op->getFlags(); 8551 8552 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8553 8554 // Without !fpmath accuracy information, we can't do more because we don't 8555 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8556 if (!AllowInaccurateRcp) 8557 return SDValue(); 8558 8559 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8560 if (CLHS->isExactlyValue(1.0)) { 8561 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8562 // the CI documentation has a worst case error of 1 ulp. 8563 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8564 // use it as long as we aren't trying to use denormals. 8565 // 8566 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8567 8568 // 1.0 / sqrt(x) -> rsq(x) 8569 8570 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8571 // error seems really high at 2^29 ULP. 8572 if (RHS.getOpcode() == ISD::FSQRT) 8573 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8574 8575 // 1.0 / x -> rcp(x) 8576 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8577 } 8578 8579 // Same as for 1.0, but expand the sign out of the constant. 8580 if (CLHS->isExactlyValue(-1.0)) { 8581 // -1.0 / x -> rcp (fneg x) 8582 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8583 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8584 } 8585 } 8586 8587 // Turn into multiply by the reciprocal. 8588 // x / y -> x * (1.0 / y) 8589 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8590 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8591 } 8592 8593 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8594 SelectionDAG &DAG) const { 8595 SDLoc SL(Op); 8596 SDValue X = Op.getOperand(0); 8597 SDValue Y = Op.getOperand(1); 8598 EVT VT = Op.getValueType(); 8599 const SDNodeFlags Flags = Op->getFlags(); 8600 8601 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8602 DAG.getTarget().Options.UnsafeFPMath; 8603 if (!AllowInaccurateDiv) 8604 return SDValue(); 8605 8606 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8607 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8608 8609 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8610 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8611 8612 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8613 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8614 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8615 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8616 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8617 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8618 } 8619 8620 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8621 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8622 SDNodeFlags Flags) { 8623 if (GlueChain->getNumValues() <= 1) { 8624 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8625 } 8626 8627 assert(GlueChain->getNumValues() == 3); 8628 8629 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8630 switch (Opcode) { 8631 default: llvm_unreachable("no chain equivalent for opcode"); 8632 case ISD::FMUL: 8633 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8634 break; 8635 } 8636 8637 return DAG.getNode(Opcode, SL, VTList, 8638 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8639 Flags); 8640 } 8641 8642 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8643 EVT VT, SDValue A, SDValue B, SDValue C, 8644 SDValue GlueChain, SDNodeFlags Flags) { 8645 if (GlueChain->getNumValues() <= 1) { 8646 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8647 } 8648 8649 assert(GlueChain->getNumValues() == 3); 8650 8651 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8652 switch (Opcode) { 8653 default: llvm_unreachable("no chain equivalent for opcode"); 8654 case ISD::FMA: 8655 Opcode = AMDGPUISD::FMA_W_CHAIN; 8656 break; 8657 } 8658 8659 return DAG.getNode(Opcode, SL, VTList, 8660 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8661 Flags); 8662 } 8663 8664 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8665 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8666 return FastLowered; 8667 8668 SDLoc SL(Op); 8669 SDValue Src0 = Op.getOperand(0); 8670 SDValue Src1 = Op.getOperand(1); 8671 8672 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8673 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8674 8675 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8676 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8677 8678 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8679 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8680 8681 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8682 } 8683 8684 // Faster 2.5 ULP division that does not support denormals. 8685 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8686 SDLoc SL(Op); 8687 SDValue LHS = Op.getOperand(1); 8688 SDValue RHS = Op.getOperand(2); 8689 8690 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8691 8692 const APFloat K0Val(BitsToFloat(0x6f800000)); 8693 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8694 8695 const APFloat K1Val(BitsToFloat(0x2f800000)); 8696 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8697 8698 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8699 8700 EVT SetCCVT = 8701 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8702 8703 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8704 8705 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8706 8707 // TODO: Should this propagate fast-math-flags? 8708 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8709 8710 // rcp does not support denormals. 8711 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8712 8713 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8714 8715 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8716 } 8717 8718 // Returns immediate value for setting the F32 denorm mode when using the 8719 // S_DENORM_MODE instruction. 8720 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8721 const SDLoc &SL, const GCNSubtarget *ST) { 8722 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8723 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8724 ? FP_DENORM_FLUSH_NONE 8725 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8726 8727 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8728 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8729 } 8730 8731 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8732 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8733 return FastLowered; 8734 8735 // The selection matcher assumes anything with a chain selecting to a 8736 // mayRaiseFPException machine instruction. Since we're introducing a chain 8737 // here, we need to explicitly report nofpexcept for the regular fdiv 8738 // lowering. 8739 SDNodeFlags Flags = Op->getFlags(); 8740 Flags.setNoFPExcept(true); 8741 8742 SDLoc SL(Op); 8743 SDValue LHS = Op.getOperand(0); 8744 SDValue RHS = Op.getOperand(1); 8745 8746 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8747 8748 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8749 8750 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8751 {RHS, RHS, LHS}, Flags); 8752 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8753 {LHS, RHS, LHS}, Flags); 8754 8755 // Denominator is scaled to not be denormal, so using rcp is ok. 8756 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8757 DenominatorScaled, Flags); 8758 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8759 DenominatorScaled, Flags); 8760 8761 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8762 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8763 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8764 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8765 8766 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8767 8768 if (!HasFP32Denormals) { 8769 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8770 // lowering. The chain dependence is insufficient, and we need glue. We do 8771 // not need the glue variants in a strictfp function. 8772 8773 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8774 8775 SDNode *EnableDenorm; 8776 if (Subtarget->hasDenormModeInst()) { 8777 const SDValue EnableDenormValue = 8778 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8779 8780 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8781 DAG.getEntryNode(), EnableDenormValue).getNode(); 8782 } else { 8783 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8784 SL, MVT::i32); 8785 EnableDenorm = 8786 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8787 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8788 } 8789 8790 SDValue Ops[3] = { 8791 NegDivScale0, 8792 SDValue(EnableDenorm, 0), 8793 SDValue(EnableDenorm, 1) 8794 }; 8795 8796 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8797 } 8798 8799 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8800 ApproxRcp, One, NegDivScale0, Flags); 8801 8802 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8803 ApproxRcp, Fma0, Flags); 8804 8805 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8806 Fma1, Fma1, Flags); 8807 8808 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8809 NumeratorScaled, Mul, Flags); 8810 8811 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8812 Fma2, Fma1, Mul, Fma2, Flags); 8813 8814 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8815 NumeratorScaled, Fma3, Flags); 8816 8817 if (!HasFP32Denormals) { 8818 SDNode *DisableDenorm; 8819 if (Subtarget->hasDenormModeInst()) { 8820 const SDValue DisableDenormValue = 8821 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8822 8823 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8824 Fma4.getValue(1), DisableDenormValue, 8825 Fma4.getValue(2)).getNode(); 8826 } else { 8827 const SDValue DisableDenormValue = 8828 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8829 8830 DisableDenorm = DAG.getMachineNode( 8831 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8832 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8833 } 8834 8835 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8836 SDValue(DisableDenorm, 0), DAG.getRoot()); 8837 DAG.setRoot(OutputChain); 8838 } 8839 8840 SDValue Scale = NumeratorScaled.getValue(1); 8841 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8842 {Fma4, Fma1, Fma3, Scale}, Flags); 8843 8844 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8845 } 8846 8847 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8848 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8849 return FastLowered; 8850 8851 SDLoc SL(Op); 8852 SDValue X = Op.getOperand(0); 8853 SDValue Y = Op.getOperand(1); 8854 8855 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8856 8857 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8858 8859 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8860 8861 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8862 8863 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8864 8865 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8866 8867 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8868 8869 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8870 8871 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8872 8873 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8874 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8875 8876 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8877 NegDivScale0, Mul, DivScale1); 8878 8879 SDValue Scale; 8880 8881 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8882 // Workaround a hardware bug on SI where the condition output from div_scale 8883 // is not usable. 8884 8885 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8886 8887 // Figure out if the scale to use for div_fmas. 8888 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8889 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8890 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8891 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8892 8893 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8894 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8895 8896 SDValue Scale0Hi 8897 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8898 SDValue Scale1Hi 8899 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8900 8901 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8902 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8903 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8904 } else { 8905 Scale = DivScale1.getValue(1); 8906 } 8907 8908 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8909 Fma4, Fma3, Mul, Scale); 8910 8911 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8912 } 8913 8914 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8915 EVT VT = Op.getValueType(); 8916 8917 if (VT == MVT::f32) 8918 return LowerFDIV32(Op, DAG); 8919 8920 if (VT == MVT::f64) 8921 return LowerFDIV64(Op, DAG); 8922 8923 if (VT == MVT::f16) 8924 return LowerFDIV16(Op, DAG); 8925 8926 llvm_unreachable("Unexpected type for fdiv"); 8927 } 8928 8929 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8930 SDLoc DL(Op); 8931 StoreSDNode *Store = cast<StoreSDNode>(Op); 8932 EVT VT = Store->getMemoryVT(); 8933 8934 if (VT == MVT::i1) { 8935 return DAG.getTruncStore(Store->getChain(), DL, 8936 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8937 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8938 } 8939 8940 assert(VT.isVector() && 8941 Store->getValue().getValueType().getScalarType() == MVT::i32); 8942 8943 unsigned AS = Store->getAddressSpace(); 8944 if (Subtarget->hasLDSMisalignedBug() && 8945 AS == AMDGPUAS::FLAT_ADDRESS && 8946 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8947 return SplitVectorStore(Op, DAG); 8948 } 8949 8950 MachineFunction &MF = DAG.getMachineFunction(); 8951 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8952 // If there is a possibility that flat instruction access scratch memory 8953 // then we need to use the same legalization rules we use for private. 8954 if (AS == AMDGPUAS::FLAT_ADDRESS && 8955 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8956 AS = MFI->hasFlatScratchInit() ? 8957 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8958 8959 unsigned NumElements = VT.getVectorNumElements(); 8960 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8961 AS == AMDGPUAS::FLAT_ADDRESS) { 8962 if (NumElements > 4) 8963 return SplitVectorStore(Op, DAG); 8964 // v3 stores not supported on SI. 8965 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8966 return SplitVectorStore(Op, DAG); 8967 8968 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8969 VT, *Store->getMemOperand())) 8970 return expandUnalignedStore(Store, DAG); 8971 8972 return SDValue(); 8973 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8974 switch (Subtarget->getMaxPrivateElementSize()) { 8975 case 4: 8976 return scalarizeVectorStore(Store, DAG); 8977 case 8: 8978 if (NumElements > 2) 8979 return SplitVectorStore(Op, DAG); 8980 return SDValue(); 8981 case 16: 8982 if (NumElements > 4 || 8983 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8984 return SplitVectorStore(Op, DAG); 8985 return SDValue(); 8986 default: 8987 llvm_unreachable("unsupported private_element_size"); 8988 } 8989 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8990 // Use ds_write_b128 or ds_write_b96 when possible. 8991 if (Subtarget->hasDS96AndDS128() && 8992 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8993 (VT.getStoreSize() == 12)) && 8994 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8995 Store->getAlign())) 8996 return SDValue(); 8997 8998 if (NumElements > 2) 8999 return SplitVectorStore(Op, DAG); 9000 9001 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 9002 // address is negative, then the instruction is incorrectly treated as 9003 // out-of-bounds even if base + offsets is in bounds. Split vectorized 9004 // stores here to avoid emitting ds_write2_b32. We may re-combine the 9005 // store later in the SILoadStoreOptimizer. 9006 if (!Subtarget->hasUsableDSOffset() && 9007 NumElements == 2 && VT.getStoreSize() == 8 && 9008 Store->getAlignment() < 8) { 9009 return SplitVectorStore(Op, DAG); 9010 } 9011 9012 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9013 VT, *Store->getMemOperand())) { 9014 if (VT.isVector()) 9015 return SplitVectorStore(Op, DAG); 9016 return expandUnalignedStore(Store, DAG); 9017 } 9018 9019 return SDValue(); 9020 } else { 9021 llvm_unreachable("unhandled address space"); 9022 } 9023 } 9024 9025 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9026 SDLoc DL(Op); 9027 EVT VT = Op.getValueType(); 9028 SDValue Arg = Op.getOperand(0); 9029 SDValue TrigVal; 9030 9031 // Propagate fast-math flags so that the multiply we introduce can be folded 9032 // if Arg is already the result of a multiply by constant. 9033 auto Flags = Op->getFlags(); 9034 9035 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9036 9037 if (Subtarget->hasTrigReducedRange()) { 9038 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9039 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9040 } else { 9041 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9042 } 9043 9044 switch (Op.getOpcode()) { 9045 case ISD::FCOS: 9046 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9047 case ISD::FSIN: 9048 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9049 default: 9050 llvm_unreachable("Wrong trig opcode"); 9051 } 9052 } 9053 9054 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9055 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9056 assert(AtomicNode->isCompareAndSwap()); 9057 unsigned AS = AtomicNode->getAddressSpace(); 9058 9059 // No custom lowering required for local address space 9060 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9061 return Op; 9062 9063 // Non-local address space requires custom lowering for atomic compare 9064 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9065 SDLoc DL(Op); 9066 SDValue ChainIn = Op.getOperand(0); 9067 SDValue Addr = Op.getOperand(1); 9068 SDValue Old = Op.getOperand(2); 9069 SDValue New = Op.getOperand(3); 9070 EVT VT = Op.getValueType(); 9071 MVT SimpleVT = VT.getSimpleVT(); 9072 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9073 9074 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9075 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9076 9077 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9078 Ops, VT, AtomicNode->getMemOperand()); 9079 } 9080 9081 //===----------------------------------------------------------------------===// 9082 // Custom DAG optimizations 9083 //===----------------------------------------------------------------------===// 9084 9085 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9086 DAGCombinerInfo &DCI) const { 9087 EVT VT = N->getValueType(0); 9088 EVT ScalarVT = VT.getScalarType(); 9089 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9090 return SDValue(); 9091 9092 SelectionDAG &DAG = DCI.DAG; 9093 SDLoc DL(N); 9094 9095 SDValue Src = N->getOperand(0); 9096 EVT SrcVT = Src.getValueType(); 9097 9098 // TODO: We could try to match extracting the higher bytes, which would be 9099 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9100 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9101 // about in practice. 9102 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9103 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9104 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9105 DCI.AddToWorklist(Cvt.getNode()); 9106 9107 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9108 if (ScalarVT != MVT::f32) { 9109 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9110 DAG.getTargetConstant(0, DL, MVT::i32)); 9111 } 9112 return Cvt; 9113 } 9114 } 9115 9116 return SDValue(); 9117 } 9118 9119 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9120 9121 // This is a variant of 9122 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9123 // 9124 // The normal DAG combiner will do this, but only if the add has one use since 9125 // that would increase the number of instructions. 9126 // 9127 // This prevents us from seeing a constant offset that can be folded into a 9128 // memory instruction's addressing mode. If we know the resulting add offset of 9129 // a pointer can be folded into an addressing offset, we can replace the pointer 9130 // operand with the add of new constant offset. This eliminates one of the uses, 9131 // and may allow the remaining use to also be simplified. 9132 // 9133 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9134 unsigned AddrSpace, 9135 EVT MemVT, 9136 DAGCombinerInfo &DCI) const { 9137 SDValue N0 = N->getOperand(0); 9138 SDValue N1 = N->getOperand(1); 9139 9140 // We only do this to handle cases where it's profitable when there are 9141 // multiple uses of the add, so defer to the standard combine. 9142 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9143 N0->hasOneUse()) 9144 return SDValue(); 9145 9146 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9147 if (!CN1) 9148 return SDValue(); 9149 9150 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9151 if (!CAdd) 9152 return SDValue(); 9153 9154 // If the resulting offset is too large, we can't fold it into the addressing 9155 // mode offset. 9156 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9157 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9158 9159 AddrMode AM; 9160 AM.HasBaseReg = true; 9161 AM.BaseOffs = Offset.getSExtValue(); 9162 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9163 return SDValue(); 9164 9165 SelectionDAG &DAG = DCI.DAG; 9166 SDLoc SL(N); 9167 EVT VT = N->getValueType(0); 9168 9169 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9170 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9171 9172 SDNodeFlags Flags; 9173 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9174 (N0.getOpcode() == ISD::OR || 9175 N0->getFlags().hasNoUnsignedWrap())); 9176 9177 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9178 } 9179 9180 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9181 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9182 /// specific intrinsic, but they all place the pointer operand first. 9183 static unsigned getBasePtrIndex(const MemSDNode *N) { 9184 switch (N->getOpcode()) { 9185 case ISD::STORE: 9186 case ISD::INTRINSIC_W_CHAIN: 9187 case ISD::INTRINSIC_VOID: 9188 return 2; 9189 default: 9190 return 1; 9191 } 9192 } 9193 9194 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9195 DAGCombinerInfo &DCI) const { 9196 SelectionDAG &DAG = DCI.DAG; 9197 SDLoc SL(N); 9198 9199 unsigned PtrIdx = getBasePtrIndex(N); 9200 SDValue Ptr = N->getOperand(PtrIdx); 9201 9202 // TODO: We could also do this for multiplies. 9203 if (Ptr.getOpcode() == ISD::SHL) { 9204 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9205 N->getMemoryVT(), DCI); 9206 if (NewPtr) { 9207 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9208 9209 NewOps[PtrIdx] = NewPtr; 9210 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9211 } 9212 } 9213 9214 return SDValue(); 9215 } 9216 9217 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9218 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9219 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9220 (Opc == ISD::XOR && Val == 0); 9221 } 9222 9223 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9224 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9225 // integer combine opportunities since most 64-bit operations are decomposed 9226 // this way. TODO: We won't want this for SALU especially if it is an inline 9227 // immediate. 9228 SDValue SITargetLowering::splitBinaryBitConstantOp( 9229 DAGCombinerInfo &DCI, 9230 const SDLoc &SL, 9231 unsigned Opc, SDValue LHS, 9232 const ConstantSDNode *CRHS) const { 9233 uint64_t Val = CRHS->getZExtValue(); 9234 uint32_t ValLo = Lo_32(Val); 9235 uint32_t ValHi = Hi_32(Val); 9236 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9237 9238 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9239 bitOpWithConstantIsReducible(Opc, ValHi)) || 9240 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9241 // If we need to materialize a 64-bit immediate, it will be split up later 9242 // anyway. Avoid creating the harder to understand 64-bit immediate 9243 // materialization. 9244 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9245 } 9246 9247 return SDValue(); 9248 } 9249 9250 // Returns true if argument is a boolean value which is not serialized into 9251 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9252 static bool isBoolSGPR(SDValue V) { 9253 if (V.getValueType() != MVT::i1) 9254 return false; 9255 switch (V.getOpcode()) { 9256 default: 9257 break; 9258 case ISD::SETCC: 9259 case AMDGPUISD::FP_CLASS: 9260 return true; 9261 case ISD::AND: 9262 case ISD::OR: 9263 case ISD::XOR: 9264 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9265 } 9266 return false; 9267 } 9268 9269 // If a constant has all zeroes or all ones within each byte return it. 9270 // Otherwise return 0. 9271 static uint32_t getConstantPermuteMask(uint32_t C) { 9272 // 0xff for any zero byte in the mask 9273 uint32_t ZeroByteMask = 0; 9274 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9275 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9276 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9277 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9278 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9279 if ((NonZeroByteMask & C) != NonZeroByteMask) 9280 return 0; // Partial bytes selected. 9281 return C; 9282 } 9283 9284 // Check if a node selects whole bytes from its operand 0 starting at a byte 9285 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9286 // or -1 if not succeeded. 9287 // Note byte select encoding: 9288 // value 0-3 selects corresponding source byte; 9289 // value 0xc selects zero; 9290 // value 0xff selects 0xff. 9291 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9292 assert(V.getValueSizeInBits() == 32); 9293 9294 if (V.getNumOperands() != 2) 9295 return ~0; 9296 9297 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9298 if (!N1) 9299 return ~0; 9300 9301 uint32_t C = N1->getZExtValue(); 9302 9303 switch (V.getOpcode()) { 9304 default: 9305 break; 9306 case ISD::AND: 9307 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9308 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9309 } 9310 break; 9311 9312 case ISD::OR: 9313 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9314 return (0x03020100 & ~ConstMask) | ConstMask; 9315 } 9316 break; 9317 9318 case ISD::SHL: 9319 if (C % 8) 9320 return ~0; 9321 9322 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9323 9324 case ISD::SRL: 9325 if (C % 8) 9326 return ~0; 9327 9328 return uint32_t(0x0c0c0c0c03020100ull >> C); 9329 } 9330 9331 return ~0; 9332 } 9333 9334 SDValue SITargetLowering::performAndCombine(SDNode *N, 9335 DAGCombinerInfo &DCI) const { 9336 if (DCI.isBeforeLegalize()) 9337 return SDValue(); 9338 9339 SelectionDAG &DAG = DCI.DAG; 9340 EVT VT = N->getValueType(0); 9341 SDValue LHS = N->getOperand(0); 9342 SDValue RHS = N->getOperand(1); 9343 9344 9345 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9346 if (VT == MVT::i64 && CRHS) { 9347 if (SDValue Split 9348 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9349 return Split; 9350 } 9351 9352 if (CRHS && VT == MVT::i32) { 9353 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9354 // nb = number of trailing zeroes in mask 9355 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9356 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9357 uint64_t Mask = CRHS->getZExtValue(); 9358 unsigned Bits = countPopulation(Mask); 9359 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9360 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9361 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9362 unsigned Shift = CShift->getZExtValue(); 9363 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9364 unsigned Offset = NB + Shift; 9365 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9366 SDLoc SL(N); 9367 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9368 LHS->getOperand(0), 9369 DAG.getConstant(Offset, SL, MVT::i32), 9370 DAG.getConstant(Bits, SL, MVT::i32)); 9371 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9372 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9373 DAG.getValueType(NarrowVT)); 9374 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9375 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9376 return Shl; 9377 } 9378 } 9379 } 9380 9381 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9382 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9383 isa<ConstantSDNode>(LHS.getOperand(2))) { 9384 uint32_t Sel = getConstantPermuteMask(Mask); 9385 if (!Sel) 9386 return SDValue(); 9387 9388 // Select 0xc for all zero bytes 9389 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9390 SDLoc DL(N); 9391 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9392 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9393 } 9394 } 9395 9396 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9397 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9398 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9399 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9400 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9401 9402 SDValue X = LHS.getOperand(0); 9403 SDValue Y = RHS.getOperand(0); 9404 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9405 return SDValue(); 9406 9407 if (LCC == ISD::SETO) { 9408 if (X != LHS.getOperand(1)) 9409 return SDValue(); 9410 9411 if (RCC == ISD::SETUNE) { 9412 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9413 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9414 return SDValue(); 9415 9416 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9417 SIInstrFlags::N_SUBNORMAL | 9418 SIInstrFlags::N_ZERO | 9419 SIInstrFlags::P_ZERO | 9420 SIInstrFlags::P_SUBNORMAL | 9421 SIInstrFlags::P_NORMAL; 9422 9423 static_assert(((~(SIInstrFlags::S_NAN | 9424 SIInstrFlags::Q_NAN | 9425 SIInstrFlags::N_INFINITY | 9426 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9427 "mask not equal"); 9428 9429 SDLoc DL(N); 9430 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9431 X, DAG.getConstant(Mask, DL, MVT::i32)); 9432 } 9433 } 9434 } 9435 9436 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9437 std::swap(LHS, RHS); 9438 9439 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9440 RHS.hasOneUse()) { 9441 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9442 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9443 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9444 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9445 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9446 (RHS.getOperand(0) == LHS.getOperand(0) && 9447 LHS.getOperand(0) == LHS.getOperand(1))) { 9448 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9449 unsigned NewMask = LCC == ISD::SETO ? 9450 Mask->getZExtValue() & ~OrdMask : 9451 Mask->getZExtValue() & OrdMask; 9452 9453 SDLoc DL(N); 9454 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9455 DAG.getConstant(NewMask, DL, MVT::i32)); 9456 } 9457 } 9458 9459 if (VT == MVT::i32 && 9460 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9461 // and x, (sext cc from i1) => select cc, x, 0 9462 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9463 std::swap(LHS, RHS); 9464 if (isBoolSGPR(RHS.getOperand(0))) 9465 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9466 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9467 } 9468 9469 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9470 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9471 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9472 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9473 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9474 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9475 if (LHSMask != ~0u && RHSMask != ~0u) { 9476 // Canonicalize the expression in an attempt to have fewer unique masks 9477 // and therefore fewer registers used to hold the masks. 9478 if (LHSMask > RHSMask) { 9479 std::swap(LHSMask, RHSMask); 9480 std::swap(LHS, RHS); 9481 } 9482 9483 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9484 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9485 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9486 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9487 9488 // Check of we need to combine values from two sources within a byte. 9489 if (!(LHSUsedLanes & RHSUsedLanes) && 9490 // If we select high and lower word keep it for SDWA. 9491 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9492 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9493 // Each byte in each mask is either selector mask 0-3, or has higher 9494 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9495 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9496 // mask which is not 0xff wins. By anding both masks we have a correct 9497 // result except that 0x0c shall be corrected to give 0x0c only. 9498 uint32_t Mask = LHSMask & RHSMask; 9499 for (unsigned I = 0; I < 32; I += 8) { 9500 uint32_t ByteSel = 0xff << I; 9501 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9502 Mask &= (0x0c << I) & 0xffffffff; 9503 } 9504 9505 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9506 // or 0x0c. 9507 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9508 SDLoc DL(N); 9509 9510 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9511 LHS.getOperand(0), RHS.getOperand(0), 9512 DAG.getConstant(Sel, DL, MVT::i32)); 9513 } 9514 } 9515 } 9516 9517 return SDValue(); 9518 } 9519 9520 SDValue SITargetLowering::performOrCombine(SDNode *N, 9521 DAGCombinerInfo &DCI) const { 9522 SelectionDAG &DAG = DCI.DAG; 9523 SDValue LHS = N->getOperand(0); 9524 SDValue RHS = N->getOperand(1); 9525 9526 EVT VT = N->getValueType(0); 9527 if (VT == MVT::i1) { 9528 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9529 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9530 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9531 SDValue Src = LHS.getOperand(0); 9532 if (Src != RHS.getOperand(0)) 9533 return SDValue(); 9534 9535 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9536 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9537 if (!CLHS || !CRHS) 9538 return SDValue(); 9539 9540 // Only 10 bits are used. 9541 static const uint32_t MaxMask = 0x3ff; 9542 9543 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9544 SDLoc DL(N); 9545 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9546 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9547 } 9548 9549 return SDValue(); 9550 } 9551 9552 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9553 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9554 LHS.getOpcode() == AMDGPUISD::PERM && 9555 isa<ConstantSDNode>(LHS.getOperand(2))) { 9556 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9557 if (!Sel) 9558 return SDValue(); 9559 9560 Sel |= LHS.getConstantOperandVal(2); 9561 SDLoc DL(N); 9562 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9563 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9564 } 9565 9566 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9567 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9568 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9569 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9570 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9571 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9572 if (LHSMask != ~0u && RHSMask != ~0u) { 9573 // Canonicalize the expression in an attempt to have fewer unique masks 9574 // and therefore fewer registers used to hold the masks. 9575 if (LHSMask > RHSMask) { 9576 std::swap(LHSMask, RHSMask); 9577 std::swap(LHS, RHS); 9578 } 9579 9580 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9581 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9582 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9583 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9584 9585 // Check of we need to combine values from two sources within a byte. 9586 if (!(LHSUsedLanes & RHSUsedLanes) && 9587 // If we select high and lower word keep it for SDWA. 9588 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9589 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9590 // Kill zero bytes selected by other mask. Zero value is 0xc. 9591 LHSMask &= ~RHSUsedLanes; 9592 RHSMask &= ~LHSUsedLanes; 9593 // Add 4 to each active LHS lane 9594 LHSMask |= LHSUsedLanes & 0x04040404; 9595 // Combine masks 9596 uint32_t Sel = LHSMask | RHSMask; 9597 SDLoc DL(N); 9598 9599 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9600 LHS.getOperand(0), RHS.getOperand(0), 9601 DAG.getConstant(Sel, DL, MVT::i32)); 9602 } 9603 } 9604 } 9605 9606 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9607 return SDValue(); 9608 9609 // TODO: This could be a generic combine with a predicate for extracting the 9610 // high half of an integer being free. 9611 9612 // (or i64:x, (zero_extend i32:y)) -> 9613 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9614 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9615 RHS.getOpcode() != ISD::ZERO_EXTEND) 9616 std::swap(LHS, RHS); 9617 9618 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9619 SDValue ExtSrc = RHS.getOperand(0); 9620 EVT SrcVT = ExtSrc.getValueType(); 9621 if (SrcVT == MVT::i32) { 9622 SDLoc SL(N); 9623 SDValue LowLHS, HiBits; 9624 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9625 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9626 9627 DCI.AddToWorklist(LowOr.getNode()); 9628 DCI.AddToWorklist(HiBits.getNode()); 9629 9630 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9631 LowOr, HiBits); 9632 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9633 } 9634 } 9635 9636 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9637 if (CRHS) { 9638 if (SDValue Split 9639 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9640 N->getOperand(0), CRHS)) 9641 return Split; 9642 } 9643 9644 return SDValue(); 9645 } 9646 9647 SDValue SITargetLowering::performXorCombine(SDNode *N, 9648 DAGCombinerInfo &DCI) const { 9649 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9650 return RV; 9651 9652 EVT VT = N->getValueType(0); 9653 if (VT != MVT::i64) 9654 return SDValue(); 9655 9656 SDValue LHS = N->getOperand(0); 9657 SDValue RHS = N->getOperand(1); 9658 9659 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9660 if (CRHS) { 9661 if (SDValue Split 9662 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9663 return Split; 9664 } 9665 9666 return SDValue(); 9667 } 9668 9669 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9670 DAGCombinerInfo &DCI) const { 9671 if (!Subtarget->has16BitInsts() || 9672 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9673 return SDValue(); 9674 9675 EVT VT = N->getValueType(0); 9676 if (VT != MVT::i32) 9677 return SDValue(); 9678 9679 SDValue Src = N->getOperand(0); 9680 if (Src.getValueType() != MVT::i16) 9681 return SDValue(); 9682 9683 return SDValue(); 9684 } 9685 9686 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9687 DAGCombinerInfo &DCI) 9688 const { 9689 SDValue Src = N->getOperand(0); 9690 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9691 9692 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9693 VTSign->getVT() == MVT::i8) || 9694 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9695 VTSign->getVT() == MVT::i16)) && 9696 Src.hasOneUse()) { 9697 auto *M = cast<MemSDNode>(Src); 9698 SDValue Ops[] = { 9699 Src.getOperand(0), // Chain 9700 Src.getOperand(1), // rsrc 9701 Src.getOperand(2), // vindex 9702 Src.getOperand(3), // voffset 9703 Src.getOperand(4), // soffset 9704 Src.getOperand(5), // offset 9705 Src.getOperand(6), 9706 Src.getOperand(7) 9707 }; 9708 // replace with BUFFER_LOAD_BYTE/SHORT 9709 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9710 Src.getOperand(0).getValueType()); 9711 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9712 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9713 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9714 ResList, 9715 Ops, M->getMemoryVT(), 9716 M->getMemOperand()); 9717 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9718 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9719 } 9720 return SDValue(); 9721 } 9722 9723 SDValue SITargetLowering::performClassCombine(SDNode *N, 9724 DAGCombinerInfo &DCI) const { 9725 SelectionDAG &DAG = DCI.DAG; 9726 SDValue Mask = N->getOperand(1); 9727 9728 // fp_class x, 0 -> false 9729 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9730 if (CMask->isZero()) 9731 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9732 } 9733 9734 if (N->getOperand(0).isUndef()) 9735 return DAG.getUNDEF(MVT::i1); 9736 9737 return SDValue(); 9738 } 9739 9740 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9741 DAGCombinerInfo &DCI) const { 9742 EVT VT = N->getValueType(0); 9743 SDValue N0 = N->getOperand(0); 9744 9745 if (N0.isUndef()) 9746 return N0; 9747 9748 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9749 N0.getOpcode() == ISD::SINT_TO_FP)) { 9750 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9751 N->getFlags()); 9752 } 9753 9754 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9755 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9756 N0.getOperand(0), N->getFlags()); 9757 } 9758 9759 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9760 } 9761 9762 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9763 unsigned MaxDepth) const { 9764 unsigned Opcode = Op.getOpcode(); 9765 if (Opcode == ISD::FCANONICALIZE) 9766 return true; 9767 9768 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9769 auto F = CFP->getValueAPF(); 9770 if (F.isNaN() && F.isSignaling()) 9771 return false; 9772 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9773 } 9774 9775 // If source is a result of another standard FP operation it is already in 9776 // canonical form. 9777 if (MaxDepth == 0) 9778 return false; 9779 9780 switch (Opcode) { 9781 // These will flush denorms if required. 9782 case ISD::FADD: 9783 case ISD::FSUB: 9784 case ISD::FMUL: 9785 case ISD::FCEIL: 9786 case ISD::FFLOOR: 9787 case ISD::FMA: 9788 case ISD::FMAD: 9789 case ISD::FSQRT: 9790 case ISD::FDIV: 9791 case ISD::FREM: 9792 case ISD::FP_ROUND: 9793 case ISD::FP_EXTEND: 9794 case AMDGPUISD::FMUL_LEGACY: 9795 case AMDGPUISD::FMAD_FTZ: 9796 case AMDGPUISD::RCP: 9797 case AMDGPUISD::RSQ: 9798 case AMDGPUISD::RSQ_CLAMP: 9799 case AMDGPUISD::RCP_LEGACY: 9800 case AMDGPUISD::RCP_IFLAG: 9801 case AMDGPUISD::DIV_SCALE: 9802 case AMDGPUISD::DIV_FMAS: 9803 case AMDGPUISD::DIV_FIXUP: 9804 case AMDGPUISD::FRACT: 9805 case AMDGPUISD::LDEXP: 9806 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9807 case AMDGPUISD::CVT_F32_UBYTE0: 9808 case AMDGPUISD::CVT_F32_UBYTE1: 9809 case AMDGPUISD::CVT_F32_UBYTE2: 9810 case AMDGPUISD::CVT_F32_UBYTE3: 9811 return true; 9812 9813 // It can/will be lowered or combined as a bit operation. 9814 // Need to check their input recursively to handle. 9815 case ISD::FNEG: 9816 case ISD::FABS: 9817 case ISD::FCOPYSIGN: 9818 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9819 9820 case ISD::FSIN: 9821 case ISD::FCOS: 9822 case ISD::FSINCOS: 9823 return Op.getValueType().getScalarType() != MVT::f16; 9824 9825 case ISD::FMINNUM: 9826 case ISD::FMAXNUM: 9827 case ISD::FMINNUM_IEEE: 9828 case ISD::FMAXNUM_IEEE: 9829 case AMDGPUISD::CLAMP: 9830 case AMDGPUISD::FMED3: 9831 case AMDGPUISD::FMAX3: 9832 case AMDGPUISD::FMIN3: { 9833 // FIXME: Shouldn't treat the generic operations different based these. 9834 // However, we aren't really required to flush the result from 9835 // minnum/maxnum.. 9836 9837 // snans will be quieted, so we only need to worry about denormals. 9838 if (Subtarget->supportsMinMaxDenormModes() || 9839 denormalsEnabledForType(DAG, Op.getValueType())) 9840 return true; 9841 9842 // Flushing may be required. 9843 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9844 // targets need to check their input recursively. 9845 9846 // FIXME: Does this apply with clamp? It's implemented with max. 9847 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9848 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9849 return false; 9850 } 9851 9852 return true; 9853 } 9854 case ISD::SELECT: { 9855 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9856 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9857 } 9858 case ISD::BUILD_VECTOR: { 9859 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9860 SDValue SrcOp = Op.getOperand(i); 9861 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9862 return false; 9863 } 9864 9865 return true; 9866 } 9867 case ISD::EXTRACT_VECTOR_ELT: 9868 case ISD::EXTRACT_SUBVECTOR: { 9869 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9870 } 9871 case ISD::INSERT_VECTOR_ELT: { 9872 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9873 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9874 } 9875 case ISD::UNDEF: 9876 // Could be anything. 9877 return false; 9878 9879 case ISD::BITCAST: 9880 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9881 case ISD::TRUNCATE: { 9882 // Hack round the mess we make when legalizing extract_vector_elt 9883 if (Op.getValueType() == MVT::i16) { 9884 SDValue TruncSrc = Op.getOperand(0); 9885 if (TruncSrc.getValueType() == MVT::i32 && 9886 TruncSrc.getOpcode() == ISD::BITCAST && 9887 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9888 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9889 } 9890 } 9891 return false; 9892 } 9893 case ISD::INTRINSIC_WO_CHAIN: { 9894 unsigned IntrinsicID 9895 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9896 // TODO: Handle more intrinsics 9897 switch (IntrinsicID) { 9898 case Intrinsic::amdgcn_cvt_pkrtz: 9899 case Intrinsic::amdgcn_cubeid: 9900 case Intrinsic::amdgcn_frexp_mant: 9901 case Intrinsic::amdgcn_fdot2: 9902 case Intrinsic::amdgcn_rcp: 9903 case Intrinsic::amdgcn_rsq: 9904 case Intrinsic::amdgcn_rsq_clamp: 9905 case Intrinsic::amdgcn_rcp_legacy: 9906 case Intrinsic::amdgcn_rsq_legacy: 9907 case Intrinsic::amdgcn_trig_preop: 9908 return true; 9909 default: 9910 break; 9911 } 9912 9913 LLVM_FALLTHROUGH; 9914 } 9915 default: 9916 return denormalsEnabledForType(DAG, Op.getValueType()) && 9917 DAG.isKnownNeverSNaN(Op); 9918 } 9919 9920 llvm_unreachable("invalid operation"); 9921 } 9922 9923 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9924 unsigned MaxDepth) const { 9925 MachineRegisterInfo &MRI = MF.getRegInfo(); 9926 MachineInstr *MI = MRI.getVRegDef(Reg); 9927 unsigned Opcode = MI->getOpcode(); 9928 9929 if (Opcode == AMDGPU::G_FCANONICALIZE) 9930 return true; 9931 9932 Optional<FPValueAndVReg> FCR; 9933 // Constant splat (can be padded with undef) or scalar constant. 9934 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9935 if (FCR->Value.isSignaling()) 9936 return false; 9937 return !FCR->Value.isDenormal() || 9938 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 9939 } 9940 9941 if (MaxDepth == 0) 9942 return false; 9943 9944 switch (Opcode) { 9945 case AMDGPU::G_FMINNUM_IEEE: 9946 case AMDGPU::G_FMAXNUM_IEEE: { 9947 if (Subtarget->supportsMinMaxDenormModes() || 9948 denormalsEnabledForType(MRI.getType(Reg), MF)) 9949 return true; 9950 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 9951 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 9952 return false; 9953 return true; 9954 } 9955 default: 9956 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9957 isKnownNeverSNaN(Reg, MRI); 9958 } 9959 9960 llvm_unreachable("invalid operation"); 9961 } 9962 9963 // Constant fold canonicalize. 9964 SDValue SITargetLowering::getCanonicalConstantFP( 9965 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9966 // Flush denormals to 0 if not enabled. 9967 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9968 return DAG.getConstantFP(0.0, SL, VT); 9969 9970 if (C.isNaN()) { 9971 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9972 if (C.isSignaling()) { 9973 // Quiet a signaling NaN. 9974 // FIXME: Is this supposed to preserve payload bits? 9975 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9976 } 9977 9978 // Make sure it is the canonical NaN bitpattern. 9979 // 9980 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9981 // immediate? 9982 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9983 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9984 } 9985 9986 // Already canonical. 9987 return DAG.getConstantFP(C, SL, VT); 9988 } 9989 9990 static bool vectorEltWillFoldAway(SDValue Op) { 9991 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9992 } 9993 9994 SDValue SITargetLowering::performFCanonicalizeCombine( 9995 SDNode *N, 9996 DAGCombinerInfo &DCI) const { 9997 SelectionDAG &DAG = DCI.DAG; 9998 SDValue N0 = N->getOperand(0); 9999 EVT VT = N->getValueType(0); 10000 10001 // fcanonicalize undef -> qnan 10002 if (N0.isUndef()) { 10003 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10004 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10005 } 10006 10007 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10008 EVT VT = N->getValueType(0); 10009 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10010 } 10011 10012 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10013 // (fcanonicalize k) 10014 // 10015 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10016 10017 // TODO: This could be better with wider vectors that will be split to v2f16, 10018 // and to consider uses since there aren't that many packed operations. 10019 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10020 isTypeLegal(MVT::v2f16)) { 10021 SDLoc SL(N); 10022 SDValue NewElts[2]; 10023 SDValue Lo = N0.getOperand(0); 10024 SDValue Hi = N0.getOperand(1); 10025 EVT EltVT = Lo.getValueType(); 10026 10027 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10028 for (unsigned I = 0; I != 2; ++I) { 10029 SDValue Op = N0.getOperand(I); 10030 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10031 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10032 CFP->getValueAPF()); 10033 } else if (Op.isUndef()) { 10034 // Handled below based on what the other operand is. 10035 NewElts[I] = Op; 10036 } else { 10037 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10038 } 10039 } 10040 10041 // If one half is undef, and one is constant, prefer a splat vector rather 10042 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10043 // cheaper to use and may be free with a packed operation. 10044 if (NewElts[0].isUndef()) { 10045 if (isa<ConstantFPSDNode>(NewElts[1])) 10046 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10047 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10048 } 10049 10050 if (NewElts[1].isUndef()) { 10051 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10052 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10053 } 10054 10055 return DAG.getBuildVector(VT, SL, NewElts); 10056 } 10057 } 10058 10059 unsigned SrcOpc = N0.getOpcode(); 10060 10061 // If it's free to do so, push canonicalizes further up the source, which may 10062 // find a canonical source. 10063 // 10064 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10065 // sNaNs. 10066 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10067 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10068 if (CRHS && N0.hasOneUse()) { 10069 SDLoc SL(N); 10070 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10071 N0.getOperand(0)); 10072 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10073 DCI.AddToWorklist(Canon0.getNode()); 10074 10075 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10076 } 10077 } 10078 10079 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10080 } 10081 10082 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10083 switch (Opc) { 10084 case ISD::FMAXNUM: 10085 case ISD::FMAXNUM_IEEE: 10086 return AMDGPUISD::FMAX3; 10087 case ISD::SMAX: 10088 return AMDGPUISD::SMAX3; 10089 case ISD::UMAX: 10090 return AMDGPUISD::UMAX3; 10091 case ISD::FMINNUM: 10092 case ISD::FMINNUM_IEEE: 10093 return AMDGPUISD::FMIN3; 10094 case ISD::SMIN: 10095 return AMDGPUISD::SMIN3; 10096 case ISD::UMIN: 10097 return AMDGPUISD::UMIN3; 10098 default: 10099 llvm_unreachable("Not a min/max opcode"); 10100 } 10101 } 10102 10103 SDValue SITargetLowering::performIntMed3ImmCombine( 10104 SelectionDAG &DAG, const SDLoc &SL, 10105 SDValue Op0, SDValue Op1, bool Signed) const { 10106 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10107 if (!K1) 10108 return SDValue(); 10109 10110 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10111 if (!K0) 10112 return SDValue(); 10113 10114 if (Signed) { 10115 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10116 return SDValue(); 10117 } else { 10118 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10119 return SDValue(); 10120 } 10121 10122 EVT VT = K0->getValueType(0); 10123 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10124 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10125 return DAG.getNode(Med3Opc, SL, VT, 10126 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10127 } 10128 10129 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10130 if (VT == MVT::i16) { 10131 MVT NVT = MVT::i32; 10132 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10133 10134 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10135 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10136 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10137 10138 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10139 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10140 } 10141 10142 return SDValue(); 10143 } 10144 10145 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10146 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10147 return C; 10148 10149 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10150 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10151 return C; 10152 } 10153 10154 return nullptr; 10155 } 10156 10157 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10158 const SDLoc &SL, 10159 SDValue Op0, 10160 SDValue Op1) const { 10161 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10162 if (!K1) 10163 return SDValue(); 10164 10165 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10166 if (!K0) 10167 return SDValue(); 10168 10169 // Ordered >= (although NaN inputs should have folded away by now). 10170 if (K0->getValueAPF() > K1->getValueAPF()) 10171 return SDValue(); 10172 10173 const MachineFunction &MF = DAG.getMachineFunction(); 10174 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10175 10176 // TODO: Check IEEE bit enabled? 10177 EVT VT = Op0.getValueType(); 10178 if (Info->getMode().DX10Clamp) { 10179 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10180 // hardware fmed3 behavior converting to a min. 10181 // FIXME: Should this be allowing -0.0? 10182 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10183 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10184 } 10185 10186 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10187 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10188 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10189 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10190 // then give the other result, which is different from med3 with a NaN 10191 // input. 10192 SDValue Var = Op0.getOperand(0); 10193 if (!DAG.isKnownNeverSNaN(Var)) 10194 return SDValue(); 10195 10196 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10197 10198 if ((!K0->hasOneUse() || 10199 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10200 (!K1->hasOneUse() || 10201 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10202 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10203 Var, SDValue(K0, 0), SDValue(K1, 0)); 10204 } 10205 } 10206 10207 return SDValue(); 10208 } 10209 10210 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10211 DAGCombinerInfo &DCI) const { 10212 SelectionDAG &DAG = DCI.DAG; 10213 10214 EVT VT = N->getValueType(0); 10215 unsigned Opc = N->getOpcode(); 10216 SDValue Op0 = N->getOperand(0); 10217 SDValue Op1 = N->getOperand(1); 10218 10219 // Only do this if the inner op has one use since this will just increases 10220 // register pressure for no benefit. 10221 10222 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10223 !VT.isVector() && 10224 (VT == MVT::i32 || VT == MVT::f32 || 10225 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10226 // max(max(a, b), c) -> max3(a, b, c) 10227 // min(min(a, b), c) -> min3(a, b, c) 10228 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10229 SDLoc DL(N); 10230 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10231 DL, 10232 N->getValueType(0), 10233 Op0.getOperand(0), 10234 Op0.getOperand(1), 10235 Op1); 10236 } 10237 10238 // Try commuted. 10239 // max(a, max(b, c)) -> max3(a, b, c) 10240 // min(a, min(b, c)) -> min3(a, b, c) 10241 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10242 SDLoc DL(N); 10243 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10244 DL, 10245 N->getValueType(0), 10246 Op0, 10247 Op1.getOperand(0), 10248 Op1.getOperand(1)); 10249 } 10250 } 10251 10252 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10253 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10254 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10255 return Med3; 10256 } 10257 10258 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10259 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10260 return Med3; 10261 } 10262 10263 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10264 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10265 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10266 (Opc == AMDGPUISD::FMIN_LEGACY && 10267 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10268 (VT == MVT::f32 || VT == MVT::f64 || 10269 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10270 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10271 Op0.hasOneUse()) { 10272 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10273 return Res; 10274 } 10275 10276 return SDValue(); 10277 } 10278 10279 static bool isClampZeroToOne(SDValue A, SDValue B) { 10280 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10281 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10282 // FIXME: Should this be allowing -0.0? 10283 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10284 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10285 } 10286 } 10287 10288 return false; 10289 } 10290 10291 // FIXME: Should only worry about snans for version with chain. 10292 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10293 DAGCombinerInfo &DCI) const { 10294 EVT VT = N->getValueType(0); 10295 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10296 // NaNs. With a NaN input, the order of the operands may change the result. 10297 10298 SelectionDAG &DAG = DCI.DAG; 10299 SDLoc SL(N); 10300 10301 SDValue Src0 = N->getOperand(0); 10302 SDValue Src1 = N->getOperand(1); 10303 SDValue Src2 = N->getOperand(2); 10304 10305 if (isClampZeroToOne(Src0, Src1)) { 10306 // const_a, const_b, x -> clamp is safe in all cases including signaling 10307 // nans. 10308 // FIXME: Should this be allowing -0.0? 10309 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10310 } 10311 10312 const MachineFunction &MF = DAG.getMachineFunction(); 10313 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10314 10315 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10316 // handling no dx10-clamp? 10317 if (Info->getMode().DX10Clamp) { 10318 // If NaNs is clamped to 0, we are free to reorder the inputs. 10319 10320 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10321 std::swap(Src0, Src1); 10322 10323 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10324 std::swap(Src1, Src2); 10325 10326 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10327 std::swap(Src0, Src1); 10328 10329 if (isClampZeroToOne(Src1, Src2)) 10330 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10331 } 10332 10333 return SDValue(); 10334 } 10335 10336 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10337 DAGCombinerInfo &DCI) const { 10338 SDValue Src0 = N->getOperand(0); 10339 SDValue Src1 = N->getOperand(1); 10340 if (Src0.isUndef() && Src1.isUndef()) 10341 return DCI.DAG.getUNDEF(N->getValueType(0)); 10342 return SDValue(); 10343 } 10344 10345 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10346 // expanded into a set of cmp/select instructions. 10347 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10348 unsigned NumElem, 10349 bool IsDivergentIdx) { 10350 if (UseDivergentRegisterIndexing) 10351 return false; 10352 10353 unsigned VecSize = EltSize * NumElem; 10354 10355 // Sub-dword vectors of size 2 dword or less have better implementation. 10356 if (VecSize <= 64 && EltSize < 32) 10357 return false; 10358 10359 // Always expand the rest of sub-dword instructions, otherwise it will be 10360 // lowered via memory. 10361 if (EltSize < 32) 10362 return true; 10363 10364 // Always do this if var-idx is divergent, otherwise it will become a loop. 10365 if (IsDivergentIdx) 10366 return true; 10367 10368 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10369 unsigned NumInsts = NumElem /* Number of compares */ + 10370 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10371 return NumInsts <= 16; 10372 } 10373 10374 static bool shouldExpandVectorDynExt(SDNode *N) { 10375 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10376 if (isa<ConstantSDNode>(Idx)) 10377 return false; 10378 10379 SDValue Vec = N->getOperand(0); 10380 EVT VecVT = Vec.getValueType(); 10381 EVT EltVT = VecVT.getVectorElementType(); 10382 unsigned EltSize = EltVT.getSizeInBits(); 10383 unsigned NumElem = VecVT.getVectorNumElements(); 10384 10385 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10386 Idx->isDivergent()); 10387 } 10388 10389 SDValue SITargetLowering::performExtractVectorEltCombine( 10390 SDNode *N, DAGCombinerInfo &DCI) const { 10391 SDValue Vec = N->getOperand(0); 10392 SelectionDAG &DAG = DCI.DAG; 10393 10394 EVT VecVT = Vec.getValueType(); 10395 EVT EltVT = VecVT.getVectorElementType(); 10396 10397 if ((Vec.getOpcode() == ISD::FNEG || 10398 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10399 SDLoc SL(N); 10400 EVT EltVT = N->getValueType(0); 10401 SDValue Idx = N->getOperand(1); 10402 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10403 Vec.getOperand(0), Idx); 10404 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10405 } 10406 10407 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10408 // => 10409 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10410 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10411 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10412 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10413 SDLoc SL(N); 10414 EVT EltVT = N->getValueType(0); 10415 SDValue Idx = N->getOperand(1); 10416 unsigned Opc = Vec.getOpcode(); 10417 10418 switch(Opc) { 10419 default: 10420 break; 10421 // TODO: Support other binary operations. 10422 case ISD::FADD: 10423 case ISD::FSUB: 10424 case ISD::FMUL: 10425 case ISD::ADD: 10426 case ISD::UMIN: 10427 case ISD::UMAX: 10428 case ISD::SMIN: 10429 case ISD::SMAX: 10430 case ISD::FMAXNUM: 10431 case ISD::FMINNUM: 10432 case ISD::FMAXNUM_IEEE: 10433 case ISD::FMINNUM_IEEE: { 10434 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10435 Vec.getOperand(0), Idx); 10436 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10437 Vec.getOperand(1), Idx); 10438 10439 DCI.AddToWorklist(Elt0.getNode()); 10440 DCI.AddToWorklist(Elt1.getNode()); 10441 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10442 } 10443 } 10444 } 10445 10446 unsigned VecSize = VecVT.getSizeInBits(); 10447 unsigned EltSize = EltVT.getSizeInBits(); 10448 10449 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10450 if (::shouldExpandVectorDynExt(N)) { 10451 SDLoc SL(N); 10452 SDValue Idx = N->getOperand(1); 10453 SDValue V; 10454 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10455 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10456 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10457 if (I == 0) 10458 V = Elt; 10459 else 10460 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10461 } 10462 return V; 10463 } 10464 10465 if (!DCI.isBeforeLegalize()) 10466 return SDValue(); 10467 10468 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10469 // elements. This exposes more load reduction opportunities by replacing 10470 // multiple small extract_vector_elements with a single 32-bit extract. 10471 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10472 if (isa<MemSDNode>(Vec) && 10473 EltSize <= 16 && 10474 EltVT.isByteSized() && 10475 VecSize > 32 && 10476 VecSize % 32 == 0 && 10477 Idx) { 10478 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10479 10480 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10481 unsigned EltIdx = BitIndex / 32; 10482 unsigned LeftoverBitIdx = BitIndex % 32; 10483 SDLoc SL(N); 10484 10485 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10486 DCI.AddToWorklist(Cast.getNode()); 10487 10488 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10489 DAG.getConstant(EltIdx, SL, MVT::i32)); 10490 DCI.AddToWorklist(Elt.getNode()); 10491 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10492 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10493 DCI.AddToWorklist(Srl.getNode()); 10494 10495 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10496 DCI.AddToWorklist(Trunc.getNode()); 10497 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10498 } 10499 10500 return SDValue(); 10501 } 10502 10503 SDValue 10504 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10505 DAGCombinerInfo &DCI) const { 10506 SDValue Vec = N->getOperand(0); 10507 SDValue Idx = N->getOperand(2); 10508 EVT VecVT = Vec.getValueType(); 10509 EVT EltVT = VecVT.getVectorElementType(); 10510 10511 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10512 // => BUILD_VECTOR n x select (e, const-idx) 10513 if (!::shouldExpandVectorDynExt(N)) 10514 return SDValue(); 10515 10516 SelectionDAG &DAG = DCI.DAG; 10517 SDLoc SL(N); 10518 SDValue Ins = N->getOperand(1); 10519 EVT IdxVT = Idx.getValueType(); 10520 10521 SmallVector<SDValue, 16> Ops; 10522 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10523 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10524 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10525 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10526 Ops.push_back(V); 10527 } 10528 10529 return DAG.getBuildVector(VecVT, SL, Ops); 10530 } 10531 10532 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10533 const SDNode *N0, 10534 const SDNode *N1) const { 10535 EVT VT = N0->getValueType(0); 10536 10537 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10538 // support denormals ever. 10539 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10540 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10541 getSubtarget()->hasMadF16())) && 10542 isOperationLegal(ISD::FMAD, VT)) 10543 return ISD::FMAD; 10544 10545 const TargetOptions &Options = DAG.getTarget().Options; 10546 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10547 (N0->getFlags().hasAllowContract() && 10548 N1->getFlags().hasAllowContract())) && 10549 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10550 return ISD::FMA; 10551 } 10552 10553 return 0; 10554 } 10555 10556 // For a reassociatable opcode perform: 10557 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10558 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10559 SelectionDAG &DAG) const { 10560 EVT VT = N->getValueType(0); 10561 if (VT != MVT::i32 && VT != MVT::i64) 10562 return SDValue(); 10563 10564 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10565 return SDValue(); 10566 10567 unsigned Opc = N->getOpcode(); 10568 SDValue Op0 = N->getOperand(0); 10569 SDValue Op1 = N->getOperand(1); 10570 10571 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10572 return SDValue(); 10573 10574 if (Op0->isDivergent()) 10575 std::swap(Op0, Op1); 10576 10577 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10578 return SDValue(); 10579 10580 SDValue Op2 = Op1.getOperand(1); 10581 Op1 = Op1.getOperand(0); 10582 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10583 return SDValue(); 10584 10585 if (Op1->isDivergent()) 10586 std::swap(Op1, Op2); 10587 10588 SDLoc SL(N); 10589 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10590 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10591 } 10592 10593 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10594 EVT VT, 10595 SDValue N0, SDValue N1, SDValue N2, 10596 bool Signed) { 10597 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10598 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10599 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10600 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10601 } 10602 10603 SDValue SITargetLowering::performAddCombine(SDNode *N, 10604 DAGCombinerInfo &DCI) const { 10605 SelectionDAG &DAG = DCI.DAG; 10606 EVT VT = N->getValueType(0); 10607 SDLoc SL(N); 10608 SDValue LHS = N->getOperand(0); 10609 SDValue RHS = N->getOperand(1); 10610 10611 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10612 && Subtarget->hasMad64_32() && 10613 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10614 VT.getScalarSizeInBits() <= 64) { 10615 if (LHS.getOpcode() != ISD::MUL) 10616 std::swap(LHS, RHS); 10617 10618 SDValue MulLHS = LHS.getOperand(0); 10619 SDValue MulRHS = LHS.getOperand(1); 10620 SDValue AddRHS = RHS; 10621 10622 // TODO: Maybe restrict if SGPR inputs. 10623 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10624 numBitsUnsigned(MulRHS, DAG) <= 32) { 10625 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10626 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10627 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10628 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10629 } 10630 10631 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10632 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10633 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10634 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10635 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10636 } 10637 10638 return SDValue(); 10639 } 10640 10641 if (SDValue V = reassociateScalarOps(N, DAG)) { 10642 return V; 10643 } 10644 10645 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10646 return SDValue(); 10647 10648 // add x, zext (setcc) => addcarry x, 0, setcc 10649 // add x, sext (setcc) => subcarry x, 0, setcc 10650 unsigned Opc = LHS.getOpcode(); 10651 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10652 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10653 std::swap(RHS, LHS); 10654 10655 Opc = RHS.getOpcode(); 10656 switch (Opc) { 10657 default: break; 10658 case ISD::ZERO_EXTEND: 10659 case ISD::SIGN_EXTEND: 10660 case ISD::ANY_EXTEND: { 10661 auto Cond = RHS.getOperand(0); 10662 // If this won't be a real VOPC output, we would still need to insert an 10663 // extra instruction anyway. 10664 if (!isBoolSGPR(Cond)) 10665 break; 10666 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10667 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10668 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10669 return DAG.getNode(Opc, SL, VTList, Args); 10670 } 10671 case ISD::ADDCARRY: { 10672 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10673 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10674 if (!C || C->getZExtValue() != 0) break; 10675 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10676 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10677 } 10678 } 10679 return SDValue(); 10680 } 10681 10682 SDValue SITargetLowering::performSubCombine(SDNode *N, 10683 DAGCombinerInfo &DCI) const { 10684 SelectionDAG &DAG = DCI.DAG; 10685 EVT VT = N->getValueType(0); 10686 10687 if (VT != MVT::i32) 10688 return SDValue(); 10689 10690 SDLoc SL(N); 10691 SDValue LHS = N->getOperand(0); 10692 SDValue RHS = N->getOperand(1); 10693 10694 // sub x, zext (setcc) => subcarry x, 0, setcc 10695 // sub x, sext (setcc) => addcarry x, 0, setcc 10696 unsigned Opc = RHS.getOpcode(); 10697 switch (Opc) { 10698 default: break; 10699 case ISD::ZERO_EXTEND: 10700 case ISD::SIGN_EXTEND: 10701 case ISD::ANY_EXTEND: { 10702 auto Cond = RHS.getOperand(0); 10703 // If this won't be a real VOPC output, we would still need to insert an 10704 // extra instruction anyway. 10705 if (!isBoolSGPR(Cond)) 10706 break; 10707 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10708 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10709 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10710 return DAG.getNode(Opc, SL, VTList, Args); 10711 } 10712 } 10713 10714 if (LHS.getOpcode() == ISD::SUBCARRY) { 10715 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10716 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10717 if (!C || !C->isZero()) 10718 return SDValue(); 10719 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10720 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10721 } 10722 return SDValue(); 10723 } 10724 10725 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10726 DAGCombinerInfo &DCI) const { 10727 10728 if (N->getValueType(0) != MVT::i32) 10729 return SDValue(); 10730 10731 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10732 if (!C || C->getZExtValue() != 0) 10733 return SDValue(); 10734 10735 SelectionDAG &DAG = DCI.DAG; 10736 SDValue LHS = N->getOperand(0); 10737 10738 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10739 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10740 unsigned LHSOpc = LHS.getOpcode(); 10741 unsigned Opc = N->getOpcode(); 10742 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10743 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10744 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10745 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10746 } 10747 return SDValue(); 10748 } 10749 10750 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10751 DAGCombinerInfo &DCI) const { 10752 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10753 return SDValue(); 10754 10755 SelectionDAG &DAG = DCI.DAG; 10756 EVT VT = N->getValueType(0); 10757 10758 SDLoc SL(N); 10759 SDValue LHS = N->getOperand(0); 10760 SDValue RHS = N->getOperand(1); 10761 10762 // These should really be instruction patterns, but writing patterns with 10763 // source modifiers is a pain. 10764 10765 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10766 if (LHS.getOpcode() == ISD::FADD) { 10767 SDValue A = LHS.getOperand(0); 10768 if (A == LHS.getOperand(1)) { 10769 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10770 if (FusedOp != 0) { 10771 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10772 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10773 } 10774 } 10775 } 10776 10777 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10778 if (RHS.getOpcode() == ISD::FADD) { 10779 SDValue A = RHS.getOperand(0); 10780 if (A == RHS.getOperand(1)) { 10781 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10782 if (FusedOp != 0) { 10783 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10784 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10785 } 10786 } 10787 } 10788 10789 return SDValue(); 10790 } 10791 10792 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10793 DAGCombinerInfo &DCI) const { 10794 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10795 return SDValue(); 10796 10797 SelectionDAG &DAG = DCI.DAG; 10798 SDLoc SL(N); 10799 EVT VT = N->getValueType(0); 10800 assert(!VT.isVector()); 10801 10802 // Try to get the fneg to fold into the source modifier. This undoes generic 10803 // DAG combines and folds them into the mad. 10804 // 10805 // Only do this if we are not trying to support denormals. v_mad_f32 does 10806 // not support denormals ever. 10807 SDValue LHS = N->getOperand(0); 10808 SDValue RHS = N->getOperand(1); 10809 if (LHS.getOpcode() == ISD::FADD) { 10810 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10811 SDValue A = LHS.getOperand(0); 10812 if (A == LHS.getOperand(1)) { 10813 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10814 if (FusedOp != 0){ 10815 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10816 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10817 10818 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10819 } 10820 } 10821 } 10822 10823 if (RHS.getOpcode() == ISD::FADD) { 10824 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10825 10826 SDValue A = RHS.getOperand(0); 10827 if (A == RHS.getOperand(1)) { 10828 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10829 if (FusedOp != 0){ 10830 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10831 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10832 } 10833 } 10834 } 10835 10836 return SDValue(); 10837 } 10838 10839 SDValue SITargetLowering::performFMACombine(SDNode *N, 10840 DAGCombinerInfo &DCI) const { 10841 SelectionDAG &DAG = DCI.DAG; 10842 EVT VT = N->getValueType(0); 10843 SDLoc SL(N); 10844 10845 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10846 return SDValue(); 10847 10848 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10849 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10850 SDValue Op1 = N->getOperand(0); 10851 SDValue Op2 = N->getOperand(1); 10852 SDValue FMA = N->getOperand(2); 10853 10854 if (FMA.getOpcode() != ISD::FMA || 10855 Op1.getOpcode() != ISD::FP_EXTEND || 10856 Op2.getOpcode() != ISD::FP_EXTEND) 10857 return SDValue(); 10858 10859 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10860 // regardless of the denorm mode setting. Therefore, 10861 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 10862 const TargetOptions &Options = DAG.getTarget().Options; 10863 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10864 (N->getFlags().hasAllowContract() && 10865 FMA->getFlags().hasAllowContract())) { 10866 Op1 = Op1.getOperand(0); 10867 Op2 = Op2.getOperand(0); 10868 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10869 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10870 return SDValue(); 10871 10872 SDValue Vec1 = Op1.getOperand(0); 10873 SDValue Idx1 = Op1.getOperand(1); 10874 SDValue Vec2 = Op2.getOperand(0); 10875 10876 SDValue FMAOp1 = FMA.getOperand(0); 10877 SDValue FMAOp2 = FMA.getOperand(1); 10878 SDValue FMAAcc = FMA.getOperand(2); 10879 10880 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10881 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10882 return SDValue(); 10883 10884 FMAOp1 = FMAOp1.getOperand(0); 10885 FMAOp2 = FMAOp2.getOperand(0); 10886 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10887 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10888 return SDValue(); 10889 10890 SDValue Vec3 = FMAOp1.getOperand(0); 10891 SDValue Vec4 = FMAOp2.getOperand(0); 10892 SDValue Idx2 = FMAOp1.getOperand(1); 10893 10894 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10895 // Idx1 and Idx2 cannot be the same. 10896 Idx1 == Idx2) 10897 return SDValue(); 10898 10899 if (Vec1 == Vec2 || Vec3 == Vec4) 10900 return SDValue(); 10901 10902 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10903 return SDValue(); 10904 10905 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10906 (Vec1 == Vec4 && Vec2 == Vec3)) { 10907 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10908 DAG.getTargetConstant(0, SL, MVT::i1)); 10909 } 10910 } 10911 return SDValue(); 10912 } 10913 10914 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10915 DAGCombinerInfo &DCI) const { 10916 SelectionDAG &DAG = DCI.DAG; 10917 SDLoc SL(N); 10918 10919 SDValue LHS = N->getOperand(0); 10920 SDValue RHS = N->getOperand(1); 10921 EVT VT = LHS.getValueType(); 10922 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10923 10924 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10925 if (!CRHS) { 10926 CRHS = dyn_cast<ConstantSDNode>(LHS); 10927 if (CRHS) { 10928 std::swap(LHS, RHS); 10929 CC = getSetCCSwappedOperands(CC); 10930 } 10931 } 10932 10933 if (CRHS) { 10934 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10935 isBoolSGPR(LHS.getOperand(0))) { 10936 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10937 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10938 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10939 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10940 if ((CRHS->isAllOnes() && 10941 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10942 (CRHS->isZero() && 10943 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10944 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10945 DAG.getConstant(-1, SL, MVT::i1)); 10946 if ((CRHS->isAllOnes() && 10947 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10948 (CRHS->isZero() && 10949 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10950 return LHS.getOperand(0); 10951 } 10952 10953 const APInt &CRHSVal = CRHS->getAPIntValue(); 10954 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10955 LHS.getOpcode() == ISD::SELECT && 10956 isa<ConstantSDNode>(LHS.getOperand(1)) && 10957 isa<ConstantSDNode>(LHS.getOperand(2)) && 10958 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10959 isBoolSGPR(LHS.getOperand(0))) { 10960 // Given CT != FT: 10961 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10962 // setcc (select cc, CT, CF), CF, ne => cc 10963 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10964 // setcc (select cc, CT, CF), CT, eq => cc 10965 const APInt &CT = LHS.getConstantOperandAPInt(1); 10966 const APInt &CF = LHS.getConstantOperandAPInt(2); 10967 10968 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10969 (CT == CRHSVal && CC == ISD::SETNE)) 10970 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10971 DAG.getConstant(-1, SL, MVT::i1)); 10972 if ((CF == CRHSVal && CC == ISD::SETNE) || 10973 (CT == CRHSVal && CC == ISD::SETEQ)) 10974 return LHS.getOperand(0); 10975 } 10976 } 10977 10978 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10979 VT != MVT::f16)) 10980 return SDValue(); 10981 10982 // Match isinf/isfinite pattern 10983 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10984 // (fcmp one (fabs x), inf) -> (fp_class x, 10985 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10986 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10987 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10988 if (!CRHS) 10989 return SDValue(); 10990 10991 const APFloat &APF = CRHS->getValueAPF(); 10992 if (APF.isInfinity() && !APF.isNegative()) { 10993 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10994 SIInstrFlags::N_INFINITY; 10995 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10996 SIInstrFlags::P_ZERO | 10997 SIInstrFlags::N_NORMAL | 10998 SIInstrFlags::P_NORMAL | 10999 SIInstrFlags::N_SUBNORMAL | 11000 SIInstrFlags::P_SUBNORMAL; 11001 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11002 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11003 DAG.getConstant(Mask, SL, MVT::i32)); 11004 } 11005 } 11006 11007 return SDValue(); 11008 } 11009 11010 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11011 DAGCombinerInfo &DCI) const { 11012 SelectionDAG &DAG = DCI.DAG; 11013 SDLoc SL(N); 11014 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11015 11016 SDValue Src = N->getOperand(0); 11017 SDValue Shift = N->getOperand(0); 11018 11019 // TODO: Extend type shouldn't matter (assuming legal types). 11020 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11021 Shift = Shift.getOperand(0); 11022 11023 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11024 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11025 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11026 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11027 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11028 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11029 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11030 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11031 SDLoc(Shift.getOperand(0)), MVT::i32); 11032 11033 unsigned ShiftOffset = 8 * Offset; 11034 if (Shift.getOpcode() == ISD::SHL) 11035 ShiftOffset -= C->getZExtValue(); 11036 else 11037 ShiftOffset += C->getZExtValue(); 11038 11039 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11040 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11041 MVT::f32, Shifted); 11042 } 11043 } 11044 } 11045 11046 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11047 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11048 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11049 // We simplified Src. If this node is not dead, visit it again so it is 11050 // folded properly. 11051 if (N->getOpcode() != ISD::DELETED_NODE) 11052 DCI.AddToWorklist(N); 11053 return SDValue(N, 0); 11054 } 11055 11056 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11057 if (SDValue DemandedSrc = 11058 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11059 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11060 11061 return SDValue(); 11062 } 11063 11064 SDValue SITargetLowering::performClampCombine(SDNode *N, 11065 DAGCombinerInfo &DCI) const { 11066 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11067 if (!CSrc) 11068 return SDValue(); 11069 11070 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11071 const APFloat &F = CSrc->getValueAPF(); 11072 APFloat Zero = APFloat::getZero(F.getSemantics()); 11073 if (F < Zero || 11074 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11075 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11076 } 11077 11078 APFloat One(F.getSemantics(), "1.0"); 11079 if (F > One) 11080 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11081 11082 return SDValue(CSrc, 0); 11083 } 11084 11085 11086 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11087 DAGCombinerInfo &DCI) const { 11088 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11089 return SDValue(); 11090 switch (N->getOpcode()) { 11091 case ISD::ADD: 11092 return performAddCombine(N, DCI); 11093 case ISD::SUB: 11094 return performSubCombine(N, DCI); 11095 case ISD::ADDCARRY: 11096 case ISD::SUBCARRY: 11097 return performAddCarrySubCarryCombine(N, DCI); 11098 case ISD::FADD: 11099 return performFAddCombine(N, DCI); 11100 case ISD::FSUB: 11101 return performFSubCombine(N, DCI); 11102 case ISD::SETCC: 11103 return performSetCCCombine(N, DCI); 11104 case ISD::FMAXNUM: 11105 case ISD::FMINNUM: 11106 case ISD::FMAXNUM_IEEE: 11107 case ISD::FMINNUM_IEEE: 11108 case ISD::SMAX: 11109 case ISD::SMIN: 11110 case ISD::UMAX: 11111 case ISD::UMIN: 11112 case AMDGPUISD::FMIN_LEGACY: 11113 case AMDGPUISD::FMAX_LEGACY: 11114 return performMinMaxCombine(N, DCI); 11115 case ISD::FMA: 11116 return performFMACombine(N, DCI); 11117 case ISD::AND: 11118 return performAndCombine(N, DCI); 11119 case ISD::OR: 11120 return performOrCombine(N, DCI); 11121 case ISD::XOR: 11122 return performXorCombine(N, DCI); 11123 case ISD::ZERO_EXTEND: 11124 return performZeroExtendCombine(N, DCI); 11125 case ISD::SIGN_EXTEND_INREG: 11126 return performSignExtendInRegCombine(N , DCI); 11127 case AMDGPUISD::FP_CLASS: 11128 return performClassCombine(N, DCI); 11129 case ISD::FCANONICALIZE: 11130 return performFCanonicalizeCombine(N, DCI); 11131 case AMDGPUISD::RCP: 11132 return performRcpCombine(N, DCI); 11133 case AMDGPUISD::FRACT: 11134 case AMDGPUISD::RSQ: 11135 case AMDGPUISD::RCP_LEGACY: 11136 case AMDGPUISD::RCP_IFLAG: 11137 case AMDGPUISD::RSQ_CLAMP: 11138 case AMDGPUISD::LDEXP: { 11139 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11140 SDValue Src = N->getOperand(0); 11141 if (Src.isUndef()) 11142 return Src; 11143 break; 11144 } 11145 case ISD::SINT_TO_FP: 11146 case ISD::UINT_TO_FP: 11147 return performUCharToFloatCombine(N, DCI); 11148 case AMDGPUISD::CVT_F32_UBYTE0: 11149 case AMDGPUISD::CVT_F32_UBYTE1: 11150 case AMDGPUISD::CVT_F32_UBYTE2: 11151 case AMDGPUISD::CVT_F32_UBYTE3: 11152 return performCvtF32UByteNCombine(N, DCI); 11153 case AMDGPUISD::FMED3: 11154 return performFMed3Combine(N, DCI); 11155 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11156 return performCvtPkRTZCombine(N, DCI); 11157 case AMDGPUISD::CLAMP: 11158 return performClampCombine(N, DCI); 11159 case ISD::SCALAR_TO_VECTOR: { 11160 SelectionDAG &DAG = DCI.DAG; 11161 EVT VT = N->getValueType(0); 11162 11163 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11164 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11165 SDLoc SL(N); 11166 SDValue Src = N->getOperand(0); 11167 EVT EltVT = Src.getValueType(); 11168 if (EltVT == MVT::f16) 11169 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11170 11171 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11172 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11173 } 11174 11175 break; 11176 } 11177 case ISD::EXTRACT_VECTOR_ELT: 11178 return performExtractVectorEltCombine(N, DCI); 11179 case ISD::INSERT_VECTOR_ELT: 11180 return performInsertVectorEltCombine(N, DCI); 11181 case ISD::LOAD: { 11182 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11183 return Widended; 11184 LLVM_FALLTHROUGH; 11185 } 11186 default: { 11187 if (!DCI.isBeforeLegalize()) { 11188 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11189 return performMemSDNodeCombine(MemNode, DCI); 11190 } 11191 11192 break; 11193 } 11194 } 11195 11196 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11197 } 11198 11199 /// Helper function for adjustWritemask 11200 static unsigned SubIdx2Lane(unsigned Idx) { 11201 switch (Idx) { 11202 default: return ~0u; 11203 case AMDGPU::sub0: return 0; 11204 case AMDGPU::sub1: return 1; 11205 case AMDGPU::sub2: return 2; 11206 case AMDGPU::sub3: return 3; 11207 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11208 } 11209 } 11210 11211 /// Adjust the writemask of MIMG instructions 11212 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11213 SelectionDAG &DAG) const { 11214 unsigned Opcode = Node->getMachineOpcode(); 11215 11216 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11217 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11218 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11219 return Node; // not implemented for D16 11220 11221 SDNode *Users[5] = { nullptr }; 11222 unsigned Lane = 0; 11223 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11224 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11225 unsigned NewDmask = 0; 11226 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11227 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11228 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11229 Node->getConstantOperandVal(LWEIdx)) 11230 ? true 11231 : false; 11232 unsigned TFCLane = 0; 11233 bool HasChain = Node->getNumValues() > 1; 11234 11235 if (OldDmask == 0) { 11236 // These are folded out, but on the chance it happens don't assert. 11237 return Node; 11238 } 11239 11240 unsigned OldBitsSet = countPopulation(OldDmask); 11241 // Work out which is the TFE/LWE lane if that is enabled. 11242 if (UsesTFC) { 11243 TFCLane = OldBitsSet; 11244 } 11245 11246 // Try to figure out the used register components 11247 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11248 I != E; ++I) { 11249 11250 // Don't look at users of the chain. 11251 if (I.getUse().getResNo() != 0) 11252 continue; 11253 11254 // Abort if we can't understand the usage 11255 if (!I->isMachineOpcode() || 11256 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11257 return Node; 11258 11259 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11260 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11261 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11262 // set, etc. 11263 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11264 if (Lane == ~0u) 11265 return Node; 11266 11267 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11268 if (UsesTFC && Lane == TFCLane) { 11269 Users[Lane] = *I; 11270 } else { 11271 // Set which texture component corresponds to the lane. 11272 unsigned Comp; 11273 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11274 Comp = countTrailingZeros(Dmask); 11275 Dmask &= ~(1 << Comp); 11276 } 11277 11278 // Abort if we have more than one user per component. 11279 if (Users[Lane]) 11280 return Node; 11281 11282 Users[Lane] = *I; 11283 NewDmask |= 1 << Comp; 11284 } 11285 } 11286 11287 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11288 bool NoChannels = !NewDmask; 11289 if (NoChannels) { 11290 if (!UsesTFC) { 11291 // No uses of the result and not using TFC. Then do nothing. 11292 return Node; 11293 } 11294 // If the original dmask has one channel - then nothing to do 11295 if (OldBitsSet == 1) 11296 return Node; 11297 // Use an arbitrary dmask - required for the instruction to work 11298 NewDmask = 1; 11299 } 11300 // Abort if there's no change 11301 if (NewDmask == OldDmask) 11302 return Node; 11303 11304 unsigned BitsSet = countPopulation(NewDmask); 11305 11306 // Check for TFE or LWE - increase the number of channels by one to account 11307 // for the extra return value 11308 // This will need adjustment for D16 if this is also included in 11309 // adjustWriteMask (this function) but at present D16 are excluded. 11310 unsigned NewChannels = BitsSet + UsesTFC; 11311 11312 int NewOpcode = 11313 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11314 assert(NewOpcode != -1 && 11315 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11316 "failed to find equivalent MIMG op"); 11317 11318 // Adjust the writemask in the node 11319 SmallVector<SDValue, 12> Ops; 11320 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11321 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11322 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11323 11324 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11325 11326 MVT ResultVT = NewChannels == 1 ? 11327 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11328 NewChannels == 5 ? 8 : NewChannels); 11329 SDVTList NewVTList = HasChain ? 11330 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11331 11332 11333 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11334 NewVTList, Ops); 11335 11336 if (HasChain) { 11337 // Update chain. 11338 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11339 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11340 } 11341 11342 if (NewChannels == 1) { 11343 assert(Node->hasNUsesOfValue(1, 0)); 11344 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11345 SDLoc(Node), Users[Lane]->getValueType(0), 11346 SDValue(NewNode, 0)); 11347 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11348 return nullptr; 11349 } 11350 11351 // Update the users of the node with the new indices 11352 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11353 SDNode *User = Users[i]; 11354 if (!User) { 11355 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11356 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11357 if (i || !NoChannels) 11358 continue; 11359 } else { 11360 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11361 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11362 } 11363 11364 switch (Idx) { 11365 default: break; 11366 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11367 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11368 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11369 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11370 } 11371 } 11372 11373 DAG.RemoveDeadNode(Node); 11374 return nullptr; 11375 } 11376 11377 static bool isFrameIndexOp(SDValue Op) { 11378 if (Op.getOpcode() == ISD::AssertZext) 11379 Op = Op.getOperand(0); 11380 11381 return isa<FrameIndexSDNode>(Op); 11382 } 11383 11384 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11385 /// with frame index operands. 11386 /// LLVM assumes that inputs are to these instructions are registers. 11387 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11388 SelectionDAG &DAG) const { 11389 if (Node->getOpcode() == ISD::CopyToReg) { 11390 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11391 SDValue SrcVal = Node->getOperand(2); 11392 11393 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11394 // to try understanding copies to physical registers. 11395 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11396 SDLoc SL(Node); 11397 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11398 SDValue VReg = DAG.getRegister( 11399 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11400 11401 SDNode *Glued = Node->getGluedNode(); 11402 SDValue ToVReg 11403 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11404 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11405 SDValue ToResultReg 11406 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11407 VReg, ToVReg.getValue(1)); 11408 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11409 DAG.RemoveDeadNode(Node); 11410 return ToResultReg.getNode(); 11411 } 11412 } 11413 11414 SmallVector<SDValue, 8> Ops; 11415 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11416 if (!isFrameIndexOp(Node->getOperand(i))) { 11417 Ops.push_back(Node->getOperand(i)); 11418 continue; 11419 } 11420 11421 SDLoc DL(Node); 11422 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11423 Node->getOperand(i).getValueType(), 11424 Node->getOperand(i)), 0)); 11425 } 11426 11427 return DAG.UpdateNodeOperands(Node, Ops); 11428 } 11429 11430 /// Fold the instructions after selecting them. 11431 /// Returns null if users were already updated. 11432 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11433 SelectionDAG &DAG) const { 11434 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11435 unsigned Opcode = Node->getMachineOpcode(); 11436 11437 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11438 !TII->isGather4(Opcode) && 11439 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11440 return adjustWritemask(Node, DAG); 11441 } 11442 11443 if (Opcode == AMDGPU::INSERT_SUBREG || 11444 Opcode == AMDGPU::REG_SEQUENCE) { 11445 legalizeTargetIndependentNode(Node, DAG); 11446 return Node; 11447 } 11448 11449 switch (Opcode) { 11450 case AMDGPU::V_DIV_SCALE_F32_e64: 11451 case AMDGPU::V_DIV_SCALE_F64_e64: { 11452 // Satisfy the operand register constraint when one of the inputs is 11453 // undefined. Ordinarily each undef value will have its own implicit_def of 11454 // a vreg, so force these to use a single register. 11455 SDValue Src0 = Node->getOperand(1); 11456 SDValue Src1 = Node->getOperand(3); 11457 SDValue Src2 = Node->getOperand(5); 11458 11459 if ((Src0.isMachineOpcode() && 11460 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11461 (Src0 == Src1 || Src0 == Src2)) 11462 break; 11463 11464 MVT VT = Src0.getValueType().getSimpleVT(); 11465 const TargetRegisterClass *RC = 11466 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11467 11468 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11469 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11470 11471 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11472 UndefReg, Src0, SDValue()); 11473 11474 // src0 must be the same register as src1 or src2, even if the value is 11475 // undefined, so make sure we don't violate this constraint. 11476 if (Src0.isMachineOpcode() && 11477 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11478 if (Src1.isMachineOpcode() && 11479 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11480 Src0 = Src1; 11481 else if (Src2.isMachineOpcode() && 11482 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11483 Src0 = Src2; 11484 else { 11485 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11486 Src0 = UndefReg; 11487 Src1 = UndefReg; 11488 } 11489 } else 11490 break; 11491 11492 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11493 Ops[1] = Src0; 11494 Ops[3] = Src1; 11495 Ops[5] = Src2; 11496 Ops.push_back(ImpDef.getValue(1)); 11497 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11498 } 11499 default: 11500 break; 11501 } 11502 11503 return Node; 11504 } 11505 11506 // Any MIMG instructions that use tfe or lwe require an initialization of the 11507 // result register that will be written in the case of a memory access failure. 11508 // The required code is also added to tie this init code to the result of the 11509 // img instruction. 11510 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11511 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11512 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11513 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11514 MachineBasicBlock &MBB = *MI.getParent(); 11515 11516 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11517 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11518 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11519 11520 if (!TFE && !LWE) // intersect_ray 11521 return; 11522 11523 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11524 unsigned LWEVal = LWE->getImm(); 11525 unsigned D16Val = D16 ? D16->getImm() : 0; 11526 11527 if (!TFEVal && !LWEVal) 11528 return; 11529 11530 // At least one of TFE or LWE are non-zero 11531 // We have to insert a suitable initialization of the result value and 11532 // tie this to the dest of the image instruction. 11533 11534 const DebugLoc &DL = MI.getDebugLoc(); 11535 11536 int DstIdx = 11537 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11538 11539 // Calculate which dword we have to initialize to 0. 11540 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11541 11542 // check that dmask operand is found. 11543 assert(MO_Dmask && "Expected dmask operand in instruction"); 11544 11545 unsigned dmask = MO_Dmask->getImm(); 11546 // Determine the number of active lanes taking into account the 11547 // Gather4 special case 11548 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11549 11550 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11551 11552 unsigned InitIdx = 11553 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11554 11555 // Abandon attempt if the dst size isn't large enough 11556 // - this is in fact an error but this is picked up elsewhere and 11557 // reported correctly. 11558 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11559 if (DstSize < InitIdx) 11560 return; 11561 11562 // Create a register for the initialization value. 11563 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11564 unsigned NewDst = 0; // Final initialized value will be in here 11565 11566 // If PRTStrictNull feature is enabled (the default) then initialize 11567 // all the result registers to 0, otherwise just the error indication 11568 // register (VGPRn+1) 11569 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11570 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11571 11572 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11573 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11574 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11575 // Initialize dword 11576 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11577 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11578 .addImm(0); 11579 // Insert into the super-reg 11580 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11581 .addReg(PrevDst) 11582 .addReg(SubReg) 11583 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11584 11585 PrevDst = NewDst; 11586 } 11587 11588 // Add as an implicit operand 11589 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11590 11591 // Tie the just added implicit operand to the dst 11592 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11593 } 11594 11595 /// Assign the register class depending on the number of 11596 /// bits set in the writemask 11597 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11598 SDNode *Node) const { 11599 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11600 11601 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11602 11603 if (TII->isVOP3(MI.getOpcode())) { 11604 // Make sure constant bus requirements are respected. 11605 TII->legalizeOperandsVOP3(MRI, MI); 11606 11607 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11608 // This saves a chain-copy of registers and better balance register 11609 // use between vgpr and agpr as agpr tuples tend to be big. 11610 if (MI.getDesc().OpInfo) { 11611 unsigned Opc = MI.getOpcode(); 11612 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11613 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11614 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11615 if (I == -1) 11616 break; 11617 MachineOperand &Op = MI.getOperand(I); 11618 if (!Op.isReg() || !Op.getReg().isVirtual()) 11619 continue; 11620 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11621 if (!TRI->hasAGPRs(RC)) 11622 continue; 11623 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11624 if (!Src || !Src->isCopy() || 11625 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11626 continue; 11627 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11628 // All uses of agpr64 and agpr32 can also accept vgpr except for 11629 // v_accvgpr_read, but we do not produce agpr reads during selection, 11630 // so no use checks are needed. 11631 MRI.setRegClass(Op.getReg(), NewRC); 11632 } 11633 } 11634 11635 return; 11636 } 11637 11638 // Replace unused atomics with the no return version. 11639 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11640 if (NoRetAtomicOp != -1) { 11641 if (!Node->hasAnyUseOfValue(0)) { 11642 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11643 AMDGPU::OpName::cpol); 11644 if (CPolIdx != -1) { 11645 MachineOperand &CPol = MI.getOperand(CPolIdx); 11646 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11647 } 11648 MI.removeOperand(0); 11649 MI.setDesc(TII->get(NoRetAtomicOp)); 11650 return; 11651 } 11652 11653 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11654 // instruction, because the return type of these instructions is a vec2 of 11655 // the memory type, so it can be tied to the input operand. 11656 // This means these instructions always have a use, so we need to add a 11657 // special case to check if the atomic has only one extract_subreg use, 11658 // which itself has no uses. 11659 if ((Node->hasNUsesOfValue(1, 0) && 11660 Node->use_begin()->isMachineOpcode() && 11661 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11662 !Node->use_begin()->hasAnyUseOfValue(0))) { 11663 Register Def = MI.getOperand(0).getReg(); 11664 11665 // Change this into a noret atomic. 11666 MI.setDesc(TII->get(NoRetAtomicOp)); 11667 MI.removeOperand(0); 11668 11669 // If we only remove the def operand from the atomic instruction, the 11670 // extract_subreg will be left with a use of a vreg without a def. 11671 // So we need to insert an implicit_def to avoid machine verifier 11672 // errors. 11673 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11674 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11675 } 11676 return; 11677 } 11678 11679 if (TII->isMIMG(MI) && !MI.mayStore()) 11680 AddIMGInit(MI); 11681 } 11682 11683 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11684 uint64_t Val) { 11685 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11686 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11687 } 11688 11689 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11690 const SDLoc &DL, 11691 SDValue Ptr) const { 11692 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11693 11694 // Build the half of the subregister with the constants before building the 11695 // full 128-bit register. If we are building multiple resource descriptors, 11696 // this will allow CSEing of the 2-component register. 11697 const SDValue Ops0[] = { 11698 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11699 buildSMovImm32(DAG, DL, 0), 11700 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11701 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11702 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11703 }; 11704 11705 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11706 MVT::v2i32, Ops0), 0); 11707 11708 // Combine the constants and the pointer. 11709 const SDValue Ops1[] = { 11710 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11711 Ptr, 11712 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11713 SubRegHi, 11714 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11715 }; 11716 11717 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11718 } 11719 11720 /// Return a resource descriptor with the 'Add TID' bit enabled 11721 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11722 /// of the resource descriptor) to create an offset, which is added to 11723 /// the resource pointer. 11724 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11725 SDValue Ptr, uint32_t RsrcDword1, 11726 uint64_t RsrcDword2And3) const { 11727 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11728 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11729 if (RsrcDword1) { 11730 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11731 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11732 0); 11733 } 11734 11735 SDValue DataLo = buildSMovImm32(DAG, DL, 11736 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11737 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11738 11739 const SDValue Ops[] = { 11740 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11741 PtrLo, 11742 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11743 PtrHi, 11744 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11745 DataLo, 11746 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11747 DataHi, 11748 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11749 }; 11750 11751 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11752 } 11753 11754 //===----------------------------------------------------------------------===// 11755 // SI Inline Assembly Support 11756 //===----------------------------------------------------------------------===// 11757 11758 std::pair<unsigned, const TargetRegisterClass *> 11759 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11760 StringRef Constraint, 11761 MVT VT) const { 11762 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11763 11764 const TargetRegisterClass *RC = nullptr; 11765 if (Constraint.size() == 1) { 11766 const unsigned BitWidth = VT.getSizeInBits(); 11767 switch (Constraint[0]) { 11768 default: 11769 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11770 case 's': 11771 case 'r': 11772 switch (BitWidth) { 11773 case 16: 11774 RC = &AMDGPU::SReg_32RegClass; 11775 break; 11776 case 64: 11777 RC = &AMDGPU::SGPR_64RegClass; 11778 break; 11779 default: 11780 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11781 if (!RC) 11782 return std::make_pair(0U, nullptr); 11783 break; 11784 } 11785 break; 11786 case 'v': 11787 switch (BitWidth) { 11788 case 16: 11789 RC = &AMDGPU::VGPR_32RegClass; 11790 break; 11791 default: 11792 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11793 if (!RC) 11794 return std::make_pair(0U, nullptr); 11795 break; 11796 } 11797 break; 11798 case 'a': 11799 if (!Subtarget->hasMAIInsts()) 11800 break; 11801 switch (BitWidth) { 11802 case 16: 11803 RC = &AMDGPU::AGPR_32RegClass; 11804 break; 11805 default: 11806 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11807 if (!RC) 11808 return std::make_pair(0U, nullptr); 11809 break; 11810 } 11811 break; 11812 } 11813 // We actually support i128, i16 and f16 as inline parameters 11814 // even if they are not reported as legal 11815 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11816 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11817 return std::make_pair(0U, RC); 11818 } 11819 11820 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11821 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11822 if (RegName.consume_front("v")) { 11823 RC = &AMDGPU::VGPR_32RegClass; 11824 } else if (RegName.consume_front("s")) { 11825 RC = &AMDGPU::SGPR_32RegClass; 11826 } else if (RegName.consume_front("a")) { 11827 RC = &AMDGPU::AGPR_32RegClass; 11828 } 11829 11830 if (RC) { 11831 uint32_t Idx; 11832 if (RegName.consume_front("[")) { 11833 uint32_t End; 11834 bool Failed = RegName.consumeInteger(10, Idx); 11835 Failed |= !RegName.consume_front(":"); 11836 Failed |= RegName.consumeInteger(10, End); 11837 Failed |= !RegName.consume_back("]"); 11838 if (!Failed) { 11839 uint32_t Width = (End - Idx + 1) * 32; 11840 MCRegister Reg = RC->getRegister(Idx); 11841 if (SIRegisterInfo::isVGPRClass(RC)) 11842 RC = TRI->getVGPRClassForBitWidth(Width); 11843 else if (SIRegisterInfo::isSGPRClass(RC)) 11844 RC = TRI->getSGPRClassForBitWidth(Width); 11845 else if (SIRegisterInfo::isAGPRClass(RC)) 11846 RC = TRI->getAGPRClassForBitWidth(Width); 11847 if (RC) { 11848 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 11849 return std::make_pair(Reg, RC); 11850 } 11851 } 11852 } else { 11853 bool Failed = RegName.getAsInteger(10, Idx); 11854 if (!Failed && Idx < RC->getNumRegs()) 11855 return std::make_pair(RC->getRegister(Idx), RC); 11856 } 11857 } 11858 } 11859 11860 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11861 if (Ret.first) 11862 Ret.second = TRI->getPhysRegClass(Ret.first); 11863 11864 return Ret; 11865 } 11866 11867 static bool isImmConstraint(StringRef Constraint) { 11868 if (Constraint.size() == 1) { 11869 switch (Constraint[0]) { 11870 default: break; 11871 case 'I': 11872 case 'J': 11873 case 'A': 11874 case 'B': 11875 case 'C': 11876 return true; 11877 } 11878 } else if (Constraint == "DA" || 11879 Constraint == "DB") { 11880 return true; 11881 } 11882 return false; 11883 } 11884 11885 SITargetLowering::ConstraintType 11886 SITargetLowering::getConstraintType(StringRef Constraint) const { 11887 if (Constraint.size() == 1) { 11888 switch (Constraint[0]) { 11889 default: break; 11890 case 's': 11891 case 'v': 11892 case 'a': 11893 return C_RegisterClass; 11894 } 11895 } 11896 if (isImmConstraint(Constraint)) { 11897 return C_Other; 11898 } 11899 return TargetLowering::getConstraintType(Constraint); 11900 } 11901 11902 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11903 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11904 Val = Val & maskTrailingOnes<uint64_t>(Size); 11905 } 11906 return Val; 11907 } 11908 11909 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11910 std::string &Constraint, 11911 std::vector<SDValue> &Ops, 11912 SelectionDAG &DAG) const { 11913 if (isImmConstraint(Constraint)) { 11914 uint64_t Val; 11915 if (getAsmOperandConstVal(Op, Val) && 11916 checkAsmConstraintVal(Op, Constraint, Val)) { 11917 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11918 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11919 } 11920 } else { 11921 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11922 } 11923 } 11924 11925 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11926 unsigned Size = Op.getScalarValueSizeInBits(); 11927 if (Size > 64) 11928 return false; 11929 11930 if (Size == 16 && !Subtarget->has16BitInsts()) 11931 return false; 11932 11933 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11934 Val = C->getSExtValue(); 11935 return true; 11936 } 11937 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11938 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11939 return true; 11940 } 11941 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11942 if (Size != 16 || Op.getNumOperands() != 2) 11943 return false; 11944 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11945 return false; 11946 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11947 Val = C->getSExtValue(); 11948 return true; 11949 } 11950 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11951 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11952 return true; 11953 } 11954 } 11955 11956 return false; 11957 } 11958 11959 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11960 const std::string &Constraint, 11961 uint64_t Val) const { 11962 if (Constraint.size() == 1) { 11963 switch (Constraint[0]) { 11964 case 'I': 11965 return AMDGPU::isInlinableIntLiteral(Val); 11966 case 'J': 11967 return isInt<16>(Val); 11968 case 'A': 11969 return checkAsmConstraintValA(Op, Val); 11970 case 'B': 11971 return isInt<32>(Val); 11972 case 'C': 11973 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11974 AMDGPU::isInlinableIntLiteral(Val); 11975 default: 11976 break; 11977 } 11978 } else if (Constraint.size() == 2) { 11979 if (Constraint == "DA") { 11980 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11981 int64_t LoBits = static_cast<int32_t>(Val); 11982 return checkAsmConstraintValA(Op, HiBits, 32) && 11983 checkAsmConstraintValA(Op, LoBits, 32); 11984 } 11985 if (Constraint == "DB") { 11986 return true; 11987 } 11988 } 11989 llvm_unreachable("Invalid asm constraint"); 11990 } 11991 11992 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11993 uint64_t Val, 11994 unsigned MaxSize) const { 11995 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11996 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11997 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11998 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11999 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12000 return true; 12001 } 12002 return false; 12003 } 12004 12005 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12006 switch (UnalignedClassID) { 12007 case AMDGPU::VReg_64RegClassID: 12008 return AMDGPU::VReg_64_Align2RegClassID; 12009 case AMDGPU::VReg_96RegClassID: 12010 return AMDGPU::VReg_96_Align2RegClassID; 12011 case AMDGPU::VReg_128RegClassID: 12012 return AMDGPU::VReg_128_Align2RegClassID; 12013 case AMDGPU::VReg_160RegClassID: 12014 return AMDGPU::VReg_160_Align2RegClassID; 12015 case AMDGPU::VReg_192RegClassID: 12016 return AMDGPU::VReg_192_Align2RegClassID; 12017 case AMDGPU::VReg_224RegClassID: 12018 return AMDGPU::VReg_224_Align2RegClassID; 12019 case AMDGPU::VReg_256RegClassID: 12020 return AMDGPU::VReg_256_Align2RegClassID; 12021 case AMDGPU::VReg_512RegClassID: 12022 return AMDGPU::VReg_512_Align2RegClassID; 12023 case AMDGPU::VReg_1024RegClassID: 12024 return AMDGPU::VReg_1024_Align2RegClassID; 12025 case AMDGPU::AReg_64RegClassID: 12026 return AMDGPU::AReg_64_Align2RegClassID; 12027 case AMDGPU::AReg_96RegClassID: 12028 return AMDGPU::AReg_96_Align2RegClassID; 12029 case AMDGPU::AReg_128RegClassID: 12030 return AMDGPU::AReg_128_Align2RegClassID; 12031 case AMDGPU::AReg_160RegClassID: 12032 return AMDGPU::AReg_160_Align2RegClassID; 12033 case AMDGPU::AReg_192RegClassID: 12034 return AMDGPU::AReg_192_Align2RegClassID; 12035 case AMDGPU::AReg_256RegClassID: 12036 return AMDGPU::AReg_256_Align2RegClassID; 12037 case AMDGPU::AReg_512RegClassID: 12038 return AMDGPU::AReg_512_Align2RegClassID; 12039 case AMDGPU::AReg_1024RegClassID: 12040 return AMDGPU::AReg_1024_Align2RegClassID; 12041 default: 12042 return -1; 12043 } 12044 } 12045 12046 // Figure out which registers should be reserved for stack access. Only after 12047 // the function is legalized do we know all of the non-spill stack objects or if 12048 // calls are present. 12049 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12050 MachineRegisterInfo &MRI = MF.getRegInfo(); 12051 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12052 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12053 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12054 const SIInstrInfo *TII = ST.getInstrInfo(); 12055 12056 if (Info->isEntryFunction()) { 12057 // Callable functions have fixed registers used for stack access. 12058 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12059 } 12060 12061 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12062 Info->getStackPtrOffsetReg())); 12063 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12064 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12065 12066 // We need to worry about replacing the default register with itself in case 12067 // of MIR testcases missing the MFI. 12068 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12069 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12070 12071 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12072 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12073 12074 Info->limitOccupancy(MF); 12075 12076 if (ST.isWave32() && !MF.empty()) { 12077 for (auto &MBB : MF) { 12078 for (auto &MI : MBB) { 12079 TII->fixImplicitOperands(MI); 12080 } 12081 } 12082 } 12083 12084 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12085 // classes if required. Ideally the register class constraints would differ 12086 // per-subtarget, but there's no easy way to achieve that right now. This is 12087 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12088 // from using them as the register class for legal types. 12089 if (ST.needsAlignedVGPRs()) { 12090 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12091 const Register Reg = Register::index2VirtReg(I); 12092 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12093 if (!RC) 12094 continue; 12095 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12096 if (NewClassID != -1) 12097 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12098 } 12099 } 12100 12101 TargetLoweringBase::finalizeLowering(MF); 12102 } 12103 12104 void SITargetLowering::computeKnownBitsForFrameIndex( 12105 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12106 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12107 12108 // Set the high bits to zero based on the maximum allowed scratch size per 12109 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12110 // calculation won't overflow, so assume the sign bit is never set. 12111 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12112 } 12113 12114 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12115 KnownBits &Known, unsigned Dim) { 12116 unsigned MaxValue = 12117 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12118 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12119 } 12120 12121 void SITargetLowering::computeKnownBitsForTargetInstr( 12122 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12123 const MachineRegisterInfo &MRI, unsigned Depth) const { 12124 const MachineInstr *MI = MRI.getVRegDef(R); 12125 switch (MI->getOpcode()) { 12126 case AMDGPU::G_INTRINSIC: { 12127 switch (MI->getIntrinsicID()) { 12128 case Intrinsic::amdgcn_workitem_id_x: 12129 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12130 break; 12131 case Intrinsic::amdgcn_workitem_id_y: 12132 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12133 break; 12134 case Intrinsic::amdgcn_workitem_id_z: 12135 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12136 break; 12137 case Intrinsic::amdgcn_mbcnt_lo: 12138 case Intrinsic::amdgcn_mbcnt_hi: { 12139 // These return at most the wavefront size - 1. 12140 unsigned Size = MRI.getType(R).getSizeInBits(); 12141 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12142 break; 12143 } 12144 case Intrinsic::amdgcn_groupstaticsize: { 12145 // We can report everything over the maximum size as 0. We can't report 12146 // based on the actual size because we don't know if it's accurate or not 12147 // at any given point. 12148 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12149 break; 12150 } 12151 } 12152 break; 12153 } 12154 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12155 Known.Zero.setHighBits(24); 12156 break; 12157 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12158 Known.Zero.setHighBits(16); 12159 break; 12160 } 12161 } 12162 12163 Align SITargetLowering::computeKnownAlignForTargetInstr( 12164 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12165 unsigned Depth) const { 12166 const MachineInstr *MI = MRI.getVRegDef(R); 12167 switch (MI->getOpcode()) { 12168 case AMDGPU::G_INTRINSIC: 12169 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12170 // FIXME: Can this move to generic code? What about the case where the call 12171 // site specifies a lower alignment? 12172 Intrinsic::ID IID = MI->getIntrinsicID(); 12173 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12174 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12175 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12176 return *RetAlign; 12177 return Align(1); 12178 } 12179 default: 12180 return Align(1); 12181 } 12182 } 12183 12184 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12185 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12186 const Align CacheLineAlign = Align(64); 12187 12188 // Pre-GFX10 target did not benefit from loop alignment 12189 if (!ML || DisableLoopAlignment || 12190 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12191 getSubtarget()->hasInstFwdPrefetchBug()) 12192 return PrefAlign; 12193 12194 // On GFX10 I$ is 4 x 64 bytes cache lines. 12195 // By default prefetcher keeps one cache line behind and reads two ahead. 12196 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12197 // behind and one ahead. 12198 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12199 // If loop fits 64 bytes it always spans no more than two cache lines and 12200 // does not need an alignment. 12201 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12202 // Else if loop is less or equal 192 bytes we need two lines behind. 12203 12204 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12205 const MachineBasicBlock *Header = ML->getHeader(); 12206 if (Header->getAlignment() != PrefAlign) 12207 return Header->getAlignment(); // Already processed. 12208 12209 unsigned LoopSize = 0; 12210 for (const MachineBasicBlock *MBB : ML->blocks()) { 12211 // If inner loop block is aligned assume in average half of the alignment 12212 // size to be added as nops. 12213 if (MBB != Header) 12214 LoopSize += MBB->getAlignment().value() / 2; 12215 12216 for (const MachineInstr &MI : *MBB) { 12217 LoopSize += TII->getInstSizeInBytes(MI); 12218 if (LoopSize > 192) 12219 return PrefAlign; 12220 } 12221 } 12222 12223 if (LoopSize <= 64) 12224 return PrefAlign; 12225 12226 if (LoopSize <= 128) 12227 return CacheLineAlign; 12228 12229 // If any of parent loops is surrounded by prefetch instructions do not 12230 // insert new for inner loop, which would reset parent's settings. 12231 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12232 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12233 auto I = Exit->getFirstNonDebugInstr(); 12234 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12235 return CacheLineAlign; 12236 } 12237 } 12238 12239 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12240 MachineBasicBlock *Exit = ML->getExitBlock(); 12241 12242 if (Pre && Exit) { 12243 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12244 TII->get(AMDGPU::S_INST_PREFETCH)) 12245 .addImm(1); // prefetch 2 lines behind PC 12246 12247 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12248 TII->get(AMDGPU::S_INST_PREFETCH)) 12249 .addImm(2); // prefetch 1 line behind PC 12250 } 12251 12252 return CacheLineAlign; 12253 } 12254 12255 LLVM_ATTRIBUTE_UNUSED 12256 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12257 assert(N->getOpcode() == ISD::CopyFromReg); 12258 do { 12259 // Follow the chain until we find an INLINEASM node. 12260 N = N->getOperand(0).getNode(); 12261 if (N->getOpcode() == ISD::INLINEASM || 12262 N->getOpcode() == ISD::INLINEASM_BR) 12263 return true; 12264 } while (N->getOpcode() == ISD::CopyFromReg); 12265 return false; 12266 } 12267 12268 bool SITargetLowering::isSDNodeSourceOfDivergence( 12269 const SDNode *N, FunctionLoweringInfo *FLI, 12270 LegacyDivergenceAnalysis *KDA) const { 12271 switch (N->getOpcode()) { 12272 case ISD::CopyFromReg: { 12273 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12274 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12275 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12276 Register Reg = R->getReg(); 12277 12278 // FIXME: Why does this need to consider isLiveIn? 12279 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12280 return !TRI->isSGPRReg(MRI, Reg); 12281 12282 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12283 return KDA->isDivergent(V); 12284 12285 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12286 return !TRI->isSGPRReg(MRI, Reg); 12287 } 12288 case ISD::LOAD: { 12289 const LoadSDNode *L = cast<LoadSDNode>(N); 12290 unsigned AS = L->getAddressSpace(); 12291 // A flat load may access private memory. 12292 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12293 } 12294 case ISD::CALLSEQ_END: 12295 return true; 12296 case ISD::INTRINSIC_WO_CHAIN: 12297 return AMDGPU::isIntrinsicSourceOfDivergence( 12298 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12299 case ISD::INTRINSIC_W_CHAIN: 12300 return AMDGPU::isIntrinsicSourceOfDivergence( 12301 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12302 case AMDGPUISD::ATOMIC_CMP_SWAP: 12303 case AMDGPUISD::ATOMIC_INC: 12304 case AMDGPUISD::ATOMIC_DEC: 12305 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12306 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12307 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12308 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12309 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12310 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12311 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12312 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12313 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12314 case AMDGPUISD::BUFFER_ATOMIC_AND: 12315 case AMDGPUISD::BUFFER_ATOMIC_OR: 12316 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12317 case AMDGPUISD::BUFFER_ATOMIC_INC: 12318 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12319 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12320 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12321 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12322 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12323 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12324 // Target-specific read-modify-write atomics are sources of divergence. 12325 return true; 12326 default: 12327 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12328 // Generic read-modify-write atomics are sources of divergence. 12329 return A->readMem() && A->writeMem(); 12330 } 12331 return false; 12332 } 12333 } 12334 12335 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12336 EVT VT) const { 12337 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12338 case MVT::f32: 12339 return hasFP32Denormals(DAG.getMachineFunction()); 12340 case MVT::f64: 12341 case MVT::f16: 12342 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12343 default: 12344 return false; 12345 } 12346 } 12347 12348 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12349 MachineFunction &MF) const { 12350 switch (Ty.getScalarSizeInBits()) { 12351 case 32: 12352 return hasFP32Denormals(MF); 12353 case 64: 12354 case 16: 12355 return hasFP64FP16Denormals(MF); 12356 default: 12357 return false; 12358 } 12359 } 12360 12361 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12362 const SelectionDAG &DAG, 12363 bool SNaN, 12364 unsigned Depth) const { 12365 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12366 const MachineFunction &MF = DAG.getMachineFunction(); 12367 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12368 12369 if (Info->getMode().DX10Clamp) 12370 return true; // Clamped to 0. 12371 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12372 } 12373 12374 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12375 SNaN, Depth); 12376 } 12377 12378 // Global FP atomic instructions have a hardcoded FP mode and do not support 12379 // FP32 denormals, and only support v2f16 denormals. 12380 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12381 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12382 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12383 if (&Flt == &APFloat::IEEEsingle()) 12384 return DenormMode == DenormalMode::getPreserveSign(); 12385 return DenormMode == DenormalMode::getIEEE(); 12386 } 12387 12388 TargetLowering::AtomicExpansionKind 12389 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12390 12391 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12392 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12393 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12394 SmallVector<StringRef> SSNs; 12395 Ctx.getSyncScopeNames(SSNs); 12396 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12397 ? "system" 12398 : SSNs[RMW->getSyncScopeID()]; 12399 ORE.emit([&]() { 12400 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12401 << "Hardware instruction generated for atomic " 12402 << RMW->getOperationName(RMW->getOperation()) 12403 << " operation at memory scope " << MemScope 12404 << " due to an unsafe request."; 12405 }); 12406 return Kind; 12407 }; 12408 12409 switch (RMW->getOperation()) { 12410 case AtomicRMWInst::FAdd: { 12411 Type *Ty = RMW->getType(); 12412 12413 // We don't have a way to support 16-bit atomics now, so just leave them 12414 // as-is. 12415 if (Ty->isHalfTy()) 12416 return AtomicExpansionKind::None; 12417 12418 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12419 return AtomicExpansionKind::CmpXChg; 12420 12421 unsigned AS = RMW->getPointerAddressSpace(); 12422 12423 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12424 Subtarget->hasAtomicFaddInsts()) { 12425 if (Subtarget->hasGFX940Insts()) 12426 return AtomicExpansionKind::None; 12427 12428 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12429 // floating point atomic instructions. May generate more efficient code, 12430 // but may not respect rounding and denormal modes, and may give incorrect 12431 // results for certain memory destinations. 12432 if (RMW->getFunction() 12433 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12434 .getValueAsString() != "true") 12435 return AtomicExpansionKind::CmpXChg; 12436 12437 if (Subtarget->hasGFX90AInsts()) { 12438 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12439 return AtomicExpansionKind::CmpXChg; 12440 12441 auto SSID = RMW->getSyncScopeID(); 12442 if (SSID == SyncScope::System || 12443 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12444 return AtomicExpansionKind::CmpXChg; 12445 12446 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12447 } 12448 12449 if (AS == AMDGPUAS::FLAT_ADDRESS) 12450 return AtomicExpansionKind::CmpXChg; 12451 12452 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12453 : AtomicExpansionKind::CmpXChg; 12454 } 12455 12456 // DS FP atomics do respect the denormal mode, but the rounding mode is 12457 // fixed to round-to-nearest-even. 12458 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12459 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12460 if (!Ty->isDoubleTy()) 12461 return AtomicExpansionKind::None; 12462 12463 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12464 return AtomicExpansionKind::None; 12465 12466 return RMW->getFunction() 12467 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12468 .getValueAsString() == "true" 12469 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12470 : AtomicExpansionKind::CmpXChg; 12471 } 12472 12473 return AtomicExpansionKind::CmpXChg; 12474 } 12475 default: 12476 break; 12477 } 12478 12479 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12480 } 12481 12482 const TargetRegisterClass * 12483 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12484 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12485 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12486 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12487 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12488 : &AMDGPU::SReg_32RegClass; 12489 if (!TRI->isSGPRClass(RC) && !isDivergent) 12490 return TRI->getEquivalentSGPRClass(RC); 12491 else if (TRI->isSGPRClass(RC) && isDivergent) 12492 return TRI->getEquivalentVGPRClass(RC); 12493 12494 return RC; 12495 } 12496 12497 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12498 // uniform values (as produced by the mask results of control flow intrinsics) 12499 // used outside of divergent blocks. The phi users need to also be treated as 12500 // always uniform. 12501 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12502 unsigned WaveSize) { 12503 // FIXME: We assume we never cast the mask results of a control flow 12504 // intrinsic. 12505 // Early exit if the type won't be consistent as a compile time hack. 12506 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12507 if (!IT || IT->getBitWidth() != WaveSize) 12508 return false; 12509 12510 if (!isa<Instruction>(V)) 12511 return false; 12512 if (!Visited.insert(V).second) 12513 return false; 12514 bool Result = false; 12515 for (auto U : V->users()) { 12516 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12517 if (V == U->getOperand(1)) { 12518 switch (Intrinsic->getIntrinsicID()) { 12519 default: 12520 Result = false; 12521 break; 12522 case Intrinsic::amdgcn_if_break: 12523 case Intrinsic::amdgcn_if: 12524 case Intrinsic::amdgcn_else: 12525 Result = true; 12526 break; 12527 } 12528 } 12529 if (V == U->getOperand(0)) { 12530 switch (Intrinsic->getIntrinsicID()) { 12531 default: 12532 Result = false; 12533 break; 12534 case Intrinsic::amdgcn_end_cf: 12535 case Intrinsic::amdgcn_loop: 12536 Result = true; 12537 break; 12538 } 12539 } 12540 } else { 12541 Result = hasCFUser(U, Visited, WaveSize); 12542 } 12543 if (Result) 12544 break; 12545 } 12546 return Result; 12547 } 12548 12549 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12550 const Value *V) const { 12551 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12552 if (CI->isInlineAsm()) { 12553 // FIXME: This cannot give a correct answer. This should only trigger in 12554 // the case where inline asm returns mixed SGPR and VGPR results, used 12555 // outside the defining block. We don't have a specific result to 12556 // consider, so this assumes if any value is SGPR, the overall register 12557 // also needs to be SGPR. 12558 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12559 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12560 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12561 for (auto &TC : TargetConstraints) { 12562 if (TC.Type == InlineAsm::isOutput) { 12563 ComputeConstraintToUse(TC, SDValue()); 12564 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12565 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12566 if (RC && SIRI->isSGPRClass(RC)) 12567 return true; 12568 } 12569 } 12570 } 12571 } 12572 SmallPtrSet<const Value *, 16> Visited; 12573 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12574 } 12575 12576 std::pair<InstructionCost, MVT> 12577 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12578 Type *Ty) const { 12579 std::pair<InstructionCost, MVT> Cost = 12580 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12581 auto Size = DL.getTypeSizeInBits(Ty); 12582 // Maximum load or store can handle 8 dwords for scalar and 4 for 12583 // vector ALU. Let's assume anything above 8 dwords is expensive 12584 // even if legal. 12585 if (Size <= 256) 12586 return Cost; 12587 12588 Cost.first += (Size + 255) / 256; 12589 return Cost; 12590 } 12591 12592 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12593 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12594 for (; I != E; ++I) { 12595 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12596 if (getBasePtrIndex(M) == I.getOperandNo()) 12597 return true; 12598 } 12599 } 12600 return false; 12601 } 12602 12603 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12604 SDValue N1) const { 12605 if (!N0.hasOneUse()) 12606 return false; 12607 // Take care of the opportunity to keep N0 uniform 12608 if (N0->isDivergent() || !N1->isDivergent()) 12609 return true; 12610 // Check if we have a good chance to form the memory access pattern with the 12611 // base and offset 12612 return (DAG.isBaseWithConstantOffset(N0) && 12613 hasMemSDNodeUser(*N0->use_begin())); 12614 } 12615 12616 MachineMemOperand::Flags 12617 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12618 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12619 if (I.getMetadata("amdgpu.noclobber")) 12620 return MONoClobber; 12621 return MachineMemOperand::MONone; 12622 } 12623