1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/BinaryFormat/ELF.h" 24 #include "llvm/CodeGen/Analysis.h" 25 #include "llvm/CodeGen/FunctionLoweringInfo.h" 26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineLoopInfo.h" 29 #include "llvm/IR/DiagnosticInfo.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/IntrinsicsAMDGPU.h" 32 #include "llvm/IR/IntrinsicsR600.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/KnownBits.h" 35 36 using namespace llvm; 37 38 #define DEBUG_TYPE "si-lower" 39 40 STATISTIC(NumTailCalls, "Number of tail calls"); 41 42 static cl::opt<bool> DisableLoopAlignment( 43 "amdgpu-disable-loop-alignment", 44 cl::desc("Do not align and prefetch loops"), 45 cl::init(false)); 46 47 static cl::opt<bool> VGPRReserveforSGPRSpill( 48 "amdgpu-reserve-vgpr-for-sgpr-spill", 49 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 50 51 static cl::opt<bool> UseDivergentRegisterIndexing( 52 "amdgpu-use-divergent-register-indexing", 53 cl::Hidden, 54 cl::desc("Use indirect register addressing for divergent indexes"), 55 cl::init(false)); 56 57 static bool hasFP32Denormals(const MachineFunction &MF) { 58 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 59 return Info->getMode().allFP32Denormals(); 60 } 61 62 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 63 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 64 return Info->getMode().allFP64FP16Denormals(); 65 } 66 67 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 68 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 69 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 70 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 71 return AMDGPU::SGPR0 + Reg; 72 } 73 } 74 llvm_unreachable("Cannot allocate sgpr"); 75 } 76 77 SITargetLowering::SITargetLowering(const TargetMachine &TM, 78 const GCNSubtarget &STI) 79 : AMDGPUTargetLowering(TM, STI), 80 Subtarget(&STI) { 81 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 82 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 83 84 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 85 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 86 87 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 88 89 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 90 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 91 92 addRegisterClass(MVT::f64, V64RegClass); 93 addRegisterClass(MVT::v2f32, V64RegClass); 94 95 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 96 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 97 98 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 99 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 100 101 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 102 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 103 104 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 105 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 106 107 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 108 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 109 110 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 111 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 112 113 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 114 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 115 116 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 117 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 118 119 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 120 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 121 122 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 123 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 124 125 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 126 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 127 128 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 129 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 130 131 if (Subtarget->has16BitInsts()) { 132 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 133 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 134 135 // Unless there are also VOP3P operations, not operations are really legal. 136 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 137 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 138 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 139 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 140 } 141 142 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 143 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 144 145 computeRegisterProperties(Subtarget->getRegisterInfo()); 146 147 // The boolean content concept here is too inflexible. Compares only ever 148 // really produce a 1-bit result. Any copy/extend from these will turn into a 149 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 150 // it's what most targets use. 151 setBooleanContents(ZeroOrOneBooleanContent); 152 setBooleanVectorContents(ZeroOrOneBooleanContent); 153 154 // We need to custom lower vector stores from local memory 155 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::i1, Custom); 164 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 165 166 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 174 setOperationAction(ISD::STORE, MVT::i1, Custom); 175 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 176 177 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 178 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 179 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 180 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 181 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 182 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 183 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 184 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 185 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 186 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 187 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 188 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 189 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 190 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 191 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 192 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 193 194 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 195 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 196 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 197 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 200 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 201 202 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 203 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 204 205 setOperationAction(ISD::SELECT, MVT::i1, Promote); 206 setOperationAction(ISD::SELECT, MVT::i64, Custom); 207 setOperationAction(ISD::SELECT, MVT::f64, Promote); 208 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 209 210 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 215 216 setOperationAction(ISD::SETCC, MVT::i1, Promote); 217 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 218 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 219 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 220 221 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 222 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 223 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 224 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 225 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 227 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 228 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 229 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 230 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 231 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 232 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 233 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 234 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 235 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 236 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 237 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 246 247 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 248 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 249 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 251 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 253 254 setOperationAction(ISD::UADDO, MVT::i32, Legal); 255 setOperationAction(ISD::USUBO, MVT::i32, Legal); 256 257 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 258 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 259 260 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 261 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 263 264 #if 0 265 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 266 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 267 #endif 268 269 // We only support LOAD/STORE and vector manipulation ops for vectors 270 // with > 4 elements. 271 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 272 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 273 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 274 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 275 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 276 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 277 switch (Op) { 278 case ISD::LOAD: 279 case ISD::STORE: 280 case ISD::BUILD_VECTOR: 281 case ISD::BITCAST: 282 case ISD::EXTRACT_VECTOR_ELT: 283 case ISD::INSERT_VECTOR_ELT: 284 case ISD::EXTRACT_SUBVECTOR: 285 case ISD::SCALAR_TO_VECTOR: 286 break; 287 case ISD::INSERT_SUBVECTOR: 288 case ISD::CONCAT_VECTORS: 289 setOperationAction(Op, VT, Custom); 290 break; 291 default: 292 setOperationAction(Op, VT, Expand); 293 break; 294 } 295 } 296 } 297 298 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 299 300 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 301 // is expanded to avoid having two separate loops in case the index is a VGPR. 302 303 // Most operations are naturally 32-bit vector operations. We only support 304 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 305 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 306 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 307 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 308 309 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 310 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 311 312 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 313 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 314 315 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 316 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 317 } 318 319 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 320 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 321 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 322 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 324 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 325 326 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 327 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 328 329 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 330 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 331 } 332 333 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 334 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 335 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 336 337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 338 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 339 340 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 341 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 344 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 345 } 346 347 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 348 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 349 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 350 351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 352 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 353 354 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 355 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 358 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 359 } 360 361 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 362 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 363 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 364 365 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 366 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 367 368 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 369 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 372 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 373 } 374 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 379 380 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 381 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 382 383 // Avoid stack access for these. 384 // TODO: Generalize to more vector types. 385 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 386 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 387 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 388 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 389 390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 396 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 401 402 // Deal with vec3 vector operations when widened to vec4. 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 407 408 // Deal with vec5/6/7 vector operations when widened to vec8. 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 417 418 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 419 // and output demarshalling 420 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 421 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 422 423 // We can't return success/failure, only the old value, 424 // let LLVM add the comparison 425 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 426 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 427 428 if (Subtarget->hasFlatAddressSpace()) { 429 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 430 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 431 } 432 433 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 434 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 435 436 // FIXME: This should be narrowed to i32, but that only happens if i64 is 437 // illegal. 438 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 439 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 440 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 441 442 // On SI this is s_memtime and s_memrealtime on VI. 443 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 444 setOperationAction(ISD::TRAP, MVT::Other, Custom); 445 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 446 447 if (Subtarget->has16BitInsts()) { 448 setOperationAction(ISD::FPOW, MVT::f16, Promote); 449 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 450 setOperationAction(ISD::FLOG, MVT::f16, Custom); 451 setOperationAction(ISD::FEXP, MVT::f16, Custom); 452 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 453 } 454 455 if (Subtarget->hasMadMacF32Insts()) 456 setOperationAction(ISD::FMAD, MVT::f32, Legal); 457 458 if (!Subtarget->hasBFI()) { 459 // fcopysign can be done in a single instruction with BFI. 460 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 461 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 462 } 463 464 if (!Subtarget->hasBCNT(32)) 465 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 466 467 if (!Subtarget->hasBCNT(64)) 468 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 469 470 if (Subtarget->hasFFBH()) { 471 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 473 } 474 475 if (Subtarget->hasFFBL()) { 476 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 478 } 479 480 // We only really have 32-bit BFE instructions (and 16-bit on VI). 481 // 482 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 483 // effort to match them now. We want this to be false for i64 cases when the 484 // extraction isn't restricted to the upper or lower half. Ideally we would 485 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 486 // span the midpoint are probably relatively rare, so don't worry about them 487 // for now. 488 if (Subtarget->hasBFE()) 489 setHasExtractBitsInsn(true); 490 491 // Clamp modifier on add/sub 492 if (Subtarget->hasIntClamp()) { 493 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 494 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 495 } 496 497 if (Subtarget->hasAddNoCarry()) { 498 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 502 } 503 504 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 508 509 510 // These are really only legal for ieee_mode functions. We should be avoiding 511 // them for functions that don't have ieee_mode enabled, so just say they are 512 // legal. 513 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 517 518 519 if (Subtarget->haveRoundOpsF64()) { 520 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 521 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 522 setOperationAction(ISD::FRINT, MVT::f64, Legal); 523 } else { 524 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 525 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 526 setOperationAction(ISD::FRINT, MVT::f64, Custom); 527 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 528 } 529 530 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 531 532 setOperationAction(ISD::FSIN, MVT::f32, Custom); 533 setOperationAction(ISD::FCOS, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f64, Custom); 536 537 if (Subtarget->has16BitInsts()) { 538 setOperationAction(ISD::Constant, MVT::i16, Legal); 539 540 setOperationAction(ISD::SMIN, MVT::i16, Legal); 541 setOperationAction(ISD::SMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::UMIN, MVT::i16, Legal); 544 setOperationAction(ISD::UMAX, MVT::i16, Legal); 545 546 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 547 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 548 549 setOperationAction(ISD::ROTR, MVT::i16, Expand); 550 setOperationAction(ISD::ROTL, MVT::i16, Expand); 551 552 setOperationAction(ISD::SDIV, MVT::i16, Promote); 553 setOperationAction(ISD::UDIV, MVT::i16, Promote); 554 setOperationAction(ISD::SREM, MVT::i16, Promote); 555 setOperationAction(ISD::UREM, MVT::i16, Promote); 556 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 557 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 558 559 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 560 561 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 566 567 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 568 569 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::LOAD, MVT::i16, Custom); 572 573 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 574 575 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 576 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 577 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 579 580 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 582 583 // F16 - Constant Actions. 584 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 585 586 // F16 - Load/Store Actions. 587 setOperationAction(ISD::LOAD, MVT::f16, Promote); 588 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 589 setOperationAction(ISD::STORE, MVT::f16, Promote); 590 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 591 592 // F16 - VOP1 Actions. 593 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 594 setOperationAction(ISD::FCOS, MVT::f16, Custom); 595 setOperationAction(ISD::FSIN, MVT::f16, Custom); 596 597 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 598 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 599 600 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 601 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 602 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 604 setOperationAction(ISD::FROUND, MVT::f16, Custom); 605 606 // F16 - VOP2 Actions. 607 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 608 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 609 610 setOperationAction(ISD::FDIV, MVT::f16, Custom); 611 612 // F16 - VOP3 Actions. 613 setOperationAction(ISD::FMA, MVT::f16, Legal); 614 if (STI.hasMadF16()) 615 setOperationAction(ISD::FMAD, MVT::f16, Legal); 616 617 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 618 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 619 switch (Op) { 620 case ISD::LOAD: 621 case ISD::STORE: 622 case ISD::BUILD_VECTOR: 623 case ISD::BITCAST: 624 case ISD::EXTRACT_VECTOR_ELT: 625 case ISD::INSERT_VECTOR_ELT: 626 case ISD::INSERT_SUBVECTOR: 627 case ISD::EXTRACT_SUBVECTOR: 628 case ISD::SCALAR_TO_VECTOR: 629 break; 630 case ISD::CONCAT_VECTORS: 631 setOperationAction(Op, VT, Custom); 632 break; 633 default: 634 setOperationAction(Op, VT, Expand); 635 break; 636 } 637 } 638 } 639 640 // v_perm_b32 can handle either of these. 641 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 643 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 644 645 // XXX - Do these do anything? Vector constants turn into build_vector. 646 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 647 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 648 649 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 650 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 653 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 654 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 655 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 656 657 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 658 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 659 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 660 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 661 662 setOperationAction(ISD::AND, MVT::v2i16, Promote); 663 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 664 setOperationAction(ISD::OR, MVT::v2i16, Promote); 665 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 666 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 668 669 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 670 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 671 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 672 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 673 674 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 675 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 676 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 677 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 678 679 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 682 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 683 684 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 686 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 687 688 if (!Subtarget->hasVOP3PInsts()) { 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 690 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 691 } 692 693 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 694 // This isn't really legal, but this avoids the legalizer unrolling it (and 695 // allows matching fneg (fabs x) patterns) 696 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 697 698 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 700 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 701 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 702 703 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 704 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 705 706 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 707 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 708 } 709 710 if (Subtarget->hasVOP3PInsts()) { 711 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 712 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 713 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 716 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 717 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 719 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 720 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 721 722 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 725 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 726 727 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 730 731 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 732 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 733 734 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 735 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 741 742 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 744 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 745 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 746 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 747 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 748 749 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 750 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 752 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 753 754 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 757 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 758 759 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 762 763 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 764 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 765 766 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 768 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 769 770 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 772 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 773 774 if (Subtarget->hasPackedFP32Ops()) { 775 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 776 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 777 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 778 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 779 780 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 781 setOperationAction(ISD::FADD, VT, Custom); 782 setOperationAction(ISD::FMUL, VT, Custom); 783 setOperationAction(ISD::FMA, VT, Custom); 784 } 785 } 786 } 787 788 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 789 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 790 791 if (Subtarget->has16BitInsts()) { 792 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 793 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 794 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 795 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 796 } else { 797 // Legalization hack. 798 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 799 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 800 801 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 802 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 803 } 804 805 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 806 setOperationAction(ISD::SELECT, VT, Custom); 807 } 808 809 setOperationAction(ISD::SMULO, MVT::i64, Custom); 810 setOperationAction(ISD::UMULO, MVT::i64, Custom); 811 812 if (Subtarget->hasMad64_32()) { 813 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 814 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 815 } 816 817 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 818 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 819 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 820 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 821 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 822 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 823 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 824 825 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 826 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 827 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 828 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 829 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 830 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 831 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 832 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 833 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 834 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 835 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 836 837 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 838 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 839 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 840 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 841 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 842 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 843 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 844 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 845 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 846 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 847 848 setTargetDAGCombine(ISD::ADD); 849 setTargetDAGCombine(ISD::ADDCARRY); 850 setTargetDAGCombine(ISD::SUB); 851 setTargetDAGCombine(ISD::SUBCARRY); 852 setTargetDAGCombine(ISD::FADD); 853 setTargetDAGCombine(ISD::FSUB); 854 setTargetDAGCombine(ISD::FMINNUM); 855 setTargetDAGCombine(ISD::FMAXNUM); 856 setTargetDAGCombine(ISD::FMINNUM_IEEE); 857 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 858 setTargetDAGCombine(ISD::FMA); 859 setTargetDAGCombine(ISD::SMIN); 860 setTargetDAGCombine(ISD::SMAX); 861 setTargetDAGCombine(ISD::UMIN); 862 setTargetDAGCombine(ISD::UMAX); 863 setTargetDAGCombine(ISD::SETCC); 864 setTargetDAGCombine(ISD::AND); 865 setTargetDAGCombine(ISD::OR); 866 setTargetDAGCombine(ISD::XOR); 867 setTargetDAGCombine(ISD::SINT_TO_FP); 868 setTargetDAGCombine(ISD::UINT_TO_FP); 869 setTargetDAGCombine(ISD::FCANONICALIZE); 870 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 871 setTargetDAGCombine(ISD::ZERO_EXTEND); 872 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 873 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 874 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 875 876 // All memory operations. Some folding on the pointer operand is done to help 877 // matching the constant offsets in the addressing modes. 878 setTargetDAGCombine(ISD::LOAD); 879 setTargetDAGCombine(ISD::STORE); 880 setTargetDAGCombine(ISD::ATOMIC_LOAD); 881 setTargetDAGCombine(ISD::ATOMIC_STORE); 882 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 883 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 884 setTargetDAGCombine(ISD::ATOMIC_SWAP); 885 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 886 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 887 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 888 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 889 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 890 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 891 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 892 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 893 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 894 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 895 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 896 setTargetDAGCombine(ISD::INTRINSIC_VOID); 897 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 898 899 // FIXME: In other contexts we pretend this is a per-function property. 900 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 901 902 setSchedulingPreference(Sched::RegPressure); 903 } 904 905 const GCNSubtarget *SITargetLowering::getSubtarget() const { 906 return Subtarget; 907 } 908 909 //===----------------------------------------------------------------------===// 910 // TargetLowering queries 911 //===----------------------------------------------------------------------===// 912 913 // v_mad_mix* support a conversion from f16 to f32. 914 // 915 // There is only one special case when denormals are enabled we don't currently, 916 // where this is OK to use. 917 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 918 EVT DestVT, EVT SrcVT) const { 919 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 920 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 921 DestVT.getScalarType() == MVT::f32 && 922 SrcVT.getScalarType() == MVT::f16 && 923 // TODO: This probably only requires no input flushing? 924 !hasFP32Denormals(DAG.getMachineFunction()); 925 } 926 927 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 928 // SI has some legal vector types, but no legal vector operations. Say no 929 // shuffles are legal in order to prefer scalarizing some vector operations. 930 return false; 931 } 932 933 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 934 CallingConv::ID CC, 935 EVT VT) const { 936 if (CC == CallingConv::AMDGPU_KERNEL) 937 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 938 939 if (VT.isVector()) { 940 EVT ScalarVT = VT.getScalarType(); 941 unsigned Size = ScalarVT.getSizeInBits(); 942 if (Size == 16) { 943 if (Subtarget->has16BitInsts()) 944 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 945 return VT.isInteger() ? MVT::i32 : MVT::f32; 946 } 947 948 if (Size < 16) 949 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 950 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 951 } 952 953 if (VT.getSizeInBits() > 32) 954 return MVT::i32; 955 956 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 957 } 958 959 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 960 CallingConv::ID CC, 961 EVT VT) const { 962 if (CC == CallingConv::AMDGPU_KERNEL) 963 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 964 965 if (VT.isVector()) { 966 unsigned NumElts = VT.getVectorNumElements(); 967 EVT ScalarVT = VT.getScalarType(); 968 unsigned Size = ScalarVT.getSizeInBits(); 969 970 // FIXME: Should probably promote 8-bit vectors to i16. 971 if (Size == 16 && Subtarget->has16BitInsts()) 972 return (NumElts + 1) / 2; 973 974 if (Size <= 32) 975 return NumElts; 976 977 if (Size > 32) 978 return NumElts * ((Size + 31) / 32); 979 } else if (VT.getSizeInBits() > 32) 980 return (VT.getSizeInBits() + 31) / 32; 981 982 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 983 } 984 985 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 986 LLVMContext &Context, CallingConv::ID CC, 987 EVT VT, EVT &IntermediateVT, 988 unsigned &NumIntermediates, MVT &RegisterVT) const { 989 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 990 unsigned NumElts = VT.getVectorNumElements(); 991 EVT ScalarVT = VT.getScalarType(); 992 unsigned Size = ScalarVT.getSizeInBits(); 993 // FIXME: We should fix the ABI to be the same on targets without 16-bit 994 // support, but unless we can properly handle 3-vectors, it will be still be 995 // inconsistent. 996 if (Size == 16 && Subtarget->has16BitInsts()) { 997 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 998 IntermediateVT = RegisterVT; 999 NumIntermediates = (NumElts + 1) / 2; 1000 return NumIntermediates; 1001 } 1002 1003 if (Size == 32) { 1004 RegisterVT = ScalarVT.getSimpleVT(); 1005 IntermediateVT = RegisterVT; 1006 NumIntermediates = NumElts; 1007 return NumIntermediates; 1008 } 1009 1010 if (Size < 16 && Subtarget->has16BitInsts()) { 1011 // FIXME: Should probably form v2i16 pieces 1012 RegisterVT = MVT::i16; 1013 IntermediateVT = ScalarVT; 1014 NumIntermediates = NumElts; 1015 return NumIntermediates; 1016 } 1017 1018 1019 if (Size != 16 && Size <= 32) { 1020 RegisterVT = MVT::i32; 1021 IntermediateVT = ScalarVT; 1022 NumIntermediates = NumElts; 1023 return NumIntermediates; 1024 } 1025 1026 if (Size > 32) { 1027 RegisterVT = MVT::i32; 1028 IntermediateVT = RegisterVT; 1029 NumIntermediates = NumElts * ((Size + 31) / 32); 1030 return NumIntermediates; 1031 } 1032 } 1033 1034 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1035 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1036 } 1037 1038 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1039 assert(DMaskLanes != 0); 1040 1041 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1042 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1043 return EVT::getVectorVT(Ty->getContext(), 1044 EVT::getEVT(VT->getElementType()), 1045 NumElts); 1046 } 1047 1048 return EVT::getEVT(Ty); 1049 } 1050 1051 // Peek through TFE struct returns to only use the data size. 1052 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1053 auto *ST = dyn_cast<StructType>(Ty); 1054 if (!ST) 1055 return memVTFromImageData(Ty, DMaskLanes); 1056 1057 // Some intrinsics return an aggregate type - special case to work out the 1058 // correct memVT. 1059 // 1060 // Only limited forms of aggregate type currently expected. 1061 if (ST->getNumContainedTypes() != 2 || 1062 !ST->getContainedType(1)->isIntegerTy(32)) 1063 return EVT(); 1064 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1065 } 1066 1067 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1068 const CallInst &CI, 1069 MachineFunction &MF, 1070 unsigned IntrID) const { 1071 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1072 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1073 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1074 (Intrinsic::ID)IntrID); 1075 if (Attr.hasFnAttr(Attribute::ReadNone)) 1076 return false; 1077 1078 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1079 1080 if (RsrcIntr->IsImage) { 1081 Info.ptrVal = 1082 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1083 Info.align.reset(); 1084 } else { 1085 Info.ptrVal = 1086 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1087 } 1088 1089 Info.flags = MachineMemOperand::MODereferenceable; 1090 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1091 unsigned DMaskLanes = 4; 1092 1093 if (RsrcIntr->IsImage) { 1094 const AMDGPU::ImageDimIntrinsicInfo *Intr 1095 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1096 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1097 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1098 1099 if (!BaseOpcode->Gather4) { 1100 // If this isn't a gather, we may have excess loaded elements in the 1101 // IR type. Check the dmask for the real number of elements loaded. 1102 unsigned DMask 1103 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1104 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1105 } 1106 1107 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1108 } else 1109 Info.memVT = EVT::getEVT(CI.getType()); 1110 1111 // FIXME: What does alignment mean for an image? 1112 Info.opc = ISD::INTRINSIC_W_CHAIN; 1113 Info.flags |= MachineMemOperand::MOLoad; 1114 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1115 Info.opc = ISD::INTRINSIC_VOID; 1116 1117 Type *DataTy = CI.getArgOperand(0)->getType(); 1118 if (RsrcIntr->IsImage) { 1119 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1120 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1121 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1122 } else 1123 Info.memVT = EVT::getEVT(DataTy); 1124 1125 Info.flags |= MachineMemOperand::MOStore; 1126 } else { 1127 // Atomic 1128 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1129 ISD::INTRINSIC_W_CHAIN; 1130 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1131 Info.flags = MachineMemOperand::MOLoad | 1132 MachineMemOperand::MOStore | 1133 MachineMemOperand::MODereferenceable; 1134 1135 // XXX - Should this be volatile without known ordering? 1136 Info.flags |= MachineMemOperand::MOVolatile; 1137 } 1138 return true; 1139 } 1140 1141 switch (IntrID) { 1142 case Intrinsic::amdgcn_atomic_inc: 1143 case Intrinsic::amdgcn_atomic_dec: 1144 case Intrinsic::amdgcn_ds_ordered_add: 1145 case Intrinsic::amdgcn_ds_ordered_swap: 1146 case Intrinsic::amdgcn_ds_fadd: 1147 case Intrinsic::amdgcn_ds_fmin: 1148 case Intrinsic::amdgcn_ds_fmax: { 1149 Info.opc = ISD::INTRINSIC_W_CHAIN; 1150 Info.memVT = MVT::getVT(CI.getType()); 1151 Info.ptrVal = CI.getOperand(0); 1152 Info.align.reset(); 1153 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1154 1155 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1156 if (!Vol->isZero()) 1157 Info.flags |= MachineMemOperand::MOVolatile; 1158 1159 return true; 1160 } 1161 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1162 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1163 1164 Info.opc = ISD::INTRINSIC_W_CHAIN; 1165 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1166 Info.ptrVal = 1167 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1168 Info.align.reset(); 1169 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1170 1171 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1172 if (!Vol || !Vol->isZero()) 1173 Info.flags |= MachineMemOperand::MOVolatile; 1174 1175 return true; 1176 } 1177 case Intrinsic::amdgcn_ds_append: 1178 case Intrinsic::amdgcn_ds_consume: { 1179 Info.opc = ISD::INTRINSIC_W_CHAIN; 1180 Info.memVT = MVT::getVT(CI.getType()); 1181 Info.ptrVal = CI.getOperand(0); 1182 Info.align.reset(); 1183 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1184 1185 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1186 if (!Vol->isZero()) 1187 Info.flags |= MachineMemOperand::MOVolatile; 1188 1189 return true; 1190 } 1191 case Intrinsic::amdgcn_global_atomic_csub: { 1192 Info.opc = ISD::INTRINSIC_W_CHAIN; 1193 Info.memVT = MVT::getVT(CI.getType()); 1194 Info.ptrVal = CI.getOperand(0); 1195 Info.align.reset(); 1196 Info.flags = MachineMemOperand::MOLoad | 1197 MachineMemOperand::MOStore | 1198 MachineMemOperand::MOVolatile; 1199 return true; 1200 } 1201 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1202 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1203 Info.opc = ISD::INTRINSIC_W_CHAIN; 1204 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1205 Info.ptrVal = 1206 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1207 Info.align.reset(); 1208 Info.flags = MachineMemOperand::MOLoad | 1209 MachineMemOperand::MODereferenceable; 1210 return true; 1211 } 1212 case Intrinsic::amdgcn_global_atomic_fadd: 1213 case Intrinsic::amdgcn_global_atomic_fmin: 1214 case Intrinsic::amdgcn_global_atomic_fmax: 1215 case Intrinsic::amdgcn_flat_atomic_fadd: 1216 case Intrinsic::amdgcn_flat_atomic_fmin: 1217 case Intrinsic::amdgcn_flat_atomic_fmax: { 1218 Info.opc = ISD::INTRINSIC_W_CHAIN; 1219 Info.memVT = MVT::getVT(CI.getType()); 1220 Info.ptrVal = CI.getOperand(0); 1221 Info.align.reset(); 1222 Info.flags = MachineMemOperand::MOLoad | 1223 MachineMemOperand::MOStore | 1224 MachineMemOperand::MODereferenceable | 1225 MachineMemOperand::MOVolatile; 1226 return true; 1227 } 1228 case Intrinsic::amdgcn_ds_gws_init: 1229 case Intrinsic::amdgcn_ds_gws_barrier: 1230 case Intrinsic::amdgcn_ds_gws_sema_v: 1231 case Intrinsic::amdgcn_ds_gws_sema_br: 1232 case Intrinsic::amdgcn_ds_gws_sema_p: 1233 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1234 Info.opc = ISD::INTRINSIC_VOID; 1235 1236 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1237 Info.ptrVal = 1238 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1239 1240 // This is an abstract access, but we need to specify a type and size. 1241 Info.memVT = MVT::i32; 1242 Info.size = 4; 1243 Info.align = Align(4); 1244 1245 Info.flags = MachineMemOperand::MOStore; 1246 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1247 Info.flags = MachineMemOperand::MOLoad; 1248 return true; 1249 } 1250 default: 1251 return false; 1252 } 1253 } 1254 1255 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1256 SmallVectorImpl<Value*> &Ops, 1257 Type *&AccessTy) const { 1258 switch (II->getIntrinsicID()) { 1259 case Intrinsic::amdgcn_atomic_inc: 1260 case Intrinsic::amdgcn_atomic_dec: 1261 case Intrinsic::amdgcn_ds_ordered_add: 1262 case Intrinsic::amdgcn_ds_ordered_swap: 1263 case Intrinsic::amdgcn_ds_append: 1264 case Intrinsic::amdgcn_ds_consume: 1265 case Intrinsic::amdgcn_ds_fadd: 1266 case Intrinsic::amdgcn_ds_fmin: 1267 case Intrinsic::amdgcn_ds_fmax: 1268 case Intrinsic::amdgcn_global_atomic_fadd: 1269 case Intrinsic::amdgcn_flat_atomic_fadd: 1270 case Intrinsic::amdgcn_flat_atomic_fmin: 1271 case Intrinsic::amdgcn_flat_atomic_fmax: 1272 case Intrinsic::amdgcn_global_atomic_csub: { 1273 Value *Ptr = II->getArgOperand(0); 1274 AccessTy = II->getType(); 1275 Ops.push_back(Ptr); 1276 return true; 1277 } 1278 default: 1279 return false; 1280 } 1281 } 1282 1283 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1284 if (!Subtarget->hasFlatInstOffsets()) { 1285 // Flat instructions do not have offsets, and only have the register 1286 // address. 1287 return AM.BaseOffs == 0 && AM.Scale == 0; 1288 } 1289 1290 return AM.Scale == 0 && 1291 (AM.BaseOffs == 0 || 1292 Subtarget->getInstrInfo()->isLegalFLATOffset( 1293 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1294 } 1295 1296 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1297 if (Subtarget->hasFlatGlobalInsts()) 1298 return AM.Scale == 0 && 1299 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1300 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1301 SIInstrFlags::FlatGlobal)); 1302 1303 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1304 // Assume the we will use FLAT for all global memory accesses 1305 // on VI. 1306 // FIXME: This assumption is currently wrong. On VI we still use 1307 // MUBUF instructions for the r + i addressing mode. As currently 1308 // implemented, the MUBUF instructions only work on buffer < 4GB. 1309 // It may be possible to support > 4GB buffers with MUBUF instructions, 1310 // by setting the stride value in the resource descriptor which would 1311 // increase the size limit to (stride * 4GB). However, this is risky, 1312 // because it has never been validated. 1313 return isLegalFlatAddressingMode(AM); 1314 } 1315 1316 return isLegalMUBUFAddressingMode(AM); 1317 } 1318 1319 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1320 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1321 // additionally can do r + r + i with addr64. 32-bit has more addressing 1322 // mode options. Depending on the resource constant, it can also do 1323 // (i64 r0) + (i32 r1) * (i14 i). 1324 // 1325 // Private arrays end up using a scratch buffer most of the time, so also 1326 // assume those use MUBUF instructions. Scratch loads / stores are currently 1327 // implemented as mubuf instructions with offen bit set, so slightly 1328 // different than the normal addr64. 1329 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1330 return false; 1331 1332 // FIXME: Since we can split immediate into soffset and immediate offset, 1333 // would it make sense to allow any immediate? 1334 1335 switch (AM.Scale) { 1336 case 0: // r + i or just i, depending on HasBaseReg. 1337 return true; 1338 case 1: 1339 return true; // We have r + r or r + i. 1340 case 2: 1341 if (AM.HasBaseReg) { 1342 // Reject 2 * r + r. 1343 return false; 1344 } 1345 1346 // Allow 2 * r as r + r 1347 // Or 2 * r + i is allowed as r + r + i. 1348 return true; 1349 default: // Don't allow n * r 1350 return false; 1351 } 1352 } 1353 1354 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1355 const AddrMode &AM, Type *Ty, 1356 unsigned AS, Instruction *I) const { 1357 // No global is ever allowed as a base. 1358 if (AM.BaseGV) 1359 return false; 1360 1361 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1362 return isLegalGlobalAddressingMode(AM); 1363 1364 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1365 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1366 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1367 // If the offset isn't a multiple of 4, it probably isn't going to be 1368 // correctly aligned. 1369 // FIXME: Can we get the real alignment here? 1370 if (AM.BaseOffs % 4 != 0) 1371 return isLegalMUBUFAddressingMode(AM); 1372 1373 // There are no SMRD extloads, so if we have to do a small type access we 1374 // will use a MUBUF load. 1375 // FIXME?: We also need to do this if unaligned, but we don't know the 1376 // alignment here. 1377 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1378 return isLegalGlobalAddressingMode(AM); 1379 1380 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1381 // SMRD instructions have an 8-bit, dword offset on SI. 1382 if (!isUInt<8>(AM.BaseOffs / 4)) 1383 return false; 1384 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1385 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1386 // in 8-bits, it can use a smaller encoding. 1387 if (!isUInt<32>(AM.BaseOffs / 4)) 1388 return false; 1389 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1390 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1391 if (!isUInt<20>(AM.BaseOffs)) 1392 return false; 1393 } else 1394 llvm_unreachable("unhandled generation"); 1395 1396 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1397 return true; 1398 1399 if (AM.Scale == 1 && AM.HasBaseReg) 1400 return true; 1401 1402 return false; 1403 1404 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1405 return isLegalMUBUFAddressingMode(AM); 1406 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1407 AS == AMDGPUAS::REGION_ADDRESS) { 1408 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1409 // field. 1410 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1411 // an 8-bit dword offset but we don't know the alignment here. 1412 if (!isUInt<16>(AM.BaseOffs)) 1413 return false; 1414 1415 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1416 return true; 1417 1418 if (AM.Scale == 1 && AM.HasBaseReg) 1419 return true; 1420 1421 return false; 1422 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1423 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1424 // For an unknown address space, this usually means that this is for some 1425 // reason being used for pure arithmetic, and not based on some addressing 1426 // computation. We don't have instructions that compute pointers with any 1427 // addressing modes, so treat them as having no offset like flat 1428 // instructions. 1429 return isLegalFlatAddressingMode(AM); 1430 } 1431 1432 // Assume a user alias of global for unknown address spaces. 1433 return isLegalGlobalAddressingMode(AM); 1434 } 1435 1436 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1437 const MachineFunction &MF) const { 1438 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1439 return (MemVT.getSizeInBits() <= 4 * 32); 1440 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1441 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1442 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1443 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1444 return (MemVT.getSizeInBits() <= 2 * 32); 1445 } 1446 return true; 1447 } 1448 1449 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1450 unsigned Size, unsigned AddrSpace, Align Alignment, 1451 MachineMemOperand::Flags Flags, bool *IsFast) const { 1452 if (IsFast) 1453 *IsFast = false; 1454 1455 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1456 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1457 // Check if alignment requirements for ds_read/write instructions are 1458 // disabled. 1459 if (Subtarget->hasUnalignedDSAccessEnabled() && 1460 !Subtarget->hasLDSMisalignedBug()) { 1461 if (IsFast) 1462 *IsFast = Alignment != Align(2); 1463 return true; 1464 } 1465 1466 // Either, the alignment requirements are "enabled", or there is an 1467 // unaligned LDS access related hardware bug though alignment requirements 1468 // are "disabled". In either case, we need to check for proper alignment 1469 // requirements. 1470 // 1471 if (Size == 64) { 1472 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1473 // can do a 4 byte aligned, 8 byte access in a single operation using 1474 // ds_read2/write2_b32 with adjacent offsets. 1475 bool AlignedBy4 = Alignment >= Align(4); 1476 if (IsFast) 1477 *IsFast = AlignedBy4; 1478 1479 return AlignedBy4; 1480 } 1481 if (Size == 96) { 1482 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1483 // gfx8 and older. 1484 bool AlignedBy16 = Alignment >= Align(16); 1485 if (IsFast) 1486 *IsFast = AlignedBy16; 1487 1488 return AlignedBy16; 1489 } 1490 if (Size == 128) { 1491 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1492 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1493 // single operation using ds_read2/write2_b64. 1494 bool AlignedBy8 = Alignment >= Align(8); 1495 if (IsFast) 1496 *IsFast = AlignedBy8; 1497 1498 return AlignedBy8; 1499 } 1500 } 1501 1502 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1503 bool AlignedBy4 = Alignment >= Align(4); 1504 if (IsFast) 1505 *IsFast = AlignedBy4; 1506 1507 return AlignedBy4 || 1508 Subtarget->enableFlatScratch() || 1509 Subtarget->hasUnalignedScratchAccess(); 1510 } 1511 1512 // FIXME: We have to be conservative here and assume that flat operations 1513 // will access scratch. If we had access to the IR function, then we 1514 // could determine if any private memory was used in the function. 1515 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1516 !Subtarget->hasUnalignedScratchAccess()) { 1517 bool AlignedBy4 = Alignment >= Align(4); 1518 if (IsFast) 1519 *IsFast = AlignedBy4; 1520 1521 return AlignedBy4; 1522 } 1523 1524 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1525 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1526 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1527 // If we have an uniform constant load, it still requires using a slow 1528 // buffer instruction if unaligned. 1529 if (IsFast) { 1530 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1531 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1532 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1533 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1534 Alignment >= Align(4) : Alignment != Align(2); 1535 } 1536 1537 return true; 1538 } 1539 1540 // Smaller than dword value must be aligned. 1541 if (Size < 32) 1542 return false; 1543 1544 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1545 // byte-address are ignored, thus forcing Dword alignment. 1546 // This applies to private, global, and constant memory. 1547 if (IsFast) 1548 *IsFast = true; 1549 1550 return Size >= 32 && Alignment >= Align(4); 1551 } 1552 1553 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1554 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1555 bool *IsFast) const { 1556 if (IsFast) 1557 *IsFast = false; 1558 1559 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1560 // which isn't a simple VT. 1561 // Until MVT is extended to handle this, simply check for the size and 1562 // rely on the condition below: allow accesses if the size is a multiple of 4. 1563 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1564 VT.getStoreSize() > 16)) { 1565 return false; 1566 } 1567 1568 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1569 Alignment, Flags, IsFast); 1570 } 1571 1572 EVT SITargetLowering::getOptimalMemOpType( 1573 const MemOp &Op, const AttributeList &FuncAttributes) const { 1574 // FIXME: Should account for address space here. 1575 1576 // The default fallback uses the private pointer size as a guess for a type to 1577 // use. Make sure we switch these to 64-bit accesses. 1578 1579 if (Op.size() >= 16 && 1580 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1581 return MVT::v4i32; 1582 1583 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1584 return MVT::v2i32; 1585 1586 // Use the default. 1587 return MVT::Other; 1588 } 1589 1590 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1591 const MemSDNode *MemNode = cast<MemSDNode>(N); 1592 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1593 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1594 return I && I->getMetadata("amdgpu.noclobber"); 1595 } 1596 1597 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1598 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1599 AS == AMDGPUAS::PRIVATE_ADDRESS; 1600 } 1601 1602 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1603 unsigned DestAS) const { 1604 // Flat -> private/local is a simple truncate. 1605 // Flat -> global is no-op 1606 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1607 return true; 1608 1609 const GCNTargetMachine &TM = 1610 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1611 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1612 } 1613 1614 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1615 const MemSDNode *MemNode = cast<MemSDNode>(N); 1616 1617 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1618 } 1619 1620 TargetLoweringBase::LegalizeTypeAction 1621 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1622 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1623 VT.getScalarType().bitsLE(MVT::i16)) 1624 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1625 return TargetLoweringBase::getPreferredVectorAction(VT); 1626 } 1627 1628 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1629 Type *Ty) const { 1630 // FIXME: Could be smarter if called for vector constants. 1631 return true; 1632 } 1633 1634 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1635 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1636 switch (Op) { 1637 case ISD::LOAD: 1638 case ISD::STORE: 1639 1640 // These operations are done with 32-bit instructions anyway. 1641 case ISD::AND: 1642 case ISD::OR: 1643 case ISD::XOR: 1644 case ISD::SELECT: 1645 // TODO: Extensions? 1646 return true; 1647 default: 1648 return false; 1649 } 1650 } 1651 1652 // SimplifySetCC uses this function to determine whether or not it should 1653 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1654 if (VT == MVT::i1 && Op == ISD::SETCC) 1655 return false; 1656 1657 return TargetLowering::isTypeDesirableForOp(Op, VT); 1658 } 1659 1660 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1661 const SDLoc &SL, 1662 SDValue Chain, 1663 uint64_t Offset) const { 1664 const DataLayout &DL = DAG.getDataLayout(); 1665 MachineFunction &MF = DAG.getMachineFunction(); 1666 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1667 1668 const ArgDescriptor *InputPtrReg; 1669 const TargetRegisterClass *RC; 1670 LLT ArgTy; 1671 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1672 1673 std::tie(InputPtrReg, RC, ArgTy) = 1674 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1675 1676 // We may not have the kernarg segment argument if we have no kernel 1677 // arguments. 1678 if (!InputPtrReg) 1679 return DAG.getConstant(0, SL, PtrVT); 1680 1681 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1682 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1683 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1684 1685 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1686 } 1687 1688 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1689 const SDLoc &SL) const { 1690 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1691 FIRST_IMPLICIT); 1692 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1693 } 1694 1695 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1696 const SDLoc &SL, SDValue Val, 1697 bool Signed, 1698 const ISD::InputArg *Arg) const { 1699 // First, if it is a widened vector, narrow it. 1700 if (VT.isVector() && 1701 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1702 EVT NarrowedVT = 1703 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1704 VT.getVectorNumElements()); 1705 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1706 DAG.getConstant(0, SL, MVT::i32)); 1707 } 1708 1709 // Then convert the vector elements or scalar value. 1710 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1711 VT.bitsLT(MemVT)) { 1712 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1713 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1714 } 1715 1716 if (MemVT.isFloatingPoint()) 1717 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1718 else if (Signed) 1719 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1720 else 1721 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1722 1723 return Val; 1724 } 1725 1726 SDValue SITargetLowering::lowerKernargMemParameter( 1727 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1728 uint64_t Offset, Align Alignment, bool Signed, 1729 const ISD::InputArg *Arg) const { 1730 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1731 1732 // Try to avoid using an extload by loading earlier than the argument address, 1733 // and extracting the relevant bits. The load should hopefully be merged with 1734 // the previous argument. 1735 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1736 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1737 int64_t AlignDownOffset = alignDown(Offset, 4); 1738 int64_t OffsetDiff = Offset - AlignDownOffset; 1739 1740 EVT IntVT = MemVT.changeTypeToInteger(); 1741 1742 // TODO: If we passed in the base kernel offset we could have a better 1743 // alignment than 4, but we don't really need it. 1744 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1745 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1746 MachineMemOperand::MODereferenceable | 1747 MachineMemOperand::MOInvariant); 1748 1749 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1750 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1751 1752 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1753 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1754 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1755 1756 1757 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1758 } 1759 1760 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1761 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1762 MachineMemOperand::MODereferenceable | 1763 MachineMemOperand::MOInvariant); 1764 1765 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1766 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1767 } 1768 1769 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1770 const SDLoc &SL, SDValue Chain, 1771 const ISD::InputArg &Arg) const { 1772 MachineFunction &MF = DAG.getMachineFunction(); 1773 MachineFrameInfo &MFI = MF.getFrameInfo(); 1774 1775 if (Arg.Flags.isByVal()) { 1776 unsigned Size = Arg.Flags.getByValSize(); 1777 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1778 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1779 } 1780 1781 unsigned ArgOffset = VA.getLocMemOffset(); 1782 unsigned ArgSize = VA.getValVT().getStoreSize(); 1783 1784 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1785 1786 // Create load nodes to retrieve arguments from the stack. 1787 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1788 SDValue ArgValue; 1789 1790 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1791 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1792 MVT MemVT = VA.getValVT(); 1793 1794 switch (VA.getLocInfo()) { 1795 default: 1796 break; 1797 case CCValAssign::BCvt: 1798 MemVT = VA.getLocVT(); 1799 break; 1800 case CCValAssign::SExt: 1801 ExtType = ISD::SEXTLOAD; 1802 break; 1803 case CCValAssign::ZExt: 1804 ExtType = ISD::ZEXTLOAD; 1805 break; 1806 case CCValAssign::AExt: 1807 ExtType = ISD::EXTLOAD; 1808 break; 1809 } 1810 1811 ArgValue = DAG.getExtLoad( 1812 ExtType, SL, VA.getLocVT(), Chain, FIN, 1813 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1814 MemVT); 1815 return ArgValue; 1816 } 1817 1818 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1819 const SIMachineFunctionInfo &MFI, 1820 EVT VT, 1821 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1822 const ArgDescriptor *Reg; 1823 const TargetRegisterClass *RC; 1824 LLT Ty; 1825 1826 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1827 if (!Reg) { 1828 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1829 // It's possible for a kernarg intrinsic call to appear in a kernel with 1830 // no allocated segment, in which case we do not add the user sgpr 1831 // argument, so just return null. 1832 return DAG.getConstant(0, SDLoc(), VT); 1833 } 1834 1835 // It's undefined behavior if a function marked with the amdgpu-no-* 1836 // attributes uses the corresponding intrinsic. 1837 return DAG.getUNDEF(VT); 1838 } 1839 1840 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1841 } 1842 1843 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1844 CallingConv::ID CallConv, 1845 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1846 FunctionType *FType, 1847 SIMachineFunctionInfo *Info) { 1848 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1849 const ISD::InputArg *Arg = &Ins[I]; 1850 1851 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1852 "vector type argument should have been split"); 1853 1854 // First check if it's a PS input addr. 1855 if (CallConv == CallingConv::AMDGPU_PS && 1856 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1857 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1858 1859 // Inconveniently only the first part of the split is marked as isSplit, 1860 // so skip to the end. We only want to increment PSInputNum once for the 1861 // entire split argument. 1862 if (Arg->Flags.isSplit()) { 1863 while (!Arg->Flags.isSplitEnd()) { 1864 assert((!Arg->VT.isVector() || 1865 Arg->VT.getScalarSizeInBits() == 16) && 1866 "unexpected vector split in ps argument type"); 1867 if (!SkipArg) 1868 Splits.push_back(*Arg); 1869 Arg = &Ins[++I]; 1870 } 1871 } 1872 1873 if (SkipArg) { 1874 // We can safely skip PS inputs. 1875 Skipped.set(Arg->getOrigArgIndex()); 1876 ++PSInputNum; 1877 continue; 1878 } 1879 1880 Info->markPSInputAllocated(PSInputNum); 1881 if (Arg->Used) 1882 Info->markPSInputEnabled(PSInputNum); 1883 1884 ++PSInputNum; 1885 } 1886 1887 Splits.push_back(*Arg); 1888 } 1889 } 1890 1891 // Allocate special inputs passed in VGPRs. 1892 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1893 MachineFunction &MF, 1894 const SIRegisterInfo &TRI, 1895 SIMachineFunctionInfo &Info) const { 1896 const LLT S32 = LLT::scalar(32); 1897 MachineRegisterInfo &MRI = MF.getRegInfo(); 1898 1899 if (Info.hasWorkItemIDX()) { 1900 Register Reg = AMDGPU::VGPR0; 1901 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1902 1903 CCInfo.AllocateReg(Reg); 1904 unsigned Mask = (Subtarget->hasPackedTID() && 1905 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1906 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1907 } 1908 1909 if (Info.hasWorkItemIDY()) { 1910 assert(Info.hasWorkItemIDX()); 1911 if (Subtarget->hasPackedTID()) { 1912 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1913 0x3ff << 10)); 1914 } else { 1915 unsigned Reg = AMDGPU::VGPR1; 1916 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1917 1918 CCInfo.AllocateReg(Reg); 1919 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1920 } 1921 } 1922 1923 if (Info.hasWorkItemIDZ()) { 1924 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1925 if (Subtarget->hasPackedTID()) { 1926 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1927 0x3ff << 20)); 1928 } else { 1929 unsigned Reg = AMDGPU::VGPR2; 1930 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1931 1932 CCInfo.AllocateReg(Reg); 1933 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1934 } 1935 } 1936 } 1937 1938 // Try to allocate a VGPR at the end of the argument list, or if no argument 1939 // VGPRs are left allocating a stack slot. 1940 // If \p Mask is is given it indicates bitfield position in the register. 1941 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1942 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1943 ArgDescriptor Arg = ArgDescriptor()) { 1944 if (Arg.isSet()) 1945 return ArgDescriptor::createArg(Arg, Mask); 1946 1947 ArrayRef<MCPhysReg> ArgVGPRs 1948 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1949 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1950 if (RegIdx == ArgVGPRs.size()) { 1951 // Spill to stack required. 1952 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1953 1954 return ArgDescriptor::createStack(Offset, Mask); 1955 } 1956 1957 unsigned Reg = ArgVGPRs[RegIdx]; 1958 Reg = CCInfo.AllocateReg(Reg); 1959 assert(Reg != AMDGPU::NoRegister); 1960 1961 MachineFunction &MF = CCInfo.getMachineFunction(); 1962 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1963 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1964 return ArgDescriptor::createRegister(Reg, Mask); 1965 } 1966 1967 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1968 const TargetRegisterClass *RC, 1969 unsigned NumArgRegs) { 1970 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1971 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1972 if (RegIdx == ArgSGPRs.size()) 1973 report_fatal_error("ran out of SGPRs for arguments"); 1974 1975 unsigned Reg = ArgSGPRs[RegIdx]; 1976 Reg = CCInfo.AllocateReg(Reg); 1977 assert(Reg != AMDGPU::NoRegister); 1978 1979 MachineFunction &MF = CCInfo.getMachineFunction(); 1980 MF.addLiveIn(Reg, RC); 1981 return ArgDescriptor::createRegister(Reg); 1982 } 1983 1984 // If this has a fixed position, we still should allocate the register in the 1985 // CCInfo state. Technically we could get away with this for values passed 1986 // outside of the normal argument range. 1987 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1988 const TargetRegisterClass *RC, 1989 MCRegister Reg) { 1990 Reg = CCInfo.AllocateReg(Reg); 1991 assert(Reg != AMDGPU::NoRegister); 1992 MachineFunction &MF = CCInfo.getMachineFunction(); 1993 MF.addLiveIn(Reg, RC); 1994 } 1995 1996 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1997 if (Arg) { 1998 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1999 Arg.getRegister()); 2000 } else 2001 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2002 } 2003 2004 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2005 if (Arg) { 2006 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2007 Arg.getRegister()); 2008 } else 2009 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2010 } 2011 2012 /// Allocate implicit function VGPR arguments at the end of allocated user 2013 /// arguments. 2014 void SITargetLowering::allocateSpecialInputVGPRs( 2015 CCState &CCInfo, MachineFunction &MF, 2016 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2017 const unsigned Mask = 0x3ff; 2018 ArgDescriptor Arg; 2019 2020 if (Info.hasWorkItemIDX()) { 2021 Arg = allocateVGPR32Input(CCInfo, Mask); 2022 Info.setWorkItemIDX(Arg); 2023 } 2024 2025 if (Info.hasWorkItemIDY()) { 2026 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2027 Info.setWorkItemIDY(Arg); 2028 } 2029 2030 if (Info.hasWorkItemIDZ()) 2031 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2032 } 2033 2034 /// Allocate implicit function VGPR arguments in fixed registers. 2035 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2036 CCState &CCInfo, MachineFunction &MF, 2037 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2038 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2039 if (!Reg) 2040 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2041 2042 const unsigned Mask = 0x3ff; 2043 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2044 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2045 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2046 } 2047 2048 void SITargetLowering::allocateSpecialInputSGPRs( 2049 CCState &CCInfo, 2050 MachineFunction &MF, 2051 const SIRegisterInfo &TRI, 2052 SIMachineFunctionInfo &Info) const { 2053 auto &ArgInfo = Info.getArgInfo(); 2054 2055 // We need to allocate these in place regardless of their use. 2056 const bool IsFixed = AMDGPUTargetMachine::EnableFixedFunctionABI; 2057 2058 // TODO: Unify handling with private memory pointers. 2059 if (IsFixed || Info.hasDispatchPtr()) 2060 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2061 2062 if (IsFixed || Info.hasQueuePtr()) 2063 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2064 2065 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2066 // constant offset from the kernarg segment. 2067 if (IsFixed || Info.hasImplicitArgPtr()) 2068 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2069 2070 if (IsFixed || Info.hasDispatchID()) 2071 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2072 2073 // flat_scratch_init is not applicable for non-kernel functions. 2074 2075 if (IsFixed || Info.hasWorkGroupIDX()) 2076 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2077 2078 if (IsFixed || Info.hasWorkGroupIDY()) 2079 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2080 2081 if (IsFixed || Info.hasWorkGroupIDZ()) 2082 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2083 } 2084 2085 // Allocate special inputs passed in user SGPRs. 2086 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2087 MachineFunction &MF, 2088 const SIRegisterInfo &TRI, 2089 SIMachineFunctionInfo &Info) const { 2090 if (Info.hasImplicitBufferPtr()) { 2091 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2092 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2093 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2094 } 2095 2096 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2097 if (Info.hasPrivateSegmentBuffer()) { 2098 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2099 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2100 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2101 } 2102 2103 if (Info.hasDispatchPtr()) { 2104 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2105 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2106 CCInfo.AllocateReg(DispatchPtrReg); 2107 } 2108 2109 if (Info.hasQueuePtr()) { 2110 Register QueuePtrReg = Info.addQueuePtr(TRI); 2111 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2112 CCInfo.AllocateReg(QueuePtrReg); 2113 } 2114 2115 if (Info.hasKernargSegmentPtr()) { 2116 MachineRegisterInfo &MRI = MF.getRegInfo(); 2117 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2118 CCInfo.AllocateReg(InputPtrReg); 2119 2120 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2121 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2122 } 2123 2124 if (Info.hasDispatchID()) { 2125 Register DispatchIDReg = Info.addDispatchID(TRI); 2126 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2127 CCInfo.AllocateReg(DispatchIDReg); 2128 } 2129 2130 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2131 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2132 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2133 CCInfo.AllocateReg(FlatScratchInitReg); 2134 } 2135 2136 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2137 // these from the dispatch pointer. 2138 } 2139 2140 // Allocate special input registers that are initialized per-wave. 2141 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2142 MachineFunction &MF, 2143 SIMachineFunctionInfo &Info, 2144 CallingConv::ID CallConv, 2145 bool IsShader) const { 2146 if (Info.hasWorkGroupIDX()) { 2147 Register Reg = Info.addWorkGroupIDX(); 2148 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2149 CCInfo.AllocateReg(Reg); 2150 } 2151 2152 if (Info.hasWorkGroupIDY()) { 2153 Register Reg = Info.addWorkGroupIDY(); 2154 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2155 CCInfo.AllocateReg(Reg); 2156 } 2157 2158 if (Info.hasWorkGroupIDZ()) { 2159 Register Reg = Info.addWorkGroupIDZ(); 2160 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2161 CCInfo.AllocateReg(Reg); 2162 } 2163 2164 if (Info.hasWorkGroupInfo()) { 2165 Register Reg = Info.addWorkGroupInfo(); 2166 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2167 CCInfo.AllocateReg(Reg); 2168 } 2169 2170 if (Info.hasPrivateSegmentWaveByteOffset()) { 2171 // Scratch wave offset passed in system SGPR. 2172 unsigned PrivateSegmentWaveByteOffsetReg; 2173 2174 if (IsShader) { 2175 PrivateSegmentWaveByteOffsetReg = 2176 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2177 2178 // This is true if the scratch wave byte offset doesn't have a fixed 2179 // location. 2180 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2181 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2182 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2183 } 2184 } else 2185 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2186 2187 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2188 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2189 } 2190 } 2191 2192 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2193 MachineFunction &MF, 2194 const SIRegisterInfo &TRI, 2195 SIMachineFunctionInfo &Info) { 2196 // Now that we've figured out where the scratch register inputs are, see if 2197 // should reserve the arguments and use them directly. 2198 MachineFrameInfo &MFI = MF.getFrameInfo(); 2199 bool HasStackObjects = MFI.hasStackObjects(); 2200 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2201 2202 // Record that we know we have non-spill stack objects so we don't need to 2203 // check all stack objects later. 2204 if (HasStackObjects) 2205 Info.setHasNonSpillStackObjects(true); 2206 2207 // Everything live out of a block is spilled with fast regalloc, so it's 2208 // almost certain that spilling will be required. 2209 if (TM.getOptLevel() == CodeGenOpt::None) 2210 HasStackObjects = true; 2211 2212 // For now assume stack access is needed in any callee functions, so we need 2213 // the scratch registers to pass in. 2214 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2215 2216 if (!ST.enableFlatScratch()) { 2217 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2218 // If we have stack objects, we unquestionably need the private buffer 2219 // resource. For the Code Object V2 ABI, this will be the first 4 user 2220 // SGPR inputs. We can reserve those and use them directly. 2221 2222 Register PrivateSegmentBufferReg = 2223 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2224 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2225 } else { 2226 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2227 // We tentatively reserve the last registers (skipping the last registers 2228 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2229 // we'll replace these with the ones immediately after those which were 2230 // really allocated. In the prologue copies will be inserted from the 2231 // argument to these reserved registers. 2232 2233 // Without HSA, relocations are used for the scratch pointer and the 2234 // buffer resource setup is always inserted in the prologue. Scratch wave 2235 // offset is still in an input SGPR. 2236 Info.setScratchRSrcReg(ReservedBufferReg); 2237 } 2238 } 2239 2240 MachineRegisterInfo &MRI = MF.getRegInfo(); 2241 2242 // For entry functions we have to set up the stack pointer if we use it, 2243 // whereas non-entry functions get this "for free". This means there is no 2244 // intrinsic advantage to using S32 over S34 in cases where we do not have 2245 // calls but do need a frame pointer (i.e. if we are requested to have one 2246 // because frame pointer elimination is disabled). To keep things simple we 2247 // only ever use S32 as the call ABI stack pointer, and so using it does not 2248 // imply we need a separate frame pointer. 2249 // 2250 // Try to use s32 as the SP, but move it if it would interfere with input 2251 // arguments. This won't work with calls though. 2252 // 2253 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2254 // registers. 2255 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2256 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2257 } else { 2258 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2259 2260 if (MFI.hasCalls()) 2261 report_fatal_error("call in graphics shader with too many input SGPRs"); 2262 2263 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2264 if (!MRI.isLiveIn(Reg)) { 2265 Info.setStackPtrOffsetReg(Reg); 2266 break; 2267 } 2268 } 2269 2270 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2271 report_fatal_error("failed to find register for SP"); 2272 } 2273 2274 // hasFP should be accurate for entry functions even before the frame is 2275 // finalized, because it does not rely on the known stack size, only 2276 // properties like whether variable sized objects are present. 2277 if (ST.getFrameLowering()->hasFP(MF)) { 2278 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2279 } 2280 } 2281 2282 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2283 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2284 return !Info->isEntryFunction(); 2285 } 2286 2287 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2288 2289 } 2290 2291 void SITargetLowering::insertCopiesSplitCSR( 2292 MachineBasicBlock *Entry, 2293 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2294 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2295 2296 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2297 if (!IStart) 2298 return; 2299 2300 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2301 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2302 MachineBasicBlock::iterator MBBI = Entry->begin(); 2303 for (const MCPhysReg *I = IStart; *I; ++I) { 2304 const TargetRegisterClass *RC = nullptr; 2305 if (AMDGPU::SReg_64RegClass.contains(*I)) 2306 RC = &AMDGPU::SGPR_64RegClass; 2307 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2308 RC = &AMDGPU::SGPR_32RegClass; 2309 else 2310 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2311 2312 Register NewVR = MRI->createVirtualRegister(RC); 2313 // Create copy from CSR to a virtual register. 2314 Entry->addLiveIn(*I); 2315 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2316 .addReg(*I); 2317 2318 // Insert the copy-back instructions right before the terminator. 2319 for (auto *Exit : Exits) 2320 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2321 TII->get(TargetOpcode::COPY), *I) 2322 .addReg(NewVR); 2323 } 2324 } 2325 2326 SDValue SITargetLowering::LowerFormalArguments( 2327 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2328 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2329 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2330 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2331 2332 MachineFunction &MF = DAG.getMachineFunction(); 2333 const Function &Fn = MF.getFunction(); 2334 FunctionType *FType = MF.getFunction().getFunctionType(); 2335 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2336 2337 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2338 DiagnosticInfoUnsupported NoGraphicsHSA( 2339 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2340 DAG.getContext()->diagnose(NoGraphicsHSA); 2341 return DAG.getEntryNode(); 2342 } 2343 2344 Info->allocateModuleLDSGlobal(Fn.getParent()); 2345 2346 SmallVector<ISD::InputArg, 16> Splits; 2347 SmallVector<CCValAssign, 16> ArgLocs; 2348 BitVector Skipped(Ins.size()); 2349 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2350 *DAG.getContext()); 2351 2352 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2353 bool IsKernel = AMDGPU::isKernel(CallConv); 2354 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2355 2356 if (IsGraphics) { 2357 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2358 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2359 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2360 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2361 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2362 !Info->hasWorkItemIDZ()); 2363 } 2364 2365 if (CallConv == CallingConv::AMDGPU_PS) { 2366 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2367 2368 // At least one interpolation mode must be enabled or else the GPU will 2369 // hang. 2370 // 2371 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2372 // set PSInputAddr, the user wants to enable some bits after the compilation 2373 // based on run-time states. Since we can't know what the final PSInputEna 2374 // will look like, so we shouldn't do anything here and the user should take 2375 // responsibility for the correct programming. 2376 // 2377 // Otherwise, the following restrictions apply: 2378 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2379 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2380 // enabled too. 2381 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2382 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2383 CCInfo.AllocateReg(AMDGPU::VGPR0); 2384 CCInfo.AllocateReg(AMDGPU::VGPR1); 2385 Info->markPSInputAllocated(0); 2386 Info->markPSInputEnabled(0); 2387 } 2388 if (Subtarget->isAmdPalOS()) { 2389 // For isAmdPalOS, the user does not enable some bits after compilation 2390 // based on run-time states; the register values being generated here are 2391 // the final ones set in hardware. Therefore we need to apply the 2392 // workaround to PSInputAddr and PSInputEnable together. (The case where 2393 // a bit is set in PSInputAddr but not PSInputEnable is where the 2394 // frontend set up an input arg for a particular interpolation mode, but 2395 // nothing uses that input arg. Really we should have an earlier pass 2396 // that removes such an arg.) 2397 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2398 if ((PsInputBits & 0x7F) == 0 || 2399 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2400 Info->markPSInputEnabled( 2401 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2402 } 2403 } else if (IsKernel) { 2404 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2405 } else { 2406 Splits.append(Ins.begin(), Ins.end()); 2407 } 2408 2409 if (IsEntryFunc) { 2410 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2411 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2412 } else { 2413 // For the fixed ABI, pass workitem IDs in the last argument register. 2414 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2415 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2416 } 2417 2418 if (IsKernel) { 2419 analyzeFormalArgumentsCompute(CCInfo, Ins); 2420 } else { 2421 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2422 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2423 } 2424 2425 SmallVector<SDValue, 16> Chains; 2426 2427 // FIXME: This is the minimum kernel argument alignment. We should improve 2428 // this to the maximum alignment of the arguments. 2429 // 2430 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2431 // kern arg offset. 2432 const Align KernelArgBaseAlign = Align(16); 2433 2434 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2435 const ISD::InputArg &Arg = Ins[i]; 2436 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2437 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2438 continue; 2439 } 2440 2441 CCValAssign &VA = ArgLocs[ArgIdx++]; 2442 MVT VT = VA.getLocVT(); 2443 2444 if (IsEntryFunc && VA.isMemLoc()) { 2445 VT = Ins[i].VT; 2446 EVT MemVT = VA.getLocVT(); 2447 2448 const uint64_t Offset = VA.getLocMemOffset(); 2449 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2450 2451 if (Arg.Flags.isByRef()) { 2452 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2453 2454 const GCNTargetMachine &TM = 2455 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2456 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2457 Arg.Flags.getPointerAddrSpace())) { 2458 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2459 Arg.Flags.getPointerAddrSpace()); 2460 } 2461 2462 InVals.push_back(Ptr); 2463 continue; 2464 } 2465 2466 SDValue Arg = lowerKernargMemParameter( 2467 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2468 Chains.push_back(Arg.getValue(1)); 2469 2470 auto *ParamTy = 2471 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2472 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2473 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2474 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2475 // On SI local pointers are just offsets into LDS, so they are always 2476 // less than 16-bits. On CI and newer they could potentially be 2477 // real pointers, so we can't guarantee their size. 2478 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2479 DAG.getValueType(MVT::i16)); 2480 } 2481 2482 InVals.push_back(Arg); 2483 continue; 2484 } else if (!IsEntryFunc && VA.isMemLoc()) { 2485 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2486 InVals.push_back(Val); 2487 if (!Arg.Flags.isByVal()) 2488 Chains.push_back(Val.getValue(1)); 2489 continue; 2490 } 2491 2492 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2493 2494 Register Reg = VA.getLocReg(); 2495 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2496 EVT ValVT = VA.getValVT(); 2497 2498 Reg = MF.addLiveIn(Reg, RC); 2499 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2500 2501 if (Arg.Flags.isSRet()) { 2502 // The return object should be reasonably addressable. 2503 2504 // FIXME: This helps when the return is a real sret. If it is a 2505 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2506 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2507 unsigned NumBits 2508 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2509 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2510 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2511 } 2512 2513 // If this is an 8 or 16-bit value, it is really passed promoted 2514 // to 32 bits. Insert an assert[sz]ext to capture this, then 2515 // truncate to the right size. 2516 switch (VA.getLocInfo()) { 2517 case CCValAssign::Full: 2518 break; 2519 case CCValAssign::BCvt: 2520 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2521 break; 2522 case CCValAssign::SExt: 2523 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2524 DAG.getValueType(ValVT)); 2525 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2526 break; 2527 case CCValAssign::ZExt: 2528 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2529 DAG.getValueType(ValVT)); 2530 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2531 break; 2532 case CCValAssign::AExt: 2533 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2534 break; 2535 default: 2536 llvm_unreachable("Unknown loc info!"); 2537 } 2538 2539 InVals.push_back(Val); 2540 } 2541 2542 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2543 // Special inputs come after user arguments. 2544 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2545 } 2546 2547 // Start adding system SGPRs. 2548 if (IsEntryFunc) { 2549 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2550 } else { 2551 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2552 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2553 } 2554 2555 auto &ArgUsageInfo = 2556 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2557 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2558 2559 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2560 Info->setBytesInStackArgArea(StackArgSize); 2561 2562 return Chains.empty() ? Chain : 2563 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2564 } 2565 2566 // TODO: If return values can't fit in registers, we should return as many as 2567 // possible in registers before passing on stack. 2568 bool SITargetLowering::CanLowerReturn( 2569 CallingConv::ID CallConv, 2570 MachineFunction &MF, bool IsVarArg, 2571 const SmallVectorImpl<ISD::OutputArg> &Outs, 2572 LLVMContext &Context) const { 2573 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2574 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2575 // for shaders. Vector types should be explicitly handled by CC. 2576 if (AMDGPU::isEntryFunctionCC(CallConv)) 2577 return true; 2578 2579 SmallVector<CCValAssign, 16> RVLocs; 2580 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2581 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2582 } 2583 2584 SDValue 2585 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2586 bool isVarArg, 2587 const SmallVectorImpl<ISD::OutputArg> &Outs, 2588 const SmallVectorImpl<SDValue> &OutVals, 2589 const SDLoc &DL, SelectionDAG &DAG) const { 2590 MachineFunction &MF = DAG.getMachineFunction(); 2591 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2592 2593 if (AMDGPU::isKernel(CallConv)) { 2594 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2595 OutVals, DL, DAG); 2596 } 2597 2598 bool IsShader = AMDGPU::isShader(CallConv); 2599 2600 Info->setIfReturnsVoid(Outs.empty()); 2601 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2602 2603 // CCValAssign - represent the assignment of the return value to a location. 2604 SmallVector<CCValAssign, 48> RVLocs; 2605 SmallVector<ISD::OutputArg, 48> Splits; 2606 2607 // CCState - Info about the registers and stack slots. 2608 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2609 *DAG.getContext()); 2610 2611 // Analyze outgoing return values. 2612 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2613 2614 SDValue Flag; 2615 SmallVector<SDValue, 48> RetOps; 2616 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2617 2618 // Add return address for callable functions. 2619 if (!Info->isEntryFunction()) { 2620 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2621 SDValue ReturnAddrReg = CreateLiveInRegister( 2622 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2623 2624 SDValue ReturnAddrVirtualReg = 2625 DAG.getRegister(MF.getRegInfo().createVirtualRegister( 2626 CallConv != CallingConv::AMDGPU_Gfx 2627 ? &AMDGPU::CCR_SGPR_64RegClass 2628 : &AMDGPU::Gfx_CCR_SGPR_64RegClass), 2629 MVT::i64); 2630 Chain = 2631 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2632 Flag = Chain.getValue(1); 2633 RetOps.push_back(ReturnAddrVirtualReg); 2634 } 2635 2636 // Copy the result values into the output registers. 2637 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2638 ++I, ++RealRVLocIdx) { 2639 CCValAssign &VA = RVLocs[I]; 2640 assert(VA.isRegLoc() && "Can only return in registers!"); 2641 // TODO: Partially return in registers if return values don't fit. 2642 SDValue Arg = OutVals[RealRVLocIdx]; 2643 2644 // Copied from other backends. 2645 switch (VA.getLocInfo()) { 2646 case CCValAssign::Full: 2647 break; 2648 case CCValAssign::BCvt: 2649 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2650 break; 2651 case CCValAssign::SExt: 2652 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2653 break; 2654 case CCValAssign::ZExt: 2655 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2656 break; 2657 case CCValAssign::AExt: 2658 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2659 break; 2660 default: 2661 llvm_unreachable("Unknown loc info!"); 2662 } 2663 2664 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2665 Flag = Chain.getValue(1); 2666 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2667 } 2668 2669 // FIXME: Does sret work properly? 2670 if (!Info->isEntryFunction()) { 2671 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2672 const MCPhysReg *I = 2673 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2674 if (I) { 2675 for (; *I; ++I) { 2676 if (AMDGPU::SReg_64RegClass.contains(*I)) 2677 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2678 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2679 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2680 else 2681 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2682 } 2683 } 2684 } 2685 2686 // Update chain and glue. 2687 RetOps[0] = Chain; 2688 if (Flag.getNode()) 2689 RetOps.push_back(Flag); 2690 2691 unsigned Opc = AMDGPUISD::ENDPGM; 2692 if (!IsWaveEnd) { 2693 if (IsShader) 2694 Opc = AMDGPUISD::RETURN_TO_EPILOG; 2695 else if (CallConv == CallingConv::AMDGPU_Gfx) 2696 Opc = AMDGPUISD::RET_GFX_FLAG; 2697 else 2698 Opc = AMDGPUISD::RET_FLAG; 2699 } 2700 2701 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2702 } 2703 2704 SDValue SITargetLowering::LowerCallResult( 2705 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2706 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2707 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2708 SDValue ThisVal) const { 2709 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2710 2711 // Assign locations to each value returned by this call. 2712 SmallVector<CCValAssign, 16> RVLocs; 2713 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2714 *DAG.getContext()); 2715 CCInfo.AnalyzeCallResult(Ins, RetCC); 2716 2717 // Copy all of the result registers out of their specified physreg. 2718 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2719 CCValAssign VA = RVLocs[i]; 2720 SDValue Val; 2721 2722 if (VA.isRegLoc()) { 2723 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2724 Chain = Val.getValue(1); 2725 InFlag = Val.getValue(2); 2726 } else if (VA.isMemLoc()) { 2727 report_fatal_error("TODO: return values in memory"); 2728 } else 2729 llvm_unreachable("unknown argument location type"); 2730 2731 switch (VA.getLocInfo()) { 2732 case CCValAssign::Full: 2733 break; 2734 case CCValAssign::BCvt: 2735 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2736 break; 2737 case CCValAssign::ZExt: 2738 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2739 DAG.getValueType(VA.getValVT())); 2740 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2741 break; 2742 case CCValAssign::SExt: 2743 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2744 DAG.getValueType(VA.getValVT())); 2745 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2746 break; 2747 case CCValAssign::AExt: 2748 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2749 break; 2750 default: 2751 llvm_unreachable("Unknown loc info!"); 2752 } 2753 2754 InVals.push_back(Val); 2755 } 2756 2757 return Chain; 2758 } 2759 2760 // Add code to pass special inputs required depending on used features separate 2761 // from the explicit user arguments present in the IR. 2762 void SITargetLowering::passSpecialInputs( 2763 CallLoweringInfo &CLI, 2764 CCState &CCInfo, 2765 const SIMachineFunctionInfo &Info, 2766 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2767 SmallVectorImpl<SDValue> &MemOpChains, 2768 SDValue Chain) const { 2769 // If we don't have a call site, this was a call inserted by 2770 // legalization. These can never use special inputs. 2771 if (!CLI.CB) 2772 return; 2773 2774 SelectionDAG &DAG = CLI.DAG; 2775 const SDLoc &DL = CLI.DL; 2776 2777 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2778 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2779 2780 const AMDGPUFunctionArgInfo *CalleeArgInfo 2781 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2782 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2783 auto &ArgUsageInfo = 2784 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2785 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2786 } 2787 2788 // TODO: Unify with private memory register handling. This is complicated by 2789 // the fact that at least in kernels, the input argument is not necessarily 2790 // in the same location as the input. 2791 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2792 StringLiteral> ImplicitAttrs[] = { 2793 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2794 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2795 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2796 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2797 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2798 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2799 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2800 }; 2801 2802 for (auto Attr : ImplicitAttrs) { 2803 const ArgDescriptor *OutgoingArg; 2804 const TargetRegisterClass *ArgRC; 2805 LLT ArgTy; 2806 2807 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2808 2809 // If the callee does not use the attribute value, skip copying the value. 2810 if (CLI.CB->hasFnAttr(Attr.second)) 2811 continue; 2812 2813 std::tie(OutgoingArg, ArgRC, ArgTy) = 2814 CalleeArgInfo->getPreloadedValue(InputID); 2815 if (!OutgoingArg) 2816 continue; 2817 2818 const ArgDescriptor *IncomingArg; 2819 const TargetRegisterClass *IncomingArgRC; 2820 LLT Ty; 2821 std::tie(IncomingArg, IncomingArgRC, Ty) = 2822 CallerArgInfo.getPreloadedValue(InputID); 2823 assert(IncomingArgRC == ArgRC); 2824 2825 // All special arguments are ints for now. 2826 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2827 SDValue InputReg; 2828 2829 if (IncomingArg) { 2830 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2831 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2832 // The implicit arg ptr is special because it doesn't have a corresponding 2833 // input for kernels, and is computed from the kernarg segment pointer. 2834 InputReg = getImplicitArgPtr(DAG, DL); 2835 } else { 2836 // We may have proven the input wasn't needed, although the ABI is 2837 // requiring it. We just need to allocate the register appropriately. 2838 InputReg = DAG.getUNDEF(ArgVT); 2839 } 2840 2841 if (OutgoingArg->isRegister()) { 2842 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2843 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2844 report_fatal_error("failed to allocate implicit input argument"); 2845 } else { 2846 unsigned SpecialArgOffset = 2847 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2848 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2849 SpecialArgOffset); 2850 MemOpChains.push_back(ArgStore); 2851 } 2852 } 2853 2854 // Pack workitem IDs into a single register or pass it as is if already 2855 // packed. 2856 const ArgDescriptor *OutgoingArg; 2857 const TargetRegisterClass *ArgRC; 2858 LLT Ty; 2859 2860 std::tie(OutgoingArg, ArgRC, Ty) = 2861 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2862 if (!OutgoingArg) 2863 std::tie(OutgoingArg, ArgRC, Ty) = 2864 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2865 if (!OutgoingArg) 2866 std::tie(OutgoingArg, ArgRC, Ty) = 2867 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2868 if (!OutgoingArg) 2869 return; 2870 2871 const ArgDescriptor *IncomingArgX = std::get<0>( 2872 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2873 const ArgDescriptor *IncomingArgY = std::get<0>( 2874 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2875 const ArgDescriptor *IncomingArgZ = std::get<0>( 2876 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2877 2878 SDValue InputReg; 2879 SDLoc SL; 2880 2881 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2882 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2883 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2884 2885 // If incoming ids are not packed we need to pack them. 2886 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2887 NeedWorkItemIDX) 2888 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2889 2890 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2891 NeedWorkItemIDY) { 2892 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2893 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2894 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2895 InputReg = InputReg.getNode() ? 2896 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2897 } 2898 2899 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2900 NeedWorkItemIDZ) { 2901 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2902 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2903 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2904 InputReg = InputReg.getNode() ? 2905 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2906 } 2907 2908 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2909 // Workitem ids are already packed, any of present incoming arguments 2910 // will carry all required fields. 2911 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2912 IncomingArgX ? *IncomingArgX : 2913 IncomingArgY ? *IncomingArgY : 2914 *IncomingArgZ, ~0u); 2915 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2916 } 2917 2918 if (OutgoingArg->isRegister()) { 2919 if (InputReg) 2920 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2921 2922 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2923 } else { 2924 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2925 if (InputReg) { 2926 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2927 SpecialArgOffset); 2928 MemOpChains.push_back(ArgStore); 2929 } 2930 } 2931 } 2932 2933 static bool canGuaranteeTCO(CallingConv::ID CC) { 2934 return CC == CallingConv::Fast; 2935 } 2936 2937 /// Return true if we might ever do TCO for calls with this calling convention. 2938 static bool mayTailCallThisCC(CallingConv::ID CC) { 2939 switch (CC) { 2940 case CallingConv::C: 2941 case CallingConv::AMDGPU_Gfx: 2942 return true; 2943 default: 2944 return canGuaranteeTCO(CC); 2945 } 2946 } 2947 2948 bool SITargetLowering::isEligibleForTailCallOptimization( 2949 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2950 const SmallVectorImpl<ISD::OutputArg> &Outs, 2951 const SmallVectorImpl<SDValue> &OutVals, 2952 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2953 if (!mayTailCallThisCC(CalleeCC)) 2954 return false; 2955 2956 // For a divergent call target, we need to do a waterfall loop over the 2957 // possible callees which precludes us from using a simple jump. 2958 if (Callee->isDivergent()) 2959 return false; 2960 2961 MachineFunction &MF = DAG.getMachineFunction(); 2962 const Function &CallerF = MF.getFunction(); 2963 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2964 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2965 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2966 2967 // Kernels aren't callable, and don't have a live in return address so it 2968 // doesn't make sense to do a tail call with entry functions. 2969 if (!CallerPreserved) 2970 return false; 2971 2972 bool CCMatch = CallerCC == CalleeCC; 2973 2974 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2975 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2976 return true; 2977 return false; 2978 } 2979 2980 // TODO: Can we handle var args? 2981 if (IsVarArg) 2982 return false; 2983 2984 for (const Argument &Arg : CallerF.args()) { 2985 if (Arg.hasByValAttr()) 2986 return false; 2987 } 2988 2989 LLVMContext &Ctx = *DAG.getContext(); 2990 2991 // Check that the call results are passed in the same way. 2992 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2993 CCAssignFnForCall(CalleeCC, IsVarArg), 2994 CCAssignFnForCall(CallerCC, IsVarArg))) 2995 return false; 2996 2997 // The callee has to preserve all registers the caller needs to preserve. 2998 if (!CCMatch) { 2999 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3000 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3001 return false; 3002 } 3003 3004 // Nothing more to check if the callee is taking no arguments. 3005 if (Outs.empty()) 3006 return true; 3007 3008 SmallVector<CCValAssign, 16> ArgLocs; 3009 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3010 3011 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3012 3013 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3014 // If the stack arguments for this call do not fit into our own save area then 3015 // the call cannot be made tail. 3016 // TODO: Is this really necessary? 3017 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3018 return false; 3019 3020 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3021 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3022 } 3023 3024 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3025 if (!CI->isTailCall()) 3026 return false; 3027 3028 const Function *ParentFn = CI->getParent()->getParent(); 3029 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3030 return false; 3031 return true; 3032 } 3033 3034 // The wave scratch offset register is used as the global base pointer. 3035 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3036 SmallVectorImpl<SDValue> &InVals) const { 3037 SelectionDAG &DAG = CLI.DAG; 3038 const SDLoc &DL = CLI.DL; 3039 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3040 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3041 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3042 SDValue Chain = CLI.Chain; 3043 SDValue Callee = CLI.Callee; 3044 bool &IsTailCall = CLI.IsTailCall; 3045 CallingConv::ID CallConv = CLI.CallConv; 3046 bool IsVarArg = CLI.IsVarArg; 3047 bool IsSibCall = false; 3048 bool IsThisReturn = false; 3049 MachineFunction &MF = DAG.getMachineFunction(); 3050 3051 if (Callee.isUndef() || isNullConstant(Callee)) { 3052 if (!CLI.IsTailCall) { 3053 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3054 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3055 } 3056 3057 return Chain; 3058 } 3059 3060 if (IsVarArg) { 3061 return lowerUnhandledCall(CLI, InVals, 3062 "unsupported call to variadic function "); 3063 } 3064 3065 if (!CLI.CB) 3066 report_fatal_error("unsupported libcall legalization"); 3067 3068 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3069 return lowerUnhandledCall(CLI, InVals, 3070 "unsupported required tail call to function "); 3071 } 3072 3073 if (AMDGPU::isShader(CallConv)) { 3074 // Note the issue is with the CC of the called function, not of the call 3075 // itself. 3076 return lowerUnhandledCall(CLI, InVals, 3077 "unsupported call to a shader function "); 3078 } 3079 3080 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3081 CallConv != CallingConv::AMDGPU_Gfx) { 3082 // Only allow calls with specific calling conventions. 3083 return lowerUnhandledCall(CLI, InVals, 3084 "unsupported calling convention for call from " 3085 "graphics shader of function "); 3086 } 3087 3088 if (IsTailCall) { 3089 IsTailCall = isEligibleForTailCallOptimization( 3090 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3091 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3092 report_fatal_error("failed to perform tail call elimination on a call " 3093 "site marked musttail"); 3094 } 3095 3096 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3097 3098 // A sibling call is one where we're under the usual C ABI and not planning 3099 // to change that but can still do a tail call: 3100 if (!TailCallOpt && IsTailCall) 3101 IsSibCall = true; 3102 3103 if (IsTailCall) 3104 ++NumTailCalls; 3105 } 3106 3107 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3108 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3109 SmallVector<SDValue, 8> MemOpChains; 3110 3111 // Analyze operands of the call, assigning locations to each operand. 3112 SmallVector<CCValAssign, 16> ArgLocs; 3113 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3114 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3115 3116 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3117 CallConv != CallingConv::AMDGPU_Gfx) { 3118 // With a fixed ABI, allocate fixed registers before user arguments. 3119 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3120 } 3121 3122 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3123 3124 // Get a count of how many bytes are to be pushed on the stack. 3125 unsigned NumBytes = CCInfo.getNextStackOffset(); 3126 3127 if (IsSibCall) { 3128 // Since we're not changing the ABI to make this a tail call, the memory 3129 // operands are already available in the caller's incoming argument space. 3130 NumBytes = 0; 3131 } 3132 3133 // FPDiff is the byte offset of the call's argument area from the callee's. 3134 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3135 // by this amount for a tail call. In a sibling call it must be 0 because the 3136 // caller will deallocate the entire stack and the callee still expects its 3137 // arguments to begin at SP+0. Completely unused for non-tail calls. 3138 int32_t FPDiff = 0; 3139 MachineFrameInfo &MFI = MF.getFrameInfo(); 3140 3141 // Adjust the stack pointer for the new arguments... 3142 // These operations are automatically eliminated by the prolog/epilog pass 3143 if (!IsSibCall) { 3144 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3145 3146 if (!Subtarget->enableFlatScratch()) { 3147 SmallVector<SDValue, 4> CopyFromChains; 3148 3149 // In the HSA case, this should be an identity copy. 3150 SDValue ScratchRSrcReg 3151 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3152 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3153 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3154 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3155 } 3156 } 3157 3158 MVT PtrVT = MVT::i32; 3159 3160 // Walk the register/memloc assignments, inserting copies/loads. 3161 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3162 CCValAssign &VA = ArgLocs[i]; 3163 SDValue Arg = OutVals[i]; 3164 3165 // Promote the value if needed. 3166 switch (VA.getLocInfo()) { 3167 case CCValAssign::Full: 3168 break; 3169 case CCValAssign::BCvt: 3170 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3171 break; 3172 case CCValAssign::ZExt: 3173 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3174 break; 3175 case CCValAssign::SExt: 3176 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3177 break; 3178 case CCValAssign::AExt: 3179 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3180 break; 3181 case CCValAssign::FPExt: 3182 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3183 break; 3184 default: 3185 llvm_unreachable("Unknown loc info!"); 3186 } 3187 3188 if (VA.isRegLoc()) { 3189 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3190 } else { 3191 assert(VA.isMemLoc()); 3192 3193 SDValue DstAddr; 3194 MachinePointerInfo DstInfo; 3195 3196 unsigned LocMemOffset = VA.getLocMemOffset(); 3197 int32_t Offset = LocMemOffset; 3198 3199 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3200 MaybeAlign Alignment; 3201 3202 if (IsTailCall) { 3203 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3204 unsigned OpSize = Flags.isByVal() ? 3205 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3206 3207 // FIXME: We can have better than the minimum byval required alignment. 3208 Alignment = 3209 Flags.isByVal() 3210 ? Flags.getNonZeroByValAlign() 3211 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3212 3213 Offset = Offset + FPDiff; 3214 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3215 3216 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3217 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3218 3219 // Make sure any stack arguments overlapping with where we're storing 3220 // are loaded before this eventual operation. Otherwise they'll be 3221 // clobbered. 3222 3223 // FIXME: Why is this really necessary? This seems to just result in a 3224 // lot of code to copy the stack and write them back to the same 3225 // locations, which are supposed to be immutable? 3226 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3227 } else { 3228 // Stores to the argument stack area are relative to the stack pointer. 3229 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3230 MVT::i32); 3231 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3232 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3233 Alignment = 3234 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3235 } 3236 3237 if (Outs[i].Flags.isByVal()) { 3238 SDValue SizeNode = 3239 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3240 SDValue Cpy = 3241 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3242 Outs[i].Flags.getNonZeroByValAlign(), 3243 /*isVol = */ false, /*AlwaysInline = */ true, 3244 /*isTailCall = */ false, DstInfo, 3245 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3246 3247 MemOpChains.push_back(Cpy); 3248 } else { 3249 SDValue Store = 3250 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3251 MemOpChains.push_back(Store); 3252 } 3253 } 3254 } 3255 3256 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3257 CallConv != CallingConv::AMDGPU_Gfx) { 3258 // Copy special input registers after user input arguments. 3259 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3260 } 3261 3262 if (!MemOpChains.empty()) 3263 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3264 3265 // Build a sequence of copy-to-reg nodes chained together with token chain 3266 // and flag operands which copy the outgoing args into the appropriate regs. 3267 SDValue InFlag; 3268 for (auto &RegToPass : RegsToPass) { 3269 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3270 RegToPass.second, InFlag); 3271 InFlag = Chain.getValue(1); 3272 } 3273 3274 3275 SDValue PhysReturnAddrReg; 3276 if (IsTailCall) { 3277 // Since the return is being combined with the call, we need to pass on the 3278 // return address. 3279 3280 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3281 SDValue ReturnAddrReg = CreateLiveInRegister( 3282 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3283 3284 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3285 MVT::i64); 3286 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3287 InFlag = Chain.getValue(1); 3288 } 3289 3290 // We don't usually want to end the call-sequence here because we would tidy 3291 // the frame up *after* the call, however in the ABI-changing tail-call case 3292 // we've carefully laid out the parameters so that when sp is reset they'll be 3293 // in the correct location. 3294 if (IsTailCall && !IsSibCall) { 3295 Chain = DAG.getCALLSEQ_END(Chain, 3296 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3297 DAG.getTargetConstant(0, DL, MVT::i32), 3298 InFlag, DL); 3299 InFlag = Chain.getValue(1); 3300 } 3301 3302 std::vector<SDValue> Ops; 3303 Ops.push_back(Chain); 3304 Ops.push_back(Callee); 3305 // Add a redundant copy of the callee global which will not be legalized, as 3306 // we need direct access to the callee later. 3307 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3308 const GlobalValue *GV = GSD->getGlobal(); 3309 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3310 } else { 3311 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3312 } 3313 3314 if (IsTailCall) { 3315 // Each tail call may have to adjust the stack by a different amount, so 3316 // this information must travel along with the operation for eventual 3317 // consumption by emitEpilogue. 3318 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3319 3320 Ops.push_back(PhysReturnAddrReg); 3321 } 3322 3323 // Add argument registers to the end of the list so that they are known live 3324 // into the call. 3325 for (auto &RegToPass : RegsToPass) { 3326 Ops.push_back(DAG.getRegister(RegToPass.first, 3327 RegToPass.second.getValueType())); 3328 } 3329 3330 // Add a register mask operand representing the call-preserved registers. 3331 3332 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3333 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3334 assert(Mask && "Missing call preserved mask for calling convention"); 3335 Ops.push_back(DAG.getRegisterMask(Mask)); 3336 3337 if (InFlag.getNode()) 3338 Ops.push_back(InFlag); 3339 3340 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3341 3342 // If we're doing a tall call, use a TC_RETURN here rather than an 3343 // actual call instruction. 3344 if (IsTailCall) { 3345 MFI.setHasTailCall(); 3346 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3347 } 3348 3349 // Returns a chain and a flag for retval copy to use. 3350 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3351 Chain = Call.getValue(0); 3352 InFlag = Call.getValue(1); 3353 3354 uint64_t CalleePopBytes = NumBytes; 3355 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3356 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3357 InFlag, DL); 3358 if (!Ins.empty()) 3359 InFlag = Chain.getValue(1); 3360 3361 // Handle result values, copying them out of physregs into vregs that we 3362 // return. 3363 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3364 InVals, IsThisReturn, 3365 IsThisReturn ? OutVals[0] : SDValue()); 3366 } 3367 3368 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3369 // except for applying the wave size scale to the increment amount. 3370 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3371 SDValue Op, SelectionDAG &DAG) const { 3372 const MachineFunction &MF = DAG.getMachineFunction(); 3373 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3374 3375 SDLoc dl(Op); 3376 EVT VT = Op.getValueType(); 3377 SDValue Tmp1 = Op; 3378 SDValue Tmp2 = Op.getValue(1); 3379 SDValue Tmp3 = Op.getOperand(2); 3380 SDValue Chain = Tmp1.getOperand(0); 3381 3382 Register SPReg = Info->getStackPtrOffsetReg(); 3383 3384 // Chain the dynamic stack allocation so that it doesn't modify the stack 3385 // pointer when other instructions are using the stack. 3386 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3387 3388 SDValue Size = Tmp2.getOperand(1); 3389 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3390 Chain = SP.getValue(1); 3391 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3392 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3393 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3394 unsigned Opc = 3395 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3396 ISD::ADD : ISD::SUB; 3397 3398 SDValue ScaledSize = DAG.getNode( 3399 ISD::SHL, dl, VT, Size, 3400 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3401 3402 Align StackAlign = TFL->getStackAlign(); 3403 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3404 if (Alignment && *Alignment > StackAlign) { 3405 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3406 DAG.getConstant(-(uint64_t)Alignment->value() 3407 << ST.getWavefrontSizeLog2(), 3408 dl, VT)); 3409 } 3410 3411 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3412 Tmp2 = DAG.getCALLSEQ_END( 3413 Chain, DAG.getIntPtrConstant(0, dl, true), 3414 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3415 3416 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3417 } 3418 3419 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3420 SelectionDAG &DAG) const { 3421 // We only handle constant sizes here to allow non-entry block, static sized 3422 // allocas. A truly dynamic value is more difficult to support because we 3423 // don't know if the size value is uniform or not. If the size isn't uniform, 3424 // we would need to do a wave reduction to get the maximum size to know how 3425 // much to increment the uniform stack pointer. 3426 SDValue Size = Op.getOperand(1); 3427 if (isa<ConstantSDNode>(Size)) 3428 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3429 3430 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3431 } 3432 3433 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3434 const MachineFunction &MF) const { 3435 Register Reg = StringSwitch<Register>(RegName) 3436 .Case("m0", AMDGPU::M0) 3437 .Case("exec", AMDGPU::EXEC) 3438 .Case("exec_lo", AMDGPU::EXEC_LO) 3439 .Case("exec_hi", AMDGPU::EXEC_HI) 3440 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3441 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3442 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3443 .Default(Register()); 3444 3445 if (Reg == AMDGPU::NoRegister) { 3446 report_fatal_error(Twine("invalid register name \"" 3447 + StringRef(RegName) + "\".")); 3448 3449 } 3450 3451 if (!Subtarget->hasFlatScrRegister() && 3452 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3453 report_fatal_error(Twine("invalid register \"" 3454 + StringRef(RegName) + "\" for subtarget.")); 3455 } 3456 3457 switch (Reg) { 3458 case AMDGPU::M0: 3459 case AMDGPU::EXEC_LO: 3460 case AMDGPU::EXEC_HI: 3461 case AMDGPU::FLAT_SCR_LO: 3462 case AMDGPU::FLAT_SCR_HI: 3463 if (VT.getSizeInBits() == 32) 3464 return Reg; 3465 break; 3466 case AMDGPU::EXEC: 3467 case AMDGPU::FLAT_SCR: 3468 if (VT.getSizeInBits() == 64) 3469 return Reg; 3470 break; 3471 default: 3472 llvm_unreachable("missing register type checking"); 3473 } 3474 3475 report_fatal_error(Twine("invalid type for register \"" 3476 + StringRef(RegName) + "\".")); 3477 } 3478 3479 // If kill is not the last instruction, split the block so kill is always a 3480 // proper terminator. 3481 MachineBasicBlock * 3482 SITargetLowering::splitKillBlock(MachineInstr &MI, 3483 MachineBasicBlock *BB) const { 3484 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3485 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3486 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3487 return SplitBB; 3488 } 3489 3490 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3491 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3492 // be the first instruction in the remainder block. 3493 // 3494 /// \returns { LoopBody, Remainder } 3495 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3496 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3497 MachineFunction *MF = MBB.getParent(); 3498 MachineBasicBlock::iterator I(&MI); 3499 3500 // To insert the loop we need to split the block. Move everything after this 3501 // point to a new block, and insert a new empty block between the two. 3502 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3503 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3504 MachineFunction::iterator MBBI(MBB); 3505 ++MBBI; 3506 3507 MF->insert(MBBI, LoopBB); 3508 MF->insert(MBBI, RemainderBB); 3509 3510 LoopBB->addSuccessor(LoopBB); 3511 LoopBB->addSuccessor(RemainderBB); 3512 3513 // Move the rest of the block into a new block. 3514 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3515 3516 if (InstInLoop) { 3517 auto Next = std::next(I); 3518 3519 // Move instruction to loop body. 3520 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3521 3522 // Move the rest of the block. 3523 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3524 } else { 3525 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3526 } 3527 3528 MBB.addSuccessor(LoopBB); 3529 3530 return std::make_pair(LoopBB, RemainderBB); 3531 } 3532 3533 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3534 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3535 MachineBasicBlock *MBB = MI.getParent(); 3536 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3537 auto I = MI.getIterator(); 3538 auto E = std::next(I); 3539 3540 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3541 .addImm(0); 3542 3543 MIBundleBuilder Bundler(*MBB, I, E); 3544 finalizeBundle(*MBB, Bundler.begin()); 3545 } 3546 3547 MachineBasicBlock * 3548 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3549 MachineBasicBlock *BB) const { 3550 const DebugLoc &DL = MI.getDebugLoc(); 3551 3552 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3553 3554 MachineBasicBlock *LoopBB; 3555 MachineBasicBlock *RemainderBB; 3556 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3557 3558 // Apparently kill flags are only valid if the def is in the same block? 3559 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3560 Src->setIsKill(false); 3561 3562 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3563 3564 MachineBasicBlock::iterator I = LoopBB->end(); 3565 3566 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3567 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3568 3569 // Clear TRAP_STS.MEM_VIOL 3570 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3571 .addImm(0) 3572 .addImm(EncodedReg); 3573 3574 bundleInstWithWaitcnt(MI); 3575 3576 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3577 3578 // Load and check TRAP_STS.MEM_VIOL 3579 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3580 .addImm(EncodedReg); 3581 3582 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3583 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3584 .addReg(Reg, RegState::Kill) 3585 .addImm(0); 3586 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3587 .addMBB(LoopBB); 3588 3589 return RemainderBB; 3590 } 3591 3592 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3593 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3594 // will only do one iteration. In the worst case, this will loop 64 times. 3595 // 3596 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3597 static MachineBasicBlock::iterator 3598 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3599 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3600 const DebugLoc &DL, const MachineOperand &Idx, 3601 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3602 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3603 Register &SGPRIdxReg) { 3604 3605 MachineFunction *MF = OrigBB.getParent(); 3606 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3607 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3608 MachineBasicBlock::iterator I = LoopBB.begin(); 3609 3610 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3611 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3612 Register NewExec = MRI.createVirtualRegister(BoolRC); 3613 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3614 Register CondReg = MRI.createVirtualRegister(BoolRC); 3615 3616 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3617 .addReg(InitReg) 3618 .addMBB(&OrigBB) 3619 .addReg(ResultReg) 3620 .addMBB(&LoopBB); 3621 3622 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3623 .addReg(InitSaveExecReg) 3624 .addMBB(&OrigBB) 3625 .addReg(NewExec) 3626 .addMBB(&LoopBB); 3627 3628 // Read the next variant <- also loop target. 3629 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3630 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3631 3632 // Compare the just read M0 value to all possible Idx values. 3633 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3634 .addReg(CurrentIdxReg) 3635 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3636 3637 // Update EXEC, save the original EXEC value to VCC. 3638 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3639 : AMDGPU::S_AND_SAVEEXEC_B64), 3640 NewExec) 3641 .addReg(CondReg, RegState::Kill); 3642 3643 MRI.setSimpleHint(NewExec, CondReg); 3644 3645 if (UseGPRIdxMode) { 3646 if (Offset == 0) { 3647 SGPRIdxReg = CurrentIdxReg; 3648 } else { 3649 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3650 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3651 .addReg(CurrentIdxReg, RegState::Kill) 3652 .addImm(Offset); 3653 } 3654 } else { 3655 // Move index from VCC into M0 3656 if (Offset == 0) { 3657 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3658 .addReg(CurrentIdxReg, RegState::Kill); 3659 } else { 3660 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3661 .addReg(CurrentIdxReg, RegState::Kill) 3662 .addImm(Offset); 3663 } 3664 } 3665 3666 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3667 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3668 MachineInstr *InsertPt = 3669 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3670 : AMDGPU::S_XOR_B64_term), Exec) 3671 .addReg(Exec) 3672 .addReg(NewExec); 3673 3674 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3675 // s_cbranch_scc0? 3676 3677 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3678 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3679 .addMBB(&LoopBB); 3680 3681 return InsertPt->getIterator(); 3682 } 3683 3684 // This has slightly sub-optimal regalloc when the source vector is killed by 3685 // the read. The register allocator does not understand that the kill is 3686 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3687 // subregister from it, using 1 more VGPR than necessary. This was saved when 3688 // this was expanded after register allocation. 3689 static MachineBasicBlock::iterator 3690 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3691 unsigned InitResultReg, unsigned PhiReg, int Offset, 3692 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3693 MachineFunction *MF = MBB.getParent(); 3694 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3695 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3696 MachineRegisterInfo &MRI = MF->getRegInfo(); 3697 const DebugLoc &DL = MI.getDebugLoc(); 3698 MachineBasicBlock::iterator I(&MI); 3699 3700 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3701 Register DstReg = MI.getOperand(0).getReg(); 3702 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3703 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3704 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3705 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3706 3707 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3708 3709 // Save the EXEC mask 3710 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3711 .addReg(Exec); 3712 3713 MachineBasicBlock *LoopBB; 3714 MachineBasicBlock *RemainderBB; 3715 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3716 3717 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3718 3719 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3720 InitResultReg, DstReg, PhiReg, TmpExec, 3721 Offset, UseGPRIdxMode, SGPRIdxReg); 3722 3723 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3724 MachineFunction::iterator MBBI(LoopBB); 3725 ++MBBI; 3726 MF->insert(MBBI, LandingPad); 3727 LoopBB->removeSuccessor(RemainderBB); 3728 LandingPad->addSuccessor(RemainderBB); 3729 LoopBB->addSuccessor(LandingPad); 3730 MachineBasicBlock::iterator First = LandingPad->begin(); 3731 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3732 .addReg(SaveExec); 3733 3734 return InsPt; 3735 } 3736 3737 // Returns subreg index, offset 3738 static std::pair<unsigned, int> 3739 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3740 const TargetRegisterClass *SuperRC, 3741 unsigned VecReg, 3742 int Offset) { 3743 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3744 3745 // Skip out of bounds offsets, or else we would end up using an undefined 3746 // register. 3747 if (Offset >= NumElts || Offset < 0) 3748 return std::make_pair(AMDGPU::sub0, Offset); 3749 3750 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3751 } 3752 3753 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3754 MachineRegisterInfo &MRI, MachineInstr &MI, 3755 int Offset) { 3756 MachineBasicBlock *MBB = MI.getParent(); 3757 const DebugLoc &DL = MI.getDebugLoc(); 3758 MachineBasicBlock::iterator I(&MI); 3759 3760 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3761 3762 assert(Idx->getReg() != AMDGPU::NoRegister); 3763 3764 if (Offset == 0) { 3765 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3766 } else { 3767 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3768 .add(*Idx) 3769 .addImm(Offset); 3770 } 3771 } 3772 3773 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3774 MachineRegisterInfo &MRI, MachineInstr &MI, 3775 int Offset) { 3776 MachineBasicBlock *MBB = MI.getParent(); 3777 const DebugLoc &DL = MI.getDebugLoc(); 3778 MachineBasicBlock::iterator I(&MI); 3779 3780 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3781 3782 if (Offset == 0) 3783 return Idx->getReg(); 3784 3785 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3786 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3787 .add(*Idx) 3788 .addImm(Offset); 3789 return Tmp; 3790 } 3791 3792 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3793 MachineBasicBlock &MBB, 3794 const GCNSubtarget &ST) { 3795 const SIInstrInfo *TII = ST.getInstrInfo(); 3796 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3797 MachineFunction *MF = MBB.getParent(); 3798 MachineRegisterInfo &MRI = MF->getRegInfo(); 3799 3800 Register Dst = MI.getOperand(0).getReg(); 3801 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3802 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3803 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3804 3805 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3806 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3807 3808 unsigned SubReg; 3809 std::tie(SubReg, Offset) 3810 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3811 3812 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3813 3814 // Check for a SGPR index. 3815 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3816 MachineBasicBlock::iterator I(&MI); 3817 const DebugLoc &DL = MI.getDebugLoc(); 3818 3819 if (UseGPRIdxMode) { 3820 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3821 // to avoid interfering with other uses, so probably requires a new 3822 // optimization pass. 3823 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3824 3825 const MCInstrDesc &GPRIDXDesc = 3826 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3827 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3828 .addReg(SrcReg) 3829 .addReg(Idx) 3830 .addImm(SubReg); 3831 } else { 3832 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3833 3834 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3835 .addReg(SrcReg, 0, SubReg) 3836 .addReg(SrcReg, RegState::Implicit); 3837 } 3838 3839 MI.eraseFromParent(); 3840 3841 return &MBB; 3842 } 3843 3844 // Control flow needs to be inserted if indexing with a VGPR. 3845 const DebugLoc &DL = MI.getDebugLoc(); 3846 MachineBasicBlock::iterator I(&MI); 3847 3848 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3849 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3850 3851 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3852 3853 Register SGPRIdxReg; 3854 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3855 UseGPRIdxMode, SGPRIdxReg); 3856 3857 MachineBasicBlock *LoopBB = InsPt->getParent(); 3858 3859 if (UseGPRIdxMode) { 3860 const MCInstrDesc &GPRIDXDesc = 3861 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3862 3863 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3864 .addReg(SrcReg) 3865 .addReg(SGPRIdxReg) 3866 .addImm(SubReg); 3867 } else { 3868 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3869 .addReg(SrcReg, 0, SubReg) 3870 .addReg(SrcReg, RegState::Implicit); 3871 } 3872 3873 MI.eraseFromParent(); 3874 3875 return LoopBB; 3876 } 3877 3878 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3879 MachineBasicBlock &MBB, 3880 const GCNSubtarget &ST) { 3881 const SIInstrInfo *TII = ST.getInstrInfo(); 3882 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3883 MachineFunction *MF = MBB.getParent(); 3884 MachineRegisterInfo &MRI = MF->getRegInfo(); 3885 3886 Register Dst = MI.getOperand(0).getReg(); 3887 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3888 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3889 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3890 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3891 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3892 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3893 3894 // This can be an immediate, but will be folded later. 3895 assert(Val->getReg()); 3896 3897 unsigned SubReg; 3898 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3899 SrcVec->getReg(), 3900 Offset); 3901 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3902 3903 if (Idx->getReg() == AMDGPU::NoRegister) { 3904 MachineBasicBlock::iterator I(&MI); 3905 const DebugLoc &DL = MI.getDebugLoc(); 3906 3907 assert(Offset == 0); 3908 3909 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3910 .add(*SrcVec) 3911 .add(*Val) 3912 .addImm(SubReg); 3913 3914 MI.eraseFromParent(); 3915 return &MBB; 3916 } 3917 3918 // Check for a SGPR index. 3919 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3920 MachineBasicBlock::iterator I(&MI); 3921 const DebugLoc &DL = MI.getDebugLoc(); 3922 3923 if (UseGPRIdxMode) { 3924 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3925 3926 const MCInstrDesc &GPRIDXDesc = 3927 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3928 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3929 .addReg(SrcVec->getReg()) 3930 .add(*Val) 3931 .addReg(Idx) 3932 .addImm(SubReg); 3933 } else { 3934 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3935 3936 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3937 TRI.getRegSizeInBits(*VecRC), 32, false); 3938 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3939 .addReg(SrcVec->getReg()) 3940 .add(*Val) 3941 .addImm(SubReg); 3942 } 3943 MI.eraseFromParent(); 3944 return &MBB; 3945 } 3946 3947 // Control flow needs to be inserted if indexing with a VGPR. 3948 if (Val->isReg()) 3949 MRI.clearKillFlags(Val->getReg()); 3950 3951 const DebugLoc &DL = MI.getDebugLoc(); 3952 3953 Register PhiReg = MRI.createVirtualRegister(VecRC); 3954 3955 Register SGPRIdxReg; 3956 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3957 UseGPRIdxMode, SGPRIdxReg); 3958 MachineBasicBlock *LoopBB = InsPt->getParent(); 3959 3960 if (UseGPRIdxMode) { 3961 const MCInstrDesc &GPRIDXDesc = 3962 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3963 3964 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3965 .addReg(PhiReg) 3966 .add(*Val) 3967 .addReg(SGPRIdxReg) 3968 .addImm(AMDGPU::sub0); 3969 } else { 3970 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3971 TRI.getRegSizeInBits(*VecRC), 32, false); 3972 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3973 .addReg(PhiReg) 3974 .add(*Val) 3975 .addImm(AMDGPU::sub0); 3976 } 3977 3978 MI.eraseFromParent(); 3979 return LoopBB; 3980 } 3981 3982 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3983 MachineInstr &MI, MachineBasicBlock *BB) const { 3984 3985 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3986 MachineFunction *MF = BB->getParent(); 3987 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3988 3989 switch (MI.getOpcode()) { 3990 case AMDGPU::S_UADDO_PSEUDO: 3991 case AMDGPU::S_USUBO_PSEUDO: { 3992 const DebugLoc &DL = MI.getDebugLoc(); 3993 MachineOperand &Dest0 = MI.getOperand(0); 3994 MachineOperand &Dest1 = MI.getOperand(1); 3995 MachineOperand &Src0 = MI.getOperand(2); 3996 MachineOperand &Src1 = MI.getOperand(3); 3997 3998 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3999 ? AMDGPU::S_ADD_I32 4000 : AMDGPU::S_SUB_I32; 4001 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4002 4003 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4004 .addImm(1) 4005 .addImm(0); 4006 4007 MI.eraseFromParent(); 4008 return BB; 4009 } 4010 case AMDGPU::S_ADD_U64_PSEUDO: 4011 case AMDGPU::S_SUB_U64_PSEUDO: { 4012 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4013 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4014 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4015 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4016 const DebugLoc &DL = MI.getDebugLoc(); 4017 4018 MachineOperand &Dest = MI.getOperand(0); 4019 MachineOperand &Src0 = MI.getOperand(1); 4020 MachineOperand &Src1 = MI.getOperand(2); 4021 4022 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4023 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4024 4025 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4026 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4027 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4028 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4029 4030 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4031 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4032 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4033 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4034 4035 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4036 4037 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4038 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4039 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4040 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4041 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4042 .addReg(DestSub0) 4043 .addImm(AMDGPU::sub0) 4044 .addReg(DestSub1) 4045 .addImm(AMDGPU::sub1); 4046 MI.eraseFromParent(); 4047 return BB; 4048 } 4049 case AMDGPU::V_ADD_U64_PSEUDO: 4050 case AMDGPU::V_SUB_U64_PSEUDO: { 4051 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4052 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4053 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4054 const DebugLoc &DL = MI.getDebugLoc(); 4055 4056 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4057 4058 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4059 4060 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4061 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4062 4063 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4064 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4065 4066 MachineOperand &Dest = MI.getOperand(0); 4067 MachineOperand &Src0 = MI.getOperand(1); 4068 MachineOperand &Src1 = MI.getOperand(2); 4069 4070 const TargetRegisterClass *Src0RC = Src0.isReg() 4071 ? MRI.getRegClass(Src0.getReg()) 4072 : &AMDGPU::VReg_64RegClass; 4073 const TargetRegisterClass *Src1RC = Src1.isReg() 4074 ? MRI.getRegClass(Src1.getReg()) 4075 : &AMDGPU::VReg_64RegClass; 4076 4077 const TargetRegisterClass *Src0SubRC = 4078 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4079 const TargetRegisterClass *Src1SubRC = 4080 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4081 4082 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4083 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4084 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4085 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4086 4087 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4088 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4089 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4090 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4091 4092 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4093 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4094 .addReg(CarryReg, RegState::Define) 4095 .add(SrcReg0Sub0) 4096 .add(SrcReg1Sub0) 4097 .addImm(0); // clamp bit 4098 4099 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4100 MachineInstr *HiHalf = 4101 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4102 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4103 .add(SrcReg0Sub1) 4104 .add(SrcReg1Sub1) 4105 .addReg(CarryReg, RegState::Kill) 4106 .addImm(0); // clamp bit 4107 4108 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4109 .addReg(DestSub0) 4110 .addImm(AMDGPU::sub0) 4111 .addReg(DestSub1) 4112 .addImm(AMDGPU::sub1); 4113 TII->legalizeOperands(*LoHalf); 4114 TII->legalizeOperands(*HiHalf); 4115 MI.eraseFromParent(); 4116 return BB; 4117 } 4118 case AMDGPU::S_ADD_CO_PSEUDO: 4119 case AMDGPU::S_SUB_CO_PSEUDO: { 4120 // This pseudo has a chance to be selected 4121 // only from uniform add/subcarry node. All the VGPR operands 4122 // therefore assumed to be splat vectors. 4123 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4124 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4125 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4126 MachineBasicBlock::iterator MII = MI; 4127 const DebugLoc &DL = MI.getDebugLoc(); 4128 MachineOperand &Dest = MI.getOperand(0); 4129 MachineOperand &CarryDest = MI.getOperand(1); 4130 MachineOperand &Src0 = MI.getOperand(2); 4131 MachineOperand &Src1 = MI.getOperand(3); 4132 MachineOperand &Src2 = MI.getOperand(4); 4133 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4134 ? AMDGPU::S_ADDC_U32 4135 : AMDGPU::S_SUBB_U32; 4136 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4137 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4138 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4139 .addReg(Src0.getReg()); 4140 Src0.setReg(RegOp0); 4141 } 4142 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4143 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4144 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4145 .addReg(Src1.getReg()); 4146 Src1.setReg(RegOp1); 4147 } 4148 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4149 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4150 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4151 .addReg(Src2.getReg()); 4152 Src2.setReg(RegOp2); 4153 } 4154 4155 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4156 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4157 assert(WaveSize == 64 || WaveSize == 32); 4158 4159 if (WaveSize == 64) { 4160 if (ST.hasScalarCompareEq64()) { 4161 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4162 .addReg(Src2.getReg()) 4163 .addImm(0); 4164 } else { 4165 const TargetRegisterClass *SubRC = 4166 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4167 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4168 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4169 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4170 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4171 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4172 4173 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4174 .add(Src2Sub0) 4175 .add(Src2Sub1); 4176 4177 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4178 .addReg(Src2_32, RegState::Kill) 4179 .addImm(0); 4180 } 4181 } else { 4182 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4183 .addReg(Src2.getReg()) 4184 .addImm(0); 4185 } 4186 4187 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4188 4189 unsigned SelOpc = 4190 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4191 4192 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4193 .addImm(-1) 4194 .addImm(0); 4195 4196 MI.eraseFromParent(); 4197 return BB; 4198 } 4199 case AMDGPU::SI_INIT_M0: { 4200 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4201 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4202 .add(MI.getOperand(0)); 4203 MI.eraseFromParent(); 4204 return BB; 4205 } 4206 case AMDGPU::GET_GROUPSTATICSIZE: { 4207 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4208 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4209 DebugLoc DL = MI.getDebugLoc(); 4210 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4211 .add(MI.getOperand(0)) 4212 .addImm(MFI->getLDSSize()); 4213 MI.eraseFromParent(); 4214 return BB; 4215 } 4216 case AMDGPU::SI_INDIRECT_SRC_V1: 4217 case AMDGPU::SI_INDIRECT_SRC_V2: 4218 case AMDGPU::SI_INDIRECT_SRC_V4: 4219 case AMDGPU::SI_INDIRECT_SRC_V8: 4220 case AMDGPU::SI_INDIRECT_SRC_V16: 4221 case AMDGPU::SI_INDIRECT_SRC_V32: 4222 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4223 case AMDGPU::SI_INDIRECT_DST_V1: 4224 case AMDGPU::SI_INDIRECT_DST_V2: 4225 case AMDGPU::SI_INDIRECT_DST_V4: 4226 case AMDGPU::SI_INDIRECT_DST_V8: 4227 case AMDGPU::SI_INDIRECT_DST_V16: 4228 case AMDGPU::SI_INDIRECT_DST_V32: 4229 return emitIndirectDst(MI, *BB, *getSubtarget()); 4230 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4231 case AMDGPU::SI_KILL_I1_PSEUDO: 4232 return splitKillBlock(MI, BB); 4233 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4234 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4235 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4236 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4237 4238 Register Dst = MI.getOperand(0).getReg(); 4239 Register Src0 = MI.getOperand(1).getReg(); 4240 Register Src1 = MI.getOperand(2).getReg(); 4241 const DebugLoc &DL = MI.getDebugLoc(); 4242 Register SrcCond = MI.getOperand(3).getReg(); 4243 4244 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4245 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4246 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4247 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4248 4249 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4250 .addReg(SrcCond); 4251 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4252 .addImm(0) 4253 .addReg(Src0, 0, AMDGPU::sub0) 4254 .addImm(0) 4255 .addReg(Src1, 0, AMDGPU::sub0) 4256 .addReg(SrcCondCopy); 4257 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4258 .addImm(0) 4259 .addReg(Src0, 0, AMDGPU::sub1) 4260 .addImm(0) 4261 .addReg(Src1, 0, AMDGPU::sub1) 4262 .addReg(SrcCondCopy); 4263 4264 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4265 .addReg(DstLo) 4266 .addImm(AMDGPU::sub0) 4267 .addReg(DstHi) 4268 .addImm(AMDGPU::sub1); 4269 MI.eraseFromParent(); 4270 return BB; 4271 } 4272 case AMDGPU::SI_BR_UNDEF: { 4273 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4274 const DebugLoc &DL = MI.getDebugLoc(); 4275 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4276 .add(MI.getOperand(0)); 4277 Br->getOperand(1).setIsUndef(true); // read undef SCC 4278 MI.eraseFromParent(); 4279 return BB; 4280 } 4281 case AMDGPU::ADJCALLSTACKUP: 4282 case AMDGPU::ADJCALLSTACKDOWN: { 4283 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4284 MachineInstrBuilder MIB(*MF, &MI); 4285 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4286 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4287 return BB; 4288 } 4289 case AMDGPU::SI_CALL_ISEL: { 4290 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4291 const DebugLoc &DL = MI.getDebugLoc(); 4292 4293 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4294 4295 MachineInstrBuilder MIB; 4296 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4297 4298 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4299 MIB.add(MI.getOperand(I)); 4300 4301 MIB.cloneMemRefs(MI); 4302 MI.eraseFromParent(); 4303 return BB; 4304 } 4305 case AMDGPU::V_ADD_CO_U32_e32: 4306 case AMDGPU::V_SUB_CO_U32_e32: 4307 case AMDGPU::V_SUBREV_CO_U32_e32: { 4308 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4309 const DebugLoc &DL = MI.getDebugLoc(); 4310 unsigned Opc = MI.getOpcode(); 4311 4312 bool NeedClampOperand = false; 4313 if (TII->pseudoToMCOpcode(Opc) == -1) { 4314 Opc = AMDGPU::getVOPe64(Opc); 4315 NeedClampOperand = true; 4316 } 4317 4318 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4319 if (TII->isVOP3(*I)) { 4320 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4321 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4322 I.addReg(TRI->getVCC(), RegState::Define); 4323 } 4324 I.add(MI.getOperand(1)) 4325 .add(MI.getOperand(2)); 4326 if (NeedClampOperand) 4327 I.addImm(0); // clamp bit for e64 encoding 4328 4329 TII->legalizeOperands(*I); 4330 4331 MI.eraseFromParent(); 4332 return BB; 4333 } 4334 case AMDGPU::V_ADDC_U32_e32: 4335 case AMDGPU::V_SUBB_U32_e32: 4336 case AMDGPU::V_SUBBREV_U32_e32: 4337 // These instructions have an implicit use of vcc which counts towards the 4338 // constant bus limit. 4339 TII->legalizeOperands(MI); 4340 return BB; 4341 case AMDGPU::DS_GWS_INIT: 4342 case AMDGPU::DS_GWS_SEMA_BR: 4343 case AMDGPU::DS_GWS_BARRIER: 4344 if (Subtarget->needsAlignedVGPRs()) { 4345 // Add implicit aligned super-reg to force alignment on the data operand. 4346 const DebugLoc &DL = MI.getDebugLoc(); 4347 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4348 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4349 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4350 Register DataReg = Op->getReg(); 4351 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4352 Register Undef = MRI.createVirtualRegister( 4353 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4354 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4355 Register NewVR = 4356 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4357 : &AMDGPU::VReg_64_Align2RegClass); 4358 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4359 .addReg(DataReg, 0, Op->getSubReg()) 4360 .addImm(AMDGPU::sub0) 4361 .addReg(Undef) 4362 .addImm(AMDGPU::sub1); 4363 Op->setReg(NewVR); 4364 Op->setSubReg(AMDGPU::sub0); 4365 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4366 } 4367 LLVM_FALLTHROUGH; 4368 case AMDGPU::DS_GWS_SEMA_V: 4369 case AMDGPU::DS_GWS_SEMA_P: 4370 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4371 // A s_waitcnt 0 is required to be the instruction immediately following. 4372 if (getSubtarget()->hasGWSAutoReplay()) { 4373 bundleInstWithWaitcnt(MI); 4374 return BB; 4375 } 4376 4377 return emitGWSMemViolTestLoop(MI, BB); 4378 case AMDGPU::S_SETREG_B32: { 4379 // Try to optimize cases that only set the denormal mode or rounding mode. 4380 // 4381 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4382 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4383 // instead. 4384 // 4385 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4386 // allow you to have a no side effect instruction in the output of a 4387 // sideeffecting pattern. 4388 unsigned ID, Offset, Width; 4389 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4390 if (ID != AMDGPU::Hwreg::ID_MODE) 4391 return BB; 4392 4393 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4394 const unsigned SetMask = WidthMask << Offset; 4395 4396 if (getSubtarget()->hasDenormModeInst()) { 4397 unsigned SetDenormOp = 0; 4398 unsigned SetRoundOp = 0; 4399 4400 // The dedicated instructions can only set the whole denorm or round mode 4401 // at once, not a subset of bits in either. 4402 if (SetMask == 4403 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4404 // If this fully sets both the round and denorm mode, emit the two 4405 // dedicated instructions for these. 4406 SetRoundOp = AMDGPU::S_ROUND_MODE; 4407 SetDenormOp = AMDGPU::S_DENORM_MODE; 4408 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4409 SetRoundOp = AMDGPU::S_ROUND_MODE; 4410 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4411 SetDenormOp = AMDGPU::S_DENORM_MODE; 4412 } 4413 4414 if (SetRoundOp || SetDenormOp) { 4415 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4416 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4417 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4418 unsigned ImmVal = Def->getOperand(1).getImm(); 4419 if (SetRoundOp) { 4420 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4421 .addImm(ImmVal & 0xf); 4422 4423 // If we also have the denorm mode, get just the denorm mode bits. 4424 ImmVal >>= 4; 4425 } 4426 4427 if (SetDenormOp) { 4428 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4429 .addImm(ImmVal & 0xf); 4430 } 4431 4432 MI.eraseFromParent(); 4433 return BB; 4434 } 4435 } 4436 } 4437 4438 // If only FP bits are touched, used the no side effects pseudo. 4439 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4440 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4441 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4442 4443 return BB; 4444 } 4445 default: 4446 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4447 } 4448 } 4449 4450 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4451 return isTypeLegal(VT.getScalarType()); 4452 } 4453 4454 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4455 // This currently forces unfolding various combinations of fsub into fma with 4456 // free fneg'd operands. As long as we have fast FMA (controlled by 4457 // isFMAFasterThanFMulAndFAdd), we should perform these. 4458 4459 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4460 // most of these combines appear to be cycle neutral but save on instruction 4461 // count / code size. 4462 return true; 4463 } 4464 4465 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4466 EVT VT) const { 4467 if (!VT.isVector()) { 4468 return MVT::i1; 4469 } 4470 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4471 } 4472 4473 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4474 // TODO: Should i16 be used always if legal? For now it would force VALU 4475 // shifts. 4476 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4477 } 4478 4479 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4480 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4481 ? Ty.changeElementSize(16) 4482 : Ty.changeElementSize(32); 4483 } 4484 4485 // Answering this is somewhat tricky and depends on the specific device which 4486 // have different rates for fma or all f64 operations. 4487 // 4488 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4489 // regardless of which device (although the number of cycles differs between 4490 // devices), so it is always profitable for f64. 4491 // 4492 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4493 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4494 // which we can always do even without fused FP ops since it returns the same 4495 // result as the separate operations and since it is always full 4496 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4497 // however does not support denormals, so we do report fma as faster if we have 4498 // a fast fma device and require denormals. 4499 // 4500 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4501 EVT VT) const { 4502 VT = VT.getScalarType(); 4503 4504 switch (VT.getSimpleVT().SimpleTy) { 4505 case MVT::f32: { 4506 // If mad is not available this depends only on if f32 fma is full rate. 4507 if (!Subtarget->hasMadMacF32Insts()) 4508 return Subtarget->hasFastFMAF32(); 4509 4510 // Otherwise f32 mad is always full rate and returns the same result as 4511 // the separate operations so should be preferred over fma. 4512 // However does not support denomals. 4513 if (hasFP32Denormals(MF)) 4514 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4515 4516 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4517 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4518 } 4519 case MVT::f64: 4520 return true; 4521 case MVT::f16: 4522 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4523 default: 4524 break; 4525 } 4526 4527 return false; 4528 } 4529 4530 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4531 const SDNode *N) const { 4532 // TODO: Check future ftz flag 4533 // v_mad_f32/v_mac_f32 do not support denormals. 4534 EVT VT = N->getValueType(0); 4535 if (VT == MVT::f32) 4536 return Subtarget->hasMadMacF32Insts() && 4537 !hasFP32Denormals(DAG.getMachineFunction()); 4538 if (VT == MVT::f16) { 4539 return Subtarget->hasMadF16() && 4540 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4541 } 4542 4543 return false; 4544 } 4545 4546 //===----------------------------------------------------------------------===// 4547 // Custom DAG Lowering Operations 4548 //===----------------------------------------------------------------------===// 4549 4550 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4551 // wider vector type is legal. 4552 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4553 SelectionDAG &DAG) const { 4554 unsigned Opc = Op.getOpcode(); 4555 EVT VT = Op.getValueType(); 4556 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4557 4558 SDValue Lo, Hi; 4559 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4560 4561 SDLoc SL(Op); 4562 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4563 Op->getFlags()); 4564 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4565 Op->getFlags()); 4566 4567 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4568 } 4569 4570 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4571 // wider vector type is legal. 4572 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4573 SelectionDAG &DAG) const { 4574 unsigned Opc = Op.getOpcode(); 4575 EVT VT = Op.getValueType(); 4576 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4577 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4578 4579 SDValue Lo0, Hi0; 4580 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4581 SDValue Lo1, Hi1; 4582 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4583 4584 SDLoc SL(Op); 4585 4586 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4587 Op->getFlags()); 4588 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4589 Op->getFlags()); 4590 4591 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4592 } 4593 4594 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4595 SelectionDAG &DAG) const { 4596 unsigned Opc = Op.getOpcode(); 4597 EVT VT = Op.getValueType(); 4598 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4599 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4600 4601 SDValue Lo0, Hi0; 4602 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4603 SDValue Lo1, Hi1; 4604 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4605 SDValue Lo2, Hi2; 4606 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4607 4608 SDLoc SL(Op); 4609 4610 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4611 Op->getFlags()); 4612 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4613 Op->getFlags()); 4614 4615 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4616 } 4617 4618 4619 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4620 switch (Op.getOpcode()) { 4621 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4622 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4623 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4624 case ISD::LOAD: { 4625 SDValue Result = LowerLOAD(Op, DAG); 4626 assert((!Result.getNode() || 4627 Result.getNode()->getNumValues() == 2) && 4628 "Load should return a value and a chain"); 4629 return Result; 4630 } 4631 4632 case ISD::FSIN: 4633 case ISD::FCOS: 4634 return LowerTrig(Op, DAG); 4635 case ISD::SELECT: return LowerSELECT(Op, DAG); 4636 case ISD::FDIV: return LowerFDIV(Op, DAG); 4637 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4638 case ISD::STORE: return LowerSTORE(Op, DAG); 4639 case ISD::GlobalAddress: { 4640 MachineFunction &MF = DAG.getMachineFunction(); 4641 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4642 return LowerGlobalAddress(MFI, Op, DAG); 4643 } 4644 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4645 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4646 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4647 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4648 case ISD::INSERT_SUBVECTOR: 4649 return lowerINSERT_SUBVECTOR(Op, DAG); 4650 case ISD::INSERT_VECTOR_ELT: 4651 return lowerINSERT_VECTOR_ELT(Op, DAG); 4652 case ISD::EXTRACT_VECTOR_ELT: 4653 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4654 case ISD::VECTOR_SHUFFLE: 4655 return lowerVECTOR_SHUFFLE(Op, DAG); 4656 case ISD::BUILD_VECTOR: 4657 return lowerBUILD_VECTOR(Op, DAG); 4658 case ISD::FP_ROUND: 4659 return lowerFP_ROUND(Op, DAG); 4660 case ISD::TRAP: 4661 return lowerTRAP(Op, DAG); 4662 case ISD::DEBUGTRAP: 4663 return lowerDEBUGTRAP(Op, DAG); 4664 case ISD::FABS: 4665 case ISD::FNEG: 4666 case ISD::FCANONICALIZE: 4667 case ISD::BSWAP: 4668 return splitUnaryVectorOp(Op, DAG); 4669 case ISD::FMINNUM: 4670 case ISD::FMAXNUM: 4671 return lowerFMINNUM_FMAXNUM(Op, DAG); 4672 case ISD::FMA: 4673 return splitTernaryVectorOp(Op, DAG); 4674 case ISD::FP_TO_SINT: 4675 case ISD::FP_TO_UINT: 4676 return LowerFP_TO_INT(Op, DAG); 4677 case ISD::SHL: 4678 case ISD::SRA: 4679 case ISD::SRL: 4680 case ISD::ADD: 4681 case ISD::SUB: 4682 case ISD::MUL: 4683 case ISD::SMIN: 4684 case ISD::SMAX: 4685 case ISD::UMIN: 4686 case ISD::UMAX: 4687 case ISD::FADD: 4688 case ISD::FMUL: 4689 case ISD::FMINNUM_IEEE: 4690 case ISD::FMAXNUM_IEEE: 4691 case ISD::UADDSAT: 4692 case ISD::USUBSAT: 4693 case ISD::SADDSAT: 4694 case ISD::SSUBSAT: 4695 return splitBinaryVectorOp(Op, DAG); 4696 case ISD::SMULO: 4697 case ISD::UMULO: 4698 return lowerXMULO(Op, DAG); 4699 case ISD::SMUL_LOHI: 4700 case ISD::UMUL_LOHI: 4701 return lowerXMUL_LOHI(Op, DAG); 4702 case ISD::DYNAMIC_STACKALLOC: 4703 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4704 } 4705 return SDValue(); 4706 } 4707 4708 // Used for D16: Casts the result of an instruction into the right vector, 4709 // packs values if loads return unpacked values. 4710 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4711 const SDLoc &DL, 4712 SelectionDAG &DAG, bool Unpacked) { 4713 if (!LoadVT.isVector()) 4714 return Result; 4715 4716 // Cast back to the original packed type or to a larger type that is a 4717 // multiple of 32 bit for D16. Widening the return type is a required for 4718 // legalization. 4719 EVT FittingLoadVT = LoadVT; 4720 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4721 FittingLoadVT = 4722 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4723 LoadVT.getVectorNumElements() + 1); 4724 } 4725 4726 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4727 // Truncate to v2i16/v4i16. 4728 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4729 4730 // Workaround legalizer not scalarizing truncate after vector op 4731 // legalization but not creating intermediate vector trunc. 4732 SmallVector<SDValue, 4> Elts; 4733 DAG.ExtractVectorElements(Result, Elts); 4734 for (SDValue &Elt : Elts) 4735 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4736 4737 // Pad illegal v1i16/v3fi6 to v4i16 4738 if ((LoadVT.getVectorNumElements() % 2) == 1) 4739 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4740 4741 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4742 4743 // Bitcast to original type (v2f16/v4f16). 4744 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4745 } 4746 4747 // Cast back to the original packed type. 4748 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4749 } 4750 4751 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4752 MemSDNode *M, 4753 SelectionDAG &DAG, 4754 ArrayRef<SDValue> Ops, 4755 bool IsIntrinsic) const { 4756 SDLoc DL(M); 4757 4758 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4759 EVT LoadVT = M->getValueType(0); 4760 4761 EVT EquivLoadVT = LoadVT; 4762 if (LoadVT.isVector()) { 4763 if (Unpacked) { 4764 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4765 LoadVT.getVectorNumElements()); 4766 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4767 // Widen v3f16 to legal type 4768 EquivLoadVT = 4769 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4770 LoadVT.getVectorNumElements() + 1); 4771 } 4772 } 4773 4774 // Change from v4f16/v2f16 to EquivLoadVT. 4775 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4776 4777 SDValue Load 4778 = DAG.getMemIntrinsicNode( 4779 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4780 VTList, Ops, M->getMemoryVT(), 4781 M->getMemOperand()); 4782 4783 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4784 4785 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4786 } 4787 4788 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4789 SelectionDAG &DAG, 4790 ArrayRef<SDValue> Ops) const { 4791 SDLoc DL(M); 4792 EVT LoadVT = M->getValueType(0); 4793 EVT EltType = LoadVT.getScalarType(); 4794 EVT IntVT = LoadVT.changeTypeToInteger(); 4795 4796 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4797 4798 unsigned Opc = 4799 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4800 4801 if (IsD16) { 4802 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4803 } 4804 4805 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4806 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4807 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4808 4809 if (isTypeLegal(LoadVT)) { 4810 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4811 M->getMemOperand(), DAG); 4812 } 4813 4814 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4815 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4816 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4817 M->getMemOperand(), DAG); 4818 return DAG.getMergeValues( 4819 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4820 DL); 4821 } 4822 4823 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4824 SDNode *N, SelectionDAG &DAG) { 4825 EVT VT = N->getValueType(0); 4826 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4827 unsigned CondCode = CD->getZExtValue(); 4828 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4829 return DAG.getUNDEF(VT); 4830 4831 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4832 4833 SDValue LHS = N->getOperand(1); 4834 SDValue RHS = N->getOperand(2); 4835 4836 SDLoc DL(N); 4837 4838 EVT CmpVT = LHS.getValueType(); 4839 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4840 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4841 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4842 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4843 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4844 } 4845 4846 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4847 4848 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4849 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4850 4851 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4852 DAG.getCondCode(CCOpcode)); 4853 if (VT.bitsEq(CCVT)) 4854 return SetCC; 4855 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4856 } 4857 4858 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4859 SDNode *N, SelectionDAG &DAG) { 4860 EVT VT = N->getValueType(0); 4861 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4862 4863 unsigned CondCode = CD->getZExtValue(); 4864 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4865 return DAG.getUNDEF(VT); 4866 4867 SDValue Src0 = N->getOperand(1); 4868 SDValue Src1 = N->getOperand(2); 4869 EVT CmpVT = Src0.getValueType(); 4870 SDLoc SL(N); 4871 4872 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4873 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4874 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4875 } 4876 4877 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4878 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4879 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4880 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4881 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4882 Src1, DAG.getCondCode(CCOpcode)); 4883 if (VT.bitsEq(CCVT)) 4884 return SetCC; 4885 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4886 } 4887 4888 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4889 SelectionDAG &DAG) { 4890 EVT VT = N->getValueType(0); 4891 SDValue Src = N->getOperand(1); 4892 SDLoc SL(N); 4893 4894 if (Src.getOpcode() == ISD::SETCC) { 4895 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4896 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4897 Src.getOperand(1), Src.getOperand(2)); 4898 } 4899 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4900 // (ballot 0) -> 0 4901 if (Arg->isZero()) 4902 return DAG.getConstant(0, SL, VT); 4903 4904 // (ballot 1) -> EXEC/EXEC_LO 4905 if (Arg->isOne()) { 4906 Register Exec; 4907 if (VT.getScalarSizeInBits() == 32) 4908 Exec = AMDGPU::EXEC_LO; 4909 else if (VT.getScalarSizeInBits() == 64) 4910 Exec = AMDGPU::EXEC; 4911 else 4912 return SDValue(); 4913 4914 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4915 } 4916 } 4917 4918 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4919 // ISD::SETNE) 4920 return DAG.getNode( 4921 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4922 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4923 } 4924 4925 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4926 SmallVectorImpl<SDValue> &Results, 4927 SelectionDAG &DAG) const { 4928 switch (N->getOpcode()) { 4929 case ISD::INSERT_VECTOR_ELT: { 4930 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4931 Results.push_back(Res); 4932 return; 4933 } 4934 case ISD::EXTRACT_VECTOR_ELT: { 4935 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4936 Results.push_back(Res); 4937 return; 4938 } 4939 case ISD::INTRINSIC_WO_CHAIN: { 4940 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4941 switch (IID) { 4942 case Intrinsic::amdgcn_cvt_pkrtz: { 4943 SDValue Src0 = N->getOperand(1); 4944 SDValue Src1 = N->getOperand(2); 4945 SDLoc SL(N); 4946 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4947 Src0, Src1); 4948 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4949 return; 4950 } 4951 case Intrinsic::amdgcn_cvt_pknorm_i16: 4952 case Intrinsic::amdgcn_cvt_pknorm_u16: 4953 case Intrinsic::amdgcn_cvt_pk_i16: 4954 case Intrinsic::amdgcn_cvt_pk_u16: { 4955 SDValue Src0 = N->getOperand(1); 4956 SDValue Src1 = N->getOperand(2); 4957 SDLoc SL(N); 4958 unsigned Opcode; 4959 4960 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4961 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4962 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4963 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4964 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4965 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4966 else 4967 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4968 4969 EVT VT = N->getValueType(0); 4970 if (isTypeLegal(VT)) 4971 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4972 else { 4973 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4974 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4975 } 4976 return; 4977 } 4978 } 4979 break; 4980 } 4981 case ISD::INTRINSIC_W_CHAIN: { 4982 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4983 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4984 // FIXME: Hacky 4985 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4986 Results.push_back(Res.getOperand(I)); 4987 } 4988 } else { 4989 Results.push_back(Res); 4990 Results.push_back(Res.getValue(1)); 4991 } 4992 return; 4993 } 4994 4995 break; 4996 } 4997 case ISD::SELECT: { 4998 SDLoc SL(N); 4999 EVT VT = N->getValueType(0); 5000 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5001 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5002 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5003 5004 EVT SelectVT = NewVT; 5005 if (NewVT.bitsLT(MVT::i32)) { 5006 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5007 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5008 SelectVT = MVT::i32; 5009 } 5010 5011 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5012 N->getOperand(0), LHS, RHS); 5013 5014 if (NewVT != SelectVT) 5015 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5016 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5017 return; 5018 } 5019 case ISD::FNEG: { 5020 if (N->getValueType(0) != MVT::v2f16) 5021 break; 5022 5023 SDLoc SL(N); 5024 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5025 5026 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5027 BC, 5028 DAG.getConstant(0x80008000, SL, MVT::i32)); 5029 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5030 return; 5031 } 5032 case ISD::FABS: { 5033 if (N->getValueType(0) != MVT::v2f16) 5034 break; 5035 5036 SDLoc SL(N); 5037 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5038 5039 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5040 BC, 5041 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5042 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5043 return; 5044 } 5045 default: 5046 break; 5047 } 5048 } 5049 5050 /// Helper function for LowerBRCOND 5051 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5052 5053 SDNode *Parent = Value.getNode(); 5054 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5055 I != E; ++I) { 5056 5057 if (I.getUse().get() != Value) 5058 continue; 5059 5060 if (I->getOpcode() == Opcode) 5061 return *I; 5062 } 5063 return nullptr; 5064 } 5065 5066 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5067 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5068 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5069 case Intrinsic::amdgcn_if: 5070 return AMDGPUISD::IF; 5071 case Intrinsic::amdgcn_else: 5072 return AMDGPUISD::ELSE; 5073 case Intrinsic::amdgcn_loop: 5074 return AMDGPUISD::LOOP; 5075 case Intrinsic::amdgcn_end_cf: 5076 llvm_unreachable("should not occur"); 5077 default: 5078 return 0; 5079 } 5080 } 5081 5082 // break, if_break, else_break are all only used as inputs to loop, not 5083 // directly as branch conditions. 5084 return 0; 5085 } 5086 5087 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5088 const Triple &TT = getTargetMachine().getTargetTriple(); 5089 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5090 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5091 AMDGPU::shouldEmitConstantsToTextSection(TT); 5092 } 5093 5094 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5095 // FIXME: Either avoid relying on address space here or change the default 5096 // address space for functions to avoid the explicit check. 5097 return (GV->getValueType()->isFunctionTy() || 5098 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5099 !shouldEmitFixup(GV) && 5100 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5101 } 5102 5103 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5104 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5105 } 5106 5107 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5108 if (!GV->hasExternalLinkage()) 5109 return true; 5110 5111 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5112 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5113 } 5114 5115 /// This transforms the control flow intrinsics to get the branch destination as 5116 /// last parameter, also switches branch target with BR if the need arise 5117 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5118 SelectionDAG &DAG) const { 5119 SDLoc DL(BRCOND); 5120 5121 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5122 SDValue Target = BRCOND.getOperand(2); 5123 SDNode *BR = nullptr; 5124 SDNode *SetCC = nullptr; 5125 5126 if (Intr->getOpcode() == ISD::SETCC) { 5127 // As long as we negate the condition everything is fine 5128 SetCC = Intr; 5129 Intr = SetCC->getOperand(0).getNode(); 5130 5131 } else { 5132 // Get the target from BR if we don't negate the condition 5133 BR = findUser(BRCOND, ISD::BR); 5134 assert(BR && "brcond missing unconditional branch user"); 5135 Target = BR->getOperand(1); 5136 } 5137 5138 unsigned CFNode = isCFIntrinsic(Intr); 5139 if (CFNode == 0) { 5140 // This is a uniform branch so we don't need to legalize. 5141 return BRCOND; 5142 } 5143 5144 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5145 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5146 5147 assert(!SetCC || 5148 (SetCC->getConstantOperandVal(1) == 1 && 5149 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5150 ISD::SETNE)); 5151 5152 // operands of the new intrinsic call 5153 SmallVector<SDValue, 4> Ops; 5154 if (HaveChain) 5155 Ops.push_back(BRCOND.getOperand(0)); 5156 5157 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5158 Ops.push_back(Target); 5159 5160 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5161 5162 // build the new intrinsic call 5163 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5164 5165 if (!HaveChain) { 5166 SDValue Ops[] = { 5167 SDValue(Result, 0), 5168 BRCOND.getOperand(0) 5169 }; 5170 5171 Result = DAG.getMergeValues(Ops, DL).getNode(); 5172 } 5173 5174 if (BR) { 5175 // Give the branch instruction our target 5176 SDValue Ops[] = { 5177 BR->getOperand(0), 5178 BRCOND.getOperand(2) 5179 }; 5180 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5181 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5182 } 5183 5184 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5185 5186 // Copy the intrinsic results to registers 5187 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5188 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5189 if (!CopyToReg) 5190 continue; 5191 5192 Chain = DAG.getCopyToReg( 5193 Chain, DL, 5194 CopyToReg->getOperand(1), 5195 SDValue(Result, i - 1), 5196 SDValue()); 5197 5198 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5199 } 5200 5201 // Remove the old intrinsic from the chain 5202 DAG.ReplaceAllUsesOfValueWith( 5203 SDValue(Intr, Intr->getNumValues() - 1), 5204 Intr->getOperand(0)); 5205 5206 return Chain; 5207 } 5208 5209 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5210 SelectionDAG &DAG) const { 5211 MVT VT = Op.getSimpleValueType(); 5212 SDLoc DL(Op); 5213 // Checking the depth 5214 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5215 return DAG.getConstant(0, DL, VT); 5216 5217 MachineFunction &MF = DAG.getMachineFunction(); 5218 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5219 // Check for kernel and shader functions 5220 if (Info->isEntryFunction()) 5221 return DAG.getConstant(0, DL, VT); 5222 5223 MachineFrameInfo &MFI = MF.getFrameInfo(); 5224 // There is a call to @llvm.returnaddress in this function 5225 MFI.setReturnAddressIsTaken(true); 5226 5227 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5228 // Get the return address reg and mark it as an implicit live-in 5229 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5230 5231 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5232 } 5233 5234 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5235 SDValue Op, 5236 const SDLoc &DL, 5237 EVT VT) const { 5238 return Op.getValueType().bitsLE(VT) ? 5239 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5240 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5241 DAG.getTargetConstant(0, DL, MVT::i32)); 5242 } 5243 5244 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5245 assert(Op.getValueType() == MVT::f16 && 5246 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5247 5248 SDValue Src = Op.getOperand(0); 5249 EVT SrcVT = Src.getValueType(); 5250 if (SrcVT != MVT::f64) 5251 return Op; 5252 5253 SDLoc DL(Op); 5254 5255 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5256 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5257 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5258 } 5259 5260 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5261 SelectionDAG &DAG) const { 5262 EVT VT = Op.getValueType(); 5263 const MachineFunction &MF = DAG.getMachineFunction(); 5264 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5265 bool IsIEEEMode = Info->getMode().IEEE; 5266 5267 // FIXME: Assert during selection that this is only selected for 5268 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5269 // mode functions, but this happens to be OK since it's only done in cases 5270 // where there is known no sNaN. 5271 if (IsIEEEMode) 5272 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5273 5274 if (VT == MVT::v4f16) 5275 return splitBinaryVectorOp(Op, DAG); 5276 return Op; 5277 } 5278 5279 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5280 EVT VT = Op.getValueType(); 5281 SDLoc SL(Op); 5282 SDValue LHS = Op.getOperand(0); 5283 SDValue RHS = Op.getOperand(1); 5284 bool isSigned = Op.getOpcode() == ISD::SMULO; 5285 5286 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5287 const APInt &C = RHSC->getAPIntValue(); 5288 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5289 if (C.isPowerOf2()) { 5290 // smulo(x, signed_min) is same as umulo(x, signed_min). 5291 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5292 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5293 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5294 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5295 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5296 SL, VT, Result, ShiftAmt), 5297 LHS, ISD::SETNE); 5298 return DAG.getMergeValues({ Result, Overflow }, SL); 5299 } 5300 } 5301 5302 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5303 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5304 SL, VT, LHS, RHS); 5305 5306 SDValue Sign = isSigned 5307 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5308 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5309 : DAG.getConstant(0, SL, VT); 5310 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5311 5312 return DAG.getMergeValues({ Result, Overflow }, SL); 5313 } 5314 5315 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5316 if (Op->isDivergent()) { 5317 // Select to V_MAD_[IU]64_[IU]32. 5318 return Op; 5319 } 5320 if (Subtarget->hasSMulHi()) { 5321 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5322 return SDValue(); 5323 } 5324 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5325 // calculate the high part, so we might as well do the whole thing with 5326 // V_MAD_[IU]64_[IU]32. 5327 return Op; 5328 } 5329 5330 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5331 if (!Subtarget->isTrapHandlerEnabled() || 5332 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5333 return lowerTrapEndpgm(Op, DAG); 5334 5335 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5336 switch (*HsaAbiVer) { 5337 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5338 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5339 return lowerTrapHsaQueuePtr(Op, DAG); 5340 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5341 return Subtarget->supportsGetDoorbellID() ? 5342 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5343 } 5344 } 5345 5346 llvm_unreachable("Unknown trap handler"); 5347 } 5348 5349 SDValue SITargetLowering::lowerTrapEndpgm( 5350 SDValue Op, SelectionDAG &DAG) const { 5351 SDLoc SL(Op); 5352 SDValue Chain = Op.getOperand(0); 5353 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5354 } 5355 5356 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5357 SDValue Op, SelectionDAG &DAG) const { 5358 SDLoc SL(Op); 5359 SDValue Chain = Op.getOperand(0); 5360 5361 MachineFunction &MF = DAG.getMachineFunction(); 5362 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5363 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5364 5365 SDValue QueuePtr; 5366 if (UserSGPR == AMDGPU::NoRegister) { 5367 // We probably are in a function incorrectly marked with 5368 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5369 // so just use a null pointer. 5370 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5371 } else { 5372 QueuePtr = CreateLiveInRegister( 5373 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5374 } 5375 5376 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5377 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5378 QueuePtr, SDValue()); 5379 5380 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5381 SDValue Ops[] = { 5382 ToReg, 5383 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5384 SGPR01, 5385 ToReg.getValue(1) 5386 }; 5387 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5388 } 5389 5390 SDValue SITargetLowering::lowerTrapHsa( 5391 SDValue Op, SelectionDAG &DAG) const { 5392 SDLoc SL(Op); 5393 SDValue Chain = Op.getOperand(0); 5394 5395 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5396 SDValue Ops[] = { 5397 Chain, 5398 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5399 }; 5400 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5401 } 5402 5403 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5404 SDLoc SL(Op); 5405 SDValue Chain = Op.getOperand(0); 5406 MachineFunction &MF = DAG.getMachineFunction(); 5407 5408 if (!Subtarget->isTrapHandlerEnabled() || 5409 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5410 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5411 "debugtrap handler not supported", 5412 Op.getDebugLoc(), 5413 DS_Warning); 5414 LLVMContext &Ctx = MF.getFunction().getContext(); 5415 Ctx.diagnose(NoTrap); 5416 return Chain; 5417 } 5418 5419 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5420 SDValue Ops[] = { 5421 Chain, 5422 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5423 }; 5424 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5425 } 5426 5427 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5428 SelectionDAG &DAG) const { 5429 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5430 if (Subtarget->hasApertureRegs()) { 5431 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5432 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5433 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5434 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5435 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5436 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5437 unsigned Encoding = 5438 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5439 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5440 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5441 5442 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5443 SDValue ApertureReg = SDValue( 5444 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5445 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5446 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5447 } 5448 5449 MachineFunction &MF = DAG.getMachineFunction(); 5450 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5451 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5452 if (UserSGPR == AMDGPU::NoRegister) { 5453 // We probably are in a function incorrectly marked with 5454 // amdgpu-no-queue-ptr. This is undefined. 5455 return DAG.getUNDEF(MVT::i32); 5456 } 5457 5458 SDValue QueuePtr = CreateLiveInRegister( 5459 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5460 5461 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5462 // private_segment_aperture_base_hi. 5463 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5464 5465 SDValue Ptr = 5466 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5467 5468 // TODO: Use custom target PseudoSourceValue. 5469 // TODO: We should use the value from the IR intrinsic call, but it might not 5470 // be available and how do we get it? 5471 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5472 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5473 commonAlignment(Align(64), StructOffset), 5474 MachineMemOperand::MODereferenceable | 5475 MachineMemOperand::MOInvariant); 5476 } 5477 5478 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5479 SelectionDAG &DAG) const { 5480 SDLoc SL(Op); 5481 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5482 5483 SDValue Src = ASC->getOperand(0); 5484 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5485 5486 const AMDGPUTargetMachine &TM = 5487 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5488 5489 // flat -> local/private 5490 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5491 unsigned DestAS = ASC->getDestAddressSpace(); 5492 5493 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5494 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5495 unsigned NullVal = TM.getNullPointerValue(DestAS); 5496 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5497 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5498 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5499 5500 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5501 NonNull, Ptr, SegmentNullPtr); 5502 } 5503 } 5504 5505 // local/private -> flat 5506 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5507 unsigned SrcAS = ASC->getSrcAddressSpace(); 5508 5509 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5510 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5511 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5512 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5513 5514 SDValue NonNull 5515 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5516 5517 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5518 SDValue CvtPtr 5519 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5520 5521 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5522 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5523 FlatNullPtr); 5524 } 5525 } 5526 5527 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5528 Src.getValueType() == MVT::i64) 5529 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5530 5531 // global <-> flat are no-ops and never emitted. 5532 5533 const MachineFunction &MF = DAG.getMachineFunction(); 5534 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5535 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5536 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5537 5538 return DAG.getUNDEF(ASC->getValueType(0)); 5539 } 5540 5541 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5542 // the small vector and inserting them into the big vector. That is better than 5543 // the default expansion of doing it via a stack slot. Even though the use of 5544 // the stack slot would be optimized away afterwards, the stack slot itself 5545 // remains. 5546 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5547 SelectionDAG &DAG) const { 5548 SDValue Vec = Op.getOperand(0); 5549 SDValue Ins = Op.getOperand(1); 5550 SDValue Idx = Op.getOperand(2); 5551 EVT VecVT = Vec.getValueType(); 5552 EVT InsVT = Ins.getValueType(); 5553 EVT EltVT = VecVT.getVectorElementType(); 5554 unsigned InsNumElts = InsVT.getVectorNumElements(); 5555 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5556 SDLoc SL(Op); 5557 5558 for (unsigned I = 0; I != InsNumElts; ++I) { 5559 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5560 DAG.getConstant(I, SL, MVT::i32)); 5561 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5562 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5563 } 5564 return Vec; 5565 } 5566 5567 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5568 SelectionDAG &DAG) const { 5569 SDValue Vec = Op.getOperand(0); 5570 SDValue InsVal = Op.getOperand(1); 5571 SDValue Idx = Op.getOperand(2); 5572 EVT VecVT = Vec.getValueType(); 5573 EVT EltVT = VecVT.getVectorElementType(); 5574 unsigned VecSize = VecVT.getSizeInBits(); 5575 unsigned EltSize = EltVT.getSizeInBits(); 5576 5577 5578 assert(VecSize <= 64); 5579 5580 unsigned NumElts = VecVT.getVectorNumElements(); 5581 SDLoc SL(Op); 5582 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5583 5584 if (NumElts == 4 && EltSize == 16 && KIdx) { 5585 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5586 5587 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5588 DAG.getConstant(0, SL, MVT::i32)); 5589 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5590 DAG.getConstant(1, SL, MVT::i32)); 5591 5592 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5593 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5594 5595 unsigned Idx = KIdx->getZExtValue(); 5596 bool InsertLo = Idx < 2; 5597 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5598 InsertLo ? LoVec : HiVec, 5599 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5600 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5601 5602 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5603 5604 SDValue Concat = InsertLo ? 5605 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5606 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5607 5608 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5609 } 5610 5611 if (isa<ConstantSDNode>(Idx)) 5612 return SDValue(); 5613 5614 MVT IntVT = MVT::getIntegerVT(VecSize); 5615 5616 // Avoid stack access for dynamic indexing. 5617 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5618 5619 // Create a congruent vector with the target value in each element so that 5620 // the required element can be masked and ORed into the target vector. 5621 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5622 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5623 5624 assert(isPowerOf2_32(EltSize)); 5625 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5626 5627 // Convert vector index to bit-index. 5628 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5629 5630 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5631 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5632 DAG.getConstant(0xffff, SL, IntVT), 5633 ScaledIdx); 5634 5635 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5636 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5637 DAG.getNOT(SL, BFM, IntVT), BCVec); 5638 5639 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5640 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5641 } 5642 5643 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5644 SelectionDAG &DAG) const { 5645 SDLoc SL(Op); 5646 5647 EVT ResultVT = Op.getValueType(); 5648 SDValue Vec = Op.getOperand(0); 5649 SDValue Idx = Op.getOperand(1); 5650 EVT VecVT = Vec.getValueType(); 5651 unsigned VecSize = VecVT.getSizeInBits(); 5652 EVT EltVT = VecVT.getVectorElementType(); 5653 assert(VecSize <= 64); 5654 5655 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5656 5657 // Make sure we do any optimizations that will make it easier to fold 5658 // source modifiers before obscuring it with bit operations. 5659 5660 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5661 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5662 return Combined; 5663 5664 unsigned EltSize = EltVT.getSizeInBits(); 5665 assert(isPowerOf2_32(EltSize)); 5666 5667 MVT IntVT = MVT::getIntegerVT(VecSize); 5668 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5669 5670 // Convert vector index to bit-index (* EltSize) 5671 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5672 5673 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5674 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5675 5676 if (ResultVT == MVT::f16) { 5677 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5678 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5679 } 5680 5681 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5682 } 5683 5684 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5685 assert(Elt % 2 == 0); 5686 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5687 } 5688 5689 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5690 SelectionDAG &DAG) const { 5691 SDLoc SL(Op); 5692 EVT ResultVT = Op.getValueType(); 5693 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5694 5695 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5696 EVT EltVT = PackVT.getVectorElementType(); 5697 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5698 5699 // vector_shuffle <0,1,6,7> lhs, rhs 5700 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5701 // 5702 // vector_shuffle <6,7,2,3> lhs, rhs 5703 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5704 // 5705 // vector_shuffle <6,7,0,1> lhs, rhs 5706 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5707 5708 // Avoid scalarizing when both halves are reading from consecutive elements. 5709 SmallVector<SDValue, 4> Pieces; 5710 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5711 if (elementPairIsContiguous(SVN->getMask(), I)) { 5712 const int Idx = SVN->getMaskElt(I); 5713 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5714 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5715 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5716 PackVT, SVN->getOperand(VecIdx), 5717 DAG.getConstant(EltIdx, SL, MVT::i32)); 5718 Pieces.push_back(SubVec); 5719 } else { 5720 const int Idx0 = SVN->getMaskElt(I); 5721 const int Idx1 = SVN->getMaskElt(I + 1); 5722 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5723 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5724 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5725 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5726 5727 SDValue Vec0 = SVN->getOperand(VecIdx0); 5728 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5729 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5730 5731 SDValue Vec1 = SVN->getOperand(VecIdx1); 5732 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5733 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5734 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5735 } 5736 } 5737 5738 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5739 } 5740 5741 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5742 SelectionDAG &DAG) const { 5743 SDLoc SL(Op); 5744 EVT VT = Op.getValueType(); 5745 5746 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5747 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5748 5749 // Turn into pair of packed build_vectors. 5750 // TODO: Special case for constants that can be materialized with s_mov_b64. 5751 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5752 { Op.getOperand(0), Op.getOperand(1) }); 5753 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5754 { Op.getOperand(2), Op.getOperand(3) }); 5755 5756 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5757 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5758 5759 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5760 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5761 } 5762 5763 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5764 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5765 5766 SDValue Lo = Op.getOperand(0); 5767 SDValue Hi = Op.getOperand(1); 5768 5769 // Avoid adding defined bits with the zero_extend. 5770 if (Hi.isUndef()) { 5771 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5772 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5773 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5774 } 5775 5776 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5777 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5778 5779 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5780 DAG.getConstant(16, SL, MVT::i32)); 5781 if (Lo.isUndef()) 5782 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5783 5784 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5785 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5786 5787 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5788 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5789 } 5790 5791 bool 5792 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5793 // We can fold offsets for anything that doesn't require a GOT relocation. 5794 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5795 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5796 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5797 !shouldEmitGOTReloc(GA->getGlobal()); 5798 } 5799 5800 static SDValue 5801 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5802 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5803 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5804 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5805 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5806 // lowered to the following code sequence: 5807 // 5808 // For constant address space: 5809 // s_getpc_b64 s[0:1] 5810 // s_add_u32 s0, s0, $symbol 5811 // s_addc_u32 s1, s1, 0 5812 // 5813 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5814 // a fixup or relocation is emitted to replace $symbol with a literal 5815 // constant, which is a pc-relative offset from the encoding of the $symbol 5816 // operand to the global variable. 5817 // 5818 // For global address space: 5819 // s_getpc_b64 s[0:1] 5820 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5821 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5822 // 5823 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5824 // fixups or relocations are emitted to replace $symbol@*@lo and 5825 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5826 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5827 // operand to the global variable. 5828 // 5829 // What we want here is an offset from the value returned by s_getpc 5830 // (which is the address of the s_add_u32 instruction) to the global 5831 // variable, but since the encoding of $symbol starts 4 bytes after the start 5832 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5833 // small. This requires us to add 4 to the global variable offset in order to 5834 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5835 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5836 // instruction. 5837 SDValue PtrLo = 5838 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5839 SDValue PtrHi; 5840 if (GAFlags == SIInstrInfo::MO_NONE) { 5841 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5842 } else { 5843 PtrHi = 5844 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5845 } 5846 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5847 } 5848 5849 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5850 SDValue Op, 5851 SelectionDAG &DAG) const { 5852 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5853 SDLoc DL(GSD); 5854 EVT PtrVT = Op.getValueType(); 5855 5856 const GlobalValue *GV = GSD->getGlobal(); 5857 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5858 shouldUseLDSConstAddress(GV)) || 5859 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5860 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5861 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5862 GV->hasExternalLinkage()) { 5863 Type *Ty = GV->getValueType(); 5864 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5865 // zero-sized type in other languages to declare the dynamic shared 5866 // memory which size is not known at the compile time. They will be 5867 // allocated by the runtime and placed directly after the static 5868 // allocated ones. They all share the same offset. 5869 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5870 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5871 // Adjust alignment for that dynamic shared memory array. 5872 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5873 return SDValue( 5874 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5875 } 5876 } 5877 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5878 } 5879 5880 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5881 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5882 SIInstrInfo::MO_ABS32_LO); 5883 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5884 } 5885 5886 if (shouldEmitFixup(GV)) 5887 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5888 else if (shouldEmitPCReloc(GV)) 5889 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5890 SIInstrInfo::MO_REL32); 5891 5892 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5893 SIInstrInfo::MO_GOTPCREL32); 5894 5895 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5896 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5897 const DataLayout &DataLayout = DAG.getDataLayout(); 5898 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5899 MachinePointerInfo PtrInfo 5900 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5901 5902 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5903 MachineMemOperand::MODereferenceable | 5904 MachineMemOperand::MOInvariant); 5905 } 5906 5907 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5908 const SDLoc &DL, SDValue V) const { 5909 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5910 // the destination register. 5911 // 5912 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5913 // so we will end up with redundant moves to m0. 5914 // 5915 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5916 5917 // A Null SDValue creates a glue result. 5918 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5919 V, Chain); 5920 return SDValue(M0, 0); 5921 } 5922 5923 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5924 SDValue Op, 5925 MVT VT, 5926 unsigned Offset) const { 5927 SDLoc SL(Op); 5928 SDValue Param = lowerKernargMemParameter( 5929 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5930 // The local size values will have the hi 16-bits as zero. 5931 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5932 DAG.getValueType(VT)); 5933 } 5934 5935 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5936 EVT VT) { 5937 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5938 "non-hsa intrinsic with hsa target", 5939 DL.getDebugLoc()); 5940 DAG.getContext()->diagnose(BadIntrin); 5941 return DAG.getUNDEF(VT); 5942 } 5943 5944 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5945 EVT VT) { 5946 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5947 "intrinsic not supported on subtarget", 5948 DL.getDebugLoc()); 5949 DAG.getContext()->diagnose(BadIntrin); 5950 return DAG.getUNDEF(VT); 5951 } 5952 5953 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5954 ArrayRef<SDValue> Elts) { 5955 assert(!Elts.empty()); 5956 MVT Type; 5957 unsigned NumElts = Elts.size(); 5958 5959 if (NumElts <= 8) { 5960 Type = MVT::getVectorVT(MVT::f32, NumElts); 5961 } else { 5962 assert(Elts.size() <= 16); 5963 Type = MVT::v16f32; 5964 NumElts = 16; 5965 } 5966 5967 SmallVector<SDValue, 16> VecElts(NumElts); 5968 for (unsigned i = 0; i < Elts.size(); ++i) { 5969 SDValue Elt = Elts[i]; 5970 if (Elt.getValueType() != MVT::f32) 5971 Elt = DAG.getBitcast(MVT::f32, Elt); 5972 VecElts[i] = Elt; 5973 } 5974 for (unsigned i = Elts.size(); i < NumElts; ++i) 5975 VecElts[i] = DAG.getUNDEF(MVT::f32); 5976 5977 if (NumElts == 1) 5978 return VecElts[0]; 5979 return DAG.getBuildVector(Type, DL, VecElts); 5980 } 5981 5982 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5983 SDValue Src, int ExtraElts) { 5984 EVT SrcVT = Src.getValueType(); 5985 5986 SmallVector<SDValue, 8> Elts; 5987 5988 if (SrcVT.isVector()) 5989 DAG.ExtractVectorElements(Src, Elts); 5990 else 5991 Elts.push_back(Src); 5992 5993 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5994 while (ExtraElts--) 5995 Elts.push_back(Undef); 5996 5997 return DAG.getBuildVector(CastVT, DL, Elts); 5998 } 5999 6000 // Re-construct the required return value for a image load intrinsic. 6001 // This is more complicated due to the optional use TexFailCtrl which means the required 6002 // return type is an aggregate 6003 static SDValue constructRetValue(SelectionDAG &DAG, 6004 MachineSDNode *Result, 6005 ArrayRef<EVT> ResultTypes, 6006 bool IsTexFail, bool Unpacked, bool IsD16, 6007 int DMaskPop, int NumVDataDwords, 6008 const SDLoc &DL) { 6009 // Determine the required return type. This is the same regardless of IsTexFail flag 6010 EVT ReqRetVT = ResultTypes[0]; 6011 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6012 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6013 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6014 6015 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6016 DMaskPop : (DMaskPop + 1) / 2; 6017 6018 MVT DataDwordVT = NumDataDwords == 1 ? 6019 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6020 6021 MVT MaskPopVT = MaskPopDwords == 1 ? 6022 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6023 6024 SDValue Data(Result, 0); 6025 SDValue TexFail; 6026 6027 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6028 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6029 if (MaskPopVT.isVector()) { 6030 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6031 SDValue(Result, 0), ZeroIdx); 6032 } else { 6033 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6034 SDValue(Result, 0), ZeroIdx); 6035 } 6036 } 6037 6038 if (DataDwordVT.isVector()) 6039 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6040 NumDataDwords - MaskPopDwords); 6041 6042 if (IsD16) 6043 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6044 6045 EVT LegalReqRetVT = ReqRetVT; 6046 if (!ReqRetVT.isVector()) { 6047 if (!Data.getValueType().isInteger()) 6048 Data = DAG.getNode(ISD::BITCAST, DL, 6049 Data.getValueType().changeTypeToInteger(), Data); 6050 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6051 } else { 6052 // We need to widen the return vector to a legal type 6053 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6054 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6055 LegalReqRetVT = 6056 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6057 ReqRetVT.getVectorNumElements() + 1); 6058 } 6059 } 6060 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6061 6062 if (IsTexFail) { 6063 TexFail = 6064 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6065 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6066 6067 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6068 } 6069 6070 if (Result->getNumValues() == 1) 6071 return Data; 6072 6073 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6074 } 6075 6076 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6077 SDValue *LWE, bool &IsTexFail) { 6078 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6079 6080 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6081 if (Value) { 6082 IsTexFail = true; 6083 } 6084 6085 SDLoc DL(TexFailCtrlConst); 6086 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6087 Value &= ~(uint64_t)0x1; 6088 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6089 Value &= ~(uint64_t)0x2; 6090 6091 return Value == 0; 6092 } 6093 6094 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6095 MVT PackVectorVT, 6096 SmallVectorImpl<SDValue> &PackedAddrs, 6097 unsigned DimIdx, unsigned EndIdx, 6098 unsigned NumGradients) { 6099 SDLoc DL(Op); 6100 for (unsigned I = DimIdx; I < EndIdx; I++) { 6101 SDValue Addr = Op.getOperand(I); 6102 6103 // Gradients are packed with undef for each coordinate. 6104 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6105 // 1D: undef,dx/dh; undef,dx/dv 6106 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6107 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6108 if (((I + 1) >= EndIdx) || 6109 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6110 I == DimIdx + NumGradients - 1))) { 6111 if (Addr.getValueType() != MVT::i16) 6112 Addr = DAG.getBitcast(MVT::i16, Addr); 6113 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6114 } else { 6115 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6116 I++; 6117 } 6118 Addr = DAG.getBitcast(MVT::f32, Addr); 6119 PackedAddrs.push_back(Addr); 6120 } 6121 } 6122 6123 SDValue SITargetLowering::lowerImage(SDValue Op, 6124 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6125 SelectionDAG &DAG, bool WithChain) const { 6126 SDLoc DL(Op); 6127 MachineFunction &MF = DAG.getMachineFunction(); 6128 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6129 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6130 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6131 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6132 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6133 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6134 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6135 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6136 unsigned IntrOpcode = Intr->BaseOpcode; 6137 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6138 6139 SmallVector<EVT, 3> ResultTypes(Op->values()); 6140 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6141 bool IsD16 = false; 6142 bool IsG16 = false; 6143 bool IsA16 = false; 6144 SDValue VData; 6145 int NumVDataDwords; 6146 bool AdjustRetType = false; 6147 6148 // Offset of intrinsic arguments 6149 const unsigned ArgOffset = WithChain ? 2 : 1; 6150 6151 unsigned DMask; 6152 unsigned DMaskLanes = 0; 6153 6154 if (BaseOpcode->Atomic) { 6155 VData = Op.getOperand(2); 6156 6157 bool Is64Bit = VData.getValueType() == MVT::i64; 6158 if (BaseOpcode->AtomicX2) { 6159 SDValue VData2 = Op.getOperand(3); 6160 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6161 {VData, VData2}); 6162 if (Is64Bit) 6163 VData = DAG.getBitcast(MVT::v4i32, VData); 6164 6165 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6166 DMask = Is64Bit ? 0xf : 0x3; 6167 NumVDataDwords = Is64Bit ? 4 : 2; 6168 } else { 6169 DMask = Is64Bit ? 0x3 : 0x1; 6170 NumVDataDwords = Is64Bit ? 2 : 1; 6171 } 6172 } else { 6173 auto *DMaskConst = 6174 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6175 DMask = DMaskConst->getZExtValue(); 6176 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6177 6178 if (BaseOpcode->Store) { 6179 VData = Op.getOperand(2); 6180 6181 MVT StoreVT = VData.getSimpleValueType(); 6182 if (StoreVT.getScalarType() == MVT::f16) { 6183 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6184 return Op; // D16 is unsupported for this instruction 6185 6186 IsD16 = true; 6187 VData = handleD16VData(VData, DAG, true); 6188 } 6189 6190 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6191 } else { 6192 // Work out the num dwords based on the dmask popcount and underlying type 6193 // and whether packing is supported. 6194 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6195 if (LoadVT.getScalarType() == MVT::f16) { 6196 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6197 return Op; // D16 is unsupported for this instruction 6198 6199 IsD16 = true; 6200 } 6201 6202 // Confirm that the return type is large enough for the dmask specified 6203 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6204 (!LoadVT.isVector() && DMaskLanes > 1)) 6205 return Op; 6206 6207 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6208 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6209 // instructions. 6210 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6211 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6212 NumVDataDwords = (DMaskLanes + 1) / 2; 6213 else 6214 NumVDataDwords = DMaskLanes; 6215 6216 AdjustRetType = true; 6217 } 6218 } 6219 6220 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6221 SmallVector<SDValue, 4> VAddrs; 6222 6223 // Optimize _L to _LZ when _L is zero 6224 if (LZMappingInfo) { 6225 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6226 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6227 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6228 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6229 VAddrEnd--; // remove 'lod' 6230 } 6231 } 6232 } 6233 6234 // Optimize _mip away, when 'lod' is zero 6235 if (MIPMappingInfo) { 6236 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6237 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6238 if (ConstantLod->isZero()) { 6239 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6240 VAddrEnd--; // remove 'mip' 6241 } 6242 } 6243 } 6244 6245 // Push back extra arguments. 6246 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6247 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6248 6249 // Check for 16 bit addresses or derivatives and pack if true. 6250 MVT VAddrVT = 6251 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6252 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6253 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6254 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6255 6256 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6257 VAddrScalarVT = VAddrVT.getScalarType(); 6258 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6259 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6260 6261 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6262 // 16 bit gradients are supported, but are tied to the A16 control 6263 // so both gradients and addresses must be 16 bit 6264 LLVM_DEBUG( 6265 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6266 "require 16 bit args for both gradients and addresses"); 6267 return Op; 6268 } 6269 6270 if (IsA16) { 6271 if (!ST->hasA16()) { 6272 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6273 "support 16 bit addresses\n"); 6274 return Op; 6275 } 6276 } 6277 6278 // We've dealt with incorrect input so we know that if IsA16, IsG16 6279 // are set then we have to compress/pack operands (either address, 6280 // gradient or both) 6281 // In the case where a16 and gradients are tied (no G16 support) then we 6282 // have already verified that both IsA16 and IsG16 are true 6283 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6284 // Activate g16 6285 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6286 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6287 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6288 } 6289 6290 // Add gradients (packed or unpacked) 6291 if (IsG16) { 6292 // Pack the gradients 6293 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6294 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6295 ArgOffset + Intr->GradientStart, 6296 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6297 } else { 6298 for (unsigned I = ArgOffset + Intr->GradientStart; 6299 I < ArgOffset + Intr->CoordStart; I++) 6300 VAddrs.push_back(Op.getOperand(I)); 6301 } 6302 6303 // Add addresses (packed or unpacked) 6304 if (IsA16) { 6305 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6306 ArgOffset + Intr->CoordStart, VAddrEnd, 6307 0 /* No gradients */); 6308 } else { 6309 // Add uncompressed address 6310 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6311 VAddrs.push_back(Op.getOperand(I)); 6312 } 6313 6314 // If the register allocator cannot place the address registers contiguously 6315 // without introducing moves, then using the non-sequential address encoding 6316 // is always preferable, since it saves VALU instructions and is usually a 6317 // wash in terms of code size or even better. 6318 // 6319 // However, we currently have no way of hinting to the register allocator that 6320 // MIMG addresses should be placed contiguously when it is possible to do so, 6321 // so force non-NSA for the common 2-address case as a heuristic. 6322 // 6323 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6324 // allocation when possible. 6325 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6326 VAddrs.size() >= 3 && 6327 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6328 SDValue VAddr; 6329 if (!UseNSA) 6330 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6331 6332 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6333 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6334 SDValue Unorm; 6335 if (!BaseOpcode->Sampler) { 6336 Unorm = True; 6337 } else { 6338 auto UnormConst = 6339 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6340 6341 Unorm = UnormConst->getZExtValue() ? True : False; 6342 } 6343 6344 SDValue TFE; 6345 SDValue LWE; 6346 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6347 bool IsTexFail = false; 6348 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6349 return Op; 6350 6351 if (IsTexFail) { 6352 if (!DMaskLanes) { 6353 // Expecting to get an error flag since TFC is on - and dmask is 0 6354 // Force dmask to be at least 1 otherwise the instruction will fail 6355 DMask = 0x1; 6356 DMaskLanes = 1; 6357 NumVDataDwords = 1; 6358 } 6359 NumVDataDwords += 1; 6360 AdjustRetType = true; 6361 } 6362 6363 // Has something earlier tagged that the return type needs adjusting 6364 // This happens if the instruction is a load or has set TexFailCtrl flags 6365 if (AdjustRetType) { 6366 // NumVDataDwords reflects the true number of dwords required in the return type 6367 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6368 // This is a no-op load. This can be eliminated 6369 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6370 if (isa<MemSDNode>(Op)) 6371 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6372 return Undef; 6373 } 6374 6375 EVT NewVT = NumVDataDwords > 1 ? 6376 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6377 : MVT::i32; 6378 6379 ResultTypes[0] = NewVT; 6380 if (ResultTypes.size() == 3) { 6381 // Original result was aggregate type used for TexFailCtrl results 6382 // The actual instruction returns as a vector type which has now been 6383 // created. Remove the aggregate result. 6384 ResultTypes.erase(&ResultTypes[1]); 6385 } 6386 } 6387 6388 unsigned CPol = cast<ConstantSDNode>( 6389 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6390 if (BaseOpcode->Atomic) 6391 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6392 if (CPol & ~AMDGPU::CPol::ALL) 6393 return Op; 6394 6395 SmallVector<SDValue, 26> Ops; 6396 if (BaseOpcode->Store || BaseOpcode->Atomic) 6397 Ops.push_back(VData); // vdata 6398 if (UseNSA) 6399 append_range(Ops, VAddrs); 6400 else 6401 Ops.push_back(VAddr); 6402 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6403 if (BaseOpcode->Sampler) 6404 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6405 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6406 if (IsGFX10Plus) 6407 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6408 Ops.push_back(Unorm); 6409 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6410 Ops.push_back(IsA16 && // r128, a16 for gfx9 6411 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6412 if (IsGFX10Plus) 6413 Ops.push_back(IsA16 ? True : False); 6414 if (!Subtarget->hasGFX90AInsts()) { 6415 Ops.push_back(TFE); //tfe 6416 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6417 report_fatal_error("TFE is not supported on this GPU"); 6418 } 6419 Ops.push_back(LWE); // lwe 6420 if (!IsGFX10Plus) 6421 Ops.push_back(DimInfo->DA ? True : False); 6422 if (BaseOpcode->HasD16) 6423 Ops.push_back(IsD16 ? True : False); 6424 if (isa<MemSDNode>(Op)) 6425 Ops.push_back(Op.getOperand(0)); // chain 6426 6427 int NumVAddrDwords = 6428 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6429 int Opcode = -1; 6430 6431 if (IsGFX10Plus) { 6432 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6433 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6434 : AMDGPU::MIMGEncGfx10Default, 6435 NumVDataDwords, NumVAddrDwords); 6436 } else { 6437 if (Subtarget->hasGFX90AInsts()) { 6438 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6439 NumVDataDwords, NumVAddrDwords); 6440 if (Opcode == -1) 6441 report_fatal_error( 6442 "requested image instruction is not supported on this GPU"); 6443 } 6444 if (Opcode == -1 && 6445 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6446 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6447 NumVDataDwords, NumVAddrDwords); 6448 if (Opcode == -1) 6449 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6450 NumVDataDwords, NumVAddrDwords); 6451 } 6452 assert(Opcode != -1); 6453 6454 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6455 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6456 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6457 DAG.setNodeMemRefs(NewNode, {MemRef}); 6458 } 6459 6460 if (BaseOpcode->AtomicX2) { 6461 SmallVector<SDValue, 1> Elt; 6462 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6463 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6464 } 6465 if (BaseOpcode->Store) 6466 return SDValue(NewNode, 0); 6467 return constructRetValue(DAG, NewNode, 6468 OrigResultTypes, IsTexFail, 6469 Subtarget->hasUnpackedD16VMem(), IsD16, 6470 DMaskLanes, NumVDataDwords, DL); 6471 } 6472 6473 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6474 SDValue Offset, SDValue CachePolicy, 6475 SelectionDAG &DAG) const { 6476 MachineFunction &MF = DAG.getMachineFunction(); 6477 6478 const DataLayout &DataLayout = DAG.getDataLayout(); 6479 Align Alignment = 6480 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6481 6482 MachineMemOperand *MMO = MF.getMachineMemOperand( 6483 MachinePointerInfo(), 6484 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6485 MachineMemOperand::MOInvariant, 6486 VT.getStoreSize(), Alignment); 6487 6488 if (!Offset->isDivergent()) { 6489 SDValue Ops[] = { 6490 Rsrc, 6491 Offset, // Offset 6492 CachePolicy 6493 }; 6494 6495 // Widen vec3 load to vec4. 6496 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6497 EVT WidenedVT = 6498 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6499 auto WidenedOp = DAG.getMemIntrinsicNode( 6500 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6501 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6502 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6503 DAG.getVectorIdxConstant(0, DL)); 6504 return Subvector; 6505 } 6506 6507 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6508 DAG.getVTList(VT), Ops, VT, MMO); 6509 } 6510 6511 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6512 // assume that the buffer is unswizzled. 6513 SmallVector<SDValue, 4> Loads; 6514 unsigned NumLoads = 1; 6515 MVT LoadVT = VT.getSimpleVT(); 6516 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6517 assert((LoadVT.getScalarType() == MVT::i32 || 6518 LoadVT.getScalarType() == MVT::f32)); 6519 6520 if (NumElts == 8 || NumElts == 16) { 6521 NumLoads = NumElts / 4; 6522 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6523 } 6524 6525 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6526 SDValue Ops[] = { 6527 DAG.getEntryNode(), // Chain 6528 Rsrc, // rsrc 6529 DAG.getConstant(0, DL, MVT::i32), // vindex 6530 {}, // voffset 6531 {}, // soffset 6532 {}, // offset 6533 CachePolicy, // cachepolicy 6534 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6535 }; 6536 6537 // Use the alignment to ensure that the required offsets will fit into the 6538 // immediate offsets. 6539 setBufferOffsets(Offset, DAG, &Ops[3], 6540 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6541 6542 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6543 for (unsigned i = 0; i < NumLoads; ++i) { 6544 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6545 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6546 LoadVT, MMO, DAG)); 6547 } 6548 6549 if (NumElts == 8 || NumElts == 16) 6550 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6551 6552 return Loads[0]; 6553 } 6554 6555 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6556 SelectionDAG &DAG) const { 6557 MachineFunction &MF = DAG.getMachineFunction(); 6558 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6559 6560 EVT VT = Op.getValueType(); 6561 SDLoc DL(Op); 6562 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6563 6564 // TODO: Should this propagate fast-math-flags? 6565 6566 switch (IntrinsicID) { 6567 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6568 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6569 return emitNonHSAIntrinsicError(DAG, DL, VT); 6570 return getPreloadedValue(DAG, *MFI, VT, 6571 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6572 } 6573 case Intrinsic::amdgcn_dispatch_ptr: 6574 case Intrinsic::amdgcn_queue_ptr: { 6575 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6576 DiagnosticInfoUnsupported BadIntrin( 6577 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6578 DL.getDebugLoc()); 6579 DAG.getContext()->diagnose(BadIntrin); 6580 return DAG.getUNDEF(VT); 6581 } 6582 6583 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6584 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6585 return getPreloadedValue(DAG, *MFI, VT, RegID); 6586 } 6587 case Intrinsic::amdgcn_implicitarg_ptr: { 6588 if (MFI->isEntryFunction()) 6589 return getImplicitArgPtr(DAG, DL); 6590 return getPreloadedValue(DAG, *MFI, VT, 6591 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6592 } 6593 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6594 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6595 // This only makes sense to call in a kernel, so just lower to null. 6596 return DAG.getConstant(0, DL, VT); 6597 } 6598 6599 return getPreloadedValue(DAG, *MFI, VT, 6600 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6601 } 6602 case Intrinsic::amdgcn_dispatch_id: { 6603 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6604 } 6605 case Intrinsic::amdgcn_rcp: 6606 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6607 case Intrinsic::amdgcn_rsq: 6608 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6609 case Intrinsic::amdgcn_rsq_legacy: 6610 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6611 return emitRemovedIntrinsicError(DAG, DL, VT); 6612 return SDValue(); 6613 case Intrinsic::amdgcn_rcp_legacy: 6614 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6615 return emitRemovedIntrinsicError(DAG, DL, VT); 6616 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6617 case Intrinsic::amdgcn_rsq_clamp: { 6618 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6619 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6620 6621 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6622 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6623 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6624 6625 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6626 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6627 DAG.getConstantFP(Max, DL, VT)); 6628 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6629 DAG.getConstantFP(Min, DL, VT)); 6630 } 6631 case Intrinsic::r600_read_ngroups_x: 6632 if (Subtarget->isAmdHsaOS()) 6633 return emitNonHSAIntrinsicError(DAG, DL, VT); 6634 6635 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6636 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6637 false); 6638 case Intrinsic::r600_read_ngroups_y: 6639 if (Subtarget->isAmdHsaOS()) 6640 return emitNonHSAIntrinsicError(DAG, DL, VT); 6641 6642 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6643 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6644 false); 6645 case Intrinsic::r600_read_ngroups_z: 6646 if (Subtarget->isAmdHsaOS()) 6647 return emitNonHSAIntrinsicError(DAG, DL, VT); 6648 6649 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6650 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6651 false); 6652 case Intrinsic::r600_read_global_size_x: 6653 if (Subtarget->isAmdHsaOS()) 6654 return emitNonHSAIntrinsicError(DAG, DL, VT); 6655 6656 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6657 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6658 Align(4), false); 6659 case Intrinsic::r600_read_global_size_y: 6660 if (Subtarget->isAmdHsaOS()) 6661 return emitNonHSAIntrinsicError(DAG, DL, VT); 6662 6663 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6664 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6665 Align(4), false); 6666 case Intrinsic::r600_read_global_size_z: 6667 if (Subtarget->isAmdHsaOS()) 6668 return emitNonHSAIntrinsicError(DAG, DL, VT); 6669 6670 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6671 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6672 Align(4), false); 6673 case Intrinsic::r600_read_local_size_x: 6674 if (Subtarget->isAmdHsaOS()) 6675 return emitNonHSAIntrinsicError(DAG, DL, VT); 6676 6677 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6678 SI::KernelInputOffsets::LOCAL_SIZE_X); 6679 case Intrinsic::r600_read_local_size_y: 6680 if (Subtarget->isAmdHsaOS()) 6681 return emitNonHSAIntrinsicError(DAG, DL, VT); 6682 6683 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6684 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6685 case Intrinsic::r600_read_local_size_z: 6686 if (Subtarget->isAmdHsaOS()) 6687 return emitNonHSAIntrinsicError(DAG, DL, VT); 6688 6689 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6690 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6691 case Intrinsic::amdgcn_workgroup_id_x: 6692 return getPreloadedValue(DAG, *MFI, VT, 6693 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6694 case Intrinsic::amdgcn_workgroup_id_y: 6695 return getPreloadedValue(DAG, *MFI, VT, 6696 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6697 case Intrinsic::amdgcn_workgroup_id_z: 6698 return getPreloadedValue(DAG, *MFI, VT, 6699 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6700 case Intrinsic::amdgcn_workitem_id_x: 6701 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6702 SDLoc(DAG.getEntryNode()), 6703 MFI->getArgInfo().WorkItemIDX); 6704 case Intrinsic::amdgcn_workitem_id_y: 6705 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6706 SDLoc(DAG.getEntryNode()), 6707 MFI->getArgInfo().WorkItemIDY); 6708 case Intrinsic::amdgcn_workitem_id_z: 6709 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6710 SDLoc(DAG.getEntryNode()), 6711 MFI->getArgInfo().WorkItemIDZ); 6712 case Intrinsic::amdgcn_wavefrontsize: 6713 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6714 SDLoc(Op), MVT::i32); 6715 case Intrinsic::amdgcn_s_buffer_load: { 6716 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6717 if (CPol & ~AMDGPU::CPol::ALL) 6718 return Op; 6719 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6720 DAG); 6721 } 6722 case Intrinsic::amdgcn_fdiv_fast: 6723 return lowerFDIV_FAST(Op, DAG); 6724 case Intrinsic::amdgcn_sin: 6725 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6726 6727 case Intrinsic::amdgcn_cos: 6728 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6729 6730 case Intrinsic::amdgcn_mul_u24: 6731 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6732 case Intrinsic::amdgcn_mul_i24: 6733 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6734 6735 case Intrinsic::amdgcn_log_clamp: { 6736 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6737 return SDValue(); 6738 6739 return emitRemovedIntrinsicError(DAG, DL, VT); 6740 } 6741 case Intrinsic::amdgcn_ldexp: 6742 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6743 Op.getOperand(1), Op.getOperand(2)); 6744 6745 case Intrinsic::amdgcn_fract: 6746 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6747 6748 case Intrinsic::amdgcn_class: 6749 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6750 Op.getOperand(1), Op.getOperand(2)); 6751 case Intrinsic::amdgcn_div_fmas: 6752 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6753 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6754 Op.getOperand(4)); 6755 6756 case Intrinsic::amdgcn_div_fixup: 6757 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6758 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6759 6760 case Intrinsic::amdgcn_div_scale: { 6761 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6762 6763 // Translate to the operands expected by the machine instruction. The 6764 // first parameter must be the same as the first instruction. 6765 SDValue Numerator = Op.getOperand(1); 6766 SDValue Denominator = Op.getOperand(2); 6767 6768 // Note this order is opposite of the machine instruction's operations, 6769 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6770 // intrinsic has the numerator as the first operand to match a normal 6771 // division operation. 6772 6773 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6774 6775 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6776 Denominator, Numerator); 6777 } 6778 case Intrinsic::amdgcn_icmp: { 6779 // There is a Pat that handles this variant, so return it as-is. 6780 if (Op.getOperand(1).getValueType() == MVT::i1 && 6781 Op.getConstantOperandVal(2) == 0 && 6782 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6783 return Op; 6784 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6785 } 6786 case Intrinsic::amdgcn_fcmp: { 6787 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6788 } 6789 case Intrinsic::amdgcn_ballot: 6790 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6791 case Intrinsic::amdgcn_fmed3: 6792 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6793 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6794 case Intrinsic::amdgcn_fdot2: 6795 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6796 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6797 Op.getOperand(4)); 6798 case Intrinsic::amdgcn_fmul_legacy: 6799 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6800 Op.getOperand(1), Op.getOperand(2)); 6801 case Intrinsic::amdgcn_sffbh: 6802 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6803 case Intrinsic::amdgcn_sbfe: 6804 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6805 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6806 case Intrinsic::amdgcn_ubfe: 6807 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6808 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6809 case Intrinsic::amdgcn_cvt_pkrtz: 6810 case Intrinsic::amdgcn_cvt_pknorm_i16: 6811 case Intrinsic::amdgcn_cvt_pknorm_u16: 6812 case Intrinsic::amdgcn_cvt_pk_i16: 6813 case Intrinsic::amdgcn_cvt_pk_u16: { 6814 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6815 EVT VT = Op.getValueType(); 6816 unsigned Opcode; 6817 6818 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6819 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6820 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6821 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6822 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6823 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6824 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6825 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6826 else 6827 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6828 6829 if (isTypeLegal(VT)) 6830 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6831 6832 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6833 Op.getOperand(1), Op.getOperand(2)); 6834 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6835 } 6836 case Intrinsic::amdgcn_fmad_ftz: 6837 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6838 Op.getOperand(2), Op.getOperand(3)); 6839 6840 case Intrinsic::amdgcn_if_break: 6841 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6842 Op->getOperand(1), Op->getOperand(2)), 0); 6843 6844 case Intrinsic::amdgcn_groupstaticsize: { 6845 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6846 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6847 return Op; 6848 6849 const Module *M = MF.getFunction().getParent(); 6850 const GlobalValue *GV = 6851 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6852 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6853 SIInstrInfo::MO_ABS32_LO); 6854 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6855 } 6856 case Intrinsic::amdgcn_is_shared: 6857 case Intrinsic::amdgcn_is_private: { 6858 SDLoc SL(Op); 6859 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6860 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6861 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6862 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6863 Op.getOperand(1)); 6864 6865 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6866 DAG.getConstant(1, SL, MVT::i32)); 6867 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6868 } 6869 case Intrinsic::amdgcn_alignbit: 6870 return DAG.getNode(ISD::FSHR, DL, VT, 6871 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6872 case Intrinsic::amdgcn_perm: 6873 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6874 Op.getOperand(2), Op.getOperand(3)); 6875 case Intrinsic::amdgcn_reloc_constant: { 6876 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6877 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6878 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6879 auto RelocSymbol = cast<GlobalVariable>( 6880 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6881 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6882 SIInstrInfo::MO_ABS32_LO); 6883 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6884 } 6885 default: 6886 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6887 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6888 return lowerImage(Op, ImageDimIntr, DAG, false); 6889 6890 return Op; 6891 } 6892 } 6893 6894 /// Update \p MMO based on the offset inputs to an intrinsic. 6895 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6896 SDValue SOffset, SDValue Offset, 6897 SDValue VIndex = SDValue()) { 6898 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6899 !isa<ConstantSDNode>(Offset)) { 6900 // The combined offset is not known to be constant, so we cannot represent 6901 // it in the MMO. Give up. 6902 MMO->setValue((Value *)nullptr); 6903 return; 6904 } 6905 6906 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6907 !cast<ConstantSDNode>(VIndex)->isZero())) { 6908 // The strided index component of the address is not known to be zero, so we 6909 // cannot represent it in the MMO. Give up. 6910 MMO->setValue((Value *)nullptr); 6911 return; 6912 } 6913 6914 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6915 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6916 cast<ConstantSDNode>(Offset)->getSExtValue()); 6917 } 6918 6919 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6920 SelectionDAG &DAG, 6921 unsigned NewOpcode) const { 6922 SDLoc DL(Op); 6923 6924 SDValue VData = Op.getOperand(2); 6925 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6926 SDValue Ops[] = { 6927 Op.getOperand(0), // Chain 6928 VData, // vdata 6929 Op.getOperand(3), // rsrc 6930 DAG.getConstant(0, DL, MVT::i32), // vindex 6931 Offsets.first, // voffset 6932 Op.getOperand(5), // soffset 6933 Offsets.second, // offset 6934 Op.getOperand(6), // cachepolicy 6935 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6936 }; 6937 6938 auto *M = cast<MemSDNode>(Op); 6939 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 6940 6941 EVT MemVT = VData.getValueType(); 6942 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6943 M->getMemOperand()); 6944 } 6945 6946 // Return a value to use for the idxen operand by examining the vindex operand. 6947 static unsigned getIdxEn(SDValue VIndex) { 6948 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 6949 // No need to set idxen if vindex is known to be zero. 6950 return VIndexC->getZExtValue() != 0; 6951 return 1; 6952 } 6953 6954 SDValue 6955 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6956 unsigned NewOpcode) const { 6957 SDLoc DL(Op); 6958 6959 SDValue VData = Op.getOperand(2); 6960 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6961 SDValue Ops[] = { 6962 Op.getOperand(0), // Chain 6963 VData, // vdata 6964 Op.getOperand(3), // rsrc 6965 Op.getOperand(4), // vindex 6966 Offsets.first, // voffset 6967 Op.getOperand(6), // soffset 6968 Offsets.second, // offset 6969 Op.getOperand(7), // cachepolicy 6970 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6971 }; 6972 6973 auto *M = cast<MemSDNode>(Op); 6974 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 6975 6976 EVT MemVT = VData.getValueType(); 6977 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6978 M->getMemOperand()); 6979 } 6980 6981 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6982 SelectionDAG &DAG) const { 6983 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6984 SDLoc DL(Op); 6985 6986 switch (IntrID) { 6987 case Intrinsic::amdgcn_ds_ordered_add: 6988 case Intrinsic::amdgcn_ds_ordered_swap: { 6989 MemSDNode *M = cast<MemSDNode>(Op); 6990 SDValue Chain = M->getOperand(0); 6991 SDValue M0 = M->getOperand(2); 6992 SDValue Value = M->getOperand(3); 6993 unsigned IndexOperand = M->getConstantOperandVal(7); 6994 unsigned WaveRelease = M->getConstantOperandVal(8); 6995 unsigned WaveDone = M->getConstantOperandVal(9); 6996 6997 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6998 IndexOperand &= ~0x3f; 6999 unsigned CountDw = 0; 7000 7001 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7002 CountDw = (IndexOperand >> 24) & 0xf; 7003 IndexOperand &= ~(0xf << 24); 7004 7005 if (CountDw < 1 || CountDw > 4) { 7006 report_fatal_error( 7007 "ds_ordered_count: dword count must be between 1 and 4"); 7008 } 7009 } 7010 7011 if (IndexOperand) 7012 report_fatal_error("ds_ordered_count: bad index operand"); 7013 7014 if (WaveDone && !WaveRelease) 7015 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7016 7017 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7018 unsigned ShaderType = 7019 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7020 unsigned Offset0 = OrderedCountIndex << 2; 7021 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7022 (Instruction << 4); 7023 7024 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7025 Offset1 |= (CountDw - 1) << 6; 7026 7027 unsigned Offset = Offset0 | (Offset1 << 8); 7028 7029 SDValue Ops[] = { 7030 Chain, 7031 Value, 7032 DAG.getTargetConstant(Offset, DL, MVT::i16), 7033 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7034 }; 7035 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7036 M->getVTList(), Ops, M->getMemoryVT(), 7037 M->getMemOperand()); 7038 } 7039 case Intrinsic::amdgcn_ds_fadd: { 7040 MemSDNode *M = cast<MemSDNode>(Op); 7041 unsigned Opc; 7042 switch (IntrID) { 7043 case Intrinsic::amdgcn_ds_fadd: 7044 Opc = ISD::ATOMIC_LOAD_FADD; 7045 break; 7046 } 7047 7048 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7049 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7050 M->getMemOperand()); 7051 } 7052 case Intrinsic::amdgcn_atomic_inc: 7053 case Intrinsic::amdgcn_atomic_dec: 7054 case Intrinsic::amdgcn_ds_fmin: 7055 case Intrinsic::amdgcn_ds_fmax: { 7056 MemSDNode *M = cast<MemSDNode>(Op); 7057 unsigned Opc; 7058 switch (IntrID) { 7059 case Intrinsic::amdgcn_atomic_inc: 7060 Opc = AMDGPUISD::ATOMIC_INC; 7061 break; 7062 case Intrinsic::amdgcn_atomic_dec: 7063 Opc = AMDGPUISD::ATOMIC_DEC; 7064 break; 7065 case Intrinsic::amdgcn_ds_fmin: 7066 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7067 break; 7068 case Intrinsic::amdgcn_ds_fmax: 7069 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7070 break; 7071 default: 7072 llvm_unreachable("Unknown intrinsic!"); 7073 } 7074 SDValue Ops[] = { 7075 M->getOperand(0), // Chain 7076 M->getOperand(2), // Ptr 7077 M->getOperand(3) // Value 7078 }; 7079 7080 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7081 M->getMemoryVT(), M->getMemOperand()); 7082 } 7083 case Intrinsic::amdgcn_buffer_load: 7084 case Intrinsic::amdgcn_buffer_load_format: { 7085 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7086 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7087 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7088 SDValue Ops[] = { 7089 Op.getOperand(0), // Chain 7090 Op.getOperand(2), // rsrc 7091 Op.getOperand(3), // vindex 7092 SDValue(), // voffset -- will be set by setBufferOffsets 7093 SDValue(), // soffset -- will be set by setBufferOffsets 7094 SDValue(), // offset -- will be set by setBufferOffsets 7095 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7096 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7097 }; 7098 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7099 7100 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7101 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7102 7103 EVT VT = Op.getValueType(); 7104 EVT IntVT = VT.changeTypeToInteger(); 7105 auto *M = cast<MemSDNode>(Op); 7106 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7107 EVT LoadVT = Op.getValueType(); 7108 7109 if (LoadVT.getScalarType() == MVT::f16) 7110 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7111 M, DAG, Ops); 7112 7113 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7114 if (LoadVT.getScalarType() == MVT::i8 || 7115 LoadVT.getScalarType() == MVT::i16) 7116 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7117 7118 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7119 M->getMemOperand(), DAG); 7120 } 7121 case Intrinsic::amdgcn_raw_buffer_load: 7122 case Intrinsic::amdgcn_raw_buffer_load_format: { 7123 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7124 7125 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7126 SDValue Ops[] = { 7127 Op.getOperand(0), // Chain 7128 Op.getOperand(2), // rsrc 7129 DAG.getConstant(0, DL, MVT::i32), // vindex 7130 Offsets.first, // voffset 7131 Op.getOperand(4), // soffset 7132 Offsets.second, // offset 7133 Op.getOperand(5), // cachepolicy, swizzled buffer 7134 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7135 }; 7136 7137 auto *M = cast<MemSDNode>(Op); 7138 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7139 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7140 } 7141 case Intrinsic::amdgcn_struct_buffer_load: 7142 case Intrinsic::amdgcn_struct_buffer_load_format: { 7143 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7144 7145 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7146 SDValue Ops[] = { 7147 Op.getOperand(0), // Chain 7148 Op.getOperand(2), // rsrc 7149 Op.getOperand(3), // vindex 7150 Offsets.first, // voffset 7151 Op.getOperand(5), // soffset 7152 Offsets.second, // offset 7153 Op.getOperand(6), // cachepolicy, swizzled buffer 7154 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7155 }; 7156 7157 auto *M = cast<MemSDNode>(Op); 7158 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7159 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7160 } 7161 case Intrinsic::amdgcn_tbuffer_load: { 7162 MemSDNode *M = cast<MemSDNode>(Op); 7163 EVT LoadVT = Op.getValueType(); 7164 7165 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7166 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7167 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7168 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7169 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7170 SDValue Ops[] = { 7171 Op.getOperand(0), // Chain 7172 Op.getOperand(2), // rsrc 7173 Op.getOperand(3), // vindex 7174 Op.getOperand(4), // voffset 7175 Op.getOperand(5), // soffset 7176 Op.getOperand(6), // offset 7177 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7178 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7179 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7180 }; 7181 7182 if (LoadVT.getScalarType() == MVT::f16) 7183 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7184 M, DAG, Ops); 7185 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7186 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7187 DAG); 7188 } 7189 case Intrinsic::amdgcn_raw_tbuffer_load: { 7190 MemSDNode *M = cast<MemSDNode>(Op); 7191 EVT LoadVT = Op.getValueType(); 7192 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7193 7194 SDValue Ops[] = { 7195 Op.getOperand(0), // Chain 7196 Op.getOperand(2), // rsrc 7197 DAG.getConstant(0, DL, MVT::i32), // vindex 7198 Offsets.first, // voffset 7199 Op.getOperand(4), // soffset 7200 Offsets.second, // offset 7201 Op.getOperand(5), // format 7202 Op.getOperand(6), // cachepolicy, swizzled buffer 7203 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7204 }; 7205 7206 if (LoadVT.getScalarType() == MVT::f16) 7207 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7208 M, DAG, Ops); 7209 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7210 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7211 DAG); 7212 } 7213 case Intrinsic::amdgcn_struct_tbuffer_load: { 7214 MemSDNode *M = cast<MemSDNode>(Op); 7215 EVT LoadVT = Op.getValueType(); 7216 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7217 7218 SDValue Ops[] = { 7219 Op.getOperand(0), // Chain 7220 Op.getOperand(2), // rsrc 7221 Op.getOperand(3), // vindex 7222 Offsets.first, // voffset 7223 Op.getOperand(5), // soffset 7224 Offsets.second, // offset 7225 Op.getOperand(6), // format 7226 Op.getOperand(7), // cachepolicy, swizzled buffer 7227 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7228 }; 7229 7230 if (LoadVT.getScalarType() == MVT::f16) 7231 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7232 M, DAG, Ops); 7233 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7234 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7235 DAG); 7236 } 7237 case Intrinsic::amdgcn_buffer_atomic_swap: 7238 case Intrinsic::amdgcn_buffer_atomic_add: 7239 case Intrinsic::amdgcn_buffer_atomic_sub: 7240 case Intrinsic::amdgcn_buffer_atomic_csub: 7241 case Intrinsic::amdgcn_buffer_atomic_smin: 7242 case Intrinsic::amdgcn_buffer_atomic_umin: 7243 case Intrinsic::amdgcn_buffer_atomic_smax: 7244 case Intrinsic::amdgcn_buffer_atomic_umax: 7245 case Intrinsic::amdgcn_buffer_atomic_and: 7246 case Intrinsic::amdgcn_buffer_atomic_or: 7247 case Intrinsic::amdgcn_buffer_atomic_xor: 7248 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7249 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7250 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7251 SDValue Ops[] = { 7252 Op.getOperand(0), // Chain 7253 Op.getOperand(2), // vdata 7254 Op.getOperand(3), // rsrc 7255 Op.getOperand(4), // vindex 7256 SDValue(), // voffset -- will be set by setBufferOffsets 7257 SDValue(), // soffset -- will be set by setBufferOffsets 7258 SDValue(), // offset -- will be set by setBufferOffsets 7259 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7260 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7261 }; 7262 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7263 7264 EVT VT = Op.getValueType(); 7265 7266 auto *M = cast<MemSDNode>(Op); 7267 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7268 unsigned Opcode = 0; 7269 7270 switch (IntrID) { 7271 case Intrinsic::amdgcn_buffer_atomic_swap: 7272 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7273 break; 7274 case Intrinsic::amdgcn_buffer_atomic_add: 7275 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7276 break; 7277 case Intrinsic::amdgcn_buffer_atomic_sub: 7278 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7279 break; 7280 case Intrinsic::amdgcn_buffer_atomic_csub: 7281 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7282 break; 7283 case Intrinsic::amdgcn_buffer_atomic_smin: 7284 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7285 break; 7286 case Intrinsic::amdgcn_buffer_atomic_umin: 7287 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7288 break; 7289 case Intrinsic::amdgcn_buffer_atomic_smax: 7290 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7291 break; 7292 case Intrinsic::amdgcn_buffer_atomic_umax: 7293 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7294 break; 7295 case Intrinsic::amdgcn_buffer_atomic_and: 7296 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7297 break; 7298 case Intrinsic::amdgcn_buffer_atomic_or: 7299 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7300 break; 7301 case Intrinsic::amdgcn_buffer_atomic_xor: 7302 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7303 break; 7304 case Intrinsic::amdgcn_buffer_atomic_fadd: 7305 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7306 DiagnosticInfoUnsupported 7307 NoFpRet(DAG.getMachineFunction().getFunction(), 7308 "return versions of fp atomics not supported", 7309 DL.getDebugLoc(), DS_Error); 7310 DAG.getContext()->diagnose(NoFpRet); 7311 return SDValue(); 7312 } 7313 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7314 break; 7315 default: 7316 llvm_unreachable("unhandled atomic opcode"); 7317 } 7318 7319 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7320 M->getMemOperand()); 7321 } 7322 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7323 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7324 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7325 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7326 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7327 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7328 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7329 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7330 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7331 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7332 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7333 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7334 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7335 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7336 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7337 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7338 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7339 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7340 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7341 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7342 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7343 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7344 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7345 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7346 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7347 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7348 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7349 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7350 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7351 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7352 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7353 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7354 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7355 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7356 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7357 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7358 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7359 return lowerStructBufferAtomicIntrin(Op, DAG, 7360 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7361 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7362 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7363 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7364 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7365 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7366 return lowerStructBufferAtomicIntrin(Op, DAG, 7367 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7368 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7369 return lowerStructBufferAtomicIntrin(Op, DAG, 7370 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7371 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7372 return lowerStructBufferAtomicIntrin(Op, DAG, 7373 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7374 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7375 return lowerStructBufferAtomicIntrin(Op, DAG, 7376 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7377 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7378 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7379 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7380 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7381 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7382 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7383 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7384 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7385 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7386 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7387 7388 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7389 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7390 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7391 SDValue Ops[] = { 7392 Op.getOperand(0), // Chain 7393 Op.getOperand(2), // src 7394 Op.getOperand(3), // cmp 7395 Op.getOperand(4), // rsrc 7396 Op.getOperand(5), // vindex 7397 SDValue(), // voffset -- will be set by setBufferOffsets 7398 SDValue(), // soffset -- will be set by setBufferOffsets 7399 SDValue(), // offset -- will be set by setBufferOffsets 7400 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7401 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7402 }; 7403 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7404 7405 EVT VT = Op.getValueType(); 7406 auto *M = cast<MemSDNode>(Op); 7407 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7408 7409 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7410 Op->getVTList(), Ops, VT, M->getMemOperand()); 7411 } 7412 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7413 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7414 SDValue Ops[] = { 7415 Op.getOperand(0), // Chain 7416 Op.getOperand(2), // src 7417 Op.getOperand(3), // cmp 7418 Op.getOperand(4), // rsrc 7419 DAG.getConstant(0, DL, MVT::i32), // vindex 7420 Offsets.first, // voffset 7421 Op.getOperand(6), // soffset 7422 Offsets.second, // offset 7423 Op.getOperand(7), // cachepolicy 7424 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7425 }; 7426 EVT VT = Op.getValueType(); 7427 auto *M = cast<MemSDNode>(Op); 7428 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7429 7430 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7431 Op->getVTList(), Ops, VT, M->getMemOperand()); 7432 } 7433 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7434 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7435 SDValue Ops[] = { 7436 Op.getOperand(0), // Chain 7437 Op.getOperand(2), // src 7438 Op.getOperand(3), // cmp 7439 Op.getOperand(4), // rsrc 7440 Op.getOperand(5), // vindex 7441 Offsets.first, // voffset 7442 Op.getOperand(7), // soffset 7443 Offsets.second, // offset 7444 Op.getOperand(8), // cachepolicy 7445 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7446 }; 7447 EVT VT = Op.getValueType(); 7448 auto *M = cast<MemSDNode>(Op); 7449 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7450 7451 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7452 Op->getVTList(), Ops, VT, M->getMemOperand()); 7453 } 7454 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7455 MemSDNode *M = cast<MemSDNode>(Op); 7456 SDValue NodePtr = M->getOperand(2); 7457 SDValue RayExtent = M->getOperand(3); 7458 SDValue RayOrigin = M->getOperand(4); 7459 SDValue RayDir = M->getOperand(5); 7460 SDValue RayInvDir = M->getOperand(6); 7461 SDValue TDescr = M->getOperand(7); 7462 7463 assert(NodePtr.getValueType() == MVT::i32 || 7464 NodePtr.getValueType() == MVT::i64); 7465 assert(RayDir.getValueType() == MVT::v4f16 || 7466 RayDir.getValueType() == MVT::v4f32); 7467 7468 if (!Subtarget->hasGFX10_AEncoding()) { 7469 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7470 return SDValue(); 7471 } 7472 7473 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7474 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7475 const unsigned NumVDataDwords = 4; 7476 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7477 const bool UseNSA = Subtarget->hasNSAEncoding() && 7478 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7479 const unsigned BaseOpcodes[2][2] = { 7480 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7481 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7482 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7483 int Opcode; 7484 if (UseNSA) { 7485 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7486 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7487 NumVAddrDwords); 7488 } else { 7489 Opcode = AMDGPU::getMIMGOpcode( 7490 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7491 PowerOf2Ceil(NumVAddrDwords)); 7492 } 7493 assert(Opcode != -1); 7494 7495 SmallVector<SDValue, 16> Ops; 7496 7497 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7498 SmallVector<SDValue, 3> Lanes; 7499 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7500 if (Lanes[0].getValueSizeInBits() == 32) { 7501 for (unsigned I = 0; I < 3; ++I) 7502 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7503 } else { 7504 if (IsAligned) { 7505 Ops.push_back( 7506 DAG.getBitcast(MVT::i32, 7507 DAG.getBuildVector(MVT::v2f16, DL, 7508 { Lanes[0], Lanes[1] }))); 7509 Ops.push_back(Lanes[2]); 7510 } else { 7511 SDValue Elt0 = Ops.pop_back_val(); 7512 Ops.push_back( 7513 DAG.getBitcast(MVT::i32, 7514 DAG.getBuildVector(MVT::v2f16, DL, 7515 { Elt0, Lanes[0] }))); 7516 Ops.push_back( 7517 DAG.getBitcast(MVT::i32, 7518 DAG.getBuildVector(MVT::v2f16, DL, 7519 { Lanes[1], Lanes[2] }))); 7520 } 7521 } 7522 }; 7523 7524 if (Is64) 7525 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7526 else 7527 Ops.push_back(NodePtr); 7528 7529 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7530 packLanes(RayOrigin, true); 7531 packLanes(RayDir, true); 7532 packLanes(RayInvDir, false); 7533 7534 if (!UseNSA) { 7535 // Build a single vector containing all the operands so far prepared. 7536 if (NumVAddrDwords > 8) { 7537 SDValue Undef = DAG.getUNDEF(MVT::i32); 7538 Ops.append(16 - Ops.size(), Undef); 7539 } 7540 assert(Ops.size() == 8 || Ops.size() == 16); 7541 SDValue MergedOps = DAG.getBuildVector( 7542 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7543 Ops.clear(); 7544 Ops.push_back(MergedOps); 7545 } 7546 7547 Ops.push_back(TDescr); 7548 if (IsA16) 7549 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7550 Ops.push_back(M->getChain()); 7551 7552 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7553 MachineMemOperand *MemRef = M->getMemOperand(); 7554 DAG.setNodeMemRefs(NewNode, {MemRef}); 7555 return SDValue(NewNode, 0); 7556 } 7557 case Intrinsic::amdgcn_global_atomic_fadd: 7558 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7559 DiagnosticInfoUnsupported 7560 NoFpRet(DAG.getMachineFunction().getFunction(), 7561 "return versions of fp atomics not supported", 7562 DL.getDebugLoc(), DS_Error); 7563 DAG.getContext()->diagnose(NoFpRet); 7564 return SDValue(); 7565 } 7566 LLVM_FALLTHROUGH; 7567 case Intrinsic::amdgcn_global_atomic_fmin: 7568 case Intrinsic::amdgcn_global_atomic_fmax: 7569 case Intrinsic::amdgcn_flat_atomic_fadd: 7570 case Intrinsic::amdgcn_flat_atomic_fmin: 7571 case Intrinsic::amdgcn_flat_atomic_fmax: { 7572 MemSDNode *M = cast<MemSDNode>(Op); 7573 SDValue Ops[] = { 7574 M->getOperand(0), // Chain 7575 M->getOperand(2), // Ptr 7576 M->getOperand(3) // Value 7577 }; 7578 unsigned Opcode = 0; 7579 switch (IntrID) { 7580 case Intrinsic::amdgcn_global_atomic_fadd: 7581 case Intrinsic::amdgcn_flat_atomic_fadd: { 7582 EVT VT = Op.getOperand(3).getValueType(); 7583 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7584 DAG.getVTList(VT, MVT::Other), Ops, 7585 M->getMemOperand()); 7586 } 7587 case Intrinsic::amdgcn_global_atomic_fmin: 7588 case Intrinsic::amdgcn_flat_atomic_fmin: { 7589 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7590 break; 7591 } 7592 case Intrinsic::amdgcn_global_atomic_fmax: 7593 case Intrinsic::amdgcn_flat_atomic_fmax: { 7594 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7595 break; 7596 } 7597 default: 7598 llvm_unreachable("unhandled atomic opcode"); 7599 } 7600 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7601 M->getVTList(), Ops, M->getMemoryVT(), 7602 M->getMemOperand()); 7603 } 7604 default: 7605 7606 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7607 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7608 return lowerImage(Op, ImageDimIntr, DAG, true); 7609 7610 return SDValue(); 7611 } 7612 } 7613 7614 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7615 // dwordx4 if on SI. 7616 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7617 SDVTList VTList, 7618 ArrayRef<SDValue> Ops, EVT MemVT, 7619 MachineMemOperand *MMO, 7620 SelectionDAG &DAG) const { 7621 EVT VT = VTList.VTs[0]; 7622 EVT WidenedVT = VT; 7623 EVT WidenedMemVT = MemVT; 7624 if (!Subtarget->hasDwordx3LoadStores() && 7625 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7626 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7627 WidenedVT.getVectorElementType(), 4); 7628 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7629 WidenedMemVT.getVectorElementType(), 4); 7630 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7631 } 7632 7633 assert(VTList.NumVTs == 2); 7634 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7635 7636 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7637 WidenedMemVT, MMO); 7638 if (WidenedVT != VT) { 7639 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7640 DAG.getVectorIdxConstant(0, DL)); 7641 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7642 } 7643 return NewOp; 7644 } 7645 7646 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7647 bool ImageStore) const { 7648 EVT StoreVT = VData.getValueType(); 7649 7650 // No change for f16 and legal vector D16 types. 7651 if (!StoreVT.isVector()) 7652 return VData; 7653 7654 SDLoc DL(VData); 7655 unsigned NumElements = StoreVT.getVectorNumElements(); 7656 7657 if (Subtarget->hasUnpackedD16VMem()) { 7658 // We need to unpack the packed data to store. 7659 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7660 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7661 7662 EVT EquivStoreVT = 7663 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7664 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7665 return DAG.UnrollVectorOp(ZExt.getNode()); 7666 } 7667 7668 // The sq block of gfx8.1 does not estimate register use correctly for d16 7669 // image store instructions. The data operand is computed as if it were not a 7670 // d16 image instruction. 7671 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7672 // Bitcast to i16 7673 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7674 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7675 7676 // Decompose into scalars 7677 SmallVector<SDValue, 4> Elts; 7678 DAG.ExtractVectorElements(IntVData, Elts); 7679 7680 // Group pairs of i16 into v2i16 and bitcast to i32 7681 SmallVector<SDValue, 4> PackedElts; 7682 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7683 SDValue Pair = 7684 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7685 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7686 PackedElts.push_back(IntPair); 7687 } 7688 if ((NumElements % 2) == 1) { 7689 // Handle v3i16 7690 unsigned I = Elts.size() / 2; 7691 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7692 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7693 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7694 PackedElts.push_back(IntPair); 7695 } 7696 7697 // Pad using UNDEF 7698 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7699 7700 // Build final vector 7701 EVT VecVT = 7702 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7703 return DAG.getBuildVector(VecVT, DL, PackedElts); 7704 } 7705 7706 if (NumElements == 3) { 7707 EVT IntStoreVT = 7708 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7709 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7710 7711 EVT WidenedStoreVT = EVT::getVectorVT( 7712 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7713 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7714 WidenedStoreVT.getStoreSizeInBits()); 7715 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7716 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7717 } 7718 7719 assert(isTypeLegal(StoreVT)); 7720 return VData; 7721 } 7722 7723 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7724 SelectionDAG &DAG) const { 7725 SDLoc DL(Op); 7726 SDValue Chain = Op.getOperand(0); 7727 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7728 MachineFunction &MF = DAG.getMachineFunction(); 7729 7730 switch (IntrinsicID) { 7731 case Intrinsic::amdgcn_exp_compr: { 7732 SDValue Src0 = Op.getOperand(4); 7733 SDValue Src1 = Op.getOperand(5); 7734 // Hack around illegal type on SI by directly selecting it. 7735 if (isTypeLegal(Src0.getValueType())) 7736 return SDValue(); 7737 7738 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7739 SDValue Undef = DAG.getUNDEF(MVT::f32); 7740 const SDValue Ops[] = { 7741 Op.getOperand(2), // tgt 7742 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7743 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7744 Undef, // src2 7745 Undef, // src3 7746 Op.getOperand(7), // vm 7747 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7748 Op.getOperand(3), // en 7749 Op.getOperand(0) // Chain 7750 }; 7751 7752 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7753 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7754 } 7755 case Intrinsic::amdgcn_s_barrier: { 7756 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7757 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7758 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7759 if (WGSize <= ST.getWavefrontSize()) 7760 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7761 Op.getOperand(0)), 0); 7762 } 7763 return SDValue(); 7764 }; 7765 case Intrinsic::amdgcn_tbuffer_store: { 7766 SDValue VData = Op.getOperand(2); 7767 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7768 if (IsD16) 7769 VData = handleD16VData(VData, DAG); 7770 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7771 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7772 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7773 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7774 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7775 SDValue Ops[] = { 7776 Chain, 7777 VData, // vdata 7778 Op.getOperand(3), // rsrc 7779 Op.getOperand(4), // vindex 7780 Op.getOperand(5), // voffset 7781 Op.getOperand(6), // soffset 7782 Op.getOperand(7), // offset 7783 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7784 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7785 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7786 }; 7787 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7788 AMDGPUISD::TBUFFER_STORE_FORMAT; 7789 MemSDNode *M = cast<MemSDNode>(Op); 7790 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7791 M->getMemoryVT(), M->getMemOperand()); 7792 } 7793 7794 case Intrinsic::amdgcn_struct_tbuffer_store: { 7795 SDValue VData = Op.getOperand(2); 7796 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7797 if (IsD16) 7798 VData = handleD16VData(VData, DAG); 7799 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7800 SDValue Ops[] = { 7801 Chain, 7802 VData, // vdata 7803 Op.getOperand(3), // rsrc 7804 Op.getOperand(4), // vindex 7805 Offsets.first, // voffset 7806 Op.getOperand(6), // soffset 7807 Offsets.second, // offset 7808 Op.getOperand(7), // format 7809 Op.getOperand(8), // cachepolicy, swizzled buffer 7810 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7811 }; 7812 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7813 AMDGPUISD::TBUFFER_STORE_FORMAT; 7814 MemSDNode *M = cast<MemSDNode>(Op); 7815 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7816 M->getMemoryVT(), M->getMemOperand()); 7817 } 7818 7819 case Intrinsic::amdgcn_raw_tbuffer_store: { 7820 SDValue VData = Op.getOperand(2); 7821 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7822 if (IsD16) 7823 VData = handleD16VData(VData, DAG); 7824 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7825 SDValue Ops[] = { 7826 Chain, 7827 VData, // vdata 7828 Op.getOperand(3), // rsrc 7829 DAG.getConstant(0, DL, MVT::i32), // vindex 7830 Offsets.first, // voffset 7831 Op.getOperand(5), // soffset 7832 Offsets.second, // offset 7833 Op.getOperand(6), // format 7834 Op.getOperand(7), // cachepolicy, swizzled buffer 7835 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7836 }; 7837 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7838 AMDGPUISD::TBUFFER_STORE_FORMAT; 7839 MemSDNode *M = cast<MemSDNode>(Op); 7840 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7841 M->getMemoryVT(), M->getMemOperand()); 7842 } 7843 7844 case Intrinsic::amdgcn_buffer_store: 7845 case Intrinsic::amdgcn_buffer_store_format: { 7846 SDValue VData = Op.getOperand(2); 7847 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7848 if (IsD16) 7849 VData = handleD16VData(VData, DAG); 7850 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7851 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7852 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7853 SDValue Ops[] = { 7854 Chain, 7855 VData, 7856 Op.getOperand(3), // rsrc 7857 Op.getOperand(4), // vindex 7858 SDValue(), // voffset -- will be set by setBufferOffsets 7859 SDValue(), // soffset -- will be set by setBufferOffsets 7860 SDValue(), // offset -- will be set by setBufferOffsets 7861 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7862 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7863 }; 7864 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7865 7866 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7867 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7868 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7869 MemSDNode *M = cast<MemSDNode>(Op); 7870 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7871 7872 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7873 EVT VDataType = VData.getValueType().getScalarType(); 7874 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7875 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7876 7877 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7878 M->getMemoryVT(), M->getMemOperand()); 7879 } 7880 7881 case Intrinsic::amdgcn_raw_buffer_store: 7882 case Intrinsic::amdgcn_raw_buffer_store_format: { 7883 const bool IsFormat = 7884 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7885 7886 SDValue VData = Op.getOperand(2); 7887 EVT VDataVT = VData.getValueType(); 7888 EVT EltType = VDataVT.getScalarType(); 7889 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7890 if (IsD16) { 7891 VData = handleD16VData(VData, DAG); 7892 VDataVT = VData.getValueType(); 7893 } 7894 7895 if (!isTypeLegal(VDataVT)) { 7896 VData = 7897 DAG.getNode(ISD::BITCAST, DL, 7898 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7899 } 7900 7901 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7902 SDValue Ops[] = { 7903 Chain, 7904 VData, 7905 Op.getOperand(3), // rsrc 7906 DAG.getConstant(0, DL, MVT::i32), // vindex 7907 Offsets.first, // voffset 7908 Op.getOperand(5), // soffset 7909 Offsets.second, // offset 7910 Op.getOperand(6), // cachepolicy, swizzled buffer 7911 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7912 }; 7913 unsigned Opc = 7914 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7915 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7916 MemSDNode *M = cast<MemSDNode>(Op); 7917 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7918 7919 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7920 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7921 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7922 7923 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7924 M->getMemoryVT(), M->getMemOperand()); 7925 } 7926 7927 case Intrinsic::amdgcn_struct_buffer_store: 7928 case Intrinsic::amdgcn_struct_buffer_store_format: { 7929 const bool IsFormat = 7930 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7931 7932 SDValue VData = Op.getOperand(2); 7933 EVT VDataVT = VData.getValueType(); 7934 EVT EltType = VDataVT.getScalarType(); 7935 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7936 7937 if (IsD16) { 7938 VData = handleD16VData(VData, DAG); 7939 VDataVT = VData.getValueType(); 7940 } 7941 7942 if (!isTypeLegal(VDataVT)) { 7943 VData = 7944 DAG.getNode(ISD::BITCAST, DL, 7945 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7946 } 7947 7948 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7949 SDValue Ops[] = { 7950 Chain, 7951 VData, 7952 Op.getOperand(3), // rsrc 7953 Op.getOperand(4), // vindex 7954 Offsets.first, // voffset 7955 Op.getOperand(6), // soffset 7956 Offsets.second, // offset 7957 Op.getOperand(7), // cachepolicy, swizzled buffer 7958 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7959 }; 7960 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7961 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7962 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7963 MemSDNode *M = cast<MemSDNode>(Op); 7964 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7965 7966 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7967 EVT VDataType = VData.getValueType().getScalarType(); 7968 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7969 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7970 7971 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7972 M->getMemoryVT(), M->getMemOperand()); 7973 } 7974 case Intrinsic::amdgcn_end_cf: 7975 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7976 Op->getOperand(2), Chain), 0); 7977 7978 default: { 7979 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7980 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7981 return lowerImage(Op, ImageDimIntr, DAG, true); 7982 7983 return Op; 7984 } 7985 } 7986 } 7987 7988 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7989 // offset (the offset that is included in bounds checking and swizzling, to be 7990 // split between the instruction's voffset and immoffset fields) and soffset 7991 // (the offset that is excluded from bounds checking and swizzling, to go in 7992 // the instruction's soffset field). This function takes the first kind of 7993 // offset and figures out how to split it between voffset and immoffset. 7994 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7995 SDValue Offset, SelectionDAG &DAG) const { 7996 SDLoc DL(Offset); 7997 const unsigned MaxImm = 4095; 7998 SDValue N0 = Offset; 7999 ConstantSDNode *C1 = nullptr; 8000 8001 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8002 N0 = SDValue(); 8003 else if (DAG.isBaseWithConstantOffset(N0)) { 8004 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8005 N0 = N0.getOperand(0); 8006 } 8007 8008 if (C1) { 8009 unsigned ImmOffset = C1->getZExtValue(); 8010 // If the immediate value is too big for the immoffset field, put the value 8011 // and -4096 into the immoffset field so that the value that is copied/added 8012 // for the voffset field is a multiple of 4096, and it stands more chance 8013 // of being CSEd with the copy/add for another similar load/store. 8014 // However, do not do that rounding down to a multiple of 4096 if that is a 8015 // negative number, as it appears to be illegal to have a negative offset 8016 // in the vgpr, even if adding the immediate offset makes it positive. 8017 unsigned Overflow = ImmOffset & ~MaxImm; 8018 ImmOffset -= Overflow; 8019 if ((int32_t)Overflow < 0) { 8020 Overflow += ImmOffset; 8021 ImmOffset = 0; 8022 } 8023 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8024 if (Overflow) { 8025 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8026 if (!N0) 8027 N0 = OverflowVal; 8028 else { 8029 SDValue Ops[] = { N0, OverflowVal }; 8030 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8031 } 8032 } 8033 } 8034 if (!N0) 8035 N0 = DAG.getConstant(0, DL, MVT::i32); 8036 if (!C1) 8037 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8038 return {N0, SDValue(C1, 0)}; 8039 } 8040 8041 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8042 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8043 // pointed to by Offsets. 8044 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8045 SelectionDAG &DAG, SDValue *Offsets, 8046 Align Alignment) const { 8047 SDLoc DL(CombinedOffset); 8048 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8049 uint32_t Imm = C->getZExtValue(); 8050 uint32_t SOffset, ImmOffset; 8051 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8052 Alignment)) { 8053 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8054 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8055 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8056 return; 8057 } 8058 } 8059 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8060 SDValue N0 = CombinedOffset.getOperand(0); 8061 SDValue N1 = CombinedOffset.getOperand(1); 8062 uint32_t SOffset, ImmOffset; 8063 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8064 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8065 Subtarget, Alignment)) { 8066 Offsets[0] = N0; 8067 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8068 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8069 return; 8070 } 8071 } 8072 Offsets[0] = CombinedOffset; 8073 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8074 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8075 } 8076 8077 // Handle 8 bit and 16 bit buffer loads 8078 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8079 EVT LoadVT, SDLoc DL, 8080 ArrayRef<SDValue> Ops, 8081 MemSDNode *M) const { 8082 EVT IntVT = LoadVT.changeTypeToInteger(); 8083 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8084 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8085 8086 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8087 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8088 Ops, IntVT, 8089 M->getMemOperand()); 8090 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8091 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8092 8093 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8094 } 8095 8096 // Handle 8 bit and 16 bit buffer stores 8097 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8098 EVT VDataType, SDLoc DL, 8099 SDValue Ops[], 8100 MemSDNode *M) const { 8101 if (VDataType == MVT::f16) 8102 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8103 8104 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8105 Ops[1] = BufferStoreExt; 8106 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8107 AMDGPUISD::BUFFER_STORE_SHORT; 8108 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8109 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8110 M->getMemOperand()); 8111 } 8112 8113 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8114 ISD::LoadExtType ExtType, SDValue Op, 8115 const SDLoc &SL, EVT VT) { 8116 if (VT.bitsLT(Op.getValueType())) 8117 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8118 8119 switch (ExtType) { 8120 case ISD::SEXTLOAD: 8121 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8122 case ISD::ZEXTLOAD: 8123 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8124 case ISD::EXTLOAD: 8125 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8126 case ISD::NON_EXTLOAD: 8127 return Op; 8128 } 8129 8130 llvm_unreachable("invalid ext type"); 8131 } 8132 8133 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8134 SelectionDAG &DAG = DCI.DAG; 8135 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8136 return SDValue(); 8137 8138 // FIXME: Constant loads should all be marked invariant. 8139 unsigned AS = Ld->getAddressSpace(); 8140 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8141 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8142 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8143 return SDValue(); 8144 8145 // Don't do this early, since it may interfere with adjacent load merging for 8146 // illegal types. We can avoid losing alignment information for exotic types 8147 // pre-legalize. 8148 EVT MemVT = Ld->getMemoryVT(); 8149 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8150 MemVT.getSizeInBits() >= 32) 8151 return SDValue(); 8152 8153 SDLoc SL(Ld); 8154 8155 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8156 "unexpected vector extload"); 8157 8158 // TODO: Drop only high part of range. 8159 SDValue Ptr = Ld->getBasePtr(); 8160 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8161 MVT::i32, SL, Ld->getChain(), Ptr, 8162 Ld->getOffset(), 8163 Ld->getPointerInfo(), MVT::i32, 8164 Ld->getAlignment(), 8165 Ld->getMemOperand()->getFlags(), 8166 Ld->getAAInfo(), 8167 nullptr); // Drop ranges 8168 8169 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8170 if (MemVT.isFloatingPoint()) { 8171 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8172 "unexpected fp extload"); 8173 TruncVT = MemVT.changeTypeToInteger(); 8174 } 8175 8176 SDValue Cvt = NewLoad; 8177 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8178 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8179 DAG.getValueType(TruncVT)); 8180 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8181 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8182 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8183 } else { 8184 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8185 } 8186 8187 EVT VT = Ld->getValueType(0); 8188 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8189 8190 DCI.AddToWorklist(Cvt.getNode()); 8191 8192 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8193 // the appropriate extension from the 32-bit load. 8194 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8195 DCI.AddToWorklist(Cvt.getNode()); 8196 8197 // Handle conversion back to floating point if necessary. 8198 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8199 8200 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8201 } 8202 8203 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8204 SDLoc DL(Op); 8205 LoadSDNode *Load = cast<LoadSDNode>(Op); 8206 ISD::LoadExtType ExtType = Load->getExtensionType(); 8207 EVT MemVT = Load->getMemoryVT(); 8208 8209 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8210 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8211 return SDValue(); 8212 8213 // FIXME: Copied from PPC 8214 // First, load into 32 bits, then truncate to 1 bit. 8215 8216 SDValue Chain = Load->getChain(); 8217 SDValue BasePtr = Load->getBasePtr(); 8218 MachineMemOperand *MMO = Load->getMemOperand(); 8219 8220 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8221 8222 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8223 BasePtr, RealMemVT, MMO); 8224 8225 if (!MemVT.isVector()) { 8226 SDValue Ops[] = { 8227 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8228 NewLD.getValue(1) 8229 }; 8230 8231 return DAG.getMergeValues(Ops, DL); 8232 } 8233 8234 SmallVector<SDValue, 3> Elts; 8235 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8236 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8237 DAG.getConstant(I, DL, MVT::i32)); 8238 8239 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8240 } 8241 8242 SDValue Ops[] = { 8243 DAG.getBuildVector(MemVT, DL, Elts), 8244 NewLD.getValue(1) 8245 }; 8246 8247 return DAG.getMergeValues(Ops, DL); 8248 } 8249 8250 if (!MemVT.isVector()) 8251 return SDValue(); 8252 8253 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8254 "Custom lowering for non-i32 vectors hasn't been implemented."); 8255 8256 unsigned Alignment = Load->getAlignment(); 8257 unsigned AS = Load->getAddressSpace(); 8258 if (Subtarget->hasLDSMisalignedBug() && 8259 AS == AMDGPUAS::FLAT_ADDRESS && 8260 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8261 return SplitVectorLoad(Op, DAG); 8262 } 8263 8264 MachineFunction &MF = DAG.getMachineFunction(); 8265 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8266 // If there is a possibilty that flat instruction access scratch memory 8267 // then we need to use the same legalization rules we use for private. 8268 if (AS == AMDGPUAS::FLAT_ADDRESS && 8269 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8270 AS = MFI->hasFlatScratchInit() ? 8271 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8272 8273 unsigned NumElements = MemVT.getVectorNumElements(); 8274 8275 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8276 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8277 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8278 if (MemVT.isPow2VectorType()) 8279 return SDValue(); 8280 return WidenOrSplitVectorLoad(Op, DAG); 8281 } 8282 // Non-uniform loads will be selected to MUBUF instructions, so they 8283 // have the same legalization requirements as global and private 8284 // loads. 8285 // 8286 } 8287 8288 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8289 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8290 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8291 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8292 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8293 Alignment >= 4 && NumElements < 32) { 8294 if (MemVT.isPow2VectorType()) 8295 return SDValue(); 8296 return WidenOrSplitVectorLoad(Op, DAG); 8297 } 8298 // Non-uniform loads will be selected to MUBUF instructions, so they 8299 // have the same legalization requirements as global and private 8300 // loads. 8301 // 8302 } 8303 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8304 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8305 AS == AMDGPUAS::GLOBAL_ADDRESS || 8306 AS == AMDGPUAS::FLAT_ADDRESS) { 8307 if (NumElements > 4) 8308 return SplitVectorLoad(Op, DAG); 8309 // v3 loads not supported on SI. 8310 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8311 return WidenOrSplitVectorLoad(Op, DAG); 8312 8313 // v3 and v4 loads are supported for private and global memory. 8314 return SDValue(); 8315 } 8316 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8317 // Depending on the setting of the private_element_size field in the 8318 // resource descriptor, we can only make private accesses up to a certain 8319 // size. 8320 switch (Subtarget->getMaxPrivateElementSize()) { 8321 case 4: { 8322 SDValue Ops[2]; 8323 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8324 return DAG.getMergeValues(Ops, DL); 8325 } 8326 case 8: 8327 if (NumElements > 2) 8328 return SplitVectorLoad(Op, DAG); 8329 return SDValue(); 8330 case 16: 8331 // Same as global/flat 8332 if (NumElements > 4) 8333 return SplitVectorLoad(Op, DAG); 8334 // v3 loads not supported on SI. 8335 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8336 return WidenOrSplitVectorLoad(Op, DAG); 8337 8338 return SDValue(); 8339 default: 8340 llvm_unreachable("unsupported private_element_size"); 8341 } 8342 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8343 // Use ds_read_b128 or ds_read_b96 when possible. 8344 if (Subtarget->hasDS96AndDS128() && 8345 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8346 MemVT.getStoreSize() == 12) && 8347 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8348 Load->getAlign())) 8349 return SDValue(); 8350 8351 if (NumElements > 2) 8352 return SplitVectorLoad(Op, DAG); 8353 8354 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8355 // address is negative, then the instruction is incorrectly treated as 8356 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8357 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8358 // load later in the SILoadStoreOptimizer. 8359 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8360 NumElements == 2 && MemVT.getStoreSize() == 8 && 8361 Load->getAlignment() < 8) { 8362 return SplitVectorLoad(Op, DAG); 8363 } 8364 } 8365 8366 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8367 MemVT, *Load->getMemOperand())) { 8368 SDValue Ops[2]; 8369 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8370 return DAG.getMergeValues(Ops, DL); 8371 } 8372 8373 return SDValue(); 8374 } 8375 8376 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8377 EVT VT = Op.getValueType(); 8378 assert(VT.getSizeInBits() == 64); 8379 8380 SDLoc DL(Op); 8381 SDValue Cond = Op.getOperand(0); 8382 8383 if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() && 8384 !Op->isDivergent()) { 8385 if (VT == MVT::i64) 8386 return Op; 8387 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1)); 8388 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2)); 8389 return DAG.getNode(ISD::BITCAST, DL, VT, 8390 DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS)); 8391 } 8392 8393 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8394 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8395 8396 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8397 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8398 8399 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8400 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8401 8402 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8403 8404 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8405 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8406 8407 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8408 8409 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8410 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8411 } 8412 8413 // Catch division cases where we can use shortcuts with rcp and rsq 8414 // instructions. 8415 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8416 SelectionDAG &DAG) const { 8417 SDLoc SL(Op); 8418 SDValue LHS = Op.getOperand(0); 8419 SDValue RHS = Op.getOperand(1); 8420 EVT VT = Op.getValueType(); 8421 const SDNodeFlags Flags = Op->getFlags(); 8422 8423 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8424 8425 // Without !fpmath accuracy information, we can't do more because we don't 8426 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8427 if (!AllowInaccurateRcp) 8428 return SDValue(); 8429 8430 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8431 if (CLHS->isExactlyValue(1.0)) { 8432 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8433 // the CI documentation has a worst case error of 1 ulp. 8434 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8435 // use it as long as we aren't trying to use denormals. 8436 // 8437 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8438 8439 // 1.0 / sqrt(x) -> rsq(x) 8440 8441 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8442 // error seems really high at 2^29 ULP. 8443 if (RHS.getOpcode() == ISD::FSQRT) 8444 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8445 8446 // 1.0 / x -> rcp(x) 8447 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8448 } 8449 8450 // Same as for 1.0, but expand the sign out of the constant. 8451 if (CLHS->isExactlyValue(-1.0)) { 8452 // -1.0 / x -> rcp (fneg x) 8453 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8454 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8455 } 8456 } 8457 8458 // Turn into multiply by the reciprocal. 8459 // x / y -> x * (1.0 / y) 8460 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8461 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8462 } 8463 8464 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8465 SelectionDAG &DAG) const { 8466 SDLoc SL(Op); 8467 SDValue X = Op.getOperand(0); 8468 SDValue Y = Op.getOperand(1); 8469 EVT VT = Op.getValueType(); 8470 const SDNodeFlags Flags = Op->getFlags(); 8471 8472 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8473 DAG.getTarget().Options.UnsafeFPMath; 8474 if (!AllowInaccurateDiv) 8475 return SDValue(); 8476 8477 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8478 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8479 8480 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8481 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8482 8483 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8484 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8485 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8486 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8487 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8488 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8489 } 8490 8491 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8492 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8493 SDNodeFlags Flags) { 8494 if (GlueChain->getNumValues() <= 1) { 8495 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8496 } 8497 8498 assert(GlueChain->getNumValues() == 3); 8499 8500 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8501 switch (Opcode) { 8502 default: llvm_unreachable("no chain equivalent for opcode"); 8503 case ISD::FMUL: 8504 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8505 break; 8506 } 8507 8508 return DAG.getNode(Opcode, SL, VTList, 8509 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8510 Flags); 8511 } 8512 8513 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8514 EVT VT, SDValue A, SDValue B, SDValue C, 8515 SDValue GlueChain, SDNodeFlags Flags) { 8516 if (GlueChain->getNumValues() <= 1) { 8517 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8518 } 8519 8520 assert(GlueChain->getNumValues() == 3); 8521 8522 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8523 switch (Opcode) { 8524 default: llvm_unreachable("no chain equivalent for opcode"); 8525 case ISD::FMA: 8526 Opcode = AMDGPUISD::FMA_W_CHAIN; 8527 break; 8528 } 8529 8530 return DAG.getNode(Opcode, SL, VTList, 8531 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8532 Flags); 8533 } 8534 8535 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8536 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8537 return FastLowered; 8538 8539 SDLoc SL(Op); 8540 SDValue Src0 = Op.getOperand(0); 8541 SDValue Src1 = Op.getOperand(1); 8542 8543 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8544 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8545 8546 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8547 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8548 8549 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8550 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8551 8552 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8553 } 8554 8555 // Faster 2.5 ULP division that does not support denormals. 8556 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8557 SDLoc SL(Op); 8558 SDValue LHS = Op.getOperand(1); 8559 SDValue RHS = Op.getOperand(2); 8560 8561 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8562 8563 const APFloat K0Val(BitsToFloat(0x6f800000)); 8564 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8565 8566 const APFloat K1Val(BitsToFloat(0x2f800000)); 8567 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8568 8569 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8570 8571 EVT SetCCVT = 8572 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8573 8574 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8575 8576 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8577 8578 // TODO: Should this propagate fast-math-flags? 8579 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8580 8581 // rcp does not support denormals. 8582 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8583 8584 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8585 8586 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8587 } 8588 8589 // Returns immediate value for setting the F32 denorm mode when using the 8590 // S_DENORM_MODE instruction. 8591 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8592 const SDLoc &SL, const GCNSubtarget *ST) { 8593 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8594 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8595 ? FP_DENORM_FLUSH_NONE 8596 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8597 8598 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8599 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8600 } 8601 8602 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8603 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8604 return FastLowered; 8605 8606 // The selection matcher assumes anything with a chain selecting to a 8607 // mayRaiseFPException machine instruction. Since we're introducing a chain 8608 // here, we need to explicitly report nofpexcept for the regular fdiv 8609 // lowering. 8610 SDNodeFlags Flags = Op->getFlags(); 8611 Flags.setNoFPExcept(true); 8612 8613 SDLoc SL(Op); 8614 SDValue LHS = Op.getOperand(0); 8615 SDValue RHS = Op.getOperand(1); 8616 8617 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8618 8619 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8620 8621 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8622 {RHS, RHS, LHS}, Flags); 8623 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8624 {LHS, RHS, LHS}, Flags); 8625 8626 // Denominator is scaled to not be denormal, so using rcp is ok. 8627 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8628 DenominatorScaled, Flags); 8629 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8630 DenominatorScaled, Flags); 8631 8632 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8633 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8634 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8635 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8636 8637 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8638 8639 if (!HasFP32Denormals) { 8640 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8641 // lowering. The chain dependence is insufficient, and we need glue. We do 8642 // not need the glue variants in a strictfp function. 8643 8644 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8645 8646 SDNode *EnableDenorm; 8647 if (Subtarget->hasDenormModeInst()) { 8648 const SDValue EnableDenormValue = 8649 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8650 8651 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8652 DAG.getEntryNode(), EnableDenormValue).getNode(); 8653 } else { 8654 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8655 SL, MVT::i32); 8656 EnableDenorm = 8657 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8658 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8659 } 8660 8661 SDValue Ops[3] = { 8662 NegDivScale0, 8663 SDValue(EnableDenorm, 0), 8664 SDValue(EnableDenorm, 1) 8665 }; 8666 8667 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8668 } 8669 8670 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8671 ApproxRcp, One, NegDivScale0, Flags); 8672 8673 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8674 ApproxRcp, Fma0, Flags); 8675 8676 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8677 Fma1, Fma1, Flags); 8678 8679 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8680 NumeratorScaled, Mul, Flags); 8681 8682 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8683 Fma2, Fma1, Mul, Fma2, Flags); 8684 8685 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8686 NumeratorScaled, Fma3, Flags); 8687 8688 if (!HasFP32Denormals) { 8689 SDNode *DisableDenorm; 8690 if (Subtarget->hasDenormModeInst()) { 8691 const SDValue DisableDenormValue = 8692 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8693 8694 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8695 Fma4.getValue(1), DisableDenormValue, 8696 Fma4.getValue(2)).getNode(); 8697 } else { 8698 const SDValue DisableDenormValue = 8699 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8700 8701 DisableDenorm = DAG.getMachineNode( 8702 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8703 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8704 } 8705 8706 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8707 SDValue(DisableDenorm, 0), DAG.getRoot()); 8708 DAG.setRoot(OutputChain); 8709 } 8710 8711 SDValue Scale = NumeratorScaled.getValue(1); 8712 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8713 {Fma4, Fma1, Fma3, Scale}, Flags); 8714 8715 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8716 } 8717 8718 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8719 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8720 return FastLowered; 8721 8722 SDLoc SL(Op); 8723 SDValue X = Op.getOperand(0); 8724 SDValue Y = Op.getOperand(1); 8725 8726 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8727 8728 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8729 8730 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8731 8732 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8733 8734 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8735 8736 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8737 8738 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8739 8740 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8741 8742 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8743 8744 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8745 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8746 8747 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8748 NegDivScale0, Mul, DivScale1); 8749 8750 SDValue Scale; 8751 8752 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8753 // Workaround a hardware bug on SI where the condition output from div_scale 8754 // is not usable. 8755 8756 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8757 8758 // Figure out if the scale to use for div_fmas. 8759 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8760 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8761 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8762 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8763 8764 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8765 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8766 8767 SDValue Scale0Hi 8768 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8769 SDValue Scale1Hi 8770 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8771 8772 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8773 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8774 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8775 } else { 8776 Scale = DivScale1.getValue(1); 8777 } 8778 8779 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8780 Fma4, Fma3, Mul, Scale); 8781 8782 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8783 } 8784 8785 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8786 EVT VT = Op.getValueType(); 8787 8788 if (VT == MVT::f32) 8789 return LowerFDIV32(Op, DAG); 8790 8791 if (VT == MVT::f64) 8792 return LowerFDIV64(Op, DAG); 8793 8794 if (VT == MVT::f16) 8795 return LowerFDIV16(Op, DAG); 8796 8797 llvm_unreachable("Unexpected type for fdiv"); 8798 } 8799 8800 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8801 SDLoc DL(Op); 8802 StoreSDNode *Store = cast<StoreSDNode>(Op); 8803 EVT VT = Store->getMemoryVT(); 8804 8805 if (VT == MVT::i1) { 8806 return DAG.getTruncStore(Store->getChain(), DL, 8807 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8808 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8809 } 8810 8811 assert(VT.isVector() && 8812 Store->getValue().getValueType().getScalarType() == MVT::i32); 8813 8814 unsigned AS = Store->getAddressSpace(); 8815 if (Subtarget->hasLDSMisalignedBug() && 8816 AS == AMDGPUAS::FLAT_ADDRESS && 8817 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8818 return SplitVectorStore(Op, DAG); 8819 } 8820 8821 MachineFunction &MF = DAG.getMachineFunction(); 8822 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8823 // If there is a possibilty that flat instruction access scratch memory 8824 // then we need to use the same legalization rules we use for private. 8825 if (AS == AMDGPUAS::FLAT_ADDRESS && 8826 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8827 AS = MFI->hasFlatScratchInit() ? 8828 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8829 8830 unsigned NumElements = VT.getVectorNumElements(); 8831 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8832 AS == AMDGPUAS::FLAT_ADDRESS) { 8833 if (NumElements > 4) 8834 return SplitVectorStore(Op, DAG); 8835 // v3 stores not supported on SI. 8836 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8837 return SplitVectorStore(Op, DAG); 8838 8839 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8840 VT, *Store->getMemOperand())) 8841 return expandUnalignedStore(Store, DAG); 8842 8843 return SDValue(); 8844 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8845 switch (Subtarget->getMaxPrivateElementSize()) { 8846 case 4: 8847 return scalarizeVectorStore(Store, DAG); 8848 case 8: 8849 if (NumElements > 2) 8850 return SplitVectorStore(Op, DAG); 8851 return SDValue(); 8852 case 16: 8853 if (NumElements > 4 || 8854 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8855 return SplitVectorStore(Op, DAG); 8856 return SDValue(); 8857 default: 8858 llvm_unreachable("unsupported private_element_size"); 8859 } 8860 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8861 // Use ds_write_b128 or ds_write_b96 when possible. 8862 if (Subtarget->hasDS96AndDS128() && 8863 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8864 (VT.getStoreSize() == 12)) && 8865 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8866 Store->getAlign())) 8867 return SDValue(); 8868 8869 if (NumElements > 2) 8870 return SplitVectorStore(Op, DAG); 8871 8872 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8873 // address is negative, then the instruction is incorrectly treated as 8874 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8875 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8876 // store later in the SILoadStoreOptimizer. 8877 if (!Subtarget->hasUsableDSOffset() && 8878 NumElements == 2 && VT.getStoreSize() == 8 && 8879 Store->getAlignment() < 8) { 8880 return SplitVectorStore(Op, DAG); 8881 } 8882 8883 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8884 VT, *Store->getMemOperand())) { 8885 if (VT.isVector()) 8886 return SplitVectorStore(Op, DAG); 8887 return expandUnalignedStore(Store, DAG); 8888 } 8889 8890 return SDValue(); 8891 } else { 8892 llvm_unreachable("unhandled address space"); 8893 } 8894 } 8895 8896 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8897 SDLoc DL(Op); 8898 EVT VT = Op.getValueType(); 8899 SDValue Arg = Op.getOperand(0); 8900 SDValue TrigVal; 8901 8902 // Propagate fast-math flags so that the multiply we introduce can be folded 8903 // if Arg is already the result of a multiply by constant. 8904 auto Flags = Op->getFlags(); 8905 8906 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8907 8908 if (Subtarget->hasTrigReducedRange()) { 8909 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8910 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8911 } else { 8912 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8913 } 8914 8915 switch (Op.getOpcode()) { 8916 case ISD::FCOS: 8917 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8918 case ISD::FSIN: 8919 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8920 default: 8921 llvm_unreachable("Wrong trig opcode"); 8922 } 8923 } 8924 8925 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8926 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8927 assert(AtomicNode->isCompareAndSwap()); 8928 unsigned AS = AtomicNode->getAddressSpace(); 8929 8930 // No custom lowering required for local address space 8931 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8932 return Op; 8933 8934 // Non-local address space requires custom lowering for atomic compare 8935 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8936 SDLoc DL(Op); 8937 SDValue ChainIn = Op.getOperand(0); 8938 SDValue Addr = Op.getOperand(1); 8939 SDValue Old = Op.getOperand(2); 8940 SDValue New = Op.getOperand(3); 8941 EVT VT = Op.getValueType(); 8942 MVT SimpleVT = VT.getSimpleVT(); 8943 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8944 8945 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8946 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8947 8948 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8949 Ops, VT, AtomicNode->getMemOperand()); 8950 } 8951 8952 //===----------------------------------------------------------------------===// 8953 // Custom DAG optimizations 8954 //===----------------------------------------------------------------------===// 8955 8956 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8957 DAGCombinerInfo &DCI) const { 8958 EVT VT = N->getValueType(0); 8959 EVT ScalarVT = VT.getScalarType(); 8960 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8961 return SDValue(); 8962 8963 SelectionDAG &DAG = DCI.DAG; 8964 SDLoc DL(N); 8965 8966 SDValue Src = N->getOperand(0); 8967 EVT SrcVT = Src.getValueType(); 8968 8969 // TODO: We could try to match extracting the higher bytes, which would be 8970 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8971 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8972 // about in practice. 8973 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8974 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8975 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8976 DCI.AddToWorklist(Cvt.getNode()); 8977 8978 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8979 if (ScalarVT != MVT::f32) { 8980 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8981 DAG.getTargetConstant(0, DL, MVT::i32)); 8982 } 8983 return Cvt; 8984 } 8985 } 8986 8987 return SDValue(); 8988 } 8989 8990 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8991 8992 // This is a variant of 8993 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8994 // 8995 // The normal DAG combiner will do this, but only if the add has one use since 8996 // that would increase the number of instructions. 8997 // 8998 // This prevents us from seeing a constant offset that can be folded into a 8999 // memory instruction's addressing mode. If we know the resulting add offset of 9000 // a pointer can be folded into an addressing offset, we can replace the pointer 9001 // operand with the add of new constant offset. This eliminates one of the uses, 9002 // and may allow the remaining use to also be simplified. 9003 // 9004 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9005 unsigned AddrSpace, 9006 EVT MemVT, 9007 DAGCombinerInfo &DCI) const { 9008 SDValue N0 = N->getOperand(0); 9009 SDValue N1 = N->getOperand(1); 9010 9011 // We only do this to handle cases where it's profitable when there are 9012 // multiple uses of the add, so defer to the standard combine. 9013 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9014 N0->hasOneUse()) 9015 return SDValue(); 9016 9017 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9018 if (!CN1) 9019 return SDValue(); 9020 9021 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9022 if (!CAdd) 9023 return SDValue(); 9024 9025 // If the resulting offset is too large, we can't fold it into the addressing 9026 // mode offset. 9027 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9028 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9029 9030 AddrMode AM; 9031 AM.HasBaseReg = true; 9032 AM.BaseOffs = Offset.getSExtValue(); 9033 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9034 return SDValue(); 9035 9036 SelectionDAG &DAG = DCI.DAG; 9037 SDLoc SL(N); 9038 EVT VT = N->getValueType(0); 9039 9040 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9041 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9042 9043 SDNodeFlags Flags; 9044 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9045 (N0.getOpcode() == ISD::OR || 9046 N0->getFlags().hasNoUnsignedWrap())); 9047 9048 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9049 } 9050 9051 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9052 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9053 /// specific intrinsic, but they all place the pointer operand first. 9054 static unsigned getBasePtrIndex(const MemSDNode *N) { 9055 switch (N->getOpcode()) { 9056 case ISD::STORE: 9057 case ISD::INTRINSIC_W_CHAIN: 9058 case ISD::INTRINSIC_VOID: 9059 return 2; 9060 default: 9061 return 1; 9062 } 9063 } 9064 9065 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9066 DAGCombinerInfo &DCI) const { 9067 SelectionDAG &DAG = DCI.DAG; 9068 SDLoc SL(N); 9069 9070 unsigned PtrIdx = getBasePtrIndex(N); 9071 SDValue Ptr = N->getOperand(PtrIdx); 9072 9073 // TODO: We could also do this for multiplies. 9074 if (Ptr.getOpcode() == ISD::SHL) { 9075 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9076 N->getMemoryVT(), DCI); 9077 if (NewPtr) { 9078 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9079 9080 NewOps[PtrIdx] = NewPtr; 9081 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9082 } 9083 } 9084 9085 return SDValue(); 9086 } 9087 9088 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9089 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9090 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9091 (Opc == ISD::XOR && Val == 0); 9092 } 9093 9094 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9095 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9096 // integer combine opportunities since most 64-bit operations are decomposed 9097 // this way. TODO: We won't want this for SALU especially if it is an inline 9098 // immediate. 9099 SDValue SITargetLowering::splitBinaryBitConstantOp( 9100 DAGCombinerInfo &DCI, 9101 const SDLoc &SL, 9102 unsigned Opc, SDValue LHS, 9103 const ConstantSDNode *CRHS) const { 9104 uint64_t Val = CRHS->getZExtValue(); 9105 uint32_t ValLo = Lo_32(Val); 9106 uint32_t ValHi = Hi_32(Val); 9107 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9108 9109 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9110 bitOpWithConstantIsReducible(Opc, ValHi)) || 9111 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9112 // If we need to materialize a 64-bit immediate, it will be split up later 9113 // anyway. Avoid creating the harder to understand 64-bit immediate 9114 // materialization. 9115 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9116 } 9117 9118 return SDValue(); 9119 } 9120 9121 // Returns true if argument is a boolean value which is not serialized into 9122 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9123 static bool isBoolSGPR(SDValue V) { 9124 if (V.getValueType() != MVT::i1) 9125 return false; 9126 switch (V.getOpcode()) { 9127 default: 9128 break; 9129 case ISD::SETCC: 9130 case AMDGPUISD::FP_CLASS: 9131 return true; 9132 case ISD::AND: 9133 case ISD::OR: 9134 case ISD::XOR: 9135 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9136 } 9137 return false; 9138 } 9139 9140 // If a constant has all zeroes or all ones within each byte return it. 9141 // Otherwise return 0. 9142 static uint32_t getConstantPermuteMask(uint32_t C) { 9143 // 0xff for any zero byte in the mask 9144 uint32_t ZeroByteMask = 0; 9145 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9146 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9147 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9148 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9149 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9150 if ((NonZeroByteMask & C) != NonZeroByteMask) 9151 return 0; // Partial bytes selected. 9152 return C; 9153 } 9154 9155 // Check if a node selects whole bytes from its operand 0 starting at a byte 9156 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9157 // or -1 if not succeeded. 9158 // Note byte select encoding: 9159 // value 0-3 selects corresponding source byte; 9160 // value 0xc selects zero; 9161 // value 0xff selects 0xff. 9162 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9163 assert(V.getValueSizeInBits() == 32); 9164 9165 if (V.getNumOperands() != 2) 9166 return ~0; 9167 9168 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9169 if (!N1) 9170 return ~0; 9171 9172 uint32_t C = N1->getZExtValue(); 9173 9174 switch (V.getOpcode()) { 9175 default: 9176 break; 9177 case ISD::AND: 9178 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9179 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9180 } 9181 break; 9182 9183 case ISD::OR: 9184 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9185 return (0x03020100 & ~ConstMask) | ConstMask; 9186 } 9187 break; 9188 9189 case ISD::SHL: 9190 if (C % 8) 9191 return ~0; 9192 9193 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9194 9195 case ISD::SRL: 9196 if (C % 8) 9197 return ~0; 9198 9199 return uint32_t(0x0c0c0c0c03020100ull >> C); 9200 } 9201 9202 return ~0; 9203 } 9204 9205 SDValue SITargetLowering::performAndCombine(SDNode *N, 9206 DAGCombinerInfo &DCI) const { 9207 if (DCI.isBeforeLegalize()) 9208 return SDValue(); 9209 9210 SelectionDAG &DAG = DCI.DAG; 9211 EVT VT = N->getValueType(0); 9212 SDValue LHS = N->getOperand(0); 9213 SDValue RHS = N->getOperand(1); 9214 9215 9216 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9217 if (VT == MVT::i64 && CRHS) { 9218 if (SDValue Split 9219 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9220 return Split; 9221 } 9222 9223 if (CRHS && VT == MVT::i32) { 9224 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9225 // nb = number of trailing zeroes in mask 9226 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9227 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9228 uint64_t Mask = CRHS->getZExtValue(); 9229 unsigned Bits = countPopulation(Mask); 9230 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9231 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9232 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9233 unsigned Shift = CShift->getZExtValue(); 9234 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9235 unsigned Offset = NB + Shift; 9236 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9237 SDLoc SL(N); 9238 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9239 LHS->getOperand(0), 9240 DAG.getConstant(Offset, SL, MVT::i32), 9241 DAG.getConstant(Bits, SL, MVT::i32)); 9242 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9243 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9244 DAG.getValueType(NarrowVT)); 9245 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9246 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9247 return Shl; 9248 } 9249 } 9250 } 9251 9252 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9253 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9254 isa<ConstantSDNode>(LHS.getOperand(2))) { 9255 uint32_t Sel = getConstantPermuteMask(Mask); 9256 if (!Sel) 9257 return SDValue(); 9258 9259 // Select 0xc for all zero bytes 9260 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9261 SDLoc DL(N); 9262 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9263 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9264 } 9265 } 9266 9267 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9268 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9269 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9270 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9271 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9272 9273 SDValue X = LHS.getOperand(0); 9274 SDValue Y = RHS.getOperand(0); 9275 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9276 return SDValue(); 9277 9278 if (LCC == ISD::SETO) { 9279 if (X != LHS.getOperand(1)) 9280 return SDValue(); 9281 9282 if (RCC == ISD::SETUNE) { 9283 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9284 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9285 return SDValue(); 9286 9287 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9288 SIInstrFlags::N_SUBNORMAL | 9289 SIInstrFlags::N_ZERO | 9290 SIInstrFlags::P_ZERO | 9291 SIInstrFlags::P_SUBNORMAL | 9292 SIInstrFlags::P_NORMAL; 9293 9294 static_assert(((~(SIInstrFlags::S_NAN | 9295 SIInstrFlags::Q_NAN | 9296 SIInstrFlags::N_INFINITY | 9297 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9298 "mask not equal"); 9299 9300 SDLoc DL(N); 9301 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9302 X, DAG.getConstant(Mask, DL, MVT::i32)); 9303 } 9304 } 9305 } 9306 9307 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9308 std::swap(LHS, RHS); 9309 9310 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9311 RHS.hasOneUse()) { 9312 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9313 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9314 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9315 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9316 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9317 (RHS.getOperand(0) == LHS.getOperand(0) && 9318 LHS.getOperand(0) == LHS.getOperand(1))) { 9319 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9320 unsigned NewMask = LCC == ISD::SETO ? 9321 Mask->getZExtValue() & ~OrdMask : 9322 Mask->getZExtValue() & OrdMask; 9323 9324 SDLoc DL(N); 9325 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9326 DAG.getConstant(NewMask, DL, MVT::i32)); 9327 } 9328 } 9329 9330 if (VT == MVT::i32 && 9331 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9332 // and x, (sext cc from i1) => select cc, x, 0 9333 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9334 std::swap(LHS, RHS); 9335 if (isBoolSGPR(RHS.getOperand(0))) 9336 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9337 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9338 } 9339 9340 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9341 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9342 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9343 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9344 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9345 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9346 if (LHSMask != ~0u && RHSMask != ~0u) { 9347 // Canonicalize the expression in an attempt to have fewer unique masks 9348 // and therefore fewer registers used to hold the masks. 9349 if (LHSMask > RHSMask) { 9350 std::swap(LHSMask, RHSMask); 9351 std::swap(LHS, RHS); 9352 } 9353 9354 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9355 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9356 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9357 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9358 9359 // Check of we need to combine values from two sources within a byte. 9360 if (!(LHSUsedLanes & RHSUsedLanes) && 9361 // If we select high and lower word keep it for SDWA. 9362 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9363 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9364 // Each byte in each mask is either selector mask 0-3, or has higher 9365 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9366 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9367 // mask which is not 0xff wins. By anding both masks we have a correct 9368 // result except that 0x0c shall be corrected to give 0x0c only. 9369 uint32_t Mask = LHSMask & RHSMask; 9370 for (unsigned I = 0; I < 32; I += 8) { 9371 uint32_t ByteSel = 0xff << I; 9372 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9373 Mask &= (0x0c << I) & 0xffffffff; 9374 } 9375 9376 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9377 // or 0x0c. 9378 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9379 SDLoc DL(N); 9380 9381 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9382 LHS.getOperand(0), RHS.getOperand(0), 9383 DAG.getConstant(Sel, DL, MVT::i32)); 9384 } 9385 } 9386 } 9387 9388 return SDValue(); 9389 } 9390 9391 SDValue SITargetLowering::performOrCombine(SDNode *N, 9392 DAGCombinerInfo &DCI) const { 9393 SelectionDAG &DAG = DCI.DAG; 9394 SDValue LHS = N->getOperand(0); 9395 SDValue RHS = N->getOperand(1); 9396 9397 EVT VT = N->getValueType(0); 9398 if (VT == MVT::i1) { 9399 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9400 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9401 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9402 SDValue Src = LHS.getOperand(0); 9403 if (Src != RHS.getOperand(0)) 9404 return SDValue(); 9405 9406 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9407 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9408 if (!CLHS || !CRHS) 9409 return SDValue(); 9410 9411 // Only 10 bits are used. 9412 static const uint32_t MaxMask = 0x3ff; 9413 9414 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9415 SDLoc DL(N); 9416 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9417 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9418 } 9419 9420 return SDValue(); 9421 } 9422 9423 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9424 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9425 LHS.getOpcode() == AMDGPUISD::PERM && 9426 isa<ConstantSDNode>(LHS.getOperand(2))) { 9427 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9428 if (!Sel) 9429 return SDValue(); 9430 9431 Sel |= LHS.getConstantOperandVal(2); 9432 SDLoc DL(N); 9433 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9434 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9435 } 9436 9437 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9438 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9439 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9440 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9441 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9442 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9443 if (LHSMask != ~0u && RHSMask != ~0u) { 9444 // Canonicalize the expression in an attempt to have fewer unique masks 9445 // and therefore fewer registers used to hold the masks. 9446 if (LHSMask > RHSMask) { 9447 std::swap(LHSMask, RHSMask); 9448 std::swap(LHS, RHS); 9449 } 9450 9451 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9452 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9453 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9454 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9455 9456 // Check of we need to combine values from two sources within a byte. 9457 if (!(LHSUsedLanes & RHSUsedLanes) && 9458 // If we select high and lower word keep it for SDWA. 9459 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9460 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9461 // Kill zero bytes selected by other mask. Zero value is 0xc. 9462 LHSMask &= ~RHSUsedLanes; 9463 RHSMask &= ~LHSUsedLanes; 9464 // Add 4 to each active LHS lane 9465 LHSMask |= LHSUsedLanes & 0x04040404; 9466 // Combine masks 9467 uint32_t Sel = LHSMask | RHSMask; 9468 SDLoc DL(N); 9469 9470 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9471 LHS.getOperand(0), RHS.getOperand(0), 9472 DAG.getConstant(Sel, DL, MVT::i32)); 9473 } 9474 } 9475 } 9476 9477 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9478 return SDValue(); 9479 9480 // TODO: This could be a generic combine with a predicate for extracting the 9481 // high half of an integer being free. 9482 9483 // (or i64:x, (zero_extend i32:y)) -> 9484 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9485 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9486 RHS.getOpcode() != ISD::ZERO_EXTEND) 9487 std::swap(LHS, RHS); 9488 9489 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9490 SDValue ExtSrc = RHS.getOperand(0); 9491 EVT SrcVT = ExtSrc.getValueType(); 9492 if (SrcVT == MVT::i32) { 9493 SDLoc SL(N); 9494 SDValue LowLHS, HiBits; 9495 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9496 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9497 9498 DCI.AddToWorklist(LowOr.getNode()); 9499 DCI.AddToWorklist(HiBits.getNode()); 9500 9501 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9502 LowOr, HiBits); 9503 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9504 } 9505 } 9506 9507 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9508 if (CRHS) { 9509 if (SDValue Split 9510 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9511 N->getOperand(0), CRHS)) 9512 return Split; 9513 } 9514 9515 return SDValue(); 9516 } 9517 9518 SDValue SITargetLowering::performXorCombine(SDNode *N, 9519 DAGCombinerInfo &DCI) const { 9520 EVT VT = N->getValueType(0); 9521 if (VT != MVT::i64) 9522 return SDValue(); 9523 9524 SDValue LHS = N->getOperand(0); 9525 SDValue RHS = N->getOperand(1); 9526 9527 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9528 if (CRHS) { 9529 if (SDValue Split 9530 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9531 return Split; 9532 } 9533 9534 return SDValue(); 9535 } 9536 9537 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9538 DAGCombinerInfo &DCI) const { 9539 if (!Subtarget->has16BitInsts() || 9540 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9541 return SDValue(); 9542 9543 EVT VT = N->getValueType(0); 9544 if (VT != MVT::i32) 9545 return SDValue(); 9546 9547 SDValue Src = N->getOperand(0); 9548 if (Src.getValueType() != MVT::i16) 9549 return SDValue(); 9550 9551 return SDValue(); 9552 } 9553 9554 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9555 DAGCombinerInfo &DCI) 9556 const { 9557 SDValue Src = N->getOperand(0); 9558 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9559 9560 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9561 VTSign->getVT() == MVT::i8) || 9562 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9563 VTSign->getVT() == MVT::i16)) && 9564 Src.hasOneUse()) { 9565 auto *M = cast<MemSDNode>(Src); 9566 SDValue Ops[] = { 9567 Src.getOperand(0), // Chain 9568 Src.getOperand(1), // rsrc 9569 Src.getOperand(2), // vindex 9570 Src.getOperand(3), // voffset 9571 Src.getOperand(4), // soffset 9572 Src.getOperand(5), // offset 9573 Src.getOperand(6), 9574 Src.getOperand(7) 9575 }; 9576 // replace with BUFFER_LOAD_BYTE/SHORT 9577 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9578 Src.getOperand(0).getValueType()); 9579 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9580 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9581 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9582 ResList, 9583 Ops, M->getMemoryVT(), 9584 M->getMemOperand()); 9585 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9586 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9587 } 9588 return SDValue(); 9589 } 9590 9591 SDValue SITargetLowering::performClassCombine(SDNode *N, 9592 DAGCombinerInfo &DCI) const { 9593 SelectionDAG &DAG = DCI.DAG; 9594 SDValue Mask = N->getOperand(1); 9595 9596 // fp_class x, 0 -> false 9597 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9598 if (CMask->isZero()) 9599 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9600 } 9601 9602 if (N->getOperand(0).isUndef()) 9603 return DAG.getUNDEF(MVT::i1); 9604 9605 return SDValue(); 9606 } 9607 9608 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9609 DAGCombinerInfo &DCI) const { 9610 EVT VT = N->getValueType(0); 9611 SDValue N0 = N->getOperand(0); 9612 9613 if (N0.isUndef()) 9614 return N0; 9615 9616 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9617 N0.getOpcode() == ISD::SINT_TO_FP)) { 9618 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9619 N->getFlags()); 9620 } 9621 9622 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9623 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9624 N0.getOperand(0), N->getFlags()); 9625 } 9626 9627 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9628 } 9629 9630 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9631 unsigned MaxDepth) const { 9632 unsigned Opcode = Op.getOpcode(); 9633 if (Opcode == ISD::FCANONICALIZE) 9634 return true; 9635 9636 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9637 auto F = CFP->getValueAPF(); 9638 if (F.isNaN() && F.isSignaling()) 9639 return false; 9640 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9641 } 9642 9643 // If source is a result of another standard FP operation it is already in 9644 // canonical form. 9645 if (MaxDepth == 0) 9646 return false; 9647 9648 switch (Opcode) { 9649 // These will flush denorms if required. 9650 case ISD::FADD: 9651 case ISD::FSUB: 9652 case ISD::FMUL: 9653 case ISD::FCEIL: 9654 case ISD::FFLOOR: 9655 case ISD::FMA: 9656 case ISD::FMAD: 9657 case ISD::FSQRT: 9658 case ISD::FDIV: 9659 case ISD::FREM: 9660 case ISD::FP_ROUND: 9661 case ISD::FP_EXTEND: 9662 case AMDGPUISD::FMUL_LEGACY: 9663 case AMDGPUISD::FMAD_FTZ: 9664 case AMDGPUISD::RCP: 9665 case AMDGPUISD::RSQ: 9666 case AMDGPUISD::RSQ_CLAMP: 9667 case AMDGPUISD::RCP_LEGACY: 9668 case AMDGPUISD::RCP_IFLAG: 9669 case AMDGPUISD::DIV_SCALE: 9670 case AMDGPUISD::DIV_FMAS: 9671 case AMDGPUISD::DIV_FIXUP: 9672 case AMDGPUISD::FRACT: 9673 case AMDGPUISD::LDEXP: 9674 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9675 case AMDGPUISD::CVT_F32_UBYTE0: 9676 case AMDGPUISD::CVT_F32_UBYTE1: 9677 case AMDGPUISD::CVT_F32_UBYTE2: 9678 case AMDGPUISD::CVT_F32_UBYTE3: 9679 return true; 9680 9681 // It can/will be lowered or combined as a bit operation. 9682 // Need to check their input recursively to handle. 9683 case ISD::FNEG: 9684 case ISD::FABS: 9685 case ISD::FCOPYSIGN: 9686 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9687 9688 case ISD::FSIN: 9689 case ISD::FCOS: 9690 case ISD::FSINCOS: 9691 return Op.getValueType().getScalarType() != MVT::f16; 9692 9693 case ISD::FMINNUM: 9694 case ISD::FMAXNUM: 9695 case ISD::FMINNUM_IEEE: 9696 case ISD::FMAXNUM_IEEE: 9697 case AMDGPUISD::CLAMP: 9698 case AMDGPUISD::FMED3: 9699 case AMDGPUISD::FMAX3: 9700 case AMDGPUISD::FMIN3: { 9701 // FIXME: Shouldn't treat the generic operations different based these. 9702 // However, we aren't really required to flush the result from 9703 // minnum/maxnum.. 9704 9705 // snans will be quieted, so we only need to worry about denormals. 9706 if (Subtarget->supportsMinMaxDenormModes() || 9707 denormalsEnabledForType(DAG, Op.getValueType())) 9708 return true; 9709 9710 // Flushing may be required. 9711 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9712 // targets need to check their input recursively. 9713 9714 // FIXME: Does this apply with clamp? It's implemented with max. 9715 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9716 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9717 return false; 9718 } 9719 9720 return true; 9721 } 9722 case ISD::SELECT: { 9723 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9724 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9725 } 9726 case ISD::BUILD_VECTOR: { 9727 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9728 SDValue SrcOp = Op.getOperand(i); 9729 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9730 return false; 9731 } 9732 9733 return true; 9734 } 9735 case ISD::EXTRACT_VECTOR_ELT: 9736 case ISD::EXTRACT_SUBVECTOR: { 9737 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9738 } 9739 case ISD::INSERT_VECTOR_ELT: { 9740 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9741 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9742 } 9743 case ISD::UNDEF: 9744 // Could be anything. 9745 return false; 9746 9747 case ISD::BITCAST: 9748 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9749 case ISD::TRUNCATE: { 9750 // Hack round the mess we make when legalizing extract_vector_elt 9751 if (Op.getValueType() == MVT::i16) { 9752 SDValue TruncSrc = Op.getOperand(0); 9753 if (TruncSrc.getValueType() == MVT::i32 && 9754 TruncSrc.getOpcode() == ISD::BITCAST && 9755 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9756 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9757 } 9758 } 9759 return false; 9760 } 9761 case ISD::INTRINSIC_WO_CHAIN: { 9762 unsigned IntrinsicID 9763 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9764 // TODO: Handle more intrinsics 9765 switch (IntrinsicID) { 9766 case Intrinsic::amdgcn_cvt_pkrtz: 9767 case Intrinsic::amdgcn_cubeid: 9768 case Intrinsic::amdgcn_frexp_mant: 9769 case Intrinsic::amdgcn_fdot2: 9770 case Intrinsic::amdgcn_rcp: 9771 case Intrinsic::amdgcn_rsq: 9772 case Intrinsic::amdgcn_rsq_clamp: 9773 case Intrinsic::amdgcn_rcp_legacy: 9774 case Intrinsic::amdgcn_rsq_legacy: 9775 case Intrinsic::amdgcn_trig_preop: 9776 return true; 9777 default: 9778 break; 9779 } 9780 9781 LLVM_FALLTHROUGH; 9782 } 9783 default: 9784 return denormalsEnabledForType(DAG, Op.getValueType()) && 9785 DAG.isKnownNeverSNaN(Op); 9786 } 9787 9788 llvm_unreachable("invalid operation"); 9789 } 9790 9791 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9792 unsigned MaxDepth) const { 9793 MachineRegisterInfo &MRI = MF.getRegInfo(); 9794 MachineInstr *MI = MRI.getVRegDef(Reg); 9795 unsigned Opcode = MI->getOpcode(); 9796 9797 if (Opcode == AMDGPU::G_FCANONICALIZE) 9798 return true; 9799 9800 if (Opcode == AMDGPU::G_FCONSTANT) { 9801 auto F = MI->getOperand(1).getFPImm()->getValueAPF(); 9802 if (F.isNaN() && F.isSignaling()) 9803 return false; 9804 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF); 9805 } 9806 9807 if (MaxDepth == 0) 9808 return false; 9809 9810 switch (Opcode) { 9811 case AMDGPU::G_FMINNUM_IEEE: 9812 case AMDGPU::G_FMAXNUM_IEEE: { 9813 if (Subtarget->supportsMinMaxDenormModes() || 9814 denormalsEnabledForType(MRI.getType(Reg), MF)) 9815 return true; 9816 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) { 9817 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1)) 9818 return false; 9819 } 9820 return true; 9821 } 9822 default: 9823 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9824 isKnownNeverSNaN(Reg, MRI); 9825 } 9826 9827 llvm_unreachable("invalid operation"); 9828 } 9829 9830 // Constant fold canonicalize. 9831 SDValue SITargetLowering::getCanonicalConstantFP( 9832 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9833 // Flush denormals to 0 if not enabled. 9834 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9835 return DAG.getConstantFP(0.0, SL, VT); 9836 9837 if (C.isNaN()) { 9838 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9839 if (C.isSignaling()) { 9840 // Quiet a signaling NaN. 9841 // FIXME: Is this supposed to preserve payload bits? 9842 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9843 } 9844 9845 // Make sure it is the canonical NaN bitpattern. 9846 // 9847 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9848 // immediate? 9849 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9850 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9851 } 9852 9853 // Already canonical. 9854 return DAG.getConstantFP(C, SL, VT); 9855 } 9856 9857 static bool vectorEltWillFoldAway(SDValue Op) { 9858 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9859 } 9860 9861 SDValue SITargetLowering::performFCanonicalizeCombine( 9862 SDNode *N, 9863 DAGCombinerInfo &DCI) const { 9864 SelectionDAG &DAG = DCI.DAG; 9865 SDValue N0 = N->getOperand(0); 9866 EVT VT = N->getValueType(0); 9867 9868 // fcanonicalize undef -> qnan 9869 if (N0.isUndef()) { 9870 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9871 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9872 } 9873 9874 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9875 EVT VT = N->getValueType(0); 9876 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9877 } 9878 9879 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9880 // (fcanonicalize k) 9881 // 9882 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9883 9884 // TODO: This could be better with wider vectors that will be split to v2f16, 9885 // and to consider uses since there aren't that many packed operations. 9886 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9887 isTypeLegal(MVT::v2f16)) { 9888 SDLoc SL(N); 9889 SDValue NewElts[2]; 9890 SDValue Lo = N0.getOperand(0); 9891 SDValue Hi = N0.getOperand(1); 9892 EVT EltVT = Lo.getValueType(); 9893 9894 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9895 for (unsigned I = 0; I != 2; ++I) { 9896 SDValue Op = N0.getOperand(I); 9897 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9898 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9899 CFP->getValueAPF()); 9900 } else if (Op.isUndef()) { 9901 // Handled below based on what the other operand is. 9902 NewElts[I] = Op; 9903 } else { 9904 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9905 } 9906 } 9907 9908 // If one half is undef, and one is constant, perfer a splat vector rather 9909 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9910 // cheaper to use and may be free with a packed operation. 9911 if (NewElts[0].isUndef()) { 9912 if (isa<ConstantFPSDNode>(NewElts[1])) 9913 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9914 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9915 } 9916 9917 if (NewElts[1].isUndef()) { 9918 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9919 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9920 } 9921 9922 return DAG.getBuildVector(VT, SL, NewElts); 9923 } 9924 } 9925 9926 unsigned SrcOpc = N0.getOpcode(); 9927 9928 // If it's free to do so, push canonicalizes further up the source, which may 9929 // find a canonical source. 9930 // 9931 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9932 // sNaNs. 9933 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9934 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9935 if (CRHS && N0.hasOneUse()) { 9936 SDLoc SL(N); 9937 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9938 N0.getOperand(0)); 9939 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9940 DCI.AddToWorklist(Canon0.getNode()); 9941 9942 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9943 } 9944 } 9945 9946 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9947 } 9948 9949 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9950 switch (Opc) { 9951 case ISD::FMAXNUM: 9952 case ISD::FMAXNUM_IEEE: 9953 return AMDGPUISD::FMAX3; 9954 case ISD::SMAX: 9955 return AMDGPUISD::SMAX3; 9956 case ISD::UMAX: 9957 return AMDGPUISD::UMAX3; 9958 case ISD::FMINNUM: 9959 case ISD::FMINNUM_IEEE: 9960 return AMDGPUISD::FMIN3; 9961 case ISD::SMIN: 9962 return AMDGPUISD::SMIN3; 9963 case ISD::UMIN: 9964 return AMDGPUISD::UMIN3; 9965 default: 9966 llvm_unreachable("Not a min/max opcode"); 9967 } 9968 } 9969 9970 SDValue SITargetLowering::performIntMed3ImmCombine( 9971 SelectionDAG &DAG, const SDLoc &SL, 9972 SDValue Op0, SDValue Op1, bool Signed) const { 9973 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9974 if (!K1) 9975 return SDValue(); 9976 9977 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9978 if (!K0) 9979 return SDValue(); 9980 9981 if (Signed) { 9982 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9983 return SDValue(); 9984 } else { 9985 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9986 return SDValue(); 9987 } 9988 9989 EVT VT = K0->getValueType(0); 9990 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9991 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9992 return DAG.getNode(Med3Opc, SL, VT, 9993 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9994 } 9995 9996 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9997 if (VT == MVT::i16) { 9998 MVT NVT = MVT::i32; 9999 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10000 10001 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10002 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10003 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10004 10005 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10006 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10007 } 10008 10009 return SDValue(); 10010 } 10011 10012 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10013 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10014 return C; 10015 10016 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10017 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10018 return C; 10019 } 10020 10021 return nullptr; 10022 } 10023 10024 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10025 const SDLoc &SL, 10026 SDValue Op0, 10027 SDValue Op1) const { 10028 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10029 if (!K1) 10030 return SDValue(); 10031 10032 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10033 if (!K0) 10034 return SDValue(); 10035 10036 // Ordered >= (although NaN inputs should have folded away by now). 10037 if (K0->getValueAPF() > K1->getValueAPF()) 10038 return SDValue(); 10039 10040 const MachineFunction &MF = DAG.getMachineFunction(); 10041 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10042 10043 // TODO: Check IEEE bit enabled? 10044 EVT VT = Op0.getValueType(); 10045 if (Info->getMode().DX10Clamp) { 10046 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10047 // hardware fmed3 behavior converting to a min. 10048 // FIXME: Should this be allowing -0.0? 10049 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10050 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10051 } 10052 10053 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10054 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10055 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10056 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10057 // then give the other result, which is different from med3 with a NaN 10058 // input. 10059 SDValue Var = Op0.getOperand(0); 10060 if (!DAG.isKnownNeverSNaN(Var)) 10061 return SDValue(); 10062 10063 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10064 10065 if ((!K0->hasOneUse() || 10066 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10067 (!K1->hasOneUse() || 10068 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10069 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10070 Var, SDValue(K0, 0), SDValue(K1, 0)); 10071 } 10072 } 10073 10074 return SDValue(); 10075 } 10076 10077 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10078 DAGCombinerInfo &DCI) const { 10079 SelectionDAG &DAG = DCI.DAG; 10080 10081 EVT VT = N->getValueType(0); 10082 unsigned Opc = N->getOpcode(); 10083 SDValue Op0 = N->getOperand(0); 10084 SDValue Op1 = N->getOperand(1); 10085 10086 // Only do this if the inner op has one use since this will just increases 10087 // register pressure for no benefit. 10088 10089 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10090 !VT.isVector() && 10091 (VT == MVT::i32 || VT == MVT::f32 || 10092 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10093 // max(max(a, b), c) -> max3(a, b, c) 10094 // min(min(a, b), c) -> min3(a, b, c) 10095 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10096 SDLoc DL(N); 10097 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10098 DL, 10099 N->getValueType(0), 10100 Op0.getOperand(0), 10101 Op0.getOperand(1), 10102 Op1); 10103 } 10104 10105 // Try commuted. 10106 // max(a, max(b, c)) -> max3(a, b, c) 10107 // min(a, min(b, c)) -> min3(a, b, c) 10108 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10109 SDLoc DL(N); 10110 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10111 DL, 10112 N->getValueType(0), 10113 Op0, 10114 Op1.getOperand(0), 10115 Op1.getOperand(1)); 10116 } 10117 } 10118 10119 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10120 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10121 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10122 return Med3; 10123 } 10124 10125 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10126 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10127 return Med3; 10128 } 10129 10130 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10131 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10132 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10133 (Opc == AMDGPUISD::FMIN_LEGACY && 10134 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10135 (VT == MVT::f32 || VT == MVT::f64 || 10136 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10137 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10138 Op0.hasOneUse()) { 10139 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10140 return Res; 10141 } 10142 10143 return SDValue(); 10144 } 10145 10146 static bool isClampZeroToOne(SDValue A, SDValue B) { 10147 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10148 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10149 // FIXME: Should this be allowing -0.0? 10150 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10151 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10152 } 10153 } 10154 10155 return false; 10156 } 10157 10158 // FIXME: Should only worry about snans for version with chain. 10159 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10160 DAGCombinerInfo &DCI) const { 10161 EVT VT = N->getValueType(0); 10162 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10163 // NaNs. With a NaN input, the order of the operands may change the result. 10164 10165 SelectionDAG &DAG = DCI.DAG; 10166 SDLoc SL(N); 10167 10168 SDValue Src0 = N->getOperand(0); 10169 SDValue Src1 = N->getOperand(1); 10170 SDValue Src2 = N->getOperand(2); 10171 10172 if (isClampZeroToOne(Src0, Src1)) { 10173 // const_a, const_b, x -> clamp is safe in all cases including signaling 10174 // nans. 10175 // FIXME: Should this be allowing -0.0? 10176 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10177 } 10178 10179 const MachineFunction &MF = DAG.getMachineFunction(); 10180 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10181 10182 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10183 // handling no dx10-clamp? 10184 if (Info->getMode().DX10Clamp) { 10185 // If NaNs is clamped to 0, we are free to reorder the inputs. 10186 10187 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10188 std::swap(Src0, Src1); 10189 10190 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10191 std::swap(Src1, Src2); 10192 10193 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10194 std::swap(Src0, Src1); 10195 10196 if (isClampZeroToOne(Src1, Src2)) 10197 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10198 } 10199 10200 return SDValue(); 10201 } 10202 10203 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10204 DAGCombinerInfo &DCI) const { 10205 SDValue Src0 = N->getOperand(0); 10206 SDValue Src1 = N->getOperand(1); 10207 if (Src0.isUndef() && Src1.isUndef()) 10208 return DCI.DAG.getUNDEF(N->getValueType(0)); 10209 return SDValue(); 10210 } 10211 10212 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10213 // expanded into a set of cmp/select instructions. 10214 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10215 unsigned NumElem, 10216 bool IsDivergentIdx) { 10217 if (UseDivergentRegisterIndexing) 10218 return false; 10219 10220 unsigned VecSize = EltSize * NumElem; 10221 10222 // Sub-dword vectors of size 2 dword or less have better implementation. 10223 if (VecSize <= 64 && EltSize < 32) 10224 return false; 10225 10226 // Always expand the rest of sub-dword instructions, otherwise it will be 10227 // lowered via memory. 10228 if (EltSize < 32) 10229 return true; 10230 10231 // Always do this if var-idx is divergent, otherwise it will become a loop. 10232 if (IsDivergentIdx) 10233 return true; 10234 10235 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10236 unsigned NumInsts = NumElem /* Number of compares */ + 10237 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10238 return NumInsts <= 16; 10239 } 10240 10241 static bool shouldExpandVectorDynExt(SDNode *N) { 10242 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10243 if (isa<ConstantSDNode>(Idx)) 10244 return false; 10245 10246 SDValue Vec = N->getOperand(0); 10247 EVT VecVT = Vec.getValueType(); 10248 EVT EltVT = VecVT.getVectorElementType(); 10249 unsigned EltSize = EltVT.getSizeInBits(); 10250 unsigned NumElem = VecVT.getVectorNumElements(); 10251 10252 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10253 Idx->isDivergent()); 10254 } 10255 10256 SDValue SITargetLowering::performExtractVectorEltCombine( 10257 SDNode *N, DAGCombinerInfo &DCI) const { 10258 SDValue Vec = N->getOperand(0); 10259 SelectionDAG &DAG = DCI.DAG; 10260 10261 EVT VecVT = Vec.getValueType(); 10262 EVT EltVT = VecVT.getVectorElementType(); 10263 10264 if ((Vec.getOpcode() == ISD::FNEG || 10265 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10266 SDLoc SL(N); 10267 EVT EltVT = N->getValueType(0); 10268 SDValue Idx = N->getOperand(1); 10269 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10270 Vec.getOperand(0), Idx); 10271 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10272 } 10273 10274 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10275 // => 10276 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10277 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10278 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10279 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10280 SDLoc SL(N); 10281 EVT EltVT = N->getValueType(0); 10282 SDValue Idx = N->getOperand(1); 10283 unsigned Opc = Vec.getOpcode(); 10284 10285 switch(Opc) { 10286 default: 10287 break; 10288 // TODO: Support other binary operations. 10289 case ISD::FADD: 10290 case ISD::FSUB: 10291 case ISD::FMUL: 10292 case ISD::ADD: 10293 case ISD::UMIN: 10294 case ISD::UMAX: 10295 case ISD::SMIN: 10296 case ISD::SMAX: 10297 case ISD::FMAXNUM: 10298 case ISD::FMINNUM: 10299 case ISD::FMAXNUM_IEEE: 10300 case ISD::FMINNUM_IEEE: { 10301 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10302 Vec.getOperand(0), Idx); 10303 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10304 Vec.getOperand(1), Idx); 10305 10306 DCI.AddToWorklist(Elt0.getNode()); 10307 DCI.AddToWorklist(Elt1.getNode()); 10308 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10309 } 10310 } 10311 } 10312 10313 unsigned VecSize = VecVT.getSizeInBits(); 10314 unsigned EltSize = EltVT.getSizeInBits(); 10315 10316 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10317 if (::shouldExpandVectorDynExt(N)) { 10318 SDLoc SL(N); 10319 SDValue Idx = N->getOperand(1); 10320 SDValue V; 10321 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10322 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10323 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10324 if (I == 0) 10325 V = Elt; 10326 else 10327 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10328 } 10329 return V; 10330 } 10331 10332 if (!DCI.isBeforeLegalize()) 10333 return SDValue(); 10334 10335 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10336 // elements. This exposes more load reduction opportunities by replacing 10337 // multiple small extract_vector_elements with a single 32-bit extract. 10338 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10339 if (isa<MemSDNode>(Vec) && 10340 EltSize <= 16 && 10341 EltVT.isByteSized() && 10342 VecSize > 32 && 10343 VecSize % 32 == 0 && 10344 Idx) { 10345 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10346 10347 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10348 unsigned EltIdx = BitIndex / 32; 10349 unsigned LeftoverBitIdx = BitIndex % 32; 10350 SDLoc SL(N); 10351 10352 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10353 DCI.AddToWorklist(Cast.getNode()); 10354 10355 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10356 DAG.getConstant(EltIdx, SL, MVT::i32)); 10357 DCI.AddToWorklist(Elt.getNode()); 10358 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10359 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10360 DCI.AddToWorklist(Srl.getNode()); 10361 10362 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10363 DCI.AddToWorklist(Trunc.getNode()); 10364 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10365 } 10366 10367 return SDValue(); 10368 } 10369 10370 SDValue 10371 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10372 DAGCombinerInfo &DCI) const { 10373 SDValue Vec = N->getOperand(0); 10374 SDValue Idx = N->getOperand(2); 10375 EVT VecVT = Vec.getValueType(); 10376 EVT EltVT = VecVT.getVectorElementType(); 10377 10378 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10379 // => BUILD_VECTOR n x select (e, const-idx) 10380 if (!::shouldExpandVectorDynExt(N)) 10381 return SDValue(); 10382 10383 SelectionDAG &DAG = DCI.DAG; 10384 SDLoc SL(N); 10385 SDValue Ins = N->getOperand(1); 10386 EVT IdxVT = Idx.getValueType(); 10387 10388 SmallVector<SDValue, 16> Ops; 10389 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10390 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10391 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10392 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10393 Ops.push_back(V); 10394 } 10395 10396 return DAG.getBuildVector(VecVT, SL, Ops); 10397 } 10398 10399 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10400 const SDNode *N0, 10401 const SDNode *N1) const { 10402 EVT VT = N0->getValueType(0); 10403 10404 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10405 // support denormals ever. 10406 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10407 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10408 getSubtarget()->hasMadF16())) && 10409 isOperationLegal(ISD::FMAD, VT)) 10410 return ISD::FMAD; 10411 10412 const TargetOptions &Options = DAG.getTarget().Options; 10413 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10414 (N0->getFlags().hasAllowContract() && 10415 N1->getFlags().hasAllowContract())) && 10416 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10417 return ISD::FMA; 10418 } 10419 10420 return 0; 10421 } 10422 10423 // For a reassociatable opcode perform: 10424 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10425 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10426 SelectionDAG &DAG) const { 10427 EVT VT = N->getValueType(0); 10428 if (VT != MVT::i32 && VT != MVT::i64) 10429 return SDValue(); 10430 10431 unsigned Opc = N->getOpcode(); 10432 SDValue Op0 = N->getOperand(0); 10433 SDValue Op1 = N->getOperand(1); 10434 10435 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10436 return SDValue(); 10437 10438 if (Op0->isDivergent()) 10439 std::swap(Op0, Op1); 10440 10441 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10442 return SDValue(); 10443 10444 SDValue Op2 = Op1.getOperand(1); 10445 Op1 = Op1.getOperand(0); 10446 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10447 return SDValue(); 10448 10449 if (Op1->isDivergent()) 10450 std::swap(Op1, Op2); 10451 10452 // If either operand is constant this will conflict with 10453 // DAGCombiner::ReassociateOps(). 10454 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10455 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10456 return SDValue(); 10457 10458 SDLoc SL(N); 10459 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10460 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10461 } 10462 10463 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10464 EVT VT, 10465 SDValue N0, SDValue N1, SDValue N2, 10466 bool Signed) { 10467 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10468 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10469 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10470 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10471 } 10472 10473 SDValue SITargetLowering::performAddCombine(SDNode *N, 10474 DAGCombinerInfo &DCI) const { 10475 SelectionDAG &DAG = DCI.DAG; 10476 EVT VT = N->getValueType(0); 10477 SDLoc SL(N); 10478 SDValue LHS = N->getOperand(0); 10479 SDValue RHS = N->getOperand(1); 10480 10481 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10482 && Subtarget->hasMad64_32() && 10483 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10484 VT.getScalarSizeInBits() <= 64) { 10485 if (LHS.getOpcode() != ISD::MUL) 10486 std::swap(LHS, RHS); 10487 10488 SDValue MulLHS = LHS.getOperand(0); 10489 SDValue MulRHS = LHS.getOperand(1); 10490 SDValue AddRHS = RHS; 10491 10492 // TODO: Maybe restrict if SGPR inputs. 10493 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10494 numBitsUnsigned(MulRHS, DAG) <= 32) { 10495 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10496 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10497 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10498 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10499 } 10500 10501 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10502 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10503 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10504 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10505 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10506 } 10507 10508 return SDValue(); 10509 } 10510 10511 if (SDValue V = reassociateScalarOps(N, DAG)) { 10512 return V; 10513 } 10514 10515 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10516 return SDValue(); 10517 10518 // add x, zext (setcc) => addcarry x, 0, setcc 10519 // add x, sext (setcc) => subcarry x, 0, setcc 10520 unsigned Opc = LHS.getOpcode(); 10521 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10522 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10523 std::swap(RHS, LHS); 10524 10525 Opc = RHS.getOpcode(); 10526 switch (Opc) { 10527 default: break; 10528 case ISD::ZERO_EXTEND: 10529 case ISD::SIGN_EXTEND: 10530 case ISD::ANY_EXTEND: { 10531 auto Cond = RHS.getOperand(0); 10532 // If this won't be a real VOPC output, we would still need to insert an 10533 // extra instruction anyway. 10534 if (!isBoolSGPR(Cond)) 10535 break; 10536 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10537 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10538 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10539 return DAG.getNode(Opc, SL, VTList, Args); 10540 } 10541 case ISD::ADDCARRY: { 10542 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10543 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10544 if (!C || C->getZExtValue() != 0) break; 10545 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10546 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10547 } 10548 } 10549 return SDValue(); 10550 } 10551 10552 SDValue SITargetLowering::performSubCombine(SDNode *N, 10553 DAGCombinerInfo &DCI) const { 10554 SelectionDAG &DAG = DCI.DAG; 10555 EVT VT = N->getValueType(0); 10556 10557 if (VT != MVT::i32) 10558 return SDValue(); 10559 10560 SDLoc SL(N); 10561 SDValue LHS = N->getOperand(0); 10562 SDValue RHS = N->getOperand(1); 10563 10564 // sub x, zext (setcc) => subcarry x, 0, setcc 10565 // sub x, sext (setcc) => addcarry x, 0, setcc 10566 unsigned Opc = RHS.getOpcode(); 10567 switch (Opc) { 10568 default: break; 10569 case ISD::ZERO_EXTEND: 10570 case ISD::SIGN_EXTEND: 10571 case ISD::ANY_EXTEND: { 10572 auto Cond = RHS.getOperand(0); 10573 // If this won't be a real VOPC output, we would still need to insert an 10574 // extra instruction anyway. 10575 if (!isBoolSGPR(Cond)) 10576 break; 10577 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10578 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10579 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10580 return DAG.getNode(Opc, SL, VTList, Args); 10581 } 10582 } 10583 10584 if (LHS.getOpcode() == ISD::SUBCARRY) { 10585 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10586 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10587 if (!C || !C->isZero()) 10588 return SDValue(); 10589 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10590 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10591 } 10592 return SDValue(); 10593 } 10594 10595 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10596 DAGCombinerInfo &DCI) const { 10597 10598 if (N->getValueType(0) != MVT::i32) 10599 return SDValue(); 10600 10601 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10602 if (!C || C->getZExtValue() != 0) 10603 return SDValue(); 10604 10605 SelectionDAG &DAG = DCI.DAG; 10606 SDValue LHS = N->getOperand(0); 10607 10608 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10609 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10610 unsigned LHSOpc = LHS.getOpcode(); 10611 unsigned Opc = N->getOpcode(); 10612 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10613 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10614 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10615 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10616 } 10617 return SDValue(); 10618 } 10619 10620 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10621 DAGCombinerInfo &DCI) const { 10622 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10623 return SDValue(); 10624 10625 SelectionDAG &DAG = DCI.DAG; 10626 EVT VT = N->getValueType(0); 10627 10628 SDLoc SL(N); 10629 SDValue LHS = N->getOperand(0); 10630 SDValue RHS = N->getOperand(1); 10631 10632 // These should really be instruction patterns, but writing patterns with 10633 // source modiifiers is a pain. 10634 10635 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10636 if (LHS.getOpcode() == ISD::FADD) { 10637 SDValue A = LHS.getOperand(0); 10638 if (A == LHS.getOperand(1)) { 10639 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10640 if (FusedOp != 0) { 10641 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10642 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10643 } 10644 } 10645 } 10646 10647 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10648 if (RHS.getOpcode() == ISD::FADD) { 10649 SDValue A = RHS.getOperand(0); 10650 if (A == RHS.getOperand(1)) { 10651 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10652 if (FusedOp != 0) { 10653 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10654 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10655 } 10656 } 10657 } 10658 10659 return SDValue(); 10660 } 10661 10662 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10663 DAGCombinerInfo &DCI) const { 10664 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10665 return SDValue(); 10666 10667 SelectionDAG &DAG = DCI.DAG; 10668 SDLoc SL(N); 10669 EVT VT = N->getValueType(0); 10670 assert(!VT.isVector()); 10671 10672 // Try to get the fneg to fold into the source modifier. This undoes generic 10673 // DAG combines and folds them into the mad. 10674 // 10675 // Only do this if we are not trying to support denormals. v_mad_f32 does 10676 // not support denormals ever. 10677 SDValue LHS = N->getOperand(0); 10678 SDValue RHS = N->getOperand(1); 10679 if (LHS.getOpcode() == ISD::FADD) { 10680 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10681 SDValue A = LHS.getOperand(0); 10682 if (A == LHS.getOperand(1)) { 10683 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10684 if (FusedOp != 0){ 10685 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10686 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10687 10688 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10689 } 10690 } 10691 } 10692 10693 if (RHS.getOpcode() == ISD::FADD) { 10694 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10695 10696 SDValue A = RHS.getOperand(0); 10697 if (A == RHS.getOperand(1)) { 10698 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10699 if (FusedOp != 0){ 10700 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10701 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10702 } 10703 } 10704 } 10705 10706 return SDValue(); 10707 } 10708 10709 SDValue SITargetLowering::performFMACombine(SDNode *N, 10710 DAGCombinerInfo &DCI) const { 10711 SelectionDAG &DAG = DCI.DAG; 10712 EVT VT = N->getValueType(0); 10713 SDLoc SL(N); 10714 10715 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10716 return SDValue(); 10717 10718 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10719 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10720 SDValue Op1 = N->getOperand(0); 10721 SDValue Op2 = N->getOperand(1); 10722 SDValue FMA = N->getOperand(2); 10723 10724 if (FMA.getOpcode() != ISD::FMA || 10725 Op1.getOpcode() != ISD::FP_EXTEND || 10726 Op2.getOpcode() != ISD::FP_EXTEND) 10727 return SDValue(); 10728 10729 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10730 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10731 // is sufficient to allow generaing fdot2. 10732 const TargetOptions &Options = DAG.getTarget().Options; 10733 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10734 (N->getFlags().hasAllowContract() && 10735 FMA->getFlags().hasAllowContract())) { 10736 Op1 = Op1.getOperand(0); 10737 Op2 = Op2.getOperand(0); 10738 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10739 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10740 return SDValue(); 10741 10742 SDValue Vec1 = Op1.getOperand(0); 10743 SDValue Idx1 = Op1.getOperand(1); 10744 SDValue Vec2 = Op2.getOperand(0); 10745 10746 SDValue FMAOp1 = FMA.getOperand(0); 10747 SDValue FMAOp2 = FMA.getOperand(1); 10748 SDValue FMAAcc = FMA.getOperand(2); 10749 10750 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10751 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10752 return SDValue(); 10753 10754 FMAOp1 = FMAOp1.getOperand(0); 10755 FMAOp2 = FMAOp2.getOperand(0); 10756 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10757 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10758 return SDValue(); 10759 10760 SDValue Vec3 = FMAOp1.getOperand(0); 10761 SDValue Vec4 = FMAOp2.getOperand(0); 10762 SDValue Idx2 = FMAOp1.getOperand(1); 10763 10764 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10765 // Idx1 and Idx2 cannot be the same. 10766 Idx1 == Idx2) 10767 return SDValue(); 10768 10769 if (Vec1 == Vec2 || Vec3 == Vec4) 10770 return SDValue(); 10771 10772 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10773 return SDValue(); 10774 10775 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10776 (Vec1 == Vec4 && Vec2 == Vec3)) { 10777 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10778 DAG.getTargetConstant(0, SL, MVT::i1)); 10779 } 10780 } 10781 return SDValue(); 10782 } 10783 10784 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10785 DAGCombinerInfo &DCI) const { 10786 SelectionDAG &DAG = DCI.DAG; 10787 SDLoc SL(N); 10788 10789 SDValue LHS = N->getOperand(0); 10790 SDValue RHS = N->getOperand(1); 10791 EVT VT = LHS.getValueType(); 10792 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10793 10794 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10795 if (!CRHS) { 10796 CRHS = dyn_cast<ConstantSDNode>(LHS); 10797 if (CRHS) { 10798 std::swap(LHS, RHS); 10799 CC = getSetCCSwappedOperands(CC); 10800 } 10801 } 10802 10803 if (CRHS) { 10804 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10805 isBoolSGPR(LHS.getOperand(0))) { 10806 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10807 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10808 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10809 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10810 if ((CRHS->isAllOnes() && 10811 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10812 (CRHS->isZero() && 10813 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10814 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10815 DAG.getConstant(-1, SL, MVT::i1)); 10816 if ((CRHS->isAllOnes() && 10817 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10818 (CRHS->isZero() && 10819 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10820 return LHS.getOperand(0); 10821 } 10822 10823 const APInt &CRHSVal = CRHS->getAPIntValue(); 10824 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10825 LHS.getOpcode() == ISD::SELECT && 10826 isa<ConstantSDNode>(LHS.getOperand(1)) && 10827 isa<ConstantSDNode>(LHS.getOperand(2)) && 10828 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10829 isBoolSGPR(LHS.getOperand(0))) { 10830 // Given CT != FT: 10831 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10832 // setcc (select cc, CT, CF), CF, ne => cc 10833 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10834 // setcc (select cc, CT, CF), CT, eq => cc 10835 const APInt &CT = LHS.getConstantOperandAPInt(1); 10836 const APInt &CF = LHS.getConstantOperandAPInt(2); 10837 10838 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10839 (CT == CRHSVal && CC == ISD::SETNE)) 10840 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10841 DAG.getConstant(-1, SL, MVT::i1)); 10842 if ((CF == CRHSVal && CC == ISD::SETNE) || 10843 (CT == CRHSVal && CC == ISD::SETEQ)) 10844 return LHS.getOperand(0); 10845 } 10846 } 10847 10848 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10849 VT != MVT::f16)) 10850 return SDValue(); 10851 10852 // Match isinf/isfinite pattern 10853 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10854 // (fcmp one (fabs x), inf) -> (fp_class x, 10855 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10856 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10857 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10858 if (!CRHS) 10859 return SDValue(); 10860 10861 const APFloat &APF = CRHS->getValueAPF(); 10862 if (APF.isInfinity() && !APF.isNegative()) { 10863 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10864 SIInstrFlags::N_INFINITY; 10865 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10866 SIInstrFlags::P_ZERO | 10867 SIInstrFlags::N_NORMAL | 10868 SIInstrFlags::P_NORMAL | 10869 SIInstrFlags::N_SUBNORMAL | 10870 SIInstrFlags::P_SUBNORMAL; 10871 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10872 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10873 DAG.getConstant(Mask, SL, MVT::i32)); 10874 } 10875 } 10876 10877 return SDValue(); 10878 } 10879 10880 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10881 DAGCombinerInfo &DCI) const { 10882 SelectionDAG &DAG = DCI.DAG; 10883 SDLoc SL(N); 10884 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10885 10886 SDValue Src = N->getOperand(0); 10887 SDValue Shift = N->getOperand(0); 10888 10889 // TODO: Extend type shouldn't matter (assuming legal types). 10890 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10891 Shift = Shift.getOperand(0); 10892 10893 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10894 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10895 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10896 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10897 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10898 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10899 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10900 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 10901 SDLoc(Shift.getOperand(0)), MVT::i32); 10902 10903 unsigned ShiftOffset = 8 * Offset; 10904 if (Shift.getOpcode() == ISD::SHL) 10905 ShiftOffset -= C->getZExtValue(); 10906 else 10907 ShiftOffset += C->getZExtValue(); 10908 10909 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10910 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10911 MVT::f32, Shifted); 10912 } 10913 } 10914 } 10915 10916 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10917 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10918 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10919 // We simplified Src. If this node is not dead, visit it again so it is 10920 // folded properly. 10921 if (N->getOpcode() != ISD::DELETED_NODE) 10922 DCI.AddToWorklist(N); 10923 return SDValue(N, 0); 10924 } 10925 10926 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10927 if (SDValue DemandedSrc = 10928 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10929 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10930 10931 return SDValue(); 10932 } 10933 10934 SDValue SITargetLowering::performClampCombine(SDNode *N, 10935 DAGCombinerInfo &DCI) const { 10936 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10937 if (!CSrc) 10938 return SDValue(); 10939 10940 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10941 const APFloat &F = CSrc->getValueAPF(); 10942 APFloat Zero = APFloat::getZero(F.getSemantics()); 10943 if (F < Zero || 10944 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10945 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10946 } 10947 10948 APFloat One(F.getSemantics(), "1.0"); 10949 if (F > One) 10950 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10951 10952 return SDValue(CSrc, 0); 10953 } 10954 10955 10956 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10957 DAGCombinerInfo &DCI) const { 10958 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10959 return SDValue(); 10960 switch (N->getOpcode()) { 10961 case ISD::ADD: 10962 return performAddCombine(N, DCI); 10963 case ISD::SUB: 10964 return performSubCombine(N, DCI); 10965 case ISD::ADDCARRY: 10966 case ISD::SUBCARRY: 10967 return performAddCarrySubCarryCombine(N, DCI); 10968 case ISD::FADD: 10969 return performFAddCombine(N, DCI); 10970 case ISD::FSUB: 10971 return performFSubCombine(N, DCI); 10972 case ISD::SETCC: 10973 return performSetCCCombine(N, DCI); 10974 case ISD::FMAXNUM: 10975 case ISD::FMINNUM: 10976 case ISD::FMAXNUM_IEEE: 10977 case ISD::FMINNUM_IEEE: 10978 case ISD::SMAX: 10979 case ISD::SMIN: 10980 case ISD::UMAX: 10981 case ISD::UMIN: 10982 case AMDGPUISD::FMIN_LEGACY: 10983 case AMDGPUISD::FMAX_LEGACY: 10984 return performMinMaxCombine(N, DCI); 10985 case ISD::FMA: 10986 return performFMACombine(N, DCI); 10987 case ISD::AND: 10988 return performAndCombine(N, DCI); 10989 case ISD::OR: 10990 return performOrCombine(N, DCI); 10991 case ISD::XOR: 10992 return performXorCombine(N, DCI); 10993 case ISD::ZERO_EXTEND: 10994 return performZeroExtendCombine(N, DCI); 10995 case ISD::SIGN_EXTEND_INREG: 10996 return performSignExtendInRegCombine(N , DCI); 10997 case AMDGPUISD::FP_CLASS: 10998 return performClassCombine(N, DCI); 10999 case ISD::FCANONICALIZE: 11000 return performFCanonicalizeCombine(N, DCI); 11001 case AMDGPUISD::RCP: 11002 return performRcpCombine(N, DCI); 11003 case AMDGPUISD::FRACT: 11004 case AMDGPUISD::RSQ: 11005 case AMDGPUISD::RCP_LEGACY: 11006 case AMDGPUISD::RCP_IFLAG: 11007 case AMDGPUISD::RSQ_CLAMP: 11008 case AMDGPUISD::LDEXP: { 11009 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11010 SDValue Src = N->getOperand(0); 11011 if (Src.isUndef()) 11012 return Src; 11013 break; 11014 } 11015 case ISD::SINT_TO_FP: 11016 case ISD::UINT_TO_FP: 11017 return performUCharToFloatCombine(N, DCI); 11018 case AMDGPUISD::CVT_F32_UBYTE0: 11019 case AMDGPUISD::CVT_F32_UBYTE1: 11020 case AMDGPUISD::CVT_F32_UBYTE2: 11021 case AMDGPUISD::CVT_F32_UBYTE3: 11022 return performCvtF32UByteNCombine(N, DCI); 11023 case AMDGPUISD::FMED3: 11024 return performFMed3Combine(N, DCI); 11025 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11026 return performCvtPkRTZCombine(N, DCI); 11027 case AMDGPUISD::CLAMP: 11028 return performClampCombine(N, DCI); 11029 case ISD::SCALAR_TO_VECTOR: { 11030 SelectionDAG &DAG = DCI.DAG; 11031 EVT VT = N->getValueType(0); 11032 11033 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11034 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11035 SDLoc SL(N); 11036 SDValue Src = N->getOperand(0); 11037 EVT EltVT = Src.getValueType(); 11038 if (EltVT == MVT::f16) 11039 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11040 11041 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11042 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11043 } 11044 11045 break; 11046 } 11047 case ISD::EXTRACT_VECTOR_ELT: 11048 return performExtractVectorEltCombine(N, DCI); 11049 case ISD::INSERT_VECTOR_ELT: 11050 return performInsertVectorEltCombine(N, DCI); 11051 case ISD::LOAD: { 11052 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11053 return Widended; 11054 LLVM_FALLTHROUGH; 11055 } 11056 default: { 11057 if (!DCI.isBeforeLegalize()) { 11058 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11059 return performMemSDNodeCombine(MemNode, DCI); 11060 } 11061 11062 break; 11063 } 11064 } 11065 11066 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11067 } 11068 11069 /// Helper function for adjustWritemask 11070 static unsigned SubIdx2Lane(unsigned Idx) { 11071 switch (Idx) { 11072 default: return ~0u; 11073 case AMDGPU::sub0: return 0; 11074 case AMDGPU::sub1: return 1; 11075 case AMDGPU::sub2: return 2; 11076 case AMDGPU::sub3: return 3; 11077 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11078 } 11079 } 11080 11081 /// Adjust the writemask of MIMG instructions 11082 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11083 SelectionDAG &DAG) const { 11084 unsigned Opcode = Node->getMachineOpcode(); 11085 11086 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11087 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11088 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11089 return Node; // not implemented for D16 11090 11091 SDNode *Users[5] = { nullptr }; 11092 unsigned Lane = 0; 11093 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11094 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11095 unsigned NewDmask = 0; 11096 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11097 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11098 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11099 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 11100 unsigned TFCLane = 0; 11101 bool HasChain = Node->getNumValues() > 1; 11102 11103 if (OldDmask == 0) { 11104 // These are folded out, but on the chance it happens don't assert. 11105 return Node; 11106 } 11107 11108 unsigned OldBitsSet = countPopulation(OldDmask); 11109 // Work out which is the TFE/LWE lane if that is enabled. 11110 if (UsesTFC) { 11111 TFCLane = OldBitsSet; 11112 } 11113 11114 // Try to figure out the used register components 11115 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11116 I != E; ++I) { 11117 11118 // Don't look at users of the chain. 11119 if (I.getUse().getResNo() != 0) 11120 continue; 11121 11122 // Abort if we can't understand the usage 11123 if (!I->isMachineOpcode() || 11124 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11125 return Node; 11126 11127 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11128 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11129 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11130 // set, etc. 11131 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11132 if (Lane == ~0u) 11133 return Node; 11134 11135 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11136 if (UsesTFC && Lane == TFCLane) { 11137 Users[Lane] = *I; 11138 } else { 11139 // Set which texture component corresponds to the lane. 11140 unsigned Comp; 11141 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11142 Comp = countTrailingZeros(Dmask); 11143 Dmask &= ~(1 << Comp); 11144 } 11145 11146 // Abort if we have more than one user per component. 11147 if (Users[Lane]) 11148 return Node; 11149 11150 Users[Lane] = *I; 11151 NewDmask |= 1 << Comp; 11152 } 11153 } 11154 11155 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11156 bool NoChannels = !NewDmask; 11157 if (NoChannels) { 11158 if (!UsesTFC) { 11159 // No uses of the result and not using TFC. Then do nothing. 11160 return Node; 11161 } 11162 // If the original dmask has one channel - then nothing to do 11163 if (OldBitsSet == 1) 11164 return Node; 11165 // Use an arbitrary dmask - required for the instruction to work 11166 NewDmask = 1; 11167 } 11168 // Abort if there's no change 11169 if (NewDmask == OldDmask) 11170 return Node; 11171 11172 unsigned BitsSet = countPopulation(NewDmask); 11173 11174 // Check for TFE or LWE - increase the number of channels by one to account 11175 // for the extra return value 11176 // This will need adjustment for D16 if this is also included in 11177 // adjustWriteMask (this function) but at present D16 are excluded. 11178 unsigned NewChannels = BitsSet + UsesTFC; 11179 11180 int NewOpcode = 11181 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11182 assert(NewOpcode != -1 && 11183 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11184 "failed to find equivalent MIMG op"); 11185 11186 // Adjust the writemask in the node 11187 SmallVector<SDValue, 12> Ops; 11188 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11189 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11190 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11191 11192 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11193 11194 MVT ResultVT = NewChannels == 1 ? 11195 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11196 NewChannels == 5 ? 8 : NewChannels); 11197 SDVTList NewVTList = HasChain ? 11198 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11199 11200 11201 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11202 NewVTList, Ops); 11203 11204 if (HasChain) { 11205 // Update chain. 11206 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11207 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11208 } 11209 11210 if (NewChannels == 1) { 11211 assert(Node->hasNUsesOfValue(1, 0)); 11212 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11213 SDLoc(Node), Users[Lane]->getValueType(0), 11214 SDValue(NewNode, 0)); 11215 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11216 return nullptr; 11217 } 11218 11219 // Update the users of the node with the new indices 11220 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11221 SDNode *User = Users[i]; 11222 if (!User) { 11223 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11224 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11225 if (i || !NoChannels) 11226 continue; 11227 } else { 11228 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11229 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11230 } 11231 11232 switch (Idx) { 11233 default: break; 11234 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11235 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11236 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11237 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11238 } 11239 } 11240 11241 DAG.RemoveDeadNode(Node); 11242 return nullptr; 11243 } 11244 11245 static bool isFrameIndexOp(SDValue Op) { 11246 if (Op.getOpcode() == ISD::AssertZext) 11247 Op = Op.getOperand(0); 11248 11249 return isa<FrameIndexSDNode>(Op); 11250 } 11251 11252 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11253 /// with frame index operands. 11254 /// LLVM assumes that inputs are to these instructions are registers. 11255 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11256 SelectionDAG &DAG) const { 11257 if (Node->getOpcode() == ISD::CopyToReg) { 11258 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11259 SDValue SrcVal = Node->getOperand(2); 11260 11261 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11262 // to try understanding copies to physical registers. 11263 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11264 SDLoc SL(Node); 11265 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11266 SDValue VReg = DAG.getRegister( 11267 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11268 11269 SDNode *Glued = Node->getGluedNode(); 11270 SDValue ToVReg 11271 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11272 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11273 SDValue ToResultReg 11274 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11275 VReg, ToVReg.getValue(1)); 11276 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11277 DAG.RemoveDeadNode(Node); 11278 return ToResultReg.getNode(); 11279 } 11280 } 11281 11282 SmallVector<SDValue, 8> Ops; 11283 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11284 if (!isFrameIndexOp(Node->getOperand(i))) { 11285 Ops.push_back(Node->getOperand(i)); 11286 continue; 11287 } 11288 11289 SDLoc DL(Node); 11290 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11291 Node->getOperand(i).getValueType(), 11292 Node->getOperand(i)), 0)); 11293 } 11294 11295 return DAG.UpdateNodeOperands(Node, Ops); 11296 } 11297 11298 /// Fold the instructions after selecting them. 11299 /// Returns null if users were already updated. 11300 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11301 SelectionDAG &DAG) const { 11302 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11303 unsigned Opcode = Node->getMachineOpcode(); 11304 11305 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11306 !TII->isGather4(Opcode) && 11307 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11308 return adjustWritemask(Node, DAG); 11309 } 11310 11311 if (Opcode == AMDGPU::INSERT_SUBREG || 11312 Opcode == AMDGPU::REG_SEQUENCE) { 11313 legalizeTargetIndependentNode(Node, DAG); 11314 return Node; 11315 } 11316 11317 switch (Opcode) { 11318 case AMDGPU::V_DIV_SCALE_F32_e64: 11319 case AMDGPU::V_DIV_SCALE_F64_e64: { 11320 // Satisfy the operand register constraint when one of the inputs is 11321 // undefined. Ordinarily each undef value will have its own implicit_def of 11322 // a vreg, so force these to use a single register. 11323 SDValue Src0 = Node->getOperand(1); 11324 SDValue Src1 = Node->getOperand(3); 11325 SDValue Src2 = Node->getOperand(5); 11326 11327 if ((Src0.isMachineOpcode() && 11328 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11329 (Src0 == Src1 || Src0 == Src2)) 11330 break; 11331 11332 MVT VT = Src0.getValueType().getSimpleVT(); 11333 const TargetRegisterClass *RC = 11334 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11335 11336 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11337 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11338 11339 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11340 UndefReg, Src0, SDValue()); 11341 11342 // src0 must be the same register as src1 or src2, even if the value is 11343 // undefined, so make sure we don't violate this constraint. 11344 if (Src0.isMachineOpcode() && 11345 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11346 if (Src1.isMachineOpcode() && 11347 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11348 Src0 = Src1; 11349 else if (Src2.isMachineOpcode() && 11350 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11351 Src0 = Src2; 11352 else { 11353 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11354 Src0 = UndefReg; 11355 Src1 = UndefReg; 11356 } 11357 } else 11358 break; 11359 11360 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11361 Ops[1] = Src0; 11362 Ops[3] = Src1; 11363 Ops[5] = Src2; 11364 Ops.push_back(ImpDef.getValue(1)); 11365 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11366 } 11367 default: 11368 break; 11369 } 11370 11371 return Node; 11372 } 11373 11374 // Any MIMG instructions that use tfe or lwe require an initialization of the 11375 // result register that will be written in the case of a memory access failure. 11376 // The required code is also added to tie this init code to the result of the 11377 // img instruction. 11378 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11379 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11380 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11381 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11382 MachineBasicBlock &MBB = *MI.getParent(); 11383 11384 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11385 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11386 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11387 11388 if (!TFE && !LWE) // intersect_ray 11389 return; 11390 11391 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11392 unsigned LWEVal = LWE->getImm(); 11393 unsigned D16Val = D16 ? D16->getImm() : 0; 11394 11395 if (!TFEVal && !LWEVal) 11396 return; 11397 11398 // At least one of TFE or LWE are non-zero 11399 // We have to insert a suitable initialization of the result value and 11400 // tie this to the dest of the image instruction. 11401 11402 const DebugLoc &DL = MI.getDebugLoc(); 11403 11404 int DstIdx = 11405 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11406 11407 // Calculate which dword we have to initialize to 0. 11408 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11409 11410 // check that dmask operand is found. 11411 assert(MO_Dmask && "Expected dmask operand in instruction"); 11412 11413 unsigned dmask = MO_Dmask->getImm(); 11414 // Determine the number of active lanes taking into account the 11415 // Gather4 special case 11416 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11417 11418 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11419 11420 unsigned InitIdx = 11421 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11422 11423 // Abandon attempt if the dst size isn't large enough 11424 // - this is in fact an error but this is picked up elsewhere and 11425 // reported correctly. 11426 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11427 if (DstSize < InitIdx) 11428 return; 11429 11430 // Create a register for the intialization value. 11431 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11432 unsigned NewDst = 0; // Final initialized value will be in here 11433 11434 // If PRTStrictNull feature is enabled (the default) then initialize 11435 // all the result registers to 0, otherwise just the error indication 11436 // register (VGPRn+1) 11437 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11438 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11439 11440 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11441 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11442 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11443 // Initialize dword 11444 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11445 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11446 .addImm(0); 11447 // Insert into the super-reg 11448 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11449 .addReg(PrevDst) 11450 .addReg(SubReg) 11451 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11452 11453 PrevDst = NewDst; 11454 } 11455 11456 // Add as an implicit operand 11457 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11458 11459 // Tie the just added implicit operand to the dst 11460 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11461 } 11462 11463 /// Assign the register class depending on the number of 11464 /// bits set in the writemask 11465 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11466 SDNode *Node) const { 11467 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11468 11469 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11470 11471 if (TII->isVOP3(MI.getOpcode())) { 11472 // Make sure constant bus requirements are respected. 11473 TII->legalizeOperandsVOP3(MRI, MI); 11474 11475 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11476 // This saves a chain-copy of registers and better ballance register 11477 // use between vgpr and agpr as agpr tuples tend to be big. 11478 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11479 unsigned Opc = MI.getOpcode(); 11480 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11481 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11482 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11483 if (I == -1) 11484 break; 11485 MachineOperand &Op = MI.getOperand(I); 11486 if (!Op.isReg() || !Op.getReg().isVirtual()) 11487 continue; 11488 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11489 if (!TRI->hasAGPRs(RC)) 11490 continue; 11491 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11492 if (!Src || !Src->isCopy() || 11493 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11494 continue; 11495 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11496 // All uses of agpr64 and agpr32 can also accept vgpr except for 11497 // v_accvgpr_read, but we do not produce agpr reads during selection, 11498 // so no use checks are needed. 11499 MRI.setRegClass(Op.getReg(), NewRC); 11500 } 11501 } 11502 11503 return; 11504 } 11505 11506 // Replace unused atomics with the no return version. 11507 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11508 if (NoRetAtomicOp != -1) { 11509 if (!Node->hasAnyUseOfValue(0)) { 11510 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11511 AMDGPU::OpName::cpol); 11512 if (CPolIdx != -1) { 11513 MachineOperand &CPol = MI.getOperand(CPolIdx); 11514 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11515 } 11516 MI.RemoveOperand(0); 11517 MI.setDesc(TII->get(NoRetAtomicOp)); 11518 return; 11519 } 11520 11521 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11522 // instruction, because the return type of these instructions is a vec2 of 11523 // the memory type, so it can be tied to the input operand. 11524 // This means these instructions always have a use, so we need to add a 11525 // special case to check if the atomic has only one extract_subreg use, 11526 // which itself has no uses. 11527 if ((Node->hasNUsesOfValue(1, 0) && 11528 Node->use_begin()->isMachineOpcode() && 11529 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11530 !Node->use_begin()->hasAnyUseOfValue(0))) { 11531 Register Def = MI.getOperand(0).getReg(); 11532 11533 // Change this into a noret atomic. 11534 MI.setDesc(TII->get(NoRetAtomicOp)); 11535 MI.RemoveOperand(0); 11536 11537 // If we only remove the def operand from the atomic instruction, the 11538 // extract_subreg will be left with a use of a vreg without a def. 11539 // So we need to insert an implicit_def to avoid machine verifier 11540 // errors. 11541 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11542 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11543 } 11544 return; 11545 } 11546 11547 if (TII->isMIMG(MI) && !MI.mayStore()) 11548 AddIMGInit(MI); 11549 } 11550 11551 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11552 uint64_t Val) { 11553 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11554 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11555 } 11556 11557 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11558 const SDLoc &DL, 11559 SDValue Ptr) const { 11560 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11561 11562 // Build the half of the subregister with the constants before building the 11563 // full 128-bit register. If we are building multiple resource descriptors, 11564 // this will allow CSEing of the 2-component register. 11565 const SDValue Ops0[] = { 11566 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11567 buildSMovImm32(DAG, DL, 0), 11568 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11569 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11570 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11571 }; 11572 11573 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11574 MVT::v2i32, Ops0), 0); 11575 11576 // Combine the constants and the pointer. 11577 const SDValue Ops1[] = { 11578 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11579 Ptr, 11580 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11581 SubRegHi, 11582 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11583 }; 11584 11585 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11586 } 11587 11588 /// Return a resource descriptor with the 'Add TID' bit enabled 11589 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11590 /// of the resource descriptor) to create an offset, which is added to 11591 /// the resource pointer. 11592 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11593 SDValue Ptr, uint32_t RsrcDword1, 11594 uint64_t RsrcDword2And3) const { 11595 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11596 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11597 if (RsrcDword1) { 11598 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11599 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11600 0); 11601 } 11602 11603 SDValue DataLo = buildSMovImm32(DAG, DL, 11604 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11605 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11606 11607 const SDValue Ops[] = { 11608 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11609 PtrLo, 11610 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11611 PtrHi, 11612 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11613 DataLo, 11614 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11615 DataHi, 11616 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11617 }; 11618 11619 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11620 } 11621 11622 //===----------------------------------------------------------------------===// 11623 // SI Inline Assembly Support 11624 //===----------------------------------------------------------------------===// 11625 11626 std::pair<unsigned, const TargetRegisterClass *> 11627 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11628 StringRef Constraint, 11629 MVT VT) const { 11630 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11631 11632 const TargetRegisterClass *RC = nullptr; 11633 if (Constraint.size() == 1) { 11634 const unsigned BitWidth = VT.getSizeInBits(); 11635 switch (Constraint[0]) { 11636 default: 11637 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11638 case 's': 11639 case 'r': 11640 switch (BitWidth) { 11641 case 16: 11642 RC = &AMDGPU::SReg_32RegClass; 11643 break; 11644 case 64: 11645 RC = &AMDGPU::SGPR_64RegClass; 11646 break; 11647 default: 11648 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11649 if (!RC) 11650 return std::make_pair(0U, nullptr); 11651 break; 11652 } 11653 break; 11654 case 'v': 11655 switch (BitWidth) { 11656 case 16: 11657 RC = &AMDGPU::VGPR_32RegClass; 11658 break; 11659 default: 11660 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11661 if (!RC) 11662 return std::make_pair(0U, nullptr); 11663 break; 11664 } 11665 break; 11666 case 'a': 11667 if (!Subtarget->hasMAIInsts()) 11668 break; 11669 switch (BitWidth) { 11670 case 16: 11671 RC = &AMDGPU::AGPR_32RegClass; 11672 break; 11673 default: 11674 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11675 if (!RC) 11676 return std::make_pair(0U, nullptr); 11677 break; 11678 } 11679 break; 11680 } 11681 // We actually support i128, i16 and f16 as inline parameters 11682 // even if they are not reported as legal 11683 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11684 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11685 return std::make_pair(0U, RC); 11686 } 11687 11688 if (Constraint.size() > 1) { 11689 if (Constraint[1] == 'v') { 11690 RC = &AMDGPU::VGPR_32RegClass; 11691 } else if (Constraint[1] == 's') { 11692 RC = &AMDGPU::SGPR_32RegClass; 11693 } else if (Constraint[1] == 'a') { 11694 RC = &AMDGPU::AGPR_32RegClass; 11695 } 11696 11697 if (RC) { 11698 uint32_t Idx; 11699 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11700 if (!Failed && Idx < RC->getNumRegs()) 11701 return std::make_pair(RC->getRegister(Idx), RC); 11702 } 11703 } 11704 11705 // FIXME: Returns VS_32 for physical SGPR constraints 11706 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11707 } 11708 11709 static bool isImmConstraint(StringRef Constraint) { 11710 if (Constraint.size() == 1) { 11711 switch (Constraint[0]) { 11712 default: break; 11713 case 'I': 11714 case 'J': 11715 case 'A': 11716 case 'B': 11717 case 'C': 11718 return true; 11719 } 11720 } else if (Constraint == "DA" || 11721 Constraint == "DB") { 11722 return true; 11723 } 11724 return false; 11725 } 11726 11727 SITargetLowering::ConstraintType 11728 SITargetLowering::getConstraintType(StringRef Constraint) const { 11729 if (Constraint.size() == 1) { 11730 switch (Constraint[0]) { 11731 default: break; 11732 case 's': 11733 case 'v': 11734 case 'a': 11735 return C_RegisterClass; 11736 } 11737 } 11738 if (isImmConstraint(Constraint)) { 11739 return C_Other; 11740 } 11741 return TargetLowering::getConstraintType(Constraint); 11742 } 11743 11744 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11745 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11746 Val = Val & maskTrailingOnes<uint64_t>(Size); 11747 } 11748 return Val; 11749 } 11750 11751 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11752 std::string &Constraint, 11753 std::vector<SDValue> &Ops, 11754 SelectionDAG &DAG) const { 11755 if (isImmConstraint(Constraint)) { 11756 uint64_t Val; 11757 if (getAsmOperandConstVal(Op, Val) && 11758 checkAsmConstraintVal(Op, Constraint, Val)) { 11759 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11760 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11761 } 11762 } else { 11763 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11764 } 11765 } 11766 11767 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11768 unsigned Size = Op.getScalarValueSizeInBits(); 11769 if (Size > 64) 11770 return false; 11771 11772 if (Size == 16 && !Subtarget->has16BitInsts()) 11773 return false; 11774 11775 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11776 Val = C->getSExtValue(); 11777 return true; 11778 } 11779 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11780 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11781 return true; 11782 } 11783 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11784 if (Size != 16 || Op.getNumOperands() != 2) 11785 return false; 11786 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11787 return false; 11788 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11789 Val = C->getSExtValue(); 11790 return true; 11791 } 11792 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11793 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11794 return true; 11795 } 11796 } 11797 11798 return false; 11799 } 11800 11801 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11802 const std::string &Constraint, 11803 uint64_t Val) const { 11804 if (Constraint.size() == 1) { 11805 switch (Constraint[0]) { 11806 case 'I': 11807 return AMDGPU::isInlinableIntLiteral(Val); 11808 case 'J': 11809 return isInt<16>(Val); 11810 case 'A': 11811 return checkAsmConstraintValA(Op, Val); 11812 case 'B': 11813 return isInt<32>(Val); 11814 case 'C': 11815 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11816 AMDGPU::isInlinableIntLiteral(Val); 11817 default: 11818 break; 11819 } 11820 } else if (Constraint.size() == 2) { 11821 if (Constraint == "DA") { 11822 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11823 int64_t LoBits = static_cast<int32_t>(Val); 11824 return checkAsmConstraintValA(Op, HiBits, 32) && 11825 checkAsmConstraintValA(Op, LoBits, 32); 11826 } 11827 if (Constraint == "DB") { 11828 return true; 11829 } 11830 } 11831 llvm_unreachable("Invalid asm constraint"); 11832 } 11833 11834 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11835 uint64_t Val, 11836 unsigned MaxSize) const { 11837 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11838 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11839 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11840 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11841 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11842 return true; 11843 } 11844 return false; 11845 } 11846 11847 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11848 switch (UnalignedClassID) { 11849 case AMDGPU::VReg_64RegClassID: 11850 return AMDGPU::VReg_64_Align2RegClassID; 11851 case AMDGPU::VReg_96RegClassID: 11852 return AMDGPU::VReg_96_Align2RegClassID; 11853 case AMDGPU::VReg_128RegClassID: 11854 return AMDGPU::VReg_128_Align2RegClassID; 11855 case AMDGPU::VReg_160RegClassID: 11856 return AMDGPU::VReg_160_Align2RegClassID; 11857 case AMDGPU::VReg_192RegClassID: 11858 return AMDGPU::VReg_192_Align2RegClassID; 11859 case AMDGPU::VReg_224RegClassID: 11860 return AMDGPU::VReg_224_Align2RegClassID; 11861 case AMDGPU::VReg_256RegClassID: 11862 return AMDGPU::VReg_256_Align2RegClassID; 11863 case AMDGPU::VReg_512RegClassID: 11864 return AMDGPU::VReg_512_Align2RegClassID; 11865 case AMDGPU::VReg_1024RegClassID: 11866 return AMDGPU::VReg_1024_Align2RegClassID; 11867 case AMDGPU::AReg_64RegClassID: 11868 return AMDGPU::AReg_64_Align2RegClassID; 11869 case AMDGPU::AReg_96RegClassID: 11870 return AMDGPU::AReg_96_Align2RegClassID; 11871 case AMDGPU::AReg_128RegClassID: 11872 return AMDGPU::AReg_128_Align2RegClassID; 11873 case AMDGPU::AReg_160RegClassID: 11874 return AMDGPU::AReg_160_Align2RegClassID; 11875 case AMDGPU::AReg_192RegClassID: 11876 return AMDGPU::AReg_192_Align2RegClassID; 11877 case AMDGPU::AReg_256RegClassID: 11878 return AMDGPU::AReg_256_Align2RegClassID; 11879 case AMDGPU::AReg_512RegClassID: 11880 return AMDGPU::AReg_512_Align2RegClassID; 11881 case AMDGPU::AReg_1024RegClassID: 11882 return AMDGPU::AReg_1024_Align2RegClassID; 11883 default: 11884 return -1; 11885 } 11886 } 11887 11888 // Figure out which registers should be reserved for stack access. Only after 11889 // the function is legalized do we know all of the non-spill stack objects or if 11890 // calls are present. 11891 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11892 MachineRegisterInfo &MRI = MF.getRegInfo(); 11893 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11894 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11895 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11896 const SIInstrInfo *TII = ST.getInstrInfo(); 11897 11898 if (Info->isEntryFunction()) { 11899 // Callable functions have fixed registers used for stack access. 11900 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11901 } 11902 11903 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11904 Info->getStackPtrOffsetReg())); 11905 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11906 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11907 11908 // We need to worry about replacing the default register with itself in case 11909 // of MIR testcases missing the MFI. 11910 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11911 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11912 11913 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11914 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11915 11916 Info->limitOccupancy(MF); 11917 11918 if (ST.isWave32() && !MF.empty()) { 11919 for (auto &MBB : MF) { 11920 for (auto &MI : MBB) { 11921 TII->fixImplicitOperands(MI); 11922 } 11923 } 11924 } 11925 11926 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11927 // classes if required. Ideally the register class constraints would differ 11928 // per-subtarget, but there's no easy way to achieve that right now. This is 11929 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11930 // from using them as the register class for legal types. 11931 if (ST.needsAlignedVGPRs()) { 11932 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11933 const Register Reg = Register::index2VirtReg(I); 11934 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11935 if (!RC) 11936 continue; 11937 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11938 if (NewClassID != -1) 11939 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11940 } 11941 } 11942 11943 TargetLoweringBase::finalizeLowering(MF); 11944 11945 // Allocate a VGPR for future SGPR Spill if 11946 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11947 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11948 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11949 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11950 Info->reserveVGPRforSGPRSpills(MF); 11951 } 11952 11953 void SITargetLowering::computeKnownBitsForFrameIndex( 11954 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11955 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11956 11957 // Set the high bits to zero based on the maximum allowed scratch size per 11958 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11959 // calculation won't overflow, so assume the sign bit is never set. 11960 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11961 } 11962 11963 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11964 KnownBits &Known, unsigned Dim) { 11965 unsigned MaxValue = 11966 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11967 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11968 } 11969 11970 void SITargetLowering::computeKnownBitsForTargetInstr( 11971 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11972 const MachineRegisterInfo &MRI, unsigned Depth) const { 11973 const MachineInstr *MI = MRI.getVRegDef(R); 11974 switch (MI->getOpcode()) { 11975 case AMDGPU::G_INTRINSIC: { 11976 switch (MI->getIntrinsicID()) { 11977 case Intrinsic::amdgcn_workitem_id_x: 11978 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11979 break; 11980 case Intrinsic::amdgcn_workitem_id_y: 11981 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11982 break; 11983 case Intrinsic::amdgcn_workitem_id_z: 11984 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11985 break; 11986 case Intrinsic::amdgcn_mbcnt_lo: 11987 case Intrinsic::amdgcn_mbcnt_hi: { 11988 // These return at most the wavefront size - 1. 11989 unsigned Size = MRI.getType(R).getSizeInBits(); 11990 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11991 break; 11992 } 11993 case Intrinsic::amdgcn_groupstaticsize: { 11994 // We can report everything over the maximum size as 0. We can't report 11995 // based on the actual size because we don't know if it's accurate or not 11996 // at any given point. 11997 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11998 break; 11999 } 12000 } 12001 break; 12002 } 12003 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12004 Known.Zero.setHighBits(24); 12005 break; 12006 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12007 Known.Zero.setHighBits(16); 12008 break; 12009 } 12010 } 12011 12012 Align SITargetLowering::computeKnownAlignForTargetInstr( 12013 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12014 unsigned Depth) const { 12015 const MachineInstr *MI = MRI.getVRegDef(R); 12016 switch (MI->getOpcode()) { 12017 case AMDGPU::G_INTRINSIC: 12018 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12019 // FIXME: Can this move to generic code? What about the case where the call 12020 // site specifies a lower alignment? 12021 Intrinsic::ID IID = MI->getIntrinsicID(); 12022 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12023 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12024 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12025 return *RetAlign; 12026 return Align(1); 12027 } 12028 default: 12029 return Align(1); 12030 } 12031 } 12032 12033 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12034 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12035 const Align CacheLineAlign = Align(64); 12036 12037 // Pre-GFX10 target did not benefit from loop alignment 12038 if (!ML || DisableLoopAlignment || 12039 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12040 getSubtarget()->hasInstFwdPrefetchBug()) 12041 return PrefAlign; 12042 12043 // On GFX10 I$ is 4 x 64 bytes cache lines. 12044 // By default prefetcher keeps one cache line behind and reads two ahead. 12045 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12046 // behind and one ahead. 12047 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12048 // If loop fits 64 bytes it always spans no more than two cache lines and 12049 // does not need an alignment. 12050 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12051 // Else if loop is less or equal 192 bytes we need two lines behind. 12052 12053 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12054 const MachineBasicBlock *Header = ML->getHeader(); 12055 if (Header->getAlignment() != PrefAlign) 12056 return Header->getAlignment(); // Already processed. 12057 12058 unsigned LoopSize = 0; 12059 for (const MachineBasicBlock *MBB : ML->blocks()) { 12060 // If inner loop block is aligned assume in average half of the alignment 12061 // size to be added as nops. 12062 if (MBB != Header) 12063 LoopSize += MBB->getAlignment().value() / 2; 12064 12065 for (const MachineInstr &MI : *MBB) { 12066 LoopSize += TII->getInstSizeInBytes(MI); 12067 if (LoopSize > 192) 12068 return PrefAlign; 12069 } 12070 } 12071 12072 if (LoopSize <= 64) 12073 return PrefAlign; 12074 12075 if (LoopSize <= 128) 12076 return CacheLineAlign; 12077 12078 // If any of parent loops is surrounded by prefetch instructions do not 12079 // insert new for inner loop, which would reset parent's settings. 12080 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12081 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12082 auto I = Exit->getFirstNonDebugInstr(); 12083 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12084 return CacheLineAlign; 12085 } 12086 } 12087 12088 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12089 MachineBasicBlock *Exit = ML->getExitBlock(); 12090 12091 if (Pre && Exit) { 12092 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12093 TII->get(AMDGPU::S_INST_PREFETCH)) 12094 .addImm(1); // prefetch 2 lines behind PC 12095 12096 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12097 TII->get(AMDGPU::S_INST_PREFETCH)) 12098 .addImm(2); // prefetch 1 line behind PC 12099 } 12100 12101 return CacheLineAlign; 12102 } 12103 12104 LLVM_ATTRIBUTE_UNUSED 12105 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12106 assert(N->getOpcode() == ISD::CopyFromReg); 12107 do { 12108 // Follow the chain until we find an INLINEASM node. 12109 N = N->getOperand(0).getNode(); 12110 if (N->getOpcode() == ISD::INLINEASM || 12111 N->getOpcode() == ISD::INLINEASM_BR) 12112 return true; 12113 } while (N->getOpcode() == ISD::CopyFromReg); 12114 return false; 12115 } 12116 12117 bool SITargetLowering::isSDNodeSourceOfDivergence( 12118 const SDNode *N, FunctionLoweringInfo *FLI, 12119 LegacyDivergenceAnalysis *KDA) const { 12120 switch (N->getOpcode()) { 12121 case ISD::CopyFromReg: { 12122 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12123 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12124 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12125 Register Reg = R->getReg(); 12126 12127 // FIXME: Why does this need to consider isLiveIn? 12128 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12129 return !TRI->isSGPRReg(MRI, Reg); 12130 12131 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12132 return KDA->isDivergent(V); 12133 12134 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12135 return !TRI->isSGPRReg(MRI, Reg); 12136 } 12137 case ISD::LOAD: { 12138 const LoadSDNode *L = cast<LoadSDNode>(N); 12139 unsigned AS = L->getAddressSpace(); 12140 // A flat load may access private memory. 12141 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12142 } 12143 case ISD::CALLSEQ_END: 12144 return true; 12145 case ISD::INTRINSIC_WO_CHAIN: 12146 return AMDGPU::isIntrinsicSourceOfDivergence( 12147 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12148 case ISD::INTRINSIC_W_CHAIN: 12149 return AMDGPU::isIntrinsicSourceOfDivergence( 12150 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12151 case AMDGPUISD::ATOMIC_CMP_SWAP: 12152 case AMDGPUISD::ATOMIC_INC: 12153 case AMDGPUISD::ATOMIC_DEC: 12154 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12155 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12156 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12157 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12158 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12159 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12160 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12161 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12162 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12163 case AMDGPUISD::BUFFER_ATOMIC_AND: 12164 case AMDGPUISD::BUFFER_ATOMIC_OR: 12165 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12166 case AMDGPUISD::BUFFER_ATOMIC_INC: 12167 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12168 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12169 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12170 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12171 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12172 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12173 // Target-specific read-modify-write atomics are sources of divergence. 12174 return true; 12175 default: 12176 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12177 // Generic read-modify-write atomics are sources of divergence. 12178 return A->readMem() && A->writeMem(); 12179 } 12180 return false; 12181 } 12182 } 12183 12184 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12185 EVT VT) const { 12186 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12187 case MVT::f32: 12188 return hasFP32Denormals(DAG.getMachineFunction()); 12189 case MVT::f64: 12190 case MVT::f16: 12191 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12192 default: 12193 return false; 12194 } 12195 } 12196 12197 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12198 MachineFunction &MF) const { 12199 switch (Ty.getScalarSizeInBits()) { 12200 case 32: 12201 return hasFP32Denormals(MF); 12202 case 64: 12203 case 16: 12204 return hasFP64FP16Denormals(MF); 12205 default: 12206 return false; 12207 } 12208 } 12209 12210 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12211 const SelectionDAG &DAG, 12212 bool SNaN, 12213 unsigned Depth) const { 12214 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12215 const MachineFunction &MF = DAG.getMachineFunction(); 12216 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12217 12218 if (Info->getMode().DX10Clamp) 12219 return true; // Clamped to 0. 12220 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12221 } 12222 12223 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12224 SNaN, Depth); 12225 } 12226 12227 // Global FP atomic instructions have a hardcoded FP mode and do not support 12228 // FP32 denormals, and only support v2f16 denormals. 12229 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12230 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12231 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12232 if (&Flt == &APFloat::IEEEsingle()) 12233 return DenormMode == DenormalMode::getPreserveSign(); 12234 return DenormMode == DenormalMode::getIEEE(); 12235 } 12236 12237 TargetLowering::AtomicExpansionKind 12238 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12239 12240 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12241 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12242 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12243 SmallVector<StringRef> SSNs; 12244 Ctx.getSyncScopeNames(SSNs); 12245 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12246 ? "system" 12247 : SSNs[RMW->getSyncScopeID()]; 12248 ORE.emit([&]() { 12249 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12250 << "Hardware instruction generated for atomic " 12251 << RMW->getOperationName(RMW->getOperation()) 12252 << " operation at memory scope " << MemScope 12253 << " due to an unsafe request."; 12254 }); 12255 return Kind; 12256 }; 12257 12258 switch (RMW->getOperation()) { 12259 case AtomicRMWInst::FAdd: { 12260 Type *Ty = RMW->getType(); 12261 12262 // We don't have a way to support 16-bit atomics now, so just leave them 12263 // as-is. 12264 if (Ty->isHalfTy()) 12265 return AtomicExpansionKind::None; 12266 12267 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12268 return AtomicExpansionKind::CmpXChg; 12269 12270 unsigned AS = RMW->getPointerAddressSpace(); 12271 12272 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12273 Subtarget->hasAtomicFaddInsts()) { 12274 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12275 // floating point atomic instructions. May generate more efficient code, 12276 // but may not respect rounding and denormal modes, and may give incorrect 12277 // results for certain memory destinations. 12278 if (RMW->getFunction() 12279 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12280 .getValueAsString() != "true") 12281 return AtomicExpansionKind::CmpXChg; 12282 12283 if (Subtarget->hasGFX90AInsts()) { 12284 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12285 return AtomicExpansionKind::CmpXChg; 12286 12287 auto SSID = RMW->getSyncScopeID(); 12288 if (SSID == SyncScope::System || 12289 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12290 return AtomicExpansionKind::CmpXChg; 12291 12292 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12293 } 12294 12295 if (AS == AMDGPUAS::FLAT_ADDRESS) 12296 return AtomicExpansionKind::CmpXChg; 12297 12298 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12299 : AtomicExpansionKind::CmpXChg; 12300 } 12301 12302 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12303 // to round-to-nearest-even. 12304 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12305 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12306 if (!Ty->isDoubleTy()) 12307 return AtomicExpansionKind::None; 12308 12309 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12310 return AtomicExpansionKind::None; 12311 12312 return RMW->getFunction() 12313 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12314 .getValueAsString() == "true" 12315 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12316 : AtomicExpansionKind::CmpXChg; 12317 } 12318 12319 return AtomicExpansionKind::CmpXChg; 12320 } 12321 default: 12322 break; 12323 } 12324 12325 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12326 } 12327 12328 const TargetRegisterClass * 12329 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12330 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12331 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12332 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12333 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12334 : &AMDGPU::SReg_32RegClass; 12335 if (!TRI->isSGPRClass(RC) && !isDivergent) 12336 return TRI->getEquivalentSGPRClass(RC); 12337 else if (TRI->isSGPRClass(RC) && isDivergent) 12338 return TRI->getEquivalentVGPRClass(RC); 12339 12340 return RC; 12341 } 12342 12343 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12344 // uniform values (as produced by the mask results of control flow intrinsics) 12345 // used outside of divergent blocks. The phi users need to also be treated as 12346 // always uniform. 12347 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12348 unsigned WaveSize) { 12349 // FIXME: We asssume we never cast the mask results of a control flow 12350 // intrinsic. 12351 // Early exit if the type won't be consistent as a compile time hack. 12352 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12353 if (!IT || IT->getBitWidth() != WaveSize) 12354 return false; 12355 12356 if (!isa<Instruction>(V)) 12357 return false; 12358 if (!Visited.insert(V).second) 12359 return false; 12360 bool Result = false; 12361 for (auto U : V->users()) { 12362 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12363 if (V == U->getOperand(1)) { 12364 switch (Intrinsic->getIntrinsicID()) { 12365 default: 12366 Result = false; 12367 break; 12368 case Intrinsic::amdgcn_if_break: 12369 case Intrinsic::amdgcn_if: 12370 case Intrinsic::amdgcn_else: 12371 Result = true; 12372 break; 12373 } 12374 } 12375 if (V == U->getOperand(0)) { 12376 switch (Intrinsic->getIntrinsicID()) { 12377 default: 12378 Result = false; 12379 break; 12380 case Intrinsic::amdgcn_end_cf: 12381 case Intrinsic::amdgcn_loop: 12382 Result = true; 12383 break; 12384 } 12385 } 12386 } else { 12387 Result = hasCFUser(U, Visited, WaveSize); 12388 } 12389 if (Result) 12390 break; 12391 } 12392 return Result; 12393 } 12394 12395 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12396 const Value *V) const { 12397 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12398 if (CI->isInlineAsm()) { 12399 // FIXME: This cannot give a correct answer. This should only trigger in 12400 // the case where inline asm returns mixed SGPR and VGPR results, used 12401 // outside the defining block. We don't have a specific result to 12402 // consider, so this assumes if any value is SGPR, the overall register 12403 // also needs to be SGPR. 12404 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12405 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12406 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12407 for (auto &TC : TargetConstraints) { 12408 if (TC.Type == InlineAsm::isOutput) { 12409 ComputeConstraintToUse(TC, SDValue()); 12410 unsigned AssignedReg; 12411 const TargetRegisterClass *RC; 12412 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12413 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12414 if (RC) { 12415 MachineRegisterInfo &MRI = MF.getRegInfo(); 12416 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12417 return true; 12418 else if (SIRI->isSGPRClass(RC)) 12419 return true; 12420 } 12421 } 12422 } 12423 } 12424 } 12425 SmallPtrSet<const Value *, 16> Visited; 12426 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12427 } 12428 12429 std::pair<InstructionCost, MVT> 12430 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12431 Type *Ty) const { 12432 std::pair<InstructionCost, MVT> Cost = 12433 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12434 auto Size = DL.getTypeSizeInBits(Ty); 12435 // Maximum load or store can handle 8 dwords for scalar and 4 for 12436 // vector ALU. Let's assume anything above 8 dwords is expensive 12437 // even if legal. 12438 if (Size <= 256) 12439 return Cost; 12440 12441 Cost.first = (Size + 255) / 256; 12442 return Cost; 12443 } 12444